orimização e testes de build hibrido

This commit is contained in:
Luiz Silva 2025-07-18 13:36:46 -03:00
parent 17aee620b3
commit 40dca15bff
53 changed files with 2944 additions and 697 deletions

View file

@ -22,6 +22,7 @@ __reExport(index_exports, require("./consulta"), module.exports);
__reExport(index_exports, require("./ecosistema"), module.exports); __reExport(index_exports, require("./ecosistema"), module.exports);
__reExport(index_exports, require("./extensoes"), module.exports); __reExport(index_exports, require("./extensoes"), module.exports);
__reExport(index_exports, require("./logger"), module.exports); __reExport(index_exports, require("./logger"), module.exports);
__reExport(index_exports, require("./testes-de-variaveis"), module.exports);
__reExport(index_exports, require("./texto_busca"), module.exports); __reExport(index_exports, require("./texto_busca"), module.exports);
__reExport(index_exports, require("./tipagemRotas"), module.exports); __reExport(index_exports, require("./tipagemRotas"), module.exports);
__reExport(index_exports, require("./unidades_medida"), module.exports); __reExport(index_exports, require("./unidades_medida"), module.exports);
@ -36,6 +37,7 @@ __reExport(index_exports, require("./variaveisComuns"), module.exports);
...require("./ecosistema"), ...require("./ecosistema"),
...require("./extensoes"), ...require("./extensoes"),
...require("./logger"), ...require("./logger"),
...require("./testes-de-variaveis"),
...require("./texto_busca"), ...require("./texto_busca"),
...require("./tipagemRotas"), ...require("./tipagemRotas"),
...require("./unidades_medida"), ...require("./unidades_medida"),

View file

@ -33,7 +33,7 @@ __export(logger_exports, {
postLogger: () => postLogger postLogger: () => postLogger
}); });
module.exports = __toCommonJS(logger_exports); module.exports = __toCommonJS(logger_exports);
var import_cross_fetch = __toESM(require("cross-fetch")); var import_cross_fetch = __toESM(require("cross-fetch"), 1);
var import_variaveisComuns = require("./variaveisComuns"); var import_variaveisComuns = require("./variaveisComuns");
const LOKI_BASE_URL = "https://log.idz.one"; const LOKI_BASE_URL = "https://log.idz.one";
const LOKI_ENDPOINT = "/loki/api/v1/push"; const LOKI_ENDPOINT = "/loki/api/v1/push";

View file

@ -0,0 +1,24 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var testes_de_variaveis_exports = {};
module.exports = __toCommonJS(testes_de_variaveis_exports);
__reExport(testes_de_variaveis_exports, require("./umaFuncao"), module.exports);
__reExport(testes_de_variaveis_exports, require("./umaVariavel"), module.exports);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
...require("./umaFuncao"),
...require("./umaVariavel")
});

View file

@ -16,12 +16,13 @@ var __copyProps = (to, from, except, desc) => {
return to; return to;
}; };
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var tsup_config_exports = {}; var umaFuncao_exports = {};
__export(tsup_config_exports, { __export(umaFuncao_exports, {
default: () => tsup_config_default umaFuncao: () => umaFuncao
});
module.exports = __toCommonJS(umaFuncao_exports);
const umaFuncao = () => "Ol\xE1 Mundo! (fun\xE7\xE3o)";
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
umaFuncao
}); });
module.exports = __toCommonJS(tsup_config_exports);
var import_tsup = require("tsup");
var import_tsup_config = require("./tsup.config.back");
var import_tsup_config2 = require("./tsup.config.front");
var tsup_config_default = (0, import_tsup.defineConfig)([import_tsup_config.tsup_config_back, import_tsup_config2.tsup_config_front]);

View file

@ -0,0 +1,28 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var umaVariavel_exports = {};
__export(umaVariavel_exports, {
umaVariavel: () => umaVariavel
});
module.exports = __toCommonJS(umaVariavel_exports);
const umaVariavel = "Ol\xE1 Mundo! (vari\xE1vel)";
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
umaVariavel
});

View file

@ -1,54 +0,0 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var tsup_config_back_exports = {};
__export(tsup_config_back_exports, {
default: () => tsup_config_back_default,
tsup_config_back: () => tsup_config_back
});
module.exports = __toCommonJS(tsup_config_back_exports);
var import_tsup = require("tsup");
const tsup_config_back = {
/** Não mecher aqui */
entry: ["src/**/*.ts", "src/**/*.tsx"],
// Adicionado .tsx para compatibilidade, se aplicável
format: "cjs",
// Gera módulos CommonJS, padrão para Node.js
target: "node20",
// Compila para o ambiente Node.js versão 20 (ou sua versão alvo)
outDir: "dist-back",
// Diretório de saída para os arquivos transpilados
clean: true,
// Limpa o diretório de saída antes de cada build
bundle: false,
// ESSENCIAL: Mantém a estrutura de arquivos e pastas original
splitting: false,
// Desnecessário quando bundle é false
dts: false,
// RECOMENDADO: Gera arquivos de declaração TypeScript (.d.ts)
// legacyOutput e outExtension foram removidos por não serem necessários
sourcemap: false,
minify: false,
// Geralmente não minificamos o código do backend em produção, mas você pode mudar
outExtension: () => ({ js: ".js" })
};
var tsup_config_back_default = (0, import_tsup.defineConfig)(tsup_config_back);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
tsup_config_back
});

View file

@ -1,53 +0,0 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var tsup_config_front_exports = {};
__export(tsup_config_front_exports, {
default: () => tsup_config_front_default,
tsup_config_front: () => tsup_config_front
});
module.exports = __toCommonJS(tsup_config_front_exports);
var import_tsup = require("tsup");
const tsup_config_front = {
entry: ["src/**/*.ts", "src/**/*.tsx"],
// Adicionado .tsx para compatibilidade, se aplicável
format: "esm",
// Gera módulos ES para import/export no navegador
target: "es2022",
// Ou 'esnext' para os recursos mais recentes
outDir: "dist-front",
// Diretório de saída para os arquivos transpilados
clean: true,
// Limpa o diretório de saída antes de cada build
bundle: false,
// ESSENCIAL: Mantém a estrutura de arquivos e pastas original
splitting: false,
// Desnecessário quando bundle é false
dts: false,
// Não gera arquivos de declaração TypeScript (.d.ts) para uso em front-end JS
// legacyOutput e outExtension foram removidos por não serem necessários
sourcemap: false,
minify: false,
// Recomendado para builds de produção
outExtension: () => ({ js: ".js" })
};
var tsup_config_front_default = (0, import_tsup.defineConfig)(tsup_config_front);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
tsup_config_front
});

View file

@ -1,5 +0,0 @@
const alfabeto = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
const aleatorio = (tamanho) => `eli-${Array.from({ length: tamanho || 8 }).map(() => alfabeto[(999 * Math.random() | 0) % alfabeto.length]).join("")}`;
export {
aleatorio
};

View file

@ -1,23 +0,0 @@
const _cache = {};
const cacheM = (chave, valor, validadeSeg) => {
const txChave = typeof chave == "string" ? chave : typeof chave == "number" ? String(chave) : encodeURIComponent(JSON.stringify(chave));
const validade = validadeSeg && (/* @__PURE__ */ new Date()).getTime() + validadeSeg * 1e3;
if (valor !== void 0) {
_cache[txChave] = {
valor,
validade
};
}
const busca = _cache[txChave];
if (busca?.validade && busca.validade < (/* @__PURE__ */ new Date()).getTime()) {
return void 0;
}
return busca?.valor;
};
const verCacheM = () => _cache;
const cacheMemoria = cacheM;
export {
cacheM,
cacheMemoria,
verCacheM
};

View file

@ -1,26 +0,0 @@
const uuid_null = "00000000-0000-0000-0000-000000000000";
var camposComuns = /* @__PURE__ */ ((camposComuns2) => {
camposComuns2["codigo"] = "codigo";
camposComuns2["excluido"] = "excluido";
camposComuns2["data_hora_criacao"] = "data_hora_criacao";
camposComuns2["data_hora_atualizacao"] = "data_hora_atualizacao";
camposComuns2["codigo_usuario_criacao"] = "codigo_usuario_criacao";
camposComuns2["codigo_usuario_atualizacao"] = "codigo_usuario_atualizacao";
camposComuns2["versao"] = "versao";
return camposComuns2;
})(camposComuns || {});
var tx = /* @__PURE__ */ ((tx2) => {
tx2["token"] = "token";
return tx2;
})(tx || {});
var tipoUsuarioResiduos = /* @__PURE__ */ ((tipoUsuarioResiduos2) => {
tipoUsuarioResiduos2["Usuario"] = "usuario";
tipoUsuarioResiduos2["Fornecedor"] = "fornecedor";
return tipoUsuarioResiduos2;
})(tipoUsuarioResiduos || {});
export {
camposComuns,
tipoUsuarioResiduos,
tx,
uuid_null
};

View file

@ -1,14 +0,0 @@
var operadores = /* @__PURE__ */ ((operadores2) => {
operadores2["="] = "=";
operadores2["!="] = "!=";
operadores2[">"] = ">";
operadores2[">="] = ">=";
operadores2["<"] = "<";
operadores2["<="] = "<=";
operadores2["like"] = "like";
operadores2["in"] = "in";
return operadores2;
})(operadores || {});
export {
operadores
};

View file

@ -1 +0,0 @@
export * from "./urls";

View file

@ -1,4 +0,0 @@
const cdn_carro_de_boi = "https://carro-de-boi-idz-one.b-cdn.net";
export {
cdn_carro_de_boi
};

View file

@ -1,161 +0,0 @@
const extensoes = [
{
ext: "gif",
tipo: "imagem",
mime: "image/gif"
},
{
ext: "jpg",
tipo: "imagem",
mime: "image/jpeg"
},
{
ext: "jpeg",
tipo: "imagem",
mime: "image/jpeg"
},
{
ext: "png",
tipo: "imagem",
mime: "image/png"
},
{
ext: "bmp",
tipo: "imagem",
mime: "image/bmp"
},
{
ext: "webp",
tipo: "imagem",
mime: "image/webp"
},
{
ext: "tiff",
tipo: "imagem",
mime: "image/tiff"
},
{
ext: "svg",
tipo: "imagem",
mime: "image/svg+xml"
},
{
ext: "ico",
tipo: "imagem",
mime: "image/x-icon"
},
{
ext: "pdf",
tipo: "documento",
mime: "application/pdf"
},
{
ext: "doc",
tipo: "documento",
mime: "application/msword"
},
{
ext: "docx",
tipo: "documento",
mime: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
},
{
ext: "xls",
tipo: "documento",
mime: "application/vnd.ms-excel"
},
{
ext: "xlsx",
tipo: "documento",
mime: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
},
{
ext: "ppt",
tipo: "documento",
mime: "application/vnd.ms-powerpoint"
},
{
ext: "pptx",
tipo: "documento",
mime: "application/vnd.openxmlformats-officedocument.presentationml.presentation"
},
{
ext: "txt",
tipo: "documento",
mime: "text/plain"
},
{
ext: "odt",
tipo: "documento",
mime: "application/vnd.oasis.opendocument.text"
},
{
ext: "ods",
tipo: "documento",
mime: "application/vnd.oasis.opendocument.spreadsheet"
},
{
ext: "rtf",
tipo: "documento",
mime: "application/rtf"
},
{
ext: "csv",
tipo: "documento",
mime: "text/csv"
},
{
ext: "mp4",
tipo: "v\xEDdeo",
mime: "video/mp4"
},
{
ext: "avi",
tipo: "v\xEDdeo",
mime: "video/x-msvideo"
},
{
ext: "mkv",
tipo: "v\xEDdeo",
mime: "video/x-matroska"
},
{
ext: "mov",
tipo: "v\xEDdeo",
mime: "video/quicktime"
},
{
ext: "wmv",
tipo: "v\xEDdeo",
mime: "video/x-ms-wmv"
},
{
ext: "flv",
tipo: "v\xEDdeo",
mime: "video/x-flv"
},
{
ext: "webm",
tipo: "v\xEDdeo",
mime: "video/webm"
},
{
ext: "3gp",
tipo: "v\xEDdeo",
mime: "video/3gpp"
},
{
ext: "mpeg",
tipo: "v\xEDdeo",
mime: "video/mpeg"
}
];
const tipoArquivo = (nomeArquivo) => {
const extArquivo = String(nomeArquivo || "").toLocaleLowerCase().split(".").pop();
const extensao = extensoes.find((extensao2) => extensao2.ext === extArquivo);
return extensao?.tipo || "outros";
};
export {
extensoes,
tipoArquivo
};

View file

@ -1,12 +0,0 @@
export * from "./aleatorio";
export * from "./cacheMemoria";
export * from "./constantes";
export * from "./consulta";
export * from "./ecosistema";
export * from "./extensoes";
export * from "./logger";
export * from "./texto_busca";
export * from "./tipagemRotas";
export * from "./unidades_medida";
export * from "./uuid";
export * from "./variaveisComuns";

484
dist-front/index.mjs Normal file
View file

@ -0,0 +1,484 @@
// src/aleatorio.ts
var alfabeto = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
var aleatorio = (tamanho) => `eli-${Array.from({ length: tamanho || 8 }).map(() => alfabeto[(999 * Math.random() | 0) % alfabeto.length]).join("")}`;
// src/cacheMemoria.ts
var _cache = {};
var cacheM = (chave, valor, validadeSeg) => {
const txChave = typeof chave == "string" ? chave : typeof chave == "number" ? String(chave) : encodeURIComponent(JSON.stringify(chave));
const validade = validadeSeg && (/* @__PURE__ */ new Date()).getTime() + validadeSeg * 1e3;
if (valor !== void 0) {
_cache[txChave] = {
valor,
validade
};
}
const busca = _cache[txChave];
if (busca?.validade && busca.validade < (/* @__PURE__ */ new Date()).getTime()) {
return void 0;
}
return busca?.valor;
};
var verCacheM = () => _cache;
var cacheMemoria = cacheM;
// src/constantes.ts
var uuid_null = "00000000-0000-0000-0000-000000000000";
var camposComuns = /* @__PURE__ */ ((camposComuns2) => {
camposComuns2["codigo"] = "codigo";
camposComuns2["excluido"] = "excluido";
camposComuns2["data_hora_criacao"] = "data_hora_criacao";
camposComuns2["data_hora_atualizacao"] = "data_hora_atualizacao";
camposComuns2["codigo_usuario_criacao"] = "codigo_usuario_criacao";
camposComuns2["codigo_usuario_atualizacao"] = "codigo_usuario_atualizacao";
camposComuns2["versao"] = "versao";
return camposComuns2;
})(camposComuns || {});
var tx = /* @__PURE__ */ ((tx2) => {
tx2["token"] = "token";
return tx2;
})(tx || {});
var tipoUsuarioResiduos = /* @__PURE__ */ ((tipoUsuarioResiduos2) => {
tipoUsuarioResiduos2["Usuario"] = "usuario";
tipoUsuarioResiduos2["Fornecedor"] = "fornecedor";
return tipoUsuarioResiduos2;
})(tipoUsuarioResiduos || {});
// src/consulta.ts
var operadores = /* @__PURE__ */ ((operadores2) => {
operadores2["="] = "=";
operadores2["!="] = "!=";
operadores2[">"] = ">";
operadores2[">="] = ">=";
operadores2["<"] = "<";
operadores2["<="] = "<=";
operadores2["like"] = "like";
operadores2["in"] = "in";
return operadores2;
})(operadores || {});
// src/ecosistema/urls.ts
var cdn_carro_de_boi = "https://carro-de-boi-idz-one.b-cdn.net";
// src/extensoes.ts
var extensoes = [
{
ext: "gif",
tipo: "imagem",
mime: "image/gif"
},
{
ext: "jpg",
tipo: "imagem",
mime: "image/jpeg"
},
{
ext: "jpeg",
tipo: "imagem",
mime: "image/jpeg"
},
{
ext: "png",
tipo: "imagem",
mime: "image/png"
},
{
ext: "bmp",
tipo: "imagem",
mime: "image/bmp"
},
{
ext: "webp",
tipo: "imagem",
mime: "image/webp"
},
{
ext: "tiff",
tipo: "imagem",
mime: "image/tiff"
},
{
ext: "svg",
tipo: "imagem",
mime: "image/svg+xml"
},
{
ext: "ico",
tipo: "imagem",
mime: "image/x-icon"
},
{
ext: "pdf",
tipo: "documento",
mime: "application/pdf"
},
{
ext: "doc",
tipo: "documento",
mime: "application/msword"
},
{
ext: "docx",
tipo: "documento",
mime: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
},
{
ext: "xls",
tipo: "documento",
mime: "application/vnd.ms-excel"
},
{
ext: "xlsx",
tipo: "documento",
mime: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
},
{
ext: "ppt",
tipo: "documento",
mime: "application/vnd.ms-powerpoint"
},
{
ext: "pptx",
tipo: "documento",
mime: "application/vnd.openxmlformats-officedocument.presentationml.presentation"
},
{
ext: "txt",
tipo: "documento",
mime: "text/plain"
},
{
ext: "odt",
tipo: "documento",
mime: "application/vnd.oasis.opendocument.text"
},
{
ext: "ods",
tipo: "documento",
mime: "application/vnd.oasis.opendocument.spreadsheet"
},
{
ext: "rtf",
tipo: "documento",
mime: "application/rtf"
},
{
ext: "csv",
tipo: "documento",
mime: "text/csv"
},
{
ext: "mp4",
tipo: "v\xEDdeo",
mime: "video/mp4"
},
{
ext: "avi",
tipo: "v\xEDdeo",
mime: "video/x-msvideo"
},
{
ext: "mkv",
tipo: "v\xEDdeo",
mime: "video/x-matroska"
},
{
ext: "mov",
tipo: "v\xEDdeo",
mime: "video/quicktime"
},
{
ext: "wmv",
tipo: "v\xEDdeo",
mime: "video/x-ms-wmv"
},
{
ext: "flv",
tipo: "v\xEDdeo",
mime: "video/x-flv"
},
{
ext: "webm",
tipo: "v\xEDdeo",
mime: "video/webm"
},
{
ext: "3gp",
tipo: "v\xEDdeo",
mime: "video/3gpp"
},
{
ext: "mpeg",
tipo: "v\xEDdeo",
mime: "video/mpeg"
}
];
var tipoArquivo = (nomeArquivo) => {
const extArquivo = String(nomeArquivo || "").toLocaleLowerCase().split(".").pop();
const extensao = extensoes.find((extensao2) => extensao2.ext === extArquivo);
return extensao?.tipo || "outros";
};
// src/logger.ts
import crossFetch from "cross-fetch";
// src/variaveisComuns.ts
var esperar = (ms) => new Promise(
(resolve) => setTimeout(() => resolve(true), ms)
);
var nomeVariavel = (v) => Object.keys(v).join("/");
// src/logger.ts
var LOKI_BASE_URL = "https://log.idz.one";
var LOKI_ENDPOINT = "/loki/api/v1/push";
var postLogger = async ({
objeto
}) => {
const response = await crossFetch(`${LOKI_BASE_URL}${LOKI_ENDPOINT}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(objeto)
}).catch((a) => a);
if (!response.ok) {
return [objeto, `Erro ${response.status}: ${await response?.text?.()}`];
}
return [objeto];
};
var cwd = "";
var defineCwd = (novoCwd) => {
cwd = novoCwd;
};
var logger = ({ app: app_e, eProducao, parametros: parametrosAmbiente }) => ({ inquilino, usuario, parametros: parametrosSessao }) => async (level, mensagem, op_tipoLog) => {
let {
__filename,
detalhes,
local,
parametros: parametrosLog
} = op_tipoLog || {};
const app = `${eProducao ? "" : "DEV-"}${app_e}`;
if (cwd && __filename) {
__filename = __filename.replace(cwd, "");
}
if (local) {
detalhes = [`${nomeVariavel({ local })}="${local}"`, ...detalhes || []];
}
if (__filename) {
detalhes = [
`${nomeVariavel({ __filename })}="${__filename}"`,
...detalhes || []
];
}
const timestamp = `${Date.now()}000000`;
const mainLog = detalhes?.length ? `${mensagem} | ${detalhes.map((d) => JSON.stringify(d)).join(" | ")}` : mensagem;
const payload = {
stream: {
app,
inquilino,
usuario,
level,
...parametrosAmbiente || {},
...parametrosSessao || {},
...parametrosLog || {}
},
values: [
[
timestamp,
mainLog
// Linha de log direta
]
]
};
const objeto = { streams: [payload] };
const response = await postLogger({ objeto });
return response;
};
// src/testes-de-variaveis/umaFuncao.ts
var umaFuncao = () => "Ol\xE1 Mundo! (fun\xE7\xE3o)";
// src/testes-de-variaveis/umaVariavel.ts
var umaVariavel = "Ol\xE1 Mundo! (vari\xE1vel)";
// src/texto_busca.ts
var texto_busca = (...texto) => texto.map(
(txt) => txt === null || txt === void 0 ? "" : String(txt).normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/\s+/g, " ").toLowerCase()
).join(" ");
// src/tipagemRotas.ts
var TipagemRotas = class {
/** Ao criar novo obijeto de tipagem de rota é necessário passar o caminho parcial
** export const mCaminho = new TipagemRotas<{q:string}>("aplicacao","funcionalidade")
*/
constructor({
caminho,
acaoIr
}) {
this._partesCaminho = [];
this._acaoIr = acaoIr;
this._partesCaminho = (Array.isArray(caminho) ? caminho : [caminho]).flatMap((a) => a.split("/")).filter(Boolean);
}
/** Retorna o caminho completo da rota
** console.log(mCaminho.caminho)
** "/caminho"
*/
get caminho() {
const ret = `/${this._partesCaminho.join("/")}`;
return ret;
}
/** Define o caminho completo da rota
** mCaminho.caminho = "/novoCaminho"
** console.log(mCaminho.caminho)
** "/novoCaminho"
** */
set caminho(caminhoParcial) {
this._partesCaminho = caminhoParcial.split("/").filter((parte) => parte);
}
/** Retorna o caminho completo da rota com a query
** console.log(mCaminho.resolve({q:"query"}))
** "http://localhost:3000/caminho?q=query"
*/
endereco(query, usarComoHash) {
const url = new URL(
typeof window !== "undefined" ? window.location.href : "http://localhost"
);
url.pathname = this.caminho;
url.search = "";
const queryKeys = Object.entries(query);
for (const [key, value] of queryKeys) {
url.searchParams.set(
String(key),
value === void 0 || value === null ? "" : value
);
}
url.hash = "";
if (usarComoHash) {
url.hash = `#${url.search}`;
url.search = "";
}
return url.href;
}
/** Vai para a url
** mCaminho.ir({q:"query"})
** window.location.href = "http://localhost:3000/caminho?q=query"
*/
ir(query) {
if (this._acaoIr) {
this._acaoIr(this.endereco(query));
} else {
if (typeof window != "undefined") {
window.location.href = this.endereco(query);
}
}
}
/** Retorna os parametros da url
** console.log(mCaminho.parametros())
** {q:"query"}
*/
get parametros() {
const url = new URL(
typeof window !== "undefined" ? window.location.href : "http://localhost"
);
const query = url.searchParams;
const queryObj = Object.fromEntries(query.entries());
const hash = url.hash;
if (hash) {
const hashObj = Object.fromEntries(
new URLSearchParams(hash.slice(1)).entries()
);
return { ...queryObj, ...hashObj };
}
return queryObj;
}
};
// src/unidades_medida.ts
var siglas_unidades_medida = /* @__PURE__ */ ((siglas_unidades_medida2) => {
siglas_unidades_medida2["UN"] = "UN";
siglas_unidades_medida2["KG"] = "KG";
siglas_unidades_medida2["TON"] = "TON";
siglas_unidades_medida2["g"] = "g";
siglas_unidades_medida2["M\xB3"] = "M\xB3";
siglas_unidades_medida2["Lt"] = "Lt";
return siglas_unidades_medida2;
})(siglas_unidades_medida || {});
var unidades_medida = [
{
sigla_unidade: "KG",
nome: "Quilograma",
sigla_normalizada: "KG",
normalizar: (valor) => valor,
tipo: "massa"
},
{
sigla_unidade: "g",
nome: "Grama",
sigla_normalizada: "KG",
normalizar: (valor) => valor / 1e3,
tipo: "massa"
},
{
sigla_unidade: "TON",
nome: "Tonelada",
sigla_normalizada: "KG",
normalizar: (valor) => valor * 1e3,
tipo: "massa"
},
{
sigla_unidade: "Lt",
nome: "Litro",
sigla_normalizada: "Lt",
normalizar: (valor) => valor,
tipo: "volume"
},
{
sigla_unidade: "M\xB3",
nome: "Metro C\xFAbico",
sigla_normalizada: "Lt",
normalizar: (valor) => valor * 1e3,
tipo: "volume"
},
{
sigla_unidade: "UN",
nome: "Unidade",
sigla_normalizada: "UN",
normalizar: (valor) => valor,
tipo: "unidade"
}
];
// src/uuid.ts
var letras = "0123456789abcdef".split("");
var uuid = () => {
letras.sort(() => Math.random() - 0.5);
const modelo = "xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx".split("");
const retorno = modelo.map(
(letra) => letra === "x" ? letras[(1e3 * Math.random() | 0) % letras.length] : letra
).join("");
return retorno;
};
export {
TipagemRotas,
aleatorio,
cacheM,
cacheMemoria,
camposComuns,
cdn_carro_de_boi,
defineCwd,
esperar,
extensoes,
logger,
nomeVariavel,
operadores,
postLogger,
siglas_unidades_medida,
texto_busca,
tipoArquivo,
tipoUsuarioResiduos,
tx,
umaFuncao,
umaVariavel,
unidades_medida,
uuid,
uuid_null,
verCacheM
};

View file

@ -1,70 +0,0 @@
import crossFetch from "cross-fetch";
import { nomeVariavel } from "./variaveisComuns";
const LOKI_BASE_URL = "https://log.idz.one";
const LOKI_ENDPOINT = "/loki/api/v1/push";
const postLogger = async ({
objeto
}) => {
const response = await crossFetch(`${LOKI_BASE_URL}${LOKI_ENDPOINT}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(objeto)
}).catch((a) => a);
if (!response.ok) {
return [objeto, `Erro ${response.status}: ${await response?.text?.()}`];
}
return [objeto];
};
let cwd = "";
const defineCwd = (novoCwd) => {
cwd = novoCwd;
};
const logger = ({ app: app_e, eProducao, parametros: parametrosAmbiente }) => ({ inquilino, usuario, parametros: parametrosSessao }) => async (level, mensagem, op_tipoLog) => {
let {
__filename,
detalhes,
local,
parametros: parametrosLog
} = op_tipoLog || {};
const app = `${eProducao ? "" : "DEV-"}${app_e}`;
if (cwd && __filename) {
__filename = __filename.replace(cwd, "");
}
if (local) {
detalhes = [`${nomeVariavel({ local })}="${local}"`, ...detalhes || []];
}
if (__filename) {
detalhes = [
`${nomeVariavel({ __filename })}="${__filename}"`,
...detalhes || []
];
}
const timestamp = `${Date.now()}000000`;
const mainLog = detalhes?.length ? `${mensagem} | ${detalhes.map((d) => JSON.stringify(d)).join(" | ")}` : mensagem;
const payload = {
stream: {
app,
inquilino,
usuario,
level,
...parametrosAmbiente || {},
...parametrosSessao || {},
...parametrosLog || {}
},
values: [
[
timestamp,
mainLog
// Linha de log direta
]
]
};
const objeto = { streams: [payload] };
const response = await postLogger({ objeto });
return response;
};
export {
defineCwd,
logger,
postLogger
};

View file

@ -1,5 +0,0 @@
import { cacheM } from "./cacheMemoria";
import { texto_busca } from "./texto_busca";
console.log("Vari\xE1veis funcionando", texto_busca);
cacheM(1, { Jaca: Promise.resolve() });
console.log("cache:", cacheM(1));

View file

@ -1,6 +0,0 @@
const texto_busca = (...texto) => texto.map(
(txt) => txt === null || txt === void 0 ? "" : String(txt).normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/\s+/g, " ").toLowerCase()
).join(" ");
export {
texto_busca
};

View file

@ -1,88 +0,0 @@
class TipagemRotas {
/** Ao criar novo obijeto de tipagem de rota é necessário passar o caminho parcial
** export const mCaminho = new TipagemRotas<{q:string}>("aplicacao","funcionalidade")
*/
constructor({
caminho,
acaoIr
}) {
this._partesCaminho = [];
this._acaoIr = acaoIr;
this._partesCaminho = (Array.isArray(caminho) ? caminho : [caminho]).flatMap((a) => a.split("/")).filter(Boolean);
}
/** Retorna o caminho completo da rota
** console.log(mCaminho.caminho)
** "/caminho"
*/
get caminho() {
const ret = `/${this._partesCaminho.join("/")}`;
return ret;
}
/** Define o caminho completo da rota
** mCaminho.caminho = "/novoCaminho"
** console.log(mCaminho.caminho)
** "/novoCaminho"
** */
set caminho(caminhoParcial) {
this._partesCaminho = caminhoParcial.split("/").filter((parte) => parte);
}
/** Retorna o caminho completo da rota com a query
** console.log(mCaminho.resolve({q:"query"}))
** "http://localhost:3000/caminho?q=query"
*/
endereco(query, usarComoHash) {
const url = new URL(
typeof window !== "undefined" ? window.location.href : "http://localhost"
);
url.pathname = this.caminho;
url.search = "";
const queryKeys = Object.entries(query);
for (const [key, value] of queryKeys) {
url.searchParams.set(
String(key),
value === void 0 || value === null ? "" : value
);
}
url.hash = "";
if (usarComoHash) {
url.hash = `#${url.search}`;
url.search = "";
}
return url.href;
}
/** Vai para a url
** mCaminho.ir({q:"query"})
** window.location.href = "http://localhost:3000/caminho?q=query"
*/
ir(query) {
if (this._acaoIr) {
this._acaoIr(this.endereco(query));
} else {
if (typeof window != "undefined") {
window.location.href = this.endereco(query);
}
}
}
/** Retorna os parametros da url
** console.log(mCaminho.parametros())
** {q:"query"}
*/
get parametros() {
const url = new URL(
typeof window !== "undefined" ? window.location.href : "http://localhost"
);
const query = url.searchParams;
const queryObj = Object.fromEntries(query.entries());
const hash = url.hash;
if (hash) {
const hashObj = Object.fromEntries(
new URLSearchParams(hash.slice(1)).entries()
);
return { ...queryObj, ...hashObj };
}
return queryObj;
}
}
export {
TipagemRotas
};

View file

@ -1,30 +0,0 @@
import { defineConfig } from "tsup";
const tsup_config_back = {
/** Não mecher aqui */
entry: ["src/**/*.ts", "src/**/*.tsx"],
// Adicionado .tsx para compatibilidade, se aplicável
format: "cjs",
// Gera módulos CommonJS, padrão para Node.js
target: "node20",
// Compila para o ambiente Node.js versão 20 (ou sua versão alvo)
outDir: "dist-back",
// Diretório de saída para os arquivos transpilados
clean: true,
// Limpa o diretório de saída antes de cada build
bundle: false,
// ESSENCIAL: Mantém a estrutura de arquivos e pastas original
splitting: false,
// Desnecessário quando bundle é false
dts: false,
// RECOMENDADO: Gera arquivos de declaração TypeScript (.d.ts)
// legacyOutput e outExtension foram removidos por não serem necessários
sourcemap: false,
minify: false,
// Geralmente não minificamos o código do backend em produção, mas você pode mudar
outExtension: () => ({ js: ".js" })
};
var tsup_config_back_default = defineConfig(tsup_config_back);
export {
tsup_config_back_default as default,
tsup_config_back
};

View file

@ -1,29 +0,0 @@
import { defineConfig } from "tsup";
const tsup_config_front = {
entry: ["src/**/*.ts", "src/**/*.tsx"],
// Adicionado .tsx para compatibilidade, se aplicável
format: "esm",
// Gera módulos ES para import/export no navegador
target: "es2022",
// Ou 'esnext' para os recursos mais recentes
outDir: "dist-front",
// Diretório de saída para os arquivos transpilados
clean: true,
// Limpa o diretório de saída antes de cada build
bundle: false,
// ESSENCIAL: Mantém a estrutura de arquivos e pastas original
splitting: false,
// Desnecessário quando bundle é false
dts: false,
// Não gera arquivos de declaração TypeScript (.d.ts) para uso em front-end JS
// legacyOutput e outExtension foram removidos por não serem necessários
sourcemap: false,
minify: false,
// Recomendado para builds de produção
outExtension: () => ({ js: ".js" })
};
var tsup_config_front_default = defineConfig(tsup_config_front);
export {
tsup_config_front_default as default,
tsup_config_front
};

View file

@ -1,7 +0,0 @@
import { defineConfig } from "tsup";
import { tsup_config_back } from "./tsup.config.back";
import { tsup_config_front } from "./tsup.config.front";
var tsup_config_default = defineConfig([tsup_config_back, tsup_config_front]);
export {
tsup_config_default as default
};

View file

@ -1,57 +0,0 @@
var siglas_unidades_medida = /* @__PURE__ */ ((siglas_unidades_medida2) => {
siglas_unidades_medida2["UN"] = "UN";
siglas_unidades_medida2["KG"] = "KG";
siglas_unidades_medida2["TON"] = "TON";
siglas_unidades_medida2["g"] = "g";
siglas_unidades_medida2["M\xB3"] = "M\xB3";
siglas_unidades_medida2["Lt"] = "Lt";
return siglas_unidades_medida2;
})(siglas_unidades_medida || {});
const unidades_medida = [
{
sigla_unidade: "KG",
nome: "Quilograma",
sigla_normalizada: "KG",
normalizar: (valor) => valor,
tipo: "massa"
},
{
sigla_unidade: "g",
nome: "Grama",
sigla_normalizada: "KG",
normalizar: (valor) => valor / 1e3,
tipo: "massa"
},
{
sigla_unidade: "TON",
nome: "Tonelada",
sigla_normalizada: "KG",
normalizar: (valor) => valor * 1e3,
tipo: "massa"
},
{
sigla_unidade: "Lt",
nome: "Litro",
sigla_normalizada: "Lt",
normalizar: (valor) => valor,
tipo: "volume"
},
{
sigla_unidade: "M\xB3",
nome: "Metro C\xFAbico",
sigla_normalizada: "Lt",
normalizar: (valor) => valor * 1e3,
tipo: "volume"
},
{
sigla_unidade: "UN",
nome: "Unidade",
sigla_normalizada: "UN",
normalizar: (valor) => valor,
tipo: "unidade"
}
];
export {
siglas_unidades_medida,
unidades_medida
};

View file

@ -1,12 +0,0 @@
const letras = "0123456789abcdef".split("");
const uuid = () => {
letras.sort(() => Math.random() - 0.5);
const modelo = "xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx".split("");
const retorno = modelo.map(
(letra) => letra === "x" ? letras[(1e3 * Math.random() | 0) % letras.length] : letra
).join("");
return retorno;
};
export {
uuid
};

View file

@ -1,8 +0,0 @@
const esperar = (ms) => new Promise(
(resolve) => setTimeout(() => resolve(true), ms)
);
const nomeVariavel = (v) => Object.keys(v).join("/");
export {
esperar,
nomeVariavel
};

View file

@ -1,19 +1,20 @@
{ {
"name": "p-comuns", "name": "p-comuns",
"version": "0.158.0", "version": "0.202.0",
"description": "", "description": "",
"main": "./src/index.ts", "main": "./dist-back/index.js",
"module": "./dist-front/index.mjs",
"types": "./src/index.ts",
"exports": { "exports": {
".": { ".": {
"types": "./src/index.ts", "types": "./src/index.ts",
"import": "./dist-front/index.js", "import": "./dist-front/index.mjs",
"require": "./dist-back/index.js" "require": "./dist-back/index.js"
} }
}, },
"types": "./src/index.ts",
"scripts": { "scripts": {
"biome": "npx @biomejs/biome check --write ./src", "biome": "npx @biomejs/biome check --write ./src",
"build": "npm --no-git-tag-version version minor && pnpm run biome && tsup --config ./src/tsup/tsup.config.ts" "build": "npm --no-git-tag-version version minor && pnpm run biome && tsup --config ./tsup/tsup.config.ts"
}, },
"author": { "author": {
"name": "AZTECA SOFTWARE LTDA", "name": "AZTECA SOFTWARE LTDA",

View file

@ -5,6 +5,7 @@ export * from "./consulta"
export * from "./ecosistema" export * from "./ecosistema"
export * from "./extensoes" export * from "./extensoes"
export * from "./logger" export * from "./logger"
export * from "./testes-de-variaveis"
export * from "./texto_busca" export * from "./texto_busca"
export * from "./tipagemRotas" export * from "./tipagemRotas"
export * from "./unidades_medida" export * from "./unidades_medida"

View file

@ -0,0 +1,2 @@
export * from "./umaFuncao"
export * from "./umaVariavel"

View file

@ -0,0 +1 @@
export const umaFuncao = () => "Olá Mundo! (função)"

View file

@ -0,0 +1 @@
export const umaVariavel = "Olá Mundo! (variável)"

View file

@ -1,14 +0,0 @@
"tsup --config tsup.config.ts"
tsup --config ./node_modules/p-comuns/src/tsup/tsup.config.ts
"main": "./src/index.ts",
"exports": {
".": {
"types": "./src/index.ts",
"import": "./dist-front/index.js",
"require": "./dist-back/index.js"
}
},
"types": "./src/index.ts",

3
testes/node/index.ts Normal file
View file

@ -0,0 +1,3 @@
import {umaFuncao, umaVariavel} from 'p-comuns'
console.log(umaVariavel)
console.log(umaFuncao())

15
testes/node/package.json Normal file
View file

@ -0,0 +1,15 @@
{
"name": "node",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"p-comuns": "link:../.."
}
}

13
testes/node/pnpm-lock.yaml generated Normal file
View file

@ -0,0 +1,13 @@
lockfileVersion: '9.0'
settings:
autoInstallPeers: true
excludeLinksFromLockfile: false
importers:
.:
dependencies:
p-comuns:
specifier: link:../..
version: link:../..

24
testes/react-app/.gitignore vendored Normal file
View file

@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

View file

@ -0,0 +1,69 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default tseslint.config([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
...tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
...tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
...tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default tseslint.config([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```

View file

@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { globalIgnores } from 'eslint/config'
export default tseslint.config([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs['recommended-latest'],
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])

View file

@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

View file

@ -0,0 +1,30 @@
{
"name": "react-app",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"p-comuns": "link:../..",
"react": "^19.1.0",
"react-dom": "^19.1.0"
},
"devDependencies": {
"@eslint/js": "^9.30.1",
"@types/react": "^19.1.8",
"@types/react-dom": "^19.1.6",
"@vitejs/plugin-react": "^4.6.0",
"eslint": "^9.30.1",
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.20",
"globals": "^16.3.0",
"typescript": "~5.8.3",
"typescript-eslint": "^8.35.1",
"vite": "^7.0.4"
}
}

2082
testes/react-app/pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,12 @@
import { umaFuncao, umaVariavel } from "p-comuns"
function App() {
return (
<>
{umaFuncao()}
{umaVariavel}
</>
)
}
export default App

View file

@ -0,0 +1,9 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)

1
testes/react-app/src/vite-env.d.ts vendored Normal file
View file

@ -0,0 +1 @@
/// <reference types="vite/client" />

View file

@ -0,0 +1,27 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2022",
"useDefineForClassFields": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src"]
}

View file

@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

View file

@ -0,0 +1,25 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}

View file

@ -0,0 +1,12 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import {umaFuncao,umaVariavel} from 'p-comuns'
console.log('Dentro do vitConfig', umaVariavel, umaFuncao())
export default defineConfig({
plugins: [react()],server:{ watch: {
ignored: ['**/node_modules/**'] // evita watchers pesados
}}
})

View file

@ -21,5 +21,5 @@
"strict": true, /* Habilita todas as opções de verificação estrita de tipos. */ "strict": true, /* Habilita todas as opções de verificação estrita de tipos. */
"skipLibCheck": true /* Ignora a verificação de tipos em arquivos de declaração de bibliotecas. */ "skipLibCheck": true /* Ignora a verificação de tipos em arquivos de declaração de bibliotecas. */
}, },
"include": ["src/**/*"] /* Inclui todos os arquivos TypeScript dentro da pasta src. */ "include": ["src/**/*", "tsup"] /* Inclui todos os arquivos TypeScript dentro da pasta src. */
} }

14
tsup/como usar.md Normal file
View file

@ -0,0 +1,14 @@
"tsup --config tsup.config.ts"
tsup --config ./node_modules/p-comuns/tsup/tsup.config.ts
"main": "./dist-back/index.js",
"module": "./dist-front/index.mjs",
"types": "./src/index.ts",
"exports": {
".": {
"types": "./src/index.ts",
"import": "./dist-front/index.mjs",
"require": "./dist-back/index.js"
}
},

View file

@ -16,6 +16,7 @@ export const tsup_config_back: Options = {
// legacyOutput e outExtension foram removidos por não serem necessários // legacyOutput e outExtension foram removidos por não serem necessários
sourcemap: false, sourcemap: false,
minify: false, // Geralmente não minificamos o código do backend em produção, mas você pode mudar minify: false, // Geralmente não minificamos o código do backend em produção, mas você pode mudar
platform: "node",
outExtension: () => ({ js: ".js" }), outExtension: () => ({ js: ".js" }),
} }

View file

@ -4,18 +4,19 @@ import { defineConfig, type Options } from "tsup"
// Definimos as opções em uma constante para clareza, como você fez. // Definimos as opções em uma constante para clareza, como você fez.
// Exportamos para que possam ser reutilizadas ou inspecionadas. // Exportamos para que possam ser reutilizadas ou inspecionadas.
export const tsup_config_front: Options = { export const tsup_config_front: Options = {
entry: ["src/**/*.ts", "src/**/*.tsx"], // Adicionado .tsx para compatibilidade, se aplicável entry: ["src/index.ts"], // Adicionado .tsx para compatibilidade, se aplicável
format: "esm", // Gera módulos ES para import/export no navegador format: "esm", // Gera módulos ES para import/export no navegador
target: "es2022", // Ou 'esnext' para os recursos mais recentes target: "es2022", // Ou 'esnext' para os recursos mais recentes
outDir: "dist-front", // Diretório de saída para os arquivos transpilados outDir: "dist-front", // Diretório de saída para os arquivos transpilados
clean: true, // Limpa o diretório de saída antes de cada build clean: true, // Limpa o diretório de saída antes de cada build
bundle: false, // ESSENCIAL: Mantém a estrutura de arquivos e pastas original bundle: true, // ESSENCIAL: Mantém a estrutura de arquivos e pastas original
splitting: false, // Desnecessário quando bundle é false splitting: false, // Desnecessário quando bundle é false
dts: false, // Não gera arquivos de declaração TypeScript (.d.ts) para uso em front-end JS dts: false, // Não gera arquivos de declaração TypeScript (.d.ts) para uso em front-end JS
// legacyOutput e outExtension foram removidos por não serem necessários // legacyOutput e outExtension foram removidos por não serem necessários
sourcemap: false, sourcemap: false,
minify: false, // Recomendado para builds de produção minify: false, // Recomendado para builds de produção
outExtension: () => ({ js: ".js" }), platform: "browser",
outExtension: () => ({ js: ".mjs" }),
} }
// Exporta a configuração padrão usando defineConfig // Exporta a configuração padrão usando defineConfig