diff --git a/.gitignore b/.gitignore old mode 100755 new mode 100644 diff --git a/.npmignore b/.npmignore old mode 100755 new mode 100644 diff --git a/.npmrc b/.npmrc old mode 100755 new mode 100644 diff --git a/.vscode/settings.json b/.vscode/settings.json old mode 100755 new mode 100644 diff --git a/Documentos/biome.json b/Documentos/biome.json old mode 100755 new mode 100644 diff --git a/README.md b/README.md old mode 100755 new mode 100644 index 566b352..14fc5b3 --- a/README.md +++ b/README.md @@ -88,94 +88,3 @@ adicionar em .vscode/settings.json "source.fixAll.biome": "always" } } - ---- - -## ✅ Sistema de Filtros (tipoFiltro26) - -O sistema `tipoFiltro26` foi projetado para gerar automaticamente a tipagem de filtros compatíveis com operadores padrão do PostgreSQL, a partir de um tipo base `T`. - -**Principais características:** -- Tipagem forte e segura (Typescript) -- Suporte a aninhamento de objetos -- Operadores lógicos `E` (AND) e `OU` (OR) -- Validação de operadores permitidos por tipo de dado (string, number, boolean) - -### Estrutura do Filtro - -O filtro segue uma estrutura onde chaves representam campos (simples ou aninhados) e valores representam condições com operadores específicos. - -#### 1. Campos Simples -```typescript -{ - idade: { ">=": 18 } -} -``` - -#### 2. Campos Aninhados -```typescript -{ - carro: { - ano: { "=": 2020 } - } -} -``` - -#### 3. Operadores Lógicos - -**Operador E (AND):** Todos devem ser verdadeiros. -```typescript -{ - E: [ - { idade: { ">=": 18 } }, - { nome: { like: "%pa%" } } - ] -} -``` - -**Operador OU (OR):** Pelo menos um deve ser verdadeiro. -```typescript -{ - OU: [ - { idade: { "<": 18 } }, - { idade: { ">=": 60 } } - ] -} -``` - -#### 4. Exemplo Complexo Complet -```typescript -{ - idade: { ">=": 18 }, - OU: [ - { nome: { like: "%pa%" } }, - { - E: [ - { carro: { ano: { "=": 2020 } } }, - { carro: { modelo: { in: ["Civic"] } } } - ] - } - ] -} -``` - -### Operadores Suportados (`operadores26`) - -Os operadores são fornecidos pelo enum `operadores26` e são restritos pelo tipo do campo: - -* **Number**: `=`, `!=`, `>`, `>=`, `<`, `<=`, `in` -* **String**: `=`, `!=`, `like`, `in` -* **Boolean**: `=`, `!=`, `in` - -> **Nota:** Atualmente não há suporte automático para `null`, `date`, `jsonb` ou `arrays` como tipos de campo raiz (exceto arrays dentro do operador `in`). - -### Validação em Tempo de Execução (Zod) - -O sistema inclui um validador Zod `zFiltro26` para validação estrutural dos objetos de filtro recebidos (ex: via API). - -```typescript -import { zFiltro26 } from './tipoFiltro.26'; - -// Valida a estrutura (não checa existência de colunas no DB) -zFiltro26.parse(objetoFiltro); -``` diff --git a/biome.json b/biome.json old mode 100755 new mode 100644 diff --git a/build.config.ts b/build.config.ts old mode 100755 new mode 100644 diff --git a/dist-back/dayjs.js b/dist-back/dayjs.js new file mode 100644 index 0000000..17bc264 --- /dev/null +++ b/dist-back/dayjs.js @@ -0,0 +1,72 @@ +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var dayjs_exports = {}; +__export(dayjs_exports, { + dayjsbr: () => import_dayjs.default, + duration: () => import_duration.default, + isSameOrAfter: () => import_isSameOrAfter.default, + isSameOrBefore: () => import_isSameOrBefore.default, + minMax: () => import_minMax.default, + relativeTime: () => import_relativeTime.default, + timezone: () => import_timezone.default, + utc: () => import_utc.default, + weekOfYear: () => import_weekOfYear.default +}); +module.exports = __toCommonJS(dayjs_exports); +var import_dayjs = __toESM(require("dayjs")); +var import_duration = __toESM(require("dayjs/plugin/duration")); +var import_isSameOrAfter = __toESM(require("dayjs/plugin/isSameOrAfter")); +var import_isSameOrBefore = __toESM(require("dayjs/plugin/isSameOrBefore")); +var import_minMax = __toESM(require("dayjs/plugin/minMax")); +var import_relativeTime = __toESM(require("dayjs/plugin/relativeTime")); +var import_timezone = __toESM(require("dayjs/plugin/timezone")); +var import_utc = __toESM(require("dayjs/plugin/utc")); +var import_weekOfYear = __toESM(require("dayjs/plugin/weekOfYear")); +var import_pt_br = require("dayjs/locale/pt-br"); +import_dayjs.default.locale("pt-br"); +import_dayjs.default.extend(import_utc.default); +import_dayjs.default.extend(import_timezone.default); +import_dayjs.default.extend(import_weekOfYear.default); +import_dayjs.default.extend(import_isSameOrBefore.default); +import_dayjs.default.extend(import_isSameOrAfter.default); +import_dayjs.default.extend(import_minMax.default); +import_dayjs.default.extend(import_relativeTime.default); +import_dayjs.default.extend(import_duration.default); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + dayjsbr, + duration, + isSameOrAfter, + isSameOrBefore, + minMax, + relativeTime, + timezone, + utc, + weekOfYear +}); diff --git a/dist-back/dayjs26.js b/dist-back/dayjs26.js deleted file mode 100644 index da03329..0000000 --- a/dist-back/dayjs26.js +++ /dev/null @@ -1,49 +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 dayjs26_exports = {}; -__export(dayjs26_exports, { - defineDayjsBr: () => defineDayjsBr -}); -module.exports = __toCommonJS(dayjs26_exports); -const defineDayjsBr = ({ - dayjs, - duration, - isSameOrAfter, - isSameOrBefore, - minMax, - relativeTime, - timezone, - utc, - weekOfYear -}) => { - dayjs.extend(utc); - dayjs.extend(timezone); - dayjs.extend(weekOfYear); - dayjs.extend(isSameOrBefore); - dayjs.extend(isSameOrAfter); - dayjs.extend(minMax); - dayjs.extend(relativeTime); - dayjs.extend(duration); - dayjs.locale("pt-br"); - return dayjs; -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - defineDayjsBr -}); diff --git a/dist-back/graficosPilao.js b/dist-back/graficosPilao.js deleted file mode 100644 index 12ac7cb..0000000 --- a/dist-back/graficosPilao.js +++ /dev/null @@ -1,37 +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 graficosPilao_exports = {}; -__export(graficosPilao_exports, { - graficos_pilao: () => graficos_pilao -}); -module.exports = __toCommonJS(graficosPilao_exports); -const graficos_pilao = { - Condicionantes: { - grafico: "condicionantes-criadas", - titulo: "Condicionantes Criadas" - }, - Licen\u00E7as: { - grafico: "licencas-criadas", - titulo: "Licen\xE7as Criadas" - } -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - graficos_pilao -}); diff --git a/dist-back/index.js b/dist-back/index.js index fa4757d..812a8f8 100644 --- a/dist-back/index.js +++ b/dist-back/index.js @@ -19,11 +19,13 @@ __reExport(index_exports, require("./aleatorio"), module.exports); __reExport(index_exports, require("./cacheMemoria"), module.exports); __reExport(index_exports, require("./constantes"), module.exports); __reExport(index_exports, require("./consulta"), module.exports); -__reExport(index_exports, require("./dayjs26"), module.exports); +__reExport(index_exports, require("./dayjs"), 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("./local"), module.exports); +__reExport(index_exports, require("./logger"), module.exports); +__reExport(index_exports, require("./logger"), module.exports); __reExport(index_exports, require("./postgres"), module.exports); __reExport(index_exports, require("./produtos"), module.exports); __reExport(index_exports, require("./situacoes"), module.exports); @@ -31,7 +33,6 @@ __reExport(index_exports, require("./testes-de-variaveis"), 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("./tipoFiltro.26"), module.exports); __reExport(index_exports, require("./unidades_medida"), module.exports); __reExport(index_exports, require("./uuid"), module.exports); __reExport(index_exports, require("./variaveisComuns"), module.exports); @@ -41,11 +42,13 @@ __reExport(index_exports, require("./variaveisComuns"), module.exports); ...require("./cacheMemoria"), ...require("./constantes"), ...require("./consulta"), - ...require("./dayjs26"), + ...require("./dayjs"), ...require("./ecosistema"), ...require("./extensoes"), ...require("./extensoes"), ...require("./local"), + ...require("./logger"), + ...require("./logger"), ...require("./postgres"), ...require("./produtos"), ...require("./situacoes"), @@ -53,7 +56,6 @@ __reExport(index_exports, require("./variaveisComuns"), module.exports); ...require("./texto_busca"), ...require("./tipagemRotas"), ...require("./tipagemRotas"), - ...require("./tipoFiltro.26"), ...require("./unidades_medida"), ...require("./uuid"), ...require("./variaveisComuns") diff --git a/dist-back/local/index.js b/dist-back/local/index.js index 475929f..4b0c95a 100644 --- a/dist-back/local/index.js +++ b/dist-back/local/index.js @@ -22,7 +22,7 @@ __export(local_exports, { }); module.exports = __toCommonJS(local_exports); const localValor = (chave_, valor) => { - const localStorage = "localStorage" in globalThis ? globalThis.localStorage : void 0; + const localStorage = globalThis.localStorage; if (typeof localStorage == "undefined") return null; const chave = typeof chave_ === "string" ? chave_ : encodeURIComponent(JSON.stringify(chave_)); try { diff --git a/dist-back/logger.js b/dist-back/logger.js new file mode 100644 index 0000000..8f5983c --- /dev/null +++ b/dist-back/logger.js @@ -0,0 +1,106 @@ +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var logger_exports = {}; +__export(logger_exports, { + defineCwd: () => defineCwd, + logger: () => logger, + postLogger: () => postLogger +}); +module.exports = __toCommonJS(logger_exports); +var import_cross_fetch = __toESM(require("cross-fetch")); +var import_variaveisComuns = require("./variaveisComuns"); +const LOKI_BASE_URL = "https://log.idz.one"; +const LOKI_ENDPOINT = "/loki/api/v1/push"; +const postLogger = async ({ + objeto +}) => { + const response = await (0, import_cross_fetch.default)(`${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 = [`${(0, import_variaveisComuns.nomeVariavel)({ local })}="${local}"`, ...detalhes || []]; + } + if (__filename) { + detalhes = [ + `${(0, import_variaveisComuns.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; +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + defineCwd, + logger, + postLogger +}); diff --git a/dist-back/tipagemRotas.js b/dist-back/tipagemRotas.js index ce1d130..05c4f5b 100644 --- a/dist-back/tipagemRotas.js +++ b/dist-back/tipagemRotas.js @@ -56,8 +56,9 @@ class TipagemRotas { ** "http://localhost:3000/caminho?q=query" */ endereco(query, usarComoHash) { - const win = typeof globalThis !== "undefined" && globalThis.window || void 0; - const url = new URL(win ? win.location.href : "http://localhost"); + const url = new URL( + typeof window !== "undefined" ? window.location.href : "http://localhost" + ); url.pathname = this.caminho; url.search = ""; const queryKeys = Object.entries(query); @@ -79,9 +80,8 @@ class TipagemRotas { if (this._acaoIr) { this._acaoIr(this.endereco({ ...query })); } else { - const win = typeof globalThis !== "undefined" && globalThis.window || void 0; - if (win) { - win.location.href = this.endereco({ ...query }); + if (typeof window != "undefined") { + window.location.href = this.endereco({ ...query }); } } } @@ -91,7 +91,7 @@ class TipagemRotas { */ parametros(urlEntrada) { const url = urlEntrada ? new URL(urlEntrada) : new URL( - typeof globalThis !== "undefined" && globalThis.window ? globalThis.window.location.href : "http://localhost" + typeof window !== "undefined" ? window.location.href : "http://localhost" ); const query = url.searchParams; let queryObj = Object.fromEntries(query.entries()); diff --git a/dist-back/tipoFiltro.26.js b/dist-back/tipoFiltro.26.js deleted file mode 100644 index fe14814..0000000 --- a/dist-back/tipoFiltro.26.js +++ /dev/null @@ -1,72 +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 tipoFiltro_26_exports = {}; -__export(tipoFiltro_26_exports, { - agrupadores26: () => agrupadores26, - criarFiltro26: () => criarFiltro26, - operadores26: () => operadores26, - zFiltro26: () => zFiltro26 -}); -module.exports = __toCommonJS(tipoFiltro_26_exports); -var import_zod = require("zod"); -var operadores26 = /* @__PURE__ */ ((operadores262) => { - operadores262["="] = "="; - operadores262["!="] = "!="; - operadores262[">"] = ">"; - operadores262[">="] = ">="; - operadores262["<"] = "<"; - operadores262["<="] = "<="; - operadores262["like"] = "like"; - operadores262["in"] = "in"; - return operadores262; -})(operadores26 || {}); -var agrupadores26 = /* @__PURE__ */ ((agrupadores262) => { - agrupadores262["E"] = "E"; - agrupadores262["OU"] = "OU"; - return agrupadores262; -})(agrupadores26 || {}); -const zOperadores = import_zod.z.nativeEnum(operadores26); -const zValor = import_zod.z.any(); -const zCondicao = import_zod.z.record(zOperadores, zValor); -const zFiltro26 = import_zod.z.lazy( - () => import_zod.z.object({ - E: import_zod.z.array(zFiltro26).optional(), - OU: import_zod.z.array(zFiltro26).optional() - }).catchall(import_zod.z.union([zCondicao, zFiltro26])) -); -const criarFiltro26 = (filtro) => filtro; -const _filtro = criarFiltro26({ - idade: { [">=" /* >= */]: 18 }, - ["OU" /* OU */]: [ - { nome: { ["like" /* like */]: "%pa%" } }, - { - ["E" /* E */]: [ - { carro: { ano: { ["=" /* = */]: 2020 } } }, - { carro: { modelo: { ["in" /* in */]: ["Civic", "Corolla"] } } } - ] - } - ] -}); -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - agrupadores26, - criarFiltro26, - operadores26, - zFiltro26 -}); diff --git a/dist-front/index.d.mts b/dist-front/index.d.mts index 7a0301d..ff386f1 100644 --- a/dist-front/index.d.mts +++ b/dist-front/index.d.mts @@ -1,14 +1,13 @@ -import z, { z as z$1 } from 'zod'; -import _dayjs from 'dayjs'; -export { Dayjs, ManipulateType } from 'dayjs'; -import _duration from 'dayjs/plugin/duration'; -import _isSameOrAfter from 'dayjs/plugin/isSameOrAfter'; -import _isSameOrBefore from 'dayjs/plugin/isSameOrBefore'; -import _minMax from 'dayjs/plugin/minMax'; -import _relativeTime from 'dayjs/plugin/relativeTime'; -import _timezone from 'dayjs/plugin/timezone'; -import _utc from 'dayjs/plugin/utc'; -import _weekOfYear from 'dayjs/plugin/weekOfYear'; +import z from 'zod'; +export { Dayjs, ManipulateType, default as dayjsbr } from 'dayjs'; +export { default as duration } from 'dayjs/plugin/duration'; +export { default as isSameOrAfter } from 'dayjs/plugin/isSameOrAfter'; +export { default as isSameOrBefore } from 'dayjs/plugin/isSameOrBefore'; +export { default as minMax } from 'dayjs/plugin/minMax'; +export { default as relativeTime } from 'dayjs/plugin/relativeTime'; +export { default as timezone } from 'dayjs/plugin/timezone'; +export { default as utc } from 'dayjs/plugin/utc'; +export { default as weekOfYear } from 'dayjs/plugin/weekOfYear'; import { v4 } from 'uuid'; declare const aleatorio: (tamanho?: number) => string; @@ -101,70 +100,6 @@ declare const zFiltro: z.ZodObject<{ ou: z.ZodOptional; }, z.core.$strip>; -/** - * Utilitário de configuração do Dayjs focado em compatibilidade com SSR. - * - * PROBLEMA: - * A importação direta do `dayjs` e seus plugins frequentemente causa conflitos em ambientes - * de Renderização do Lado do Servidor (SSR), como Nuxt ou Next.js, devido a discrepâncias - * na resolução de módulos (ESM vs CJS) e instabilidades de importação. - * - * SOLUÇÃO: - * Este módulo utiliza o padrão de Injeção de Dependência. Ele expõe apenas tipagens e - * uma função de configuração (`defineDayjsBr`). A responsabilidade de importar as - * bibliotecas "vivas" é delegada à aplicação consumidora (o cliente da função). - * - * Isso permite que o bundler da aplicação principal (Vite, Webpack, etc.) gerencie as - * instâncias, garantindo consistência e evitando erros de "module not found" ou - * instâncias duplicadas/não inicializadas adequadamente. - */ - -/** - * Inicializa e configura o Dayjs com o locale 'pt-br' e plugins essenciais. - * - * MODO DE USO: - * Importe os pacotes reais na sua aplicação e passe-os para esta função. - * - * @example - * ```ts - * // Em seu arquivo de configuração (ex: plugins/dayjs.ts): - * import dayjs from "dayjs" - * import duration from "dayjs/plugin/duration" - * import isSameOrAfter from "dayjs/plugin/isSameOrAfter" - * import isSameOrBefore from "dayjs/plugin/isSameOrBefore" - * import minMax from "dayjs/plugin/minMax" - * import relativeTime from "dayjs/plugin/relativeTime" - * import timezone from "dayjs/plugin/timezone" - * import utc from "dayjs/plugin/utc" - * import weekOfYear from "dayjs/plugin/weekOfYear" - * import { defineDayjsBr } from "p-comuns" - * import "dayjs/locale/pt-br" // Importante: importar o locale! - - * export const dayjsbr = defineDayjsBr({ - * dayjs, - * duration, - * isSameOrAfter, - * isSameOrBefore, - * minMax, - * relativeTime, - * timezone, - * utc, - * weekOfYear, - * }) - * ``` - */ -declare const defineDayjsBr: ({ dayjs, duration, isSameOrAfter, isSameOrBefore, minMax, relativeTime, timezone, utc, weekOfYear, }: { - dayjs: typeof _dayjs; - duration: typeof _duration; - isSameOrAfter: typeof _isSameOrAfter; - isSameOrBefore: typeof _isSameOrBefore; - minMax: typeof _minMax; - relativeTime: typeof _relativeTime; - timezone: typeof _timezone; - utc: typeof _utc; - weekOfYear: typeof _weekOfYear; -}) => typeof _dayjs; - declare const link_paiol = "https://paiol.idz.one"; type tiposArquivo = "imagem" | "documento" | "vídeo" | "outros"; @@ -186,6 +121,46 @@ declare const tipoArquivo: (nomeArquivo: string | null | undefined) => tiposArqu */ declare const localValor: (chave_: string | any, valor?: T | null) => T | null; +type tipoLokiObjeto = { + streams: { + stream: { + [k: string]: string; + }; + values: [string, string][]; + }[]; +}; +declare const postLogger: ({ objeto, }: { + objeto: tipoLokiObjeto; +}) => Promise<[objeto: tipoLokiObjeto, erro?: string]>; +/** define a localização da pasta do projeto */ +declare const defineCwd: (novoCwd: string) => void; +type tipoLevel = "info" | "warn" | "error"; +type tipoOpSessao = { + inquilino: string; + usuario: string; + parametros?: { + [k: string]: string; + }; +}; +type tipoLog = { + detalhes?: unknown[]; + __filename?: string; + local?: string; + parametros?: { + [k: string]: string; + }; +}; +type tipoLoggerLog = (level: tipoLevel, mensagem: string, op_tipoLog?: tipoLog) => Promise<[objeto: tipoLokiObjeto, erro?: string]>; +type TipoLoggerSessao = (sess: tipoOpSessao) => tipoLoggerLog; +type tipoLogger = (amb: { + app: string; + eProducao: boolean; + parametros?: { + [k: string]: string; + }; +}) => TipoLoggerSessao; +declare const logger: tipoLogger; + /** * Trata um objeto para ser imput para postgres * @param entrada @@ -324,151 +299,6 @@ declare class TipagemRotas; } -/** - * ============================================================================= - * tipoFiltro26 - * ============================================================================= - * - * OBJETIVO - * ----------------------------------------------------------------------------- - * Gerar automaticamente a tipagem de filtros compatíveis com operadores - * padrão do PostgreSQL, a partir de um tipo base T. - * - * Este tipo foi projetado para: - * - Construção de filtros dinâmicos - * - Geração posterior de WHERE (Knex / SQL) - * - Uso seguro por IA (evita filtros inválidos em nível de tipo) - * - * - * FORMATO DO FILTRO - * ----------------------------------------------------------------------------- - * 1) Campos simples: - * - * { - * idade: { ">=": 18 } - * } - * - * 2) Campos aninhados: - * - * { - * carro: { - * ano: { "=": 2020 } - * } - * } - * - * 3) Operador E (AND): - * - * { - * E: [ - * { idade: { ">=": 18 } }, - * { nome: { like: "%pa%" } } - * ] - * } - * - * 4) Operador OU (OR): - * - * { - * OU: [ - * { idade: { "<": 18 } }, - * { idade: { ">=": 60 } } - * ] - * } - * - * 5) Combinação complexa: - * - * { - * idade: { ">=": 18 }, - * OU: [ - * { nome: { like: "%pa%" } }, - * { - * E: [ - * { carro: { ano: { "=": 2020 } } }, - * { carro: { modelo: { in: ["Civic"] } } } - * ] - * } - * ] - * } - * - * - * REGRAS IMPORTANTES (PARA IA) - * ----------------------------------------------------------------------------- - * - Apenas campos existentes em T podem ser usados. - * - Operadores são restritos por tipo do campo. - * - Objetos são tratados recursivamente. - * - Arrays NÃO são tratados como objeto recursivo. - * - Funções NÃO são consideradas campos filtráveis. - * - * - * OPERADORES SUPORTADOS - * ----------------------------------------------------------------------------- - * number: - * =, !=, >, >=, <, <=, in - * - * string: - * =, !=, like, in - * - * boolean: - * =, !=, in - * - * Não há suporte automático a: - * - null - * - date - * - jsonb - * - arrays - * - * Essas extensões devem ser adicionadas explicitamente. - * - * ============================================================================= - */ -declare enum operadores26 { - "=" = "=", - "!=" = "!=", - ">" = ">", - ">=" = ">=", - "<" = "<", - "<=" = "<=", - like = "like", - in = "in" -} -declare enum agrupadores26 { - E = "E", - OU = "OU" -} -type PgOpsNumber = { - [K in Extract" | ">=" | "<" | "<=">]?: number; -} & { - [K in Extract]?: number[]; -}; -type PgOpsString = { - [K in Extract]?: string; -} & { - [K in Extract]?: string[]; -}; -type PgOpsBoolean = { - [K in Extract]?: boolean[]; -}; -type PgOpsFor = V extends number ? PgOpsNumber : V extends string ? PgOpsString : V extends boolean ? PgOpsBoolean : never; -type IsPlainObject = T extends object ? T extends Function ? false : T extends readonly any[] ? false : true : false; -type FiltroCampos = { - [K in keyof T]?: IsPlainObject extends true ? tipoFiltro26 : PgOpsFor; -}; -type tipoFiltro26 = FiltroCampos & { - /** - * E => AND lógico - * Todos os filtros dentro do array devem ser verdadeiros. - */ - E?: tipoFiltro26[]; - /** - * OU => OR lógico - * Pelo menos um filtro dentro do array deve ser verdadeiro. - */ - OU?: tipoFiltro26[]; -}; -declare const zFiltro26: z$1.ZodType; -declare const criarFiltro26: (filtro: tipoFiltro26) => tipoFiltro26; - /** * Essa variável se conecta a tabela_lidades * @@ -537,4 +367,4 @@ declare const nomeVariavel: (v: { [key: string]: any; }) => string; -export { Produtos, TipagemRotas, agrupadores26, aleatorio, cacheM, cacheMFixo, cacheMemoria, camposComuns, criarFiltro26, defineDayjsBr, erUuid, esperar, extensoes, type interfaceConsulta, link_paiol, localValor, nomeVariavel, objetoPg, operadores, operadores26, paraObjetoRegistroPg, pgObjeto, siglas_unidades_medida, texto_busca, tipoArquivo, type tipoFiltro, type tipoFiltro26, tipoUsuarioResiduos, tiposSituacoesElicencie, tx, umaFuncao, umaVariavel, unidades_medida, uuid, uuidV3, uuidV4, uuid_null, validarUuid, verCacheM, zFiltro, zFiltro26, zOperadores }; +export { Produtos, TipagemRotas, type TipoLoggerSessao, aleatorio, cacheM, cacheMFixo, cacheMemoria, camposComuns, defineCwd, erUuid, esperar, extensoes, type interfaceConsulta, link_paiol, localValor, logger, nomeVariavel, objetoPg, operadores, paraObjetoRegistroPg, pgObjeto, postLogger, siglas_unidades_medida, texto_busca, tipoArquivo, type tipoFiltro, type tipoLogger, type tipoLoggerLog, type tipoLokiObjeto, tipoUsuarioResiduos, tiposSituacoesElicencie, tx, umaFuncao, umaVariavel, unidades_medida, uuid, uuidV3, uuidV4, uuid_null, validarUuid, verCacheM, zFiltro, zOperadores }; diff --git a/dist-front/index.mjs b/dist-front/index.mjs index 3dd0ffe..8ff6881 100644 --- a/dist-front/index.mjs +++ b/dist-front/index.mjs @@ -1 +1 @@ -var u="ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),V=e=>`eli-${Array.from({length:e||8}).map(()=>u[(999*Math.random()|0)%u.length]).join("")}`;var s={};globalThis.cacheMemoria_cache=s;var g=(e,r,a)=>{let n=typeof e=="string"?e:typeof e=="number"?String(e):encodeURIComponent(JSON.stringify(e)),t=a&&new Date().getTime()+a*1e3;r!==void 0&&(s[n]={valor:r,validade:t});let i=s[n];if(!(i?.validade&&i.validades,G=g,$=e=>r=>g(e,r);var R="00000000-0000-0000-0000-000000000000",v=(m=>(m.codigo="codigo",m.excluido="excluido",m.data_hora_criacao="data_hora_criacao",m.data_hora_atualizacao="data_hora_atualizacao",m.codigo_usuario_criacao="codigo_usuario_criacao",m.codigo_usuario_atualizacao="codigo_usuario_atualizacao",m.versao="versao",m))(v||{}),b=(r=>(r.token="token",r))(b||{}),h=(a=>(a.Usuario="usuario",a.Fornecedor="fornecedor",a))(h||{});import l from"zod";var O=(n=>(n["="]="=",n["!="]="!=",n[">"]=">",n[">="]=">=",n["<"]="<",n["<="]="<=",n.like="like",n.in="in",n.isNull="isNull",n))(O||{}),T=l.enum(["=","!=",">",">=","<","<=","like","in","isNull"]),Z=l.object({coluna:l.string(),valor:l.any(),operador:T,ou:l.boolean().optional()});var W=({dayjs:e,duration:r,isSameOrAfter:a,isSameOrBefore:n,minMax:t,relativeTime:i,timezone:d,utc:m,weekOfYear:y})=>(e.extend(m),e.extend(d),e.extend(y),e.extend(n),e.extend(a),e.extend(t),e.extend(i),e.extend(r),e.locale("pt-br"),e);var S="https://paiol.idz.one";var z=[{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"}],ae=e=>{let r=String(e||"").toLocaleLowerCase().split(".").pop();return z.find(n=>n.ext===r)?.tipo||"outros"};var te=(e,r)=>{let a="localStorage"in globalThis?globalThis.localStorage:void 0;if(typeof a>"u")return null;let n=typeof e=="string"?e:encodeURIComponent(JSON.stringify(e));try{r!==void 0&&a.setItem(n,JSON.stringify(r));let t=a.getItem(n);if(t===null)return null;try{return JSON.parse(t)}catch{return t}}catch{return null}};var x=e=>{try{return Object.fromEntries(Object.entries(e).map(([r,a])=>[r,a===void 0||a==null||typeof a=="string"||typeof a=="number"||typeof a=="boolean"?a:JSON.stringify(a,null,2)]))}catch(r){throw new Error(`Erro na fun\xE7\xE3o paraObjetoRegistroPg: ${r.message} ${r.stack}`)}},ie=x,me=x;var w=(e=>(e["e-licencie"]="e-licencie",e["gov.e-licencie"]="gov.e-licencie",e))(w||{});var j=(o=>(o.modelo="000_modelo",o.vencida="100_vencida",o.expirado="200_expirado",o.alerta="300_alerta",o.protocoladafora="350_protocoladafora",o.protocolada="400_protocolada",o.protocoladaApenas="430_protocolada",o.protocolada_alteracao="450_protocolada",o.prazo="500_prazo",o.emitida="515_emitida",o.valida="518_valida",o.novo="520_novo",o.recebido="521_recebido",o.em_andamento="530_em_andamento",o.aguardando="530_aguardando",o.aguardandoresposta="540_aguardandoresposta",o.suspensaotemporaria="540_suspensaotemporaria",o.cancelada="550_cancelada",o.execucao="560_execucao",o.pendente="570_pendente",o.executadafora="600_executadafora",o.executada="700_executada",o.naoexecutada="701_naoexecutada",o.concluida="730_concluida",o.respondido_negado="740_respondido_negado",o.respondido_aceito="741_respondido_aceito",o.atendidoparcial="742_atendidoparcial",o.naoatendido="743_naoatendido",o.atendido="744_atendido",o.renovada="760_renovada",o.finalizada="800_finalizada",o.emitirnota="101_emitirnota",o.faturaatrasada="301_faturaatrasada",o.pagarfatura="302_pagarfatura",o.aguardandoconfirmacao="531_aguardandoconfirmacao",o.agendado="701_agendado",o.faturapaga="801_faturapaga",o.excluida="999_excluida",o.requerida="401_requerida",o.vigente="516_vigente",o.emrenovacao="402_emrenovacao",o.arquivada="801_arquivada",o.aguardando_sincronizacao="999_aguardando_sincronizacao",o.nao_conforme="710_nao_conforme",o.conforme="720_conforme",o.nao_aplicavel="730_nao_aplicavel",o.parcial="715_parcial",o))(j||{});var se=()=>"Ol\xE1 Mundo! (fun\xE7\xE3o)";var ue="Ol\xE1 Mundo! (vari\xE1vel)";var ye=(...e)=>e.map(r=>r==null?"":String(r).normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/\s+/g," ").toLowerCase()).join(" ");var c=class{constructor({caminho:r,acaoIr:a,rotulo:n}){this._partesCaminho=[];this._acaoIr=a,this._partesCaminho=(Array.isArray(r)?r:[r]).filter(Boolean).map(t=>String(t)).flatMap(t=>t.split("/")).filter(Boolean),this.rotulo=n}get caminho(){return`/${this._partesCaminho.join("/")}`}set caminho(r){this._partesCaminho=r.split("/").filter(a=>a)}endereco(r,a){let n=typeof globalThis<"u"&&globalThis.window||void 0,t=new URL(n?n.location.href:"http://localhost");t.pathname=this.caminho,t.search="";let i=Object.entries(r);for(let[d,m]of i)t.searchParams.set(String(d),JSON.stringify(m));return t.hash="",a&&(t.hash=`#${t.search}`,t.search=""),t.href}ir(r){if(this._acaoIr)this._acaoIr(this.endereco({...r}));else{let a=typeof globalThis<"u"&&globalThis.window||void 0;a&&(a.location.href=this.endereco({...r}))}}parametros(r){let a=r?new URL(r):new URL(typeof globalThis<"u"&&globalThis.window?globalThis.window.location.href:"http://localhost"),n=a.searchParams,t=Object.fromEntries(n.entries()),i=a.hash;if(i){let d=Object.fromEntries(new URLSearchParams(i.slice(1)).entries());t={...t,...d}}for(let d in t)try{t[d]=JSON.parse(t[d])}catch{console.log(`[${d}|${t[d]}] n\xE3o \xE9 um json v\xE1lido.`)}return t}};import{z as p}from"zod";var _=(a=>(a["="]="=",a["!="]="!=",a[">"]=">",a[">="]=">=",a["<"]="<",a["<="]="<=",a.like="like",a.in="in",a))(_||{}),k=(a=>(a.E="E",a.OU="OU",a))(k||{}),N=p.nativeEnum(_),F=p.any(),P=p.record(N,F),f=p.lazy(()=>p.object({E:p.array(f).optional(),OU:p.array(f).optional()}).catchall(p.union([P,f]))),M=e=>e,Oe=M({idade:{">=":18},OU:[{nome:{like:"%pa%"}},{E:[{carro:{ano:{"=":2020}}},{carro:{modelo:{in:["Civic","Corolla"]}}}]}]});var K=(i=>(i.UN="UN",i.KG="KG",i.TON="TON",i.g="g",i["M\xB3"]="M\xB3",i.Lt="Lt",i))(K||{}),ze=[{sigla_unidade:"KG",nome:"Quilograma",sigla_normalizada:"KG",normalizar:e=>e,tipo:"massa"},{sigla_unidade:"g",nome:"Grama",sigla_normalizada:"KG",normalizar:e=>e/1e3,tipo:"massa"},{sigla_unidade:"TON",nome:"Tonelada",sigla_normalizada:"KG",normalizar:e=>e*1e3,tipo:"massa"},{sigla_unidade:"Lt",nome:"Litro",sigla_normalizada:"Lt",normalizar:e=>e,tipo:"volume"},{sigla_unidade:"M\xB3",nome:"Metro C\xFAbico",sigla_normalizada:"Lt",normalizar:e=>e*1e3,tipo:"volume"},{sigla_unidade:"UN",nome:"Unidade",sigla_normalizada:"UN",normalizar:e=>e,tipo:"unidade"}];import{NIL as U,v3 as L,v4 as A}from"uuid";var q=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ke=e=>q.test(String(e||"")),C=(e,r)=>L(typeof e=="string"?e:typeof e=="number"?String(e):JSON.stringify(e),r?C(r):U),I=A,Ne=I;var Pe=e=>new Promise(r=>setTimeout(()=>r(!0),e)),Me=e=>Object.keys(e).join("/");export{w as Produtos,c as TipagemRotas,k as agrupadores26,V as aleatorio,g as cacheM,$ as cacheMFixo,G as cacheMemoria,v as camposComuns,M as criarFiltro26,W as defineDayjsBr,q as erUuid,Pe as esperar,z as extensoes,S as link_paiol,te as localValor,Me as nomeVariavel,me as objetoPg,O as operadores,_ as operadores26,x as paraObjetoRegistroPg,ie as pgObjeto,K as siglas_unidades_medida,ye as texto_busca,ae as tipoArquivo,h as tipoUsuarioResiduos,j as tiposSituacoesElicencie,b as tx,se as umaFuncao,ue as umaVariavel,ze as unidades_medida,Ne as uuid,C as uuidV3,I as uuidV4,R as uuid_null,ke as validarUuid,J as verCacheM,Z as zFiltro,f as zFiltro26,T as zOperadores}; +var _="ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),to=o=>`eli-${Array.from({length:o||8}).map(()=>_[(999*Math.random()|0)%_.length]).join("")}`;var f={};globalThis.cacheMemoria_cache=f;var v=(o,e,t)=>{let a=typeof o=="string"?o:typeof o=="number"?String(o):encodeURIComponent(JSON.stringify(o)),n=t&&new Date().getTime()+t*1e3;e!==void 0&&(f[a]={valor:e,validade:n});let i=f[a];if(!(i?.validade&&i.validadef,io=v,mo=o=>e=>v(o,e);var so="00000000-0000-0000-0000-000000000000",z=(p=>(p.codigo="codigo",p.excluido="excluido",p.data_hora_criacao="data_hora_criacao",p.data_hora_atualizacao="data_hora_atualizacao",p.codigo_usuario_criacao="codigo_usuario_criacao",p.codigo_usuario_atualizacao="codigo_usuario_atualizacao",p.versao="versao",p))(z||{}),N=(e=>(e.token="token",e))(N||{}),$=(t=>(t.Usuario="usuario",t.Fornecedor="fornecedor",t))($||{});import g from"zod";var M=(a=>(a["="]="=",a["!="]="!=",a[">"]=">",a[">="]=">=",a["<"]="<",a["<="]="<=",a.like="like",a.in="in",a.isNull="isNull",a))(M||{}),q=g.enum(["=","!=",">",">=","<","<=","like","in","isNull"]),fo=g.object({coluna:g.string(),valor:g.any(),operador:q,ou:g.boolean().optional()});import d from"dayjs";import I from"dayjs/plugin/duration";import U from"dayjs/plugin/isSameOrAfter";import P from"dayjs/plugin/isSameOrBefore";import A from"dayjs/plugin/minMax";import J from"dayjs/plugin/relativeTime";import C from"dayjs/plugin/timezone";import K from"dayjs/plugin/utc";import D from"dayjs/plugin/weekOfYear";import"dayjs/locale/pt-br";d.locale("pt-br");d.extend(K);d.extend(C);d.extend(D);d.extend(P);d.extend(U);d.extend(A);d.extend(J);d.extend(I);var ko="https://paiol.idz.one";var F=[{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"}],$o=o=>{let e=String(o||"").toLocaleLowerCase().split(".").pop();return F.find(a=>a.ext===e)?.tipo||"outros"};var qo=(o,e)=>{let t=globalThis.localStorage;if(typeof t>"u")return null;let a=typeof o=="string"?o:encodeURIComponent(JSON.stringify(o));try{e!==void 0&&t.setItem(a,JSON.stringify(e));let n=t.getItem(a);if(n===null)return null;try{return JSON.parse(n)}catch{return n}}catch{return null}};import G from"cross-fetch";var Uo=o=>new Promise(e=>setTimeout(()=>e(!0),o)),x=o=>Object.keys(o).join("/");var V="https://log.idz.one",R="/loki/api/v1/push",B=async({objeto:o})=>{let e=await G(`${V}${R}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}).catch(t=>t);return e.ok?[o]:[o,`Erro ${e.status}: ${await e?.text?.()}`]},c="",Co=o=>{c=o},Ko=({app:o,eProducao:e,parametros:t})=>({inquilino:a,usuario:n,parametros:i})=>async(m,p,b)=>{let{__filename:s,detalhes:l,local:u,parametros:O}=b||{},w=`${e?"":"DEV-"}${o}`;c&&s&&(s=s.replace(c,"")),u&&(l=[`${x({local:u})}="${u}"`,...l||[]]),s&&(l=[`${x({__filename:s})}="${s}"`,...l||[]]);let L=`${Date.now()}000000`,j=l?.length?`${p} | ${l.map(T=>JSON.stringify(T)).join(" | ")}`:p,k={streams:[{stream:{app:w,inquilino:a,usuario:n,level:m,...t||{},...i||{},...O||{}},values:[[L,j]]}]};return await B({objeto:k})};var y=o=>{try{return Object.fromEntries(Object.entries(o).map(([e,t])=>[e,t===void 0||t==null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"?t:JSON.stringify(t,null,2)]))}catch(e){throw new Error(`Erro na fun\xE7\xE3o paraObjetoRegistroPg: ${e.message} ${e.stack}`)}},Fo=y,Go=y;var Q=(o=>(o["e-licencie"]="e-licencie",o["gov.e-licencie"]="gov.e-licencie",o))(Q||{});var Y=(r=>(r.modelo="000_modelo",r.vencida="100_vencida",r.expirado="200_expirado",r.alerta="300_alerta",r.protocoladafora="350_protocoladafora",r.protocolada="400_protocolada",r.protocoladaApenas="430_protocolada",r.protocolada_alteracao="450_protocolada",r.prazo="500_prazo",r.emitida="515_emitida",r.valida="518_valida",r.novo="520_novo",r.recebido="521_recebido",r.em_andamento="530_em_andamento",r.aguardando="530_aguardando",r.aguardandoresposta="540_aguardandoresposta",r.suspensaotemporaria="540_suspensaotemporaria",r.cancelada="550_cancelada",r.execucao="560_execucao",r.pendente="570_pendente",r.executadafora="600_executadafora",r.executada="700_executada",r.naoexecutada="701_naoexecutada",r.concluida="730_concluida",r.respondido_negado="740_respondido_negado",r.respondido_aceito="741_respondido_aceito",r.atendidoparcial="742_atendidoparcial",r.naoatendido="743_naoatendido",r.atendido="744_atendido",r.renovada="760_renovada",r.finalizada="800_finalizada",r.emitirnota="101_emitirnota",r.faturaatrasada="301_faturaatrasada",r.pagarfatura="302_pagarfatura",r.aguardandoconfirmacao="531_aguardandoconfirmacao",r.agendado="701_agendado",r.faturapaga="801_faturapaga",r.excluida="999_excluida",r.requerida="401_requerida",r.vigente="516_vigente",r.emrenovacao="402_emrenovacao",r.arquivada="801_arquivada",r.aguardando_sincronizacao="999_aguardando_sincronizacao",r.nao_conforme="710_nao_conforme",r.conforme="720_conforme",r.nao_aplicavel="730_nao_aplicavel",r.parcial="715_parcial",r))(Y||{});var Qo=()=>"Ol\xE1 Mundo! (fun\xE7\xE3o)";var Ho="Ol\xE1 Mundo! (vari\xE1vel)";var Eo=(...o)=>o.map(e=>e==null?"":String(e).normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/\s+/g," ").toLowerCase()).join(" ");var h=class{constructor({caminho:e,acaoIr:t,rotulo:a}){this._partesCaminho=[];this._acaoIr=t,this._partesCaminho=(Array.isArray(e)?e:[e]).filter(Boolean).map(n=>String(n)).flatMap(n=>n.split("/")).filter(Boolean),this.rotulo=a}get caminho(){return`/${this._partesCaminho.join("/")}`}set caminho(e){this._partesCaminho=e.split("/").filter(t=>t)}endereco(e,t){let a=new URL(typeof window<"u"?window.location.href:"http://localhost");a.pathname=this.caminho,a.search="";let n=Object.entries(e);for(let[i,m]of n)a.searchParams.set(String(i),JSON.stringify(m));return a.hash="",t&&(a.hash=`#${a.search}`,a.search=""),a.href}ir(e){this._acaoIr?this._acaoIr(this.endereco({...e})):typeof window<"u"&&(window.location.href=this.endereco({...e}))}parametros(e){let t=e?new URL(e):new URL(typeof window<"u"?window.location.href:"http://localhost"),a=t.searchParams,n=Object.fromEntries(a.entries()),i=t.hash;if(i){let m=Object.fromEntries(new URLSearchParams(i.slice(1)).entries());n={...n,...m}}for(let m in n)try{n[m]=JSON.parse(n[m])}catch{console.log(`[${m}|${n[m]}] n\xE3o \xE9 um json v\xE1lido.`)}return n}};var H=(i=>(i.UN="UN",i.KG="KG",i.TON="TON",i.g="g",i["M\xB3"]="M\xB3",i.Lt="Lt",i))(H||{}),re=[{sigla_unidade:"KG",nome:"Quilograma",sigla_normalizada:"KG",normalizar:o=>o,tipo:"massa"},{sigla_unidade:"g",nome:"Grama",sigla_normalizada:"KG",normalizar:o=>o/1e3,tipo:"massa"},{sigla_unidade:"TON",nome:"Tonelada",sigla_normalizada:"KG",normalizar:o=>o*1e3,tipo:"massa"},{sigla_unidade:"Lt",nome:"Litro",sigla_normalizada:"Lt",normalizar:o=>o,tipo:"volume"},{sigla_unidade:"M\xB3",nome:"Metro C\xFAbico",sigla_normalizada:"Lt",normalizar:o=>o*1e3,tipo:"volume"},{sigla_unidade:"UN",nome:"Unidade",sigla_normalizada:"UN",normalizar:o=>o,tipo:"unidade"}];import{NIL as W,v3 as X,v4 as Z}from"uuid";var S=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ne=o=>S.test(String(o||"")),E=(o,e)=>X(typeof o=="string"?o:typeof o=="number"?String(o):JSON.stringify(o),e?E(e):W),oo=Z,ie=oo;export{Q as Produtos,h as TipagemRotas,to as aleatorio,v as cacheM,mo as cacheMFixo,io as cacheMemoria,z as camposComuns,d as dayjsbr,Co as defineCwd,I as duration,S as erUuid,Uo as esperar,F as extensoes,U as isSameOrAfter,P as isSameOrBefore,ko as link_paiol,qo as localValor,Ko as logger,A as minMax,x as nomeVariavel,Go as objetoPg,M as operadores,y as paraObjetoRegistroPg,Fo as pgObjeto,B as postLogger,J as relativeTime,H as siglas_unidades_medida,Eo as texto_busca,C as timezone,$o as tipoArquivo,$ as tipoUsuarioResiduos,Y as tiposSituacoesElicencie,N as tx,Qo as umaFuncao,Ho as umaVariavel,re as unidades_medida,K as utc,ie as uuid,E as uuidV3,oo as uuidV4,so as uuid_null,ne as validarUuid,no as verCacheM,D as weekOfYear,fo as zFiltro,q as zOperadores}; diff --git a/package.json b/package.json index 8bf0c6d..b75f303 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "p-comuns", - "version": "0.317.0", + "version": "0.303.0", "description": "", "main": "./dist-front/index.mjs", "module": "./dist-front/index.mjs", @@ -25,12 +25,13 @@ "url": "https://e-licencie.com.br" }, "license": "ISC", - "dependencies": {}, - "devDependencies": { + "dependencies": { "cross-fetch": "4.1.0", - "uuid": "^11.1.0", - "zod": "4.1.4", "dayjs": "^1.11.18", + "uuid": "^11.1.0", + "zod": "4.1.4" + }, + "devDependencies": { "@biomejs/biome": "2.4.0", "@types/node": "^20.19.22", "tsup": "8.5.0", diff --git a/pacote.tgz b/pacote.tgz index cca779e..14312d7 100644 Binary files a/pacote.tgz and b/pacote.tgz differ diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml old mode 100755 new mode 100644 index fd8c817..c47f9a2 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -7,6 +7,19 @@ settings: importers: .: + dependencies: + cross-fetch: + specifier: 4.1.0 + version: 4.1.0 + dayjs: + specifier: ^1.11.18 + version: 1.11.18 + uuid: + specifier: ^11.1.0 + version: 11.1.0 + zod: + specifier: 4.1.4 + version: 4.1.4 devDependencies: '@biomejs/biome': specifier: 2.4.0 @@ -14,12 +27,6 @@ importers: '@types/node': specifier: ^20.19.22 version: 20.19.22 - cross-fetch: - specifier: 4.1.0 - version: 4.1.0 - dayjs: - specifier: ^1.11.18 - version: 1.11.19 tsup: specifier: 8.5.0 version: 8.5.0(jiti@2.6.1)(postcss@8.5.6)(typescript@5.9.3) @@ -29,15 +36,9 @@ importers: unbuild: specifier: ^3.6.1 version: 3.6.1(typescript@5.9.3) - uuid: - specifier: ^11.1.0 - version: 11.1.0 vitest: specifier: ^3.2.4 version: 3.2.4(@types/node@20.19.22)(jiti@2.6.1) - zod: - specifier: 4.1.4 - version: 4.1.4 packages: @@ -657,8 +658,8 @@ packages: resolution: {integrity: sha512-0LrrStPOdJj+SPCCrGhzryycLjwcgUSHBtxNA8aIDxf0GLsRh1cKYhB00Gd1lDOS4yGH69+SNn13+TWbVHETFQ==} engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0, npm: '>=7.0.0'} - dayjs@1.11.19: - resolution: {integrity: sha512-t5EcLVS6QPBNqM2z8fakk/NKel+Xzshgt8FFKAn+qwlD1pzZWxh0nVCrvFK7ZDb6XucZeF9z8C7CBWTRIVApAw==} + dayjs@1.11.18: + resolution: {integrity: sha512-zFBQ7WFRvVRhKcWoUh+ZA1g2HVgUbsZm9sbddh8EC5iv93sui8DVVz1Npvz+r6meo9VKfa8NyLWBsQK1VvIKPA==} debug@4.4.3: resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} @@ -1970,7 +1971,7 @@ snapshots: dependencies: css-tree: 2.2.1 - dayjs@1.11.19: {} + dayjs@1.11.18: {} debug@4.4.3: dependencies: diff --git a/requisicoes.rest b/requisicoes.rest old mode 100755 new mode 100644 diff --git a/src/aleatorio.ts b/src/aleatorio.ts old mode 100755 new mode 100644 diff --git a/src/cacheMemoria.ts b/src/cacheMemoria.ts old mode 100755 new mode 100644 diff --git a/src/constantes.ts b/src/constantes.ts old mode 100755 new mode 100644 diff --git a/src/consulta.ts b/src/consulta.ts old mode 100755 new mode 100644 diff --git a/src/dayjs.ts b/src/dayjs.ts new file mode 100644 index 0000000..36b9b45 --- /dev/null +++ b/src/dayjs.ts @@ -0,0 +1,37 @@ +import dayjsbr, { type Dayjs } from "dayjs" + +export type { ManipulateType } from "dayjs" + +import duration from "dayjs/plugin/duration" +import isSameOrAfter from "dayjs/plugin/isSameOrAfter" +import isSameOrBefore from "dayjs/plugin/isSameOrBefore" +import minMax from "dayjs/plugin/minMax" +import relativeTime from "dayjs/plugin/relativeTime" +import timezone from "dayjs/plugin/timezone" +import utc from "dayjs/plugin/utc" +import weekOfYear from "dayjs/plugin/weekOfYear" +import "dayjs/locale/pt-br" +dayjsbr.locale("pt-br") + +dayjsbr.extend(utc) +dayjsbr.extend(timezone) +dayjsbr.extend(weekOfYear) +dayjsbr.extend(isSameOrBefore) +dayjsbr.extend(isSameOrAfter) +dayjsbr.extend(minMax) +dayjsbr.extend(relativeTime) +dayjsbr.extend(duration) + +export { + dayjsbr, + duration, + isSameOrAfter, + isSameOrBefore, + minMax, + relativeTime, + timezone, + utc, + weekOfYear, +} + +export type { Dayjs } diff --git a/src/dayjs26.ts b/src/dayjs26.ts deleted file mode 100755 index e3c5ab0..0000000 --- a/src/dayjs26.ts +++ /dev/null @@ -1,107 +0,0 @@ -/** - * Utilitário de configuração do Dayjs focado em compatibilidade com SSR. - * - * PROBLEMA: - * A importação direta do `dayjs` e seus plugins frequentemente causa conflitos em ambientes - * de Renderização do Lado do Servidor (SSR), como Nuxt ou Next.js, devido a discrepâncias - * na resolução de módulos (ESM vs CJS) e instabilidades de importação. - * - * SOLUÇÃO: - * Este módulo utiliza o padrão de Injeção de Dependência. Ele expõe apenas tipagens e - * uma função de configuração (`defineDayjsBr`). A responsabilidade de importar as - * bibliotecas "vivas" é delegada à aplicação consumidora (o cliente da função). - * - * Isso permite que o bundler da aplicação principal (Vite, Webpack, etc.) gerencie as - * instâncias, garantindo consistência e evitando erros de "module not found" ou - * instâncias duplicadas/não inicializadas adequadamente. - */ - -import type _dayjs from "dayjs" -import type { Dayjs } from "dayjs" - -export type { ManipulateType } from "dayjs" - -// Importação apenas de TIPOS para evitar bundling indesejado neste arquivo -import type _duration from "dayjs/plugin/duration" -import type _isSameOrAfter from "dayjs/plugin/isSameOrAfter" -import type _isSameOrBefore from "dayjs/plugin/isSameOrBefore" -import type _minMax from "dayjs/plugin/minMax" -import type _relativeTime from "dayjs/plugin/relativeTime" -import type _timezone from "dayjs/plugin/timezone" -import type _utc from "dayjs/plugin/utc" -import type _weekOfYear from "dayjs/plugin/weekOfYear" - -/** - * Inicializa e configura o Dayjs com o locale 'pt-br' e plugins essenciais. - * - * MODO DE USO: - * Importe os pacotes reais na sua aplicação e passe-os para esta função. - * - * @example - * ```ts - * // Em seu arquivo de configuração (ex: plugins/dayjs.ts): - * import dayjs from "dayjs" - * import duration from "dayjs/plugin/duration" - * import isSameOrAfter from "dayjs/plugin/isSameOrAfter" - * import isSameOrBefore from "dayjs/plugin/isSameOrBefore" - * import minMax from "dayjs/plugin/minMax" - * import relativeTime from "dayjs/plugin/relativeTime" - * import timezone from "dayjs/plugin/timezone" - * import utc from "dayjs/plugin/utc" - * import weekOfYear from "dayjs/plugin/weekOfYear" - * import { defineDayjsBr } from "p-comuns" - * import "dayjs/locale/pt-br" // Importante: importar o locale! - - * export const dayjsbr = defineDayjsBr({ - * dayjs, - * duration, - * isSameOrAfter, - * isSameOrBefore, - * minMax, - * relativeTime, - * timezone, - * utc, - * weekOfYear, - * }) - * ``` - */ -const defineDayjsBr = ({ - dayjs, - duration, - isSameOrAfter, - isSameOrBefore, - minMax, - relativeTime, - timezone, - utc, - weekOfYear, -}: { - dayjs: typeof _dayjs - duration: typeof _duration - isSameOrAfter: typeof _isSameOrAfter - isSameOrBefore: typeof _isSameOrBefore - minMax: typeof _minMax - relativeTime: typeof _relativeTime - timezone: typeof _timezone - utc: typeof _utc - weekOfYear: typeof _weekOfYear -}) => { - // Extensão da biblioteca com os plugins fornecidos - dayjs.extend(utc) - dayjs.extend(timezone) - dayjs.extend(weekOfYear) - dayjs.extend(isSameOrBefore) - dayjs.extend(isSameOrAfter) - dayjs.extend(minMax) - dayjs.extend(relativeTime) - dayjs.extend(duration) - - // Definição do locale global - dayjs.locale("pt-br") - - return dayjs -} - -export { defineDayjsBr } - -export type { Dayjs } diff --git a/src/ecosistema/index.ts b/src/ecosistema/index.ts old mode 100755 new mode 100644 diff --git a/src/ecosistema/urls.ts b/src/ecosistema/urls.ts old mode 100755 new mode 100644 diff --git a/src/extensoes.ts b/src/extensoes.ts old mode 100755 new mode 100644 diff --git a/src/graficosPilao.ts b/src/graficosPilao.ts deleted file mode 100755 index 4c9d295..0000000 --- a/src/graficosPilao.ts +++ /dev/null @@ -1,12 +0,0 @@ -export const graficos_pilao: { - [k: string]: { grafico: string; titulo: string } -} = { - Condicionantes: { - grafico: "condicionantes-criadas", - titulo: "Condicionantes Criadas", - }, - Licenças: { - grafico: "licencas-criadas", - titulo: "Licenças Criadas", - }, -} diff --git a/src/index.ts b/src/index.ts old mode 100755 new mode 100644 index a85465f..555b0f0 --- a/src/index.ts +++ b/src/index.ts @@ -2,11 +2,13 @@ export * from "./aleatorio" export * from "./cacheMemoria" export * from "./constantes" export * from "./consulta" -export * from "./dayjs26" +export * from "./dayjs" export * from "./ecosistema" export * from "./extensoes" export * from "./extensoes" export * from "./local" +export * from "./logger" +export * from "./logger" export * from "./postgres" export * from "./produtos" export * from "./situacoes" @@ -14,7 +16,6 @@ export * from "./testes-de-variaveis" export * from "./texto_busca" export * from "./tipagemRotas" export * from "./tipagemRotas" -export * from "./tipoFiltro.26" export * from "./unidades_medida" export * from "./uuid" export * from "./variaveisComuns" diff --git a/src/instalarAmbiente.ts b/src/instalarAmbiente.ts old mode 100755 new mode 100644 diff --git a/src/local/index.ts b/src/local/index.ts old mode 100755 new mode 100644 index 210f40e..94a7eed --- a/src/local/index.ts +++ b/src/local/index.ts @@ -6,8 +6,8 @@ export const localValor = ( chave_: string | any, valor?: T | null, ): T | null => { - const localStorage = - "localStorage" in globalThis ? (globalThis as any).localStorage : undefined + const localStorage = globalThis.localStorage + if (typeof localStorage == "undefined") return null const chave = diff --git a/src/logger.ts b/src/logger.ts new file mode 100644 index 0000000..7dec9f1 --- /dev/null +++ b/src/logger.ts @@ -0,0 +1,126 @@ +import crossFetch from "cross-fetch" +import { nomeVariavel } from "./variaveisComuns" + +const LOKI_BASE_URL = "https://log.idz.one" +const LOKI_ENDPOINT = "/loki/api/v1/push" +export type tipoLokiObjeto = { + streams: { + stream: { + [k: string]: string + } + values: [string, string][] + }[] +} + +export const postLogger = async ({ + objeto, +}: { + objeto: tipoLokiObjeto +}): Promise<[objeto: tipoLokiObjeto, erro?: string]> => { + 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 = "" + +/** define a localização da pasta do projeto */ +export const defineCwd = (novoCwd: string) => { + cwd = novoCwd +} + +type tipoLevel = "info" | "warn" | "error" + +type tipoOpSessao = { + inquilino: string + usuario: string + parametros?: { [k: string]: string } +} + +type tipoLog = { + detalhes?: unknown[] + __filename?: string + local?: string + parametros?: { [k: string]: string } +} + +export type tipoLoggerLog = ( + level: tipoLevel, + mensagem: string, + op_tipoLog?: tipoLog, +) => Promise<[objeto: tipoLokiObjeto, erro?: string]> + +export type TipoLoggerSessao = (sess: tipoOpSessao) => tipoLoggerLog + +export type tipoLogger = (amb: { + app: string + eProducao: boolean + parametros?: { + [k: string]: string + } +}) => TipoLoggerSessao + +export const logger: tipoLogger = + ({ 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: tipoLokiObjeto["streams"][number] = { + stream: { + app, + inquilino, + usuario, + level, + ...(parametrosAmbiente || {}), + ...(parametrosSessao || {}), + ...(parametrosLog || {}), + }, + values: [ + [ + timestamp, + mainLog, // Linha de log direta + ], + ], + } + + const objeto: tipoLokiObjeto = { streams: [payload] } + + const response = await postLogger({ objeto }) + + return response + } diff --git a/src/postgres.ts b/src/postgres.ts old mode 100755 new mode 100644 diff --git a/src/teste.ts b/src/teste.ts old mode 100755 new mode 100644 diff --git a/src/testes-de-variaveis/index.ts b/src/testes-de-variaveis/index.ts old mode 100755 new mode 100644 diff --git a/src/testes-de-variaveis/umaFuncao.ts b/src/testes-de-variaveis/umaFuncao.ts old mode 100755 new mode 100644 diff --git a/src/testes-de-variaveis/umaVariavel.ts b/src/testes-de-variaveis/umaVariavel.ts old mode 100755 new mode 100644 diff --git a/src/testes/TipagemRotas.test.ts b/src/testes/TipagemRotas.test.ts old mode 100755 new mode 100644 diff --git a/src/texto_busca.ts b/src/texto_busca.ts old mode 100755 new mode 100644 diff --git a/src/tipagemRotas.ts b/src/tipagemRotas.ts old mode 100755 new mode 100644 index 92ce985..8755a30 --- a/src/tipagemRotas.ts +++ b/src/tipagemRotas.ts @@ -63,10 +63,9 @@ export class TipagemRotas { */ endereco(query: T, usarComoHash?: boolean) { - const win = - (typeof globalThis !== "undefined" && (globalThis as any).window) || - undefined - const url = new URL(win ? win.location.href : "http://localhost") + const url = new URL( + typeof window !== "undefined" ? window.location.href : "http://localhost", + ) url.pathname = this.caminho @@ -96,11 +95,8 @@ export class TipagemRotas { if (this._acaoIr) { this._acaoIr(this.endereco({ ...query })) } else { - const win = - (typeof globalThis !== "undefined" && (globalThis as any).window) || - undefined - if (win) { - win.location.href = this.endereco({ ...query }) + if (typeof window != "undefined") { + window.location.href = this.endereco({ ...query }) } } } @@ -114,8 +110,8 @@ export class TipagemRotas { const url = urlEntrada ? new URL(urlEntrada) : new URL( - typeof globalThis !== "undefined" && (globalThis as any).window - ? (globalThis as any).window.location.href + typeof window !== "undefined" + ? window.location.href : "http://localhost", ) const query = url.searchParams diff --git a/src/tipoFiltro.26.ts b/src/tipoFiltro.26.ts deleted file mode 100644 index f3086da..0000000 --- a/src/tipoFiltro.26.ts +++ /dev/null @@ -1,235 +0,0 @@ -import { z } from "zod" - -/** - * ============================================================================= - * tipoFiltro26 - * ============================================================================= - * - * OBJETIVO - * ----------------------------------------------------------------------------- - * Gerar automaticamente a tipagem de filtros compatíveis com operadores - * padrão do PostgreSQL, a partir de um tipo base T. - * - * Este tipo foi projetado para: - * - Construção de filtros dinâmicos - * - Geração posterior de WHERE (Knex / SQL) - * - Uso seguro por IA (evita filtros inválidos em nível de tipo) - * - * - * FORMATO DO FILTRO - * ----------------------------------------------------------------------------- - * 1) Campos simples: - * - * { - * idade: { ">=": 18 } - * } - * - * 2) Campos aninhados: - * - * { - * carro: { - * ano: { "=": 2020 } - * } - * } - * - * 3) Operador E (AND): - * - * { - * E: [ - * { idade: { ">=": 18 } }, - * { nome: { like: "%pa%" } } - * ] - * } - * - * 4) Operador OU (OR): - * - * { - * OU: [ - * { idade: { "<": 18 } }, - * { idade: { ">=": 60 } } - * ] - * } - * - * 5) Combinação complexa: - * - * { - * idade: { ">=": 18 }, - * OU: [ - * { nome: { like: "%pa%" } }, - * { - * E: [ - * { carro: { ano: { "=": 2020 } } }, - * { carro: { modelo: { in: ["Civic"] } } } - * ] - * } - * ] - * } - * - * - * REGRAS IMPORTANTES (PARA IA) - * ----------------------------------------------------------------------------- - * - Apenas campos existentes em T podem ser usados. - * - Operadores são restritos por tipo do campo. - * - Objetos são tratados recursivamente. - * - Arrays NÃO são tratados como objeto recursivo. - * - Funções NÃO são consideradas campos filtráveis. - * - * - * OPERADORES SUPORTADOS - * ----------------------------------------------------------------------------- - * number: - * =, !=, >, >=, <, <=, in - * - * string: - * =, !=, like, in - * - * boolean: - * =, !=, in - * - * Não há suporte automático a: - * - null - * - date - * - jsonb - * - arrays - * - * Essas extensões devem ser adicionadas explicitamente. - * - * ============================================================================= - */ - -/* ============================================================================= - OPERADORES POSTGRESQL POR TIPO - ============================================================================= */ - -export enum operadores26 { - "=" = "=", - "!=" = "!=", - ">" = ">", - ">=" = ">=", - "<" = "<", - "<=" = "<=", - like = "like", - in = "in", -} - -export enum agrupadores26 { - E = "E", - OU = "OU", -} - -type PgOpsNumber = { - [K in Extract" | ">=" | "<" | "<=">]?: number -} & { - [K in Extract]?: number[] -} - -type PgOpsString = { - [K in Extract]?: string -} & { - [K in Extract]?: string[] -} - -type PgOpsBoolean = { - [K in Extract]?: boolean[] -} - -/* ============================================================================= - SELEÇÃO AUTOMÁTICA DE OPERADORES BASEADA NO TIPO DO CAMPO -============================================================================= */ - -type PgOpsFor = V extends number - ? PgOpsNumber - : V extends string - ? PgOpsString - : V extends boolean - ? PgOpsBoolean - : never - -/* ============================================================================= - UTILITÁRIO: DETECTAR OBJETO PLANO -============================================================================= */ - -type IsPlainObject = T extends object - ? T extends Function - ? false - : T extends readonly any[] - ? false - : true - : false - -/* ============================================================================= - FILTRO RECURSIVO POR CAMPOS -============================================================================= */ - -type FiltroCampos = { - [K in keyof T]?: IsPlainObject extends true - ? tipoFiltro26 - : PgOpsFor -} - -/* ============================================================================= - TIPO PRINCIPAL EXPORTADO -============================================================================= */ - -export type tipoFiltro26 = FiltroCampos & { - /** - * E => AND lógico - * Todos os filtros dentro do array devem ser verdadeiros. - */ - E?: tipoFiltro26[] - - /** - * OU => OR lógico - * Pelo menos um filtro dentro do array deve ser verdadeiro. - */ - OU?: tipoFiltro26[] -} - -/* ============================================================================= - VALIDAÇÃO ESTRUTURAL (ZOD) -============================================================================= */ - -const zOperadores = z.nativeEnum(operadores26) -const zValor = z.any() -const zCondicao = z.record(zOperadores, zValor) - -export const zFiltro26: z.ZodType = z.lazy(() => - z - .object({ - E: z.array(zFiltro26).optional(), - OU: z.array(zFiltro26).optional(), - }) - .catchall(z.union([zCondicao, zFiltro26])), -) - -/* ============================================================================= - EXEMPLO DE USO -============================================================================= */ - -type Pessoa = { - codigo: string - nome: string - idade: number - carro: { - modelo: string - ano: number - } -} - -export const criarFiltro26 = (filtro: tipoFiltro26) => filtro - -const _filtro = criarFiltro26({ - idade: { [operadores26[">="]]: 18 }, - - [agrupadores26.OU]: [ - { nome: { [operadores26.like]: "%pa%" } }, - { - [agrupadores26.E]: [ - { carro: { ano: { [operadores26["="]]: 2020 } } }, - { carro: { modelo: { [operadores26.in]: ["Civic", "Corolla"] } } }, - ], - }, - ], -}) diff --git a/src/unidades_medida.ts b/src/unidades_medida.ts old mode 100755 new mode 100644 diff --git a/src/uuid.ts b/src/uuid.ts old mode 100755 new mode 100644 diff --git a/src/variaveisComuns.ts b/src/variaveisComuns.ts old mode 100755 new mode 100644 diff --git a/tsconfig-back.json b/tsconfig-back.json old mode 100755 new mode 100644 diff --git a/tsconfig-front.json b/tsconfig-front.json old mode 100755 new mode 100644 diff --git a/tsconfig.json b/tsconfig.json old mode 100755 new mode 100644 diff --git a/tsup/como usar.md b/tsup/como usar.md old mode 100755 new mode 100644 diff --git a/tsup/tsup.config.back.ts b/tsup/tsup.config.back.ts old mode 100755 new mode 100644 index 912c657..cffbdf4 --- a/tsup/tsup.config.back.ts +++ b/tsup/tsup.config.back.ts @@ -18,10 +18,6 @@ export const tsup_config_back: Options = { minify: false, // Geralmente não minificamos o código do backend em produção, mas você pode mudar platform: "node", outExtension: () => ({ js: ".js" }), - loader: { - ".svg": "text", - ".md": "text", - }, } // Exporta a configuração padrão usando defineConfig diff --git a/tsup/tsup.config.front.interno.ts b/tsup/tsup.config.front.interno.ts old mode 100755 new mode 100644 diff --git a/tsup/tsup.config.front.ts b/tsup/tsup.config.front.ts old mode 100755 new mode 100644 index 38d1a87..685f79e --- a/tsup/tsup.config.front.ts +++ b/tsup/tsup.config.front.ts @@ -16,13 +16,9 @@ export const tsup_config_front: Options = { sourcemap: false, minify: true, // Recomendado para builds de produção platform: "browser", - external: ['dayjs', 'cross-fetch', 'uuid', 'zod'], + external: ['dayjs'], outExtension: () => ({ js: ".mjs" }), shims: false, - loader: { - ".svg": "text", - ".md": "text", - }, } // Exporta a configuração padrão usando defineConfig diff --git a/tsup/tsup.config.interno.ts b/tsup/tsup.config.interno.ts old mode 100755 new mode 100644 diff --git a/tsup/tsup.config.ts b/tsup/tsup.config.ts old mode 100755 new mode 100644