Compare commits

..

4 commits
bun ... master

91 changed files with 5481 additions and 3017 deletions

View file

@ -20,13 +20,13 @@
| Camada | Tecnologia | Versão | | Camada | Tecnologia | Versão |
|--------|-----------|--------| |--------|-----------|--------|
| Linguagem | TypeScript | ^7 | | Linguagem | TypeScript | ~5.9.x |
| Runtime (back) | Node.js | ≥20 | | Runtime (back) | Node.js | ≥20 |
| Framework (front) | Vue 3 | Composition API + `<script setup>` | | Framework (front) | Vue 3 | Composition API + `<script setup>` |
| JSX/TSX | Vue TSX / React-like TSX | via `jsxRuntime` | | JSX/TSX | Vue TSX / React-like TSX | via `jsxRuntime` |
| Linter/Formatter | Biome | 2.4.x | | Linter/Formatter | Biome | 2.4.x |
| Compilador | TypeScript (tsc) | ^7 | | Bundler | tsup | 8.x |
| Package manager | Bun | ≥1.2 | | Package manager | pnpm | com workspaces |
| Validação | Zod | 4.x | | Validação | Zod | 4.x |
| Utilitários de data | dayjs | 1.11.x | | Utilitários de data | dayjs | 1.11.x |
@ -204,10 +204,10 @@ export const MeuComponente = defineComponent({
## 🚀 Scripts ## 🚀 Scripts
```bash ```bash
bun run biome # Formata + lint com auto-fix pnpm biome # Formata + lint com auto-fix
bun run check # biome + tsc --noEmit (sem emitir arquivos) pnpm check # biome + tsc --noEmit (sem emitir arquivos)
bun run build # Bump de versão + biome + tsc (back e front) pnpm build # Bump de versão + biome + tsup + pack
bun test # Bun test (testes unitários) pnpm teste # Vitest (testes unitários)
``` ```
--- ---
@ -231,5 +231,4 @@ bun test # Bun test (testes unitários)
- [Biome 2.x Docs](https://biomejs.dev) - [Biome 2.x Docs](https://biomejs.dev)
- [Vue 3 Composition API](https://vuejs.org/guide/composition-api) - [Vue 3 Composition API](https://vuejs.org/guide/composition-api)
- [Zod v4](https://zod.dev) - [Zod v4](https://zod.dev)
- [TypeScript Docs](https://www.typescriptlang.org) - [tsup](https://tsup.egoist.dev)

View file

@ -17,7 +17,7 @@
"noVueDuplicateKeys": "error", "noVueDuplicateKeys": "error",
"noVueReservedKeys": "error", "noVueReservedKeys": "error",
"noVueReservedProps": "error", "noVueReservedProps": "error",
"noVueSetupPropsReactivityLoss": "error" "noVueSetupPropsReactivityLoss": "warn"
}, },
"style": { "style": {
@ -45,7 +45,7 @@
"noExplicitAny": "off", "noExplicitAny": "off",
"noApproximativeNumericConstant": "off", "noApproximativeNumericConstant": "off",
"noAsyncPromiseExecutor": "off", "noAsyncPromiseExecutor": "off",
"noEmptyBlockStatements": "warn", "noEmptyBlockStatements": "off",
"noConsole": "off", "noConsole": "off",
"noArrayIndexKey": "warn" "noArrayIndexKey": "warn"
}, },
@ -57,16 +57,13 @@
"useArrowFunction": "error", "useArrowFunction": "error",
"useDateNow": "off", "useDateNow": "off",
"noUselessFragments": "off", "noUselessFragments": "off",
"noExcessiveCognitiveComplexity": { "noExcessiveCognitiveComplexity": "off",
"level": "warn",
"options": { "maxAllowedComplexity": 20 }
},
"noImportantStyles": "off" "noImportantStyles": "off"
}, },
"performance": { "performance": {
"noAccumulatingSpread": "off", "noAccumulatingSpread": "off",
"noDelete": "warn" "noDelete": "off"
}, },
"a11y": { "a11y": {
@ -98,15 +95,6 @@
} }
}, },
"assist": {
"enabled": true,
"actions": {
"source": {
"organizeImports": "on"
}
}
},
"formatter": { "formatter": {
"enabled": true, "enabled": true,
"indentStyle": "space", "indentStyle": "space",

12
build.config.ts Executable file
View file

@ -0,0 +1,12 @@
import { defineBuildConfig } from 'unbuild'
// pnpm exec unbuild
export default defineBuildConfig({
entries: ['src/index'],
clean: true,
declaration: true,
rollup: {
emitCJS: true,
},
})

View file

@ -1,98 +0,0 @@
{
"lockfileVersion": 1,
"configVersion": 1,
"workspaces": {
"": {
"name": "p-comuns",
"devDependencies": {
"@biomejs/biome": "^2",
"@types/bun": "^1.4.2",
"@types/node": "^22",
"dayjs": "^1.11.18",
"typescript": "^7",
"uuid": "^11.1.0",
"zod": "4.4.3",
},
"peerDependencies": {
"dayjs": "^1.11.18",
"uuid": "^11.1.0",
"zod": "4.4.3",
},
},
},
"packages": {
"@biomejs/biome": ["@biomejs/biome@2.4.12", "", { "optionalDependencies": { "@biomejs/cli-darwin-arm64": "2.4.12", "@biomejs/cli-darwin-x64": "2.4.12", "@biomejs/cli-linux-arm64": "2.4.12", "@biomejs/cli-linux-arm64-musl": "2.4.12", "@biomejs/cli-linux-x64": "2.4.12", "@biomejs/cli-linux-x64-musl": "2.4.12", "@biomejs/cli-win32-arm64": "2.4.12", "@biomejs/cli-win32-x64": "2.4.12" }, "bin": { "biome": "bin/biome" } }, "sha512-Rro7adQl3NLq/zJCIL98eElXKI8eEiBtoeu5TbXF/U3qbjuSc7Jb5rjUbeHHcquDWeSf3HnGP7XI5qGrlRk/pA=="],
"@biomejs/cli-darwin-arm64": ["@biomejs/cli-darwin-arm64@2.4.12", "", { "os": "darwin", "cpu": "arm64" }, "sha512-BnMU4Pc3ciEVteVpZ0BK33MLr7X57F5w1dwDLDn+/iy/yTrA4Q/N2yftidFtsA4vrDh0FMXDpacNV/Tl3fbmng=="],
"@biomejs/cli-darwin-x64": ["@biomejs/cli-darwin-x64@2.4.12", "", { "os": "darwin", "cpu": "x64" }, "sha512-x9uJ0bI1rJsWICp3VH8w/5PnAVD3A7SqzDpbrfoUQX1QyWrK5jSU4fRLo/wSgGeplCivbxBRKmt5Xq4/nWvq8A=="],
"@biomejs/cli-linux-arm64": ["@biomejs/cli-linux-arm64@2.4.12", "", { "os": "linux", "cpu": "arm64" }, "sha512-tOwuCuZZtKi1jVzbk/5nXmIsziOB6yqN8c9r9QM0EJYPU6DpQWf11uBOSCfFKKM4H3d9ZoarvlgMfbcuD051Pw=="],
"@biomejs/cli-linux-arm64-musl": ["@biomejs/cli-linux-arm64-musl@2.4.12", "", { "os": "linux", "cpu": "arm64" }, "sha512-FhfpkAAlKL6kwvcVap0Hgp4AhZmtd3YImg0kK1jd7C/aSoh4SfsB2f++yG1rU0lr8Y5MCFJrcSkmssiL9Xnnig=="],
"@biomejs/cli-linux-x64": ["@biomejs/cli-linux-x64@2.4.12", "", { "os": "linux", "cpu": "x64" }, "sha512-8pFeAnLU9QdW9jCIslB/v82bI0lhBmz2ZAKc8pVMFPO0t0wAHsoEkrUQUbMkIorTRIjbqyNZHA3lEXavsPWYSw=="],
"@biomejs/cli-linux-x64-musl": ["@biomejs/cli-linux-x64-musl@2.4.12", "", { "os": "linux", "cpu": "x64" }, "sha512-dwTIgZrGutzhkQCuvHynCkyW6hJxUuyZqKKO0YNfaS2GUoRO+tOvxXZqZB6SkWAOdfZTzwaw8IEdUnIkHKHoew=="],
"@biomejs/cli-win32-arm64": ["@biomejs/cli-win32-arm64@2.4.12", "", { "os": "win32", "cpu": "arm64" }, "sha512-B0DLnx0vA9ya/3v7XyCaP+/lCpnbWbMOfUFFve+xb5OxyYvdHaS55YsSddr228Y+JAFk58agCuZTsqNiw2a6ig=="],
"@biomejs/cli-win32-x64": ["@biomejs/cli-win32-x64@2.4.12", "", { "os": "win32", "cpu": "x64" }, "sha512-yMckRzTyZ83hkk8iDFWswqSdU8tvZxspJKnYNh7JZr/zhZNOlzH13k4ecboU6MurKExCe2HUkH75pGI/O2JwGA=="],
"@types/bun": ["@types/bun@1.4.2", "", { "dependencies": { "bun-types": "1.4.2" } }, "sha512-GimotNn7+ZV0uVArItBbriZsR1oNf0+WTzPkdcFrzShI7k2norL0uzEaJT8T33dWr7O/c9ZDuAFQrctKCi72oQ=="],
"@types/node": ["@types/node@22.20.1", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q=="],
"@typescript/typescript-aix-ppc64": ["@typescript/typescript-aix-ppc64@7.0.2", "", { "os": "aix", "cpu": "ppc64" }, "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ=="],
"@typescript/typescript-darwin-arm64": ["@typescript/typescript-darwin-arm64@7.0.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA=="],
"@typescript/typescript-darwin-x64": ["@typescript/typescript-darwin-x64@7.0.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA=="],
"@typescript/typescript-freebsd-arm64": ["@typescript/typescript-freebsd-arm64@7.0.2", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ=="],
"@typescript/typescript-freebsd-x64": ["@typescript/typescript-freebsd-x64@7.0.2", "", { "os": "freebsd", "cpu": "x64" }, "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw=="],
"@typescript/typescript-linux-arm": ["@typescript/typescript-linux-arm@7.0.2", "", { "os": "linux", "cpu": "arm" }, "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ=="],
"@typescript/typescript-linux-arm64": ["@typescript/typescript-linux-arm64@7.0.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ=="],
"@typescript/typescript-linux-loong64": ["@typescript/typescript-linux-loong64@7.0.2", "", { "os": "linux", "cpu": "none" }, "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ=="],
"@typescript/typescript-linux-mips64el": ["@typescript/typescript-linux-mips64el@7.0.2", "", { "os": "linux", "cpu": "none" }, "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA=="],
"@typescript/typescript-linux-ppc64": ["@typescript/typescript-linux-ppc64@7.0.2", "", { "os": "linux", "cpu": "ppc64" }, "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA=="],
"@typescript/typescript-linux-riscv64": ["@typescript/typescript-linux-riscv64@7.0.2", "", { "os": "linux", "cpu": "none" }, "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ=="],
"@typescript/typescript-linux-s390x": ["@typescript/typescript-linux-s390x@7.0.2", "", { "os": "linux", "cpu": "s390x" }, "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw=="],
"@typescript/typescript-linux-x64": ["@typescript/typescript-linux-x64@7.0.2", "", { "os": "linux", "cpu": "x64" }, "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A=="],
"@typescript/typescript-netbsd-arm64": ["@typescript/typescript-netbsd-arm64@7.0.2", "", { "os": "none", "cpu": "arm64" }, "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA=="],
"@typescript/typescript-netbsd-x64": ["@typescript/typescript-netbsd-x64@7.0.2", "", { "os": "none", "cpu": "x64" }, "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA=="],
"@typescript/typescript-openbsd-arm64": ["@typescript/typescript-openbsd-arm64@7.0.2", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ=="],
"@typescript/typescript-openbsd-x64": ["@typescript/typescript-openbsd-x64@7.0.2", "", { "os": "openbsd", "cpu": "x64" }, "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg=="],
"@typescript/typescript-sunos-x64": ["@typescript/typescript-sunos-x64@7.0.2", "", { "os": "sunos", "cpu": "x64" }, "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g=="],
"@typescript/typescript-win32-arm64": ["@typescript/typescript-win32-arm64@7.0.2", "", { "os": "win32", "cpu": "arm64" }, "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ=="],
"@typescript/typescript-win32-x64": ["@typescript/typescript-win32-x64@7.0.2", "", { "os": "win32", "cpu": "x64" }, "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g=="],
"bun-types": ["bun-types@1.4.2", "", { "dependencies": { "@types/node": "*" } }, "sha512-bxV1FgK7yBIzjRe5zBozIM4Bem11ZJcCXSrjWRG3YWLt8yFDePu4cLjpebO8OvPeIE9trbyPF4fuj3Cia4Fj3w=="],
"dayjs": ["dayjs@1.11.21", "", {}, "sha512-98IT+HOahAisibz/yjKbzuOBwYcjJ7BCLPzARyHiyEBmRz4fatF+KPJszEHXsGYjUG234aH/cOjW1wwTbKUZlA=="],
"typescript": ["typescript@7.0.2", "", { "optionalDependencies": { "@typescript/typescript-aix-ppc64": "7.0.2", "@typescript/typescript-darwin-arm64": "7.0.2", "@typescript/typescript-darwin-x64": "7.0.2", "@typescript/typescript-freebsd-arm64": "7.0.2", "@typescript/typescript-freebsd-x64": "7.0.2", "@typescript/typescript-linux-arm": "7.0.2", "@typescript/typescript-linux-arm64": "7.0.2", "@typescript/typescript-linux-loong64": "7.0.2", "@typescript/typescript-linux-mips64el": "7.0.2", "@typescript/typescript-linux-ppc64": "7.0.2", "@typescript/typescript-linux-riscv64": "7.0.2", "@typescript/typescript-linux-s390x": "7.0.2", "@typescript/typescript-linux-x64": "7.0.2", "@typescript/typescript-netbsd-arm64": "7.0.2", "@typescript/typescript-netbsd-x64": "7.0.2", "@typescript/typescript-openbsd-arm64": "7.0.2", "@typescript/typescript-openbsd-x64": "7.0.2", "@typescript/typescript-sunos-x64": "7.0.2", "@typescript/typescript-win32-arm64": "7.0.2", "@typescript/typescript-win32-x64": "7.0.2" }, "bin": { "tsc": "bin/tsc" } }, "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA=="],
"undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
"uuid": ["uuid@11.1.1", "", { "bin": { "uuid": "dist/esm/bin/uuid" } }, "sha512-vIYxrBCC/N/K+Js3qSN88go7kIfNPssr/hHCesKCQNAjmgvYS2oqr69kIufEG+O4+PfezOH4EbIeHCfFov8ZgQ=="],
"zod": ["zod@4.4.3", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="],
}
}

View file

@ -1,2 +0,0 @@
[test]
root = "src/testes"

View file

@ -1,8 +1,29 @@
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); var __defProp = Object.defineProperty;
exports.aleatorio = void 0; 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 aleatorio_exports = {};
__export(aleatorio_exports, {
aleatorio: () => aleatorio
});
module.exports = __toCommonJS(aleatorio_exports);
const alfabeto = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""); const alfabeto = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
const aleatorio = (tamanho) => `eli-${Array.from({ length: tamanho || 8 }) const aleatorio = (tamanho) => `eli-${Array.from({ length: tamanho || 8 }).map(() => alfabeto[(999 * Math.random() | 0) % alfabeto.length]).join("")}`;
.map(() => alfabeto[((999 * Math.random()) | 0) % alfabeto.length]) // Annotate the CommonJS export names for ESM import in node:
.join("")}`; 0 && (module.exports = {
exports.aleatorio = aleatorio; aleatorio
});

View file

@ -1,2 +1,16 @@
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); 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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var auditoria_exports = {};
module.exports = __toCommonJS(auditoria_exports);

View file

@ -1,33 +1,53 @@
"use strict"; "use strict";
/** gerar uma função de cache para uso em memoria */ var __defProp = Object.defineProperty;
Object.defineProperty(exports, "__esModule", { value: true }); var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
exports.cacheMFixo = exports.cacheMemoria = exports.verCacheM = exports.cacheM = void 0; 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 cacheMemoria_exports = {};
__export(cacheMemoria_exports, {
cacheM: () => cacheM,
cacheMFixo: () => cacheMFixo,
cacheMemoria: () => cacheMemoria,
verCacheM: () => verCacheM
});
module.exports = __toCommonJS(cacheMemoria_exports);
const _cache = {}; const _cache = {};
globalThis.cacheMemoria_cache = _cache; globalThis.cacheMemoria_cache = _cache;
const cacheM = (chave, valor, validadeSeg) => { const cacheM = (chave, valor, validadeSeg) => {
// converte a chave e string const txChave = typeof chave == "string" ? chave : typeof chave == "number" ? String(chave) : encodeURIComponent(JSON.stringify(chave));
const txChave = typeof chave == "string" const validade = validadeSeg && (/* @__PURE__ */ new Date()).getTime() + validadeSeg * 1e3;
? chave if (valor !== void 0) {
: typeof chave == "number" _cache[txChave] = {
? String(chave) valor,
: encodeURIComponent(JSON.stringify(chave)); validade
const validade = validadeSeg && new Date().getTime() + validadeSeg * 1000; };
if (valor !== undefined) { }
_cache[txChave] = { const busca = _cache[txChave];
valor, if (busca?.validade && busca.validade < (/* @__PURE__ */ new Date()).getTime()) {
validade, return void 0;
}; }
} return busca?.valor;
const busca = _cache[txChave];
if (busca?.validade && busca.validade < new Date().getTime()) {
return undefined;
}
return busca?.valor;
}; };
exports.cacheM = cacheM;
const verCacheM = () => _cache; const verCacheM = () => _cache;
exports.verCacheM = verCacheM; const cacheMemoria = cacheM;
exports.cacheMemoria = exports.cacheM; const cacheMFixo = (chave) => (valor) => cacheM(chave, valor);
/** para uso fixo dentro de uma função, trava a chave */ // Annotate the CommonJS export names for ESM import in node:
const cacheMFixo = (chave) => (valor) => (0, exports.cacheM)(chave, valor); 0 && (module.exports = {
exports.cacheMFixo = cacheMFixo; cacheM,
cacheMFixo,
cacheMemoria,
verCacheM
});

View file

@ -1,25 +1,53 @@
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); var __defProp = Object.defineProperty;
exports.tipoUsuarioResiduos = exports.tx = exports.camposComuns = exports.uuid_null = void 0; var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
exports.uuid_null = "00000000-0000-0000-0000-000000000000"; var __getOwnPropNames = Object.getOwnPropertyNames;
/** Colunas Presentes n maioria das tabelas */ var __hasOwnProp = Object.prototype.hasOwnProperty;
var camposComuns; var __export = (target, all) => {
(function (camposComuns) { for (var name in all)
camposComuns["codigo"] = "codigo"; __defProp(target, name, { get: all[name], enumerable: true });
camposComuns["excluido"] = "excluido"; };
camposComuns["data_hora_criacao"] = "data_hora_criacao"; var __copyProps = (to, from, except, desc) => {
camposComuns["data_hora_atualizacao"] = "data_hora_atualizacao"; if (from && typeof from === "object" || typeof from === "function") {
camposComuns["codigo_usuario_criacao"] = "codigo_usuario_criacao"; for (let key of __getOwnPropNames(from))
camposComuns["codigo_usuario_atualizacao"] = "codigo_usuario_atualizacao"; if (!__hasOwnProp.call(to, key) && key !== except)
camposComuns["versao"] = "versao"; __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
})(camposComuns || (exports.camposComuns = camposComuns = {})); }
/** Palavras comumente usadas */ return to;
var tx; };
(function (tx) { var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
tx["token"] = "token"; var constantes_exports = {};
})(tx || (exports.tx = tx = {})); __export(constantes_exports, {
var tipoUsuarioResiduos; camposComuns: () => camposComuns,
(function (tipoUsuarioResiduos) { tipoUsuarioResiduos: () => tipoUsuarioResiduos,
tipoUsuarioResiduos["Usuario"] = "usuario"; tx: () => tx,
tipoUsuarioResiduos["Fornecedor"] = "fornecedor"; uuid_null: () => uuid_null
})(tipoUsuarioResiduos || (exports.tipoUsuarioResiduos = tipoUsuarioResiduos = {})); });
module.exports = __toCommonJS(constantes_exports);
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 || {});
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
camposComuns,
tipoUsuarioResiduos,
tx,
uuid_null
});

View file

@ -1,26 +1,73 @@
"use strict"; "use strict";
var __importDefault = (this && this.__importDefault) || function (mod) { var __create = Object.create;
return (mod && mod.__esModule) ? mod : { "default": mod }; 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 });
}; };
Object.defineProperty(exports, "__esModule", { value: true }); var __copyProps = (to, from, except, desc) => {
exports.zFiltro = exports.zOperadores = exports.operadores = void 0; if (from && typeof from === "object" || typeof from === "function") {
const zod_1 = __importDefault(require("zod")); for (let key of __getOwnPropNames(from))
var operadores; if (!__hasOwnProp.call(to, key) && key !== except)
(function (operadores) { __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
operadores["="] = "="; }
operadores["!="] = "!="; return to;
operadores[">"] = ">"; };
operadores[">="] = ">="; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
operadores["<"] = "<"; // If the importer is in node compatibility mode or this is not an ESM
operadores["<="] = "<="; // file that has been converted to a CommonJS file using a Babel-
operadores["like"] = "like"; // compatible transform (i.e. "__esModule" has not been set), then set
operadores["in"] = "in"; // "default" to the CommonJS "module.exports" for node compatibility.
operadores["isNull"] = "isNull"; isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
})(operadores || (exports.operadores = operadores = {})); mod
exports.zOperadores = zod_1.default.enum(["=", "!=", ">", ">=", "<", "<=", "like", "in", "isNull"]); ));
exports.zFiltro = zod_1.default.object({ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
coluna: zod_1.default.string(), var consulta_exports = {};
valor: zod_1.default.any(), __export(consulta_exports, {
operador: exports.zOperadores, operadores: () => operadores,
ou: zod_1.default.boolean().optional(), zFiltro: () => zFiltro,
zOperadores: () => zOperadores
});
module.exports = __toCommonJS(consulta_exports);
var import_zod = __toESM(require("zod"));
var operadores = /* @__PURE__ */ ((operadores2) => {
operadores2["="] = "=";
operadores2["!="] = "!=";
operadores2[">"] = ">";
operadores2[">="] = ">=";
operadores2["<"] = "<";
operadores2["<="] = "<=";
operadores2["like"] = "like";
operadores2["in"] = "in";
operadores2["isNull"] = "isNull";
operadores2["notIn"] = "notIn";
return operadores2;
})(operadores || {});
const zOperadores = import_zod.default.enum([
"=",
"!=",
">",
">=",
"<",
"<=",
"like",
"in",
"isNull",
"notIn"
]);
const zFiltro = import_zod.default.object({
coluna: import_zod.default.string(),
valor: import_zod.default.any(),
operador: zOperadores,
ou: import_zod.default.boolean().optional()
});
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
operadores,
zFiltro,
zOperadores
}); });

View file

@ -1,28 +1,58 @@
"use strict"; "use strict";
var __importDefault = (this && this.__importDefault) || function (mod) { var __create = Object.create;
return (mod && mod.__esModule) ? mod : { "default": mod }; 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 });
}; };
Object.defineProperty(exports, "__esModule", { value: true }); var __copyProps = (to, from, except, desc) => {
exports.definirDayjsbr = void 0; if (from && typeof from === "object" || typeof from === "function") {
const duration_1 = __importDefault(require("dayjs/plugin/duration")); for (let key of __getOwnPropNames(from))
const isSameOrAfter_1 = __importDefault(require("dayjs/plugin/isSameOrAfter")); if (!__hasOwnProp.call(to, key) && key !== except)
const isSameOrBefore_1 = __importDefault(require("dayjs/plugin/isSameOrBefore")); __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
const minMax_1 = __importDefault(require("dayjs/plugin/minMax")); }
const relativeTime_1 = __importDefault(require("dayjs/plugin/relativeTime")); return to;
const timezone_1 = __importDefault(require("dayjs/plugin/timezone")); };
const utc_1 = __importDefault(require("dayjs/plugin/utc")); var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
const weekOfYear_1 = __importDefault(require("dayjs/plugin/weekOfYear")); // If the importer is in node compatibility mode or this is not an ESM
require("dayjs/locale/pt-br"); // 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, {
definirDayjsbr: () => definirDayjsbr
});
module.exports = __toCommonJS(dayjs_exports);
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");
const definirDayjsbr = (dayjsEntrada) => { const definirDayjsbr = (dayjsEntrada) => {
dayjsEntrada.locale("pt-br"); dayjsEntrada.locale("pt-br");
dayjsEntrada.extend(utc_1.default); dayjsEntrada.extend(import_utc.default);
dayjsEntrada.extend(timezone_1.default); dayjsEntrada.extend(import_timezone.default);
dayjsEntrada.extend(weekOfYear_1.default); dayjsEntrada.extend(import_weekOfYear.default);
dayjsEntrada.extend(isSameOrBefore_1.default); dayjsEntrada.extend(import_isSameOrBefore.default);
dayjsEntrada.extend(isSameOrAfter_1.default); dayjsEntrada.extend(import_isSameOrAfter.default);
dayjsEntrada.extend(minMax_1.default); dayjsEntrada.extend(import_minMax.default);
dayjsEntrada.extend(relativeTime_1.default); dayjsEntrada.extend(import_relativeTime.default);
dayjsEntrada.extend(duration_1.default); dayjsEntrada.extend(import_duration.default);
return dayjsEntrada; return dayjsEntrada;
}; };
exports.definirDayjsbr = definirDayjsbr; // Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
definirDayjsbr
});

View file

@ -1,74 +1,52 @@
"use strict"; "use strict";
/** var __defProp = Object.defineProperty;
* Utilitário de configuração do Dayjs focado em compatibilidade com SSR. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
* var __getOwnPropNames = Object.getOwnPropertyNames;
* PROBLEMA: var __hasOwnProp = Object.prototype.hasOwnProperty;
* A importação direta do `dayjs` e seus plugins frequentemente causa conflitos em ambientes var __export = (target, all) => {
* de Renderização do Lado do Servidor (SSR), como Nuxt ou Next.js, devido a discrepâncias for (var name in all)
* na resolução de módulos (ESM vs CJS) e instabilidades de importação. __defProp(target, name, { get: all[name], enumerable: true });
* };
* SOLUÇÃO: var __copyProps = (to, from, except, desc) => {
* Este módulo utiliza o padrão de Injeção de Dependência. Ele expõe apenas tipagens e if (from && typeof from === "object" || typeof from === "function") {
* uma função de configuração (`defineDayjsBr`). A responsabilidade de importar as for (let key of __getOwnPropNames(from))
* bibliotecas "vivas" é delegada à aplicação consumidora (o cliente da função). if (!__hasOwnProp.call(to, key) && key !== except)
* __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
* 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 return to;
* instâncias duplicadas/não inicializadas adequadamente. };
*/ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
Object.defineProperty(exports, "__esModule", { value: true }); var dayjs26_exports = {};
exports.iniciarDayjsBr = exports.defineDayjsBr = void 0; __export(dayjs26_exports, {
/** defineDayjsBr: () => defineDayjsBr,
* Inicializa e configura o Dayjs com o locale 'pt-br' e plugins essenciais. iniciarDayjsBr: () => iniciarDayjsBr
* });
* MODO DE USO: module.exports = __toCommonJS(dayjs26_exports);
* Importe os pacotes reais na sua aplicação e passe-os para esta função. const iniciarDayjsBr = ({
* dayjs,
* @example duration,
* ```ts isSameOrAfter,
* // Em seu arquivo de configuração (ex: plugins/dayjs.ts): isSameOrBefore,
* import dayjs from "dayjs" minMax,
* import duration from "dayjs/plugin/duration" relativeTime,
* import isSameOrAfter from "dayjs/plugin/isSameOrAfter" timezone,
* import isSameOrBefore from "dayjs/plugin/isSameOrBefore" utc,
* import minMax from "dayjs/plugin/minMax" weekOfYear
* import relativeTime from "dayjs/plugin/relativeTime" }) => {
* import timezone from "dayjs/plugin/timezone" dayjs.extend(utc);
* import utc from "dayjs/plugin/utc" dayjs.extend(timezone);
* import weekOfYear from "dayjs/plugin/weekOfYear" dayjs.extend(weekOfYear);
* import { iniciarDayjsBr } from "p-comuns" dayjs.extend(isSameOrBefore);
* import "dayjs/locale/pt-br" // Importante: importar o locale! dayjs.extend(isSameOrAfter);
dayjs.extend(minMax);
* export const dayjsbr = iniciarDayjsBr({ dayjs.extend(relativeTime);
* dayjs, dayjs.extend(duration);
* duration, dayjs.locale("pt-br");
* isSameOrAfter, return dayjs;
* isSameOrBefore,
* minMax,
* relativeTime,
* timezone,
* utc,
* weekOfYear,
* })
* ```
*/
const iniciarDayjsBr = ({ dayjs, duration, isSameOrAfter, isSameOrBefore, minMax, relativeTime, timezone, utc, 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;
}; };
exports.iniciarDayjsBr = iniciarDayjsBr;
/**
* @deprecated Use iniciarDayjsBr em vez de definirDayjsBr. O método defineDayjsBr está obsoleto e será removido em futuras versões.
*/
const defineDayjsBr = iniciarDayjsBr; const defineDayjsBr = iniciarDayjsBr;
exports.defineDayjsBr = defineDayjsBr; // Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
defineDayjsBr,
iniciarDayjsBr
});

View file

@ -1,81 +1,85 @@
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); var __defProp = Object.defineProperty;
exports.iniciarELog = exports.NivelLogDetalhes = exports.NivelLog = void 0; var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
/** Níveis de severidade para o sistema de log estruturado. */ var __getOwnPropNames = Object.getOwnPropertyNames;
var NivelLog; var __hasOwnProp = Object.prototype.hasOwnProperty;
(function (NivelLog) { var __export = (target, all) => {
/** O mais baixo nível, ideal para rastreamento detalhado de fluxo e execução. */ for (var name in all)
NivelLog["RASTREAMENTO"] = "RASTREAMENTO"; __defProp(target, name, { get: all[name], enumerable: true });
/** Usado para informações que ajudam a entender o estado do sistema durante a execução. */
NivelLog["DEPURACAO"] = "DEPURACAO";
/** Informações gerais e eventos do sistema. */
NivelLog["INFORMACAO"] = "INFORMACAO";
/** Eventos inesperados, mas que não impedem o funcionamento do sistema. */
NivelLog["AVISO"] = "AVISO";
/** Erros que impactam o funcionamento do sistema, mas que podem ser recuperados. */
NivelLog["ERRO"] = "ERRO";
/** O nível mais alto de severidade, indicando falhas que requerem atenção imediata. */
NivelLog["CRITICO"] = "CRITICO";
})(NivelLog || (exports.NivelLog = NivelLog = {}));
/** Detalhes de cada nível de log — peso para filtragem, emoji e método do console. */
exports.NivelLogDetalhes = {
[NivelLog.RASTREAMENTO]: { peso: 1, rotulo: "Rastreamento", emoji: "🔍", metodo: "debug" },
[NivelLog.DEPURACAO]: { peso: 2, rotulo: "Depuração", emoji: "🐛", metodo: "debug" },
[NivelLog.INFORMACAO]: { peso: 3, rotulo: "Informação", emoji: "ℹ️", metodo: "info" },
[NivelLog.AVISO]: { peso: 4, rotulo: "Aviso", emoji: "⚠️", metodo: "warn" },
[NivelLog.ERRO]: { peso: 5, rotulo: "Erro", emoji: "❌", metodo: "error" },
[NivelLog.CRITICO]: { peso: 6, rotulo: "Crítico", emoji: "🔥", metodo: "error" },
}; };
/** var __copyProps = (to, from, except, desc) => {
* Inicializa o sistema de log estruturado. if (from && typeof from === "object" || typeof from === "function") {
* for (let key of __getOwnPropNames(from))
* @param opcoes.app - Identificador da aplicação/instância (ex: `"front:e-licencie:12345"`) if (!__hasOwnProp.call(to, key) && key !== except)
* @param opcoes.nivelMinimo - Nível mínimo para exibição no console (padrão: INFORMACAO) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
* @param opcoes.arquivamento - Callback opcional para persistir/enviar as entradas de log }
* return to;
* @example
* ```ts
* const log = iniciarELog({ app: "front:e-licencie:12345" })
*
* log.info({ origem: "criarUsuario()", mensagem: "Usuário criado", dados: { id: "abc-123" } })
* // → ℹ️ [Informação] [front:e-licencie:12345] [criarUsuario()] Usuário criado
* ```
*/
const iniciarELog = (opcoes) => {
const nivel = opcoes.nivelMinimo ?? NivelLog.INFORMACAO;
const pesoMinimo = exports.NivelLogDetalhes[nivel].peso;
const emitir = (nivelLog, pr) => {
const config = exports.NivelLogDetalhes[nivelLog];
if (config.peso < pesoMinimo)
return;
const entrada = {
timestamp: new Date().toISOString(),
nivel: nivelLog,
app: opcoes.app,
origem: pr.origem,
mensagem: pr.mensagem,
...(pr.dados !== undefined ? { dados: pr.dados } : {}),
};
console[config.metodo](`${config.emoji} [${config.rotulo}] [${opcoes.app}] [${pr.origem}] ${pr.mensagem}`, pr.dados !== undefined ? pr.dados : "");
if (opcoes.arquivamento) {
opcoes.arquivamento(entrada, { app: opcoes.app, nivelMinimo: nivel });
}
};
return {
rastreamento: (pr) => emitir(NivelLog.RASTREAMENTO, pr),
depuracao: (pr) => emitir(NivelLog.DEPURACAO, pr),
info: (pr) => emitir(NivelLog.INFORMACAO, pr),
aviso: (pr) => emitir(NivelLog.AVISO, pr),
erro: (pr) => emitir(NivelLog.ERRO, pr),
critico: (pr) => emitir(NivelLog.CRITICO, pr),
};
}; };
exports.iniciarELog = iniciarELog; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
const _log = (0, exports.iniciarELog)({ var eLog_exports = {};
app: "testando", __export(eLog_exports, {
nivelMinimo: NivelLog.INFORMACAO, NivelLog: () => NivelLog,
arquivamento: () => { NivelLogDetalhes: () => NivelLogDetalhes,
// iniciarELog: () => iniciarELog
}, });
module.exports = __toCommonJS(eLog_exports);
var NivelLog = /* @__PURE__ */ ((NivelLog2) => {
NivelLog2["RASTREAMENTO"] = "RASTREAMENTO";
NivelLog2["DEPURACAO"] = "DEPURACAO";
NivelLog2["INFORMACAO"] = "INFORMACAO";
NivelLog2["AVISO"] = "AVISO";
NivelLog2["ERRO"] = "ERRO";
NivelLog2["CRITICO"] = "CRITICO";
return NivelLog2;
})(NivelLog || {});
const NivelLogDetalhes = {
["RASTREAMENTO" /* RASTREAMENTO */]: { peso: 1, rotulo: "Rastreamento", emoji: "\u{1F50D}", metodo: "debug" },
["DEPURACAO" /* DEPURACAO */]: { peso: 2, rotulo: "Depura\xE7\xE3o", emoji: "\u{1F41B}", metodo: "debug" },
["INFORMACAO" /* INFORMACAO */]: { peso: 3, rotulo: "Informa\xE7\xE3o", emoji: "\u2139\uFE0F", metodo: "info" },
["AVISO" /* AVISO */]: { peso: 4, rotulo: "Aviso", emoji: "\u26A0\uFE0F", metodo: "warn" },
["ERRO" /* ERRO */]: { peso: 5, rotulo: "Erro", emoji: "\u274C", metodo: "error" },
["CRITICO" /* CRITICO */]: { peso: 6, rotulo: "Cr\xEDtico", emoji: "\u{1F525}", metodo: "error" }
};
const iniciarELog = (opcoes) => {
const nivel = opcoes.nivelMinimo ?? "INFORMACAO" /* INFORMACAO */;
const pesoMinimo = NivelLogDetalhes[nivel].peso;
const emitir = (nivelLog, pr) => {
const config = NivelLogDetalhes[nivelLog];
if (config.peso < pesoMinimo) return;
const entrada = {
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
nivel: nivelLog,
app: opcoes.app,
origem: pr.origem,
mensagem: pr.mensagem,
...pr.dados !== void 0 ? { dados: pr.dados } : {}
};
console[config.metodo](
`${config.emoji} [${config.rotulo}] [${opcoes.app}] [${pr.origem}] ${pr.mensagem}`,
pr.dados !== void 0 ? pr.dados : ""
);
if (opcoes.arquivamento) {
opcoes.arquivamento(entrada, { app: opcoes.app, nivelMinimo: nivel });
}
};
return {
rastreamento: (pr) => emitir("RASTREAMENTO" /* RASTREAMENTO */, pr),
depuracao: (pr) => emitir("DEPURACAO" /* DEPURACAO */, pr),
info: (pr) => emitir("INFORMACAO" /* INFORMACAO */, pr),
aviso: (pr) => emitir("AVISO" /* AVISO */, pr),
erro: (pr) => emitir("ERRO" /* ERRO */, pr),
critico: (pr) => emitir("CRITICO" /* CRITICO */, pr)
};
};
const _log = iniciarELog({
app: "testando",
nivelMinimo: "INFORMACAO" /* INFORMACAO */,
arquivamento: () => {
}
});
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
NivelLog,
NivelLogDetalhes,
iniciarELog
}); });
//log.aviso({ origem: "teste", mensagem: "teste" })

View file

@ -1,17 +1,22 @@
"use strict"; "use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { var __defProp = Object.defineProperty;
if (k2 === undefined) k2 = k; var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var desc = Object.getOwnPropertyDescriptor(m, k); var __getOwnPropNames = Object.getOwnPropertyNames;
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { var __hasOwnProp = Object.prototype.hasOwnProperty;
desc = { enumerable: true, get: function() { return m[k]; } }; var __copyProps = (to, from, except, desc) => {
} if (from && typeof from === "object" || typeof from === "function") {
Object.defineProperty(o, k2, desc); for (let key of __getOwnPropNames(from))
}) : (function(o, m, k, k2) { if (!__hasOwnProp.call(to, key) && key !== except)
if (k2 === undefined) k2 = k; __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
o[k2] = m[k]; }
})); return to;
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
}; };
Object.defineProperty(exports, "__esModule", { value: true }); var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
__exportStar(require("./urls"), exports); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var ecosistema_exports = {};
module.exports = __toCommonJS(ecosistema_exports);
__reExport(ecosistema_exports, require("./urls"), module.exports);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
...require("./urls")
});

View file

@ -1,4 +1,28 @@
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); var __defProp = Object.defineProperty;
exports.link_paiol = void 0; var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
exports.link_paiol = "https://paiol.idz.one"; 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 urls_exports = {};
__export(urls_exports, {
link_paiol: () => link_paiol
});
module.exports = __toCommonJS(urls_exports);
const link_paiol = "https://paiol.idz.one";
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
link_paiol
});

View file

@ -1,172 +1,186 @@
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); var __defProp = Object.defineProperty;
exports.tipoArquivo = exports.extensoes = void 0; var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
exports.extensoes = [ var __getOwnPropNames = Object.getOwnPropertyNames;
{ var __hasOwnProp = Object.prototype.hasOwnProperty;
ext: "gif", var __export = (target, all) => {
tipo: "imagem", for (var name in all)
mime: "image/gif", __defProp(target, name, { get: all[name], enumerable: true });
},
{
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ídeo",
mime: "video/mp4",
},
{
ext: "avi",
tipo: "vídeo",
mime: "video/x-msvideo",
},
{
ext: "mkv",
tipo: "vídeo",
mime: "video/x-matroska",
},
{
ext: "mov",
tipo: "vídeo",
mime: "video/quicktime",
},
{
ext: "wmv",
tipo: "vídeo",
mime: "video/x-ms-wmv",
},
{
ext: "flv",
tipo: "vídeo",
mime: "video/x-flv",
},
{
ext: "webm",
tipo: "vídeo",
mime: "video/webm",
},
{
ext: "3gp",
tipo: "vídeo",
mime: "video/3gpp",
},
{
ext: "mpeg",
tipo: "vídeo",
mime: "video/mpeg",
},
];
/**
* Função que retorna o tipo do arquivo
* @param nomeArquivo
* @returns
*/
const tipoArquivo = (nomeArquivo) => {
// extenssão do arquivo
const extArquivo = String(nomeArquivo || "")
.toLocaleLowerCase()
.split(".")
.pop();
// procura a extensão do arquivo na lista de extensões
const extensao = exports.extensoes.find((extensao) => extensao.ext === extArquivo);
// retorna o tipo do arquivo
return extensao?.tipo || "outros";
}; };
exports.tipoArquivo = tipoArquivo; 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 extensoes_exports = {};
__export(extensoes_exports, {
extensoes: () => extensoes,
tipoArquivo: () => tipoArquivo
});
module.exports = __toCommonJS(extensoes_exports);
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";
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
extensoes,
tipoArquivo
});

View file

@ -1,247 +1,159 @@
"use strict"; "use strict";
var __importDefault = (this && this.__importDefault) || function (mod) { var __create = Object.create;
return (mod && mod.__esModule) ? mod : { "default": mod }; 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 });
}; };
Object.defineProperty(exports, "__esModule", { value: true }); var __copyProps = (to, from, except, desc) => {
exports.iniciarFiltroDelta = exports.criarFiltroDelta = exports.zFiltroDelta = exports.zCondicaoFiltroDelta = exports.zColunaFiltroDelta = exports.regexColunaFiltroDelta = exports.operadorFiltroDeltaDetalhes = exports.zOperadorFiltroDelta = void 0; if (from && typeof from === "object" || typeof from === "function") {
const zod_1 = __importDefault(require("zod")); 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 });
* FILTRO DELTA (zFiltroDelta) }
* ============================================================================= return to;
* };
* OBJETIVO 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
* Novo sistema de filtros projetado para maior flexibilidade e geração segura // file that has been converted to a CommonJS file using a Babel-
* de instruções SQL dinâmicas (WHERE). // compatible transform (i.e. "__esModule" has not been set), then set
* // "default" to the CommonJS "module.exports" for node compatibility.
* REGRAS IMPORTANTES (PARA IA) isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
* ----------------------------------------------------------------------------- mod
* - O filtro é composto de duas partes obrigatórias: `condicoes` e `formula`. ));
* - Apenas referências aos `id`s das `condicoes` podem ser usadas na `formula`. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
* - Não use sintaxe baseada em objetos aninhados para agrupamento (ex: { E: [], OU: [] }). Use fórmulas em string. var filtroDelta_exports = {};
* __export(filtroDelta_exports, {
* 1) CONDIÇÕES (`condicoes`): criarFiltroDelta: () => criarFiltroDelta,
* Array de objetos contendo as definições isoladas de cada comparação. iniciarFiltroDelta: () => iniciarFiltroDelta,
* Exemplo: operadorFiltroDeltaDetalhes: () => operadorFiltroDeltaDetalhes,
* [ zColunaFiltroDelta: () => zColunaFiltroDelta,
* { id: "{1}", coluna: "idade", operador: ">=", valor: 18 }, zCondicaoFiltroDelta: () => zCondicaoFiltroDelta,
* { id: "{2}", coluna: "nome", operador: "like", valor: "%pa%" } zFiltroDelta: () => zFiltroDelta,
* ] zOperadorFiltroDelta: () => zOperadorFiltroDelta
* - `id`: Deve SEMPRE seguir o formato {identificador}. Ex: `{c1}`, `{idade_min}`. });
* - `coluna`: O nome da coluna ou um path JSONB válido (ex: `veiculo.ano`). module.exports = __toCommonJS(filtroDelta_exports);
* - `operador`: Um dos valores do tipo `tipoOperadorFiltroDelta` (veja a constante). var import_zod = __toESM(require("zod"));
* const zOperadorFiltroDelta = import_zod.default.enum([">", "<", ">=", "<=", "=", "!=", "in", "like", "\u2229"]);
* 2) FÓRMULA (`formula`): const operadorFiltroDeltaDetalhes = {
* String que define a expressão lógica relacionando as condições através de seus `id`s. ">": {
* Operadores Lógicos Suportados (EM MAIÚSCULO): rotulo: "Maior que",
* - `E` (AND) descricao: "O valor de A deve ser maior que o valor de B"
* - `OU` (OR) },
* - `NAO` (NOT) "<": {
* Suporta o agrupamento lógico usando parênteses `()` rotulo: "Menor que",
* Exemplo válido: "({1} E NAO({2})) OU {3}" descricao: "O valor de A deve ser menor que o valor de B"
* },
* ============================================================================= ">=": {
*/ rotulo: "Maior ou igual a",
/** descricao: "O valor de A deve ser maior ou igual ao valor de B"
* Operadores permitidos para comparação. },
*/ "<=": {
exports.zOperadorFiltroDelta = zod_1.default.enum([">", "<", ">=", "<=", "=", "!=", "in", "like", "∩"]); rotulo: "Menor ou igual a",
exports.operadorFiltroDeltaDetalhes = { descricao: "O valor de A deve ser menor ou igual ao valor de B"
">": { },
rotulo: "Maior que", "=": {
descricao: "O valor de A deve ser maior que o valor de B", rotulo: "Igual a",
}, descricao: "O valor de A deve ser igual ao valor de B"
"<": { },
rotulo: "Menor que", "!=": {
descricao: "O valor de A deve ser menor que o valor de B", rotulo: "Diferente de",
}, descricao: "O valor de A deve ser diferente do valor de B"
">=": { },
rotulo: "Maior ou igual a", in: {
descricao: "O valor de A deve ser maior ou igual ao valor de B", rotulo: "Est\xE1 em",
}, descricao: "O valor de A deve estar presente na cole\xE7\xE3o ou lista definida em B"
"<=": { },
rotulo: "Menor ou igual a", like: {
descricao: "O valor de A deve ser menor ou igual ao valor de B", rotulo: "Cont\xE9m",
}, descricao: "O valor de A deve conter o texto informado em B"
"=": { },
rotulo: "Igual a", "\u2229": {
descricao: "O valor de A deve ser igual ao valor de B", rotulo: "Interse\xE7\xE3o",
}, descricao: "A e B devem possuir pelo menos um elemento em comum"
"!=": { }
rotulo: "Diferente de",
descricao: "O valor de A deve ser diferente do valor de B",
},
in: {
rotulo: "Está em",
descricao: "O valor de A deve estar presente na coleção ou lista definida em B",
},
like: {
rotulo: "Contém",
descricao: "O valor de A deve conter o texto informado em B",
},
"∩": {
rotulo: "Interseção",
descricao: "A e B devem possuir pelo menos um elemento em comum",
},
}; };
/**
* Valida o identificador da condição.
*
* Formato esperado:
* {identificador} ou {identificador:sufixo}
*/
const regexIdCondicaoFiltroDelta = /^\{[\w:]+\}$/; const regexIdCondicaoFiltroDelta = /^\{[\w:]+\}$/;
/** const regexColunaFiltroDelta = /^\w+(\.\w+)*$/;
* Valida nomes de colunas e caminhos jsonb. const zColunaFiltroDelta = import_zod.default.string().regex(regexColunaFiltroDelta, "Coluna inv\xE1lida").describe("nome da coluna ou caminho aninhado do jsonb");
* Permite letras, números, sublinhado (_), ponto (.) e hífen (-) em qualquer combinação. const zCondicaoFiltroDelta = import_zod.default.object({
*/ /**
exports.regexColunaFiltroDelta = /^[\w.-]+$/; * Identificador único da condição.
/** *
* Coluna simples ou caminho aninhado de jsonb. * Exemplo:
*/ * {1}
exports.zColunaFiltroDelta = zod_1.default */
.string() id: import_zod.default.string().describe("id da condi\xE7\xE3o do filtro").regex(regexIdCondicaoFiltroDelta, "O id deve seguir o formato {identificador}"),
.regex(exports.regexColunaFiltroDelta, "Coluna inválida") /**
.describe("nome da coluna ou caminho aninhado do jsonb"); * Nome da coluna ou caminho jsonb.
/** */
* Estrutura individual de uma condição do filtro. coluna: zColunaFiltroDelta,
*/ /**
exports.zCondicaoFiltroDelta = zod_1.default.object({ * Operador da comparação.
/** */
* Identificador único da condição. operador: zOperadorFiltroDelta,
* /**
* Exemplo: * Valor utilizado na comparação.
* {1} */
*/ valor: import_zod.default.any().describe("valor de compara\xE7\xE3o")
id: zod_1.default
.string()
.describe("id da condição do filtro")
.regex(regexIdCondicaoFiltroDelta, "O id deve seguir o formato {identificador}"),
/**
* Nome da coluna ou caminho jsonb.
*/
coluna: exports.zColunaFiltroDelta,
/**
* Operador da comparação.
*/
operador: exports.zOperadorFiltroDelta,
/**
* Valor utilizado na comparação.
*/
valor: zod_1.default.any().describe("valor de comparação"),
}); });
/**
* Verifica se a fórmula possui uma estrutura lógica válida.
*/
const formulaFiltroDeltaValida = (formula) => { const formulaFiltroDeltaValida = (formula) => {
/** const tokensPermitidos = formula.match(/\{[\w:]+\}|\bNAO\b|\bE\b|\bOU\b|\(|\)/g) || [];
* Extrai apenas os tokens permitidos: const formulaReconstruida = tokensPermitidos.join("");
* - referências de condição: {id} ou {id:sufixo} const formulaOriginalSemEspacos = formula.replace(/\s+/g, "");
* - operadores lógicos: E, OU const formulaReconstruidaSemEspacos = formulaReconstruida.replace(/\s+/g, "");
* - negação: NAO(...) if (formulaOriginalSemEspacos !== formulaReconstruidaSemEspacos) {
* - parênteses return false;
*/ }
const tokensPermitidos = formula.match(/\{[\w:]+\}|\bNAO\b|\bE\b|\bOU\b|\(|\)/g) || []; const expressaoLogica = formula.replace(/\{[\w:]+\}/g, "true").replace(/\bNAO\b/g, "!").replace(/\bE\b/g, "&&").replace(/\bOU\b/g, "||");
/** try {
* Reconstrói a fórmula usando apenas os tokens válidos. new Function(`return (${expressaoLogica})`)();
*/ return true;
const formulaReconstruida = tokensPermitidos.join(""); } catch {
/** return false;
* Remove espaços para comparar o texto original com o texto reconstruído. }
*/
const formulaOriginalSemEspacos = formula.replace(/\s+/g, "");
const formulaReconstruidaSemEspacos = formulaReconstruida.replace(/\s+/g, "");
/**
* Se forem diferentes, há conteúdo não permitido na fórmula.
*/
if (formulaOriginalSemEspacos !== formulaReconstruidaSemEspacos) {
return false;
}
/**
* Converte a fórmula para uma expressão JavaScript equivalente.
*
* NAO(x) → !x
* E → &&
* OU → ||
*/
const expressaoLogica = formula
.replace(/\{[\w:]+\}/g, "true")
.replace(/\bNAO\b/g, "!")
.replace(/\bE\b/g, "&&")
.replace(/\bOU\b/g, "||");
try {
/**
* Valida a ordem dos operadores, parênteses e estrutura lógica geral.
*/
new Function(`return (${expressaoLogica})`)();
return true;
}
catch {
return false;
}
}; };
/** const zFiltroDelta = import_zod.default.object({
* Estrutura principal do filtro delta. /**
*/ * Lista de condições disponíveis.
exports.zFiltroDelta = zod_1.default */
.object({ condicoes: import_zod.default.array(zCondicaoFiltroDelta),
/** /**
* Lista de condições disponíveis. * Fórmula lógica que combina as condições.
*/ */
condicoes: zod_1.default.array(exports.zCondicaoFiltroDelta), formula: import_zod.default.string().refine(formulaFiltroDeltaValida, {
/** message: "F\xF3rmula inv\xE1lida. Use apenas refer\xEAncias de condi\xE7\xF5es {id} ou {id:sufixo}, operadores E/OU/NAO e par\xEAnteses."
* Fórmula lógica que combina as condições. })
*/ }).superRefine((value, ctx) => {
formula: zod_1.default.string().refine(formulaFiltroDeltaValida, { const idsCondicoes = new Set(value.condicoes.map((condicao) => condicao.id));
message: "Fórmula inválida. Use apenas referências de condições {id} ou {id:sufixo}, operadores E/OU/NAO e parênteses.", const referenciasFormula = value.formula.match(/\{[\w:]+\}/g) || [];
}), for (const referencia of referenciasFormula) {
}) if (!idsCondicoes.has(referencia)) {
.superRefine((value, ctx) => { ctx.addIssue({
/** code: "custom",
* IDs das condições cadastradas. path: ["formula"],
*/ message: `A refer\xEAncia ${referencia} n\xE3o existe em condicoes.`
const idsCondicoes = new Set(value.condicoes.map((condicao) => condicao.id)); });
/**
* Referências usadas dentro da fórmula.
*/
const referenciasFormula = value.formula.match(/\{[\w:]+\}/g) || [];
/**
* Verifica se toda referência da fórmula existe em condicoes.
*/
for (const referencia of referenciasFormula) {
if (!idsCondicoes.has(referencia)) {
ctx.addIssue({
code: "custom",
path: ["formula"],
message: `A referência ${referencia} não existe em condicoes.`,
});
}
} }
}
}); });
const criarFiltroDelta = (filtro) => exports.zFiltroDelta.parse(filtro); const criarFiltroDelta = (filtro) => zFiltroDelta.parse(filtro);
exports.criarFiltroDelta = criarFiltroDelta;
/**
* Fábrica para criar filtros com colunas estritamente tipadas.
* Útil para autocompletar os nomes das colunas e garantir a estrutura no TypeScript.
*
* @example
* ```ts
* const { criarFiltroDelta } = iniciarFiltroDelta<"nome" | "idade" | "jsonb.propriedade">()
*
* const filtro = criarFiltroDelta({
* condicoes: [
* { id: "{c1}", coluna: "idade", operador: ">", valor: 18 },
* { id: "{c2}", coluna: "nome", operador: "=", valor: "luiz" },
* { id: "{c3}", coluna: "jsonb.propriedade", operador: "=", valor: "valor" },
* ],
* formula: "({c1} E {c2}) OU {c3}",
* })
* ```
*/
const iniciarFiltroDelta = () => { const iniciarFiltroDelta = () => {
return { return {
criarFiltroDelta: exports.criarFiltroDelta, criarFiltroDelta
}; };
}; };
exports.iniciarFiltroDelta = iniciarFiltroDelta; // Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
criarFiltroDelta,
iniciarFiltroDelta,
operadorFiltroDeltaDetalhes,
zColunaFiltroDelta,
zCondicaoFiltroDelta,
zFiltroDelta,
zOperadorFiltroDelta
});

View file

@ -1,13 +1,37 @@
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); var __defProp = Object.defineProperty;
exports.graficos_pilao = void 0; var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
exports.graficos_pilao = { var __getOwnPropNames = Object.getOwnPropertyNames;
Condicionantes: { var __hasOwnProp = Object.prototype.hasOwnProperty;
grafico: "condicionantes-criadas", var __export = (target, all) => {
titulo: "Condicionantes Criadas", for (var name in all)
}, __defProp(target, name, { get: all[name], enumerable: true });
Licenças: {
grafico: "licencas-criadas",
titulo: "Licenças Criadas",
},
}; };
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
});

View file

@ -1,41 +1,70 @@
"use strict"; "use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { var __defProp = Object.defineProperty;
if (k2 === undefined) k2 = k; var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var desc = Object.getOwnPropertyDescriptor(m, k); var __getOwnPropNames = Object.getOwnPropertyNames;
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { var __hasOwnProp = Object.prototype.hasOwnProperty;
desc = { enumerable: true, get: function() { return m[k]; } }; var __copyProps = (to, from, except, desc) => {
} if (from && typeof from === "object" || typeof from === "function") {
Object.defineProperty(o, k2, desc); for (let key of __getOwnPropNames(from))
}) : (function(o, m, k, k2) { if (!__hasOwnProp.call(to, key) && key !== except)
if (k2 === undefined) k2 = k; __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
o[k2] = m[k]; }
})); return to;
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
}; };
Object.defineProperty(exports, "__esModule", { value: true }); var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
__exportStar(require("./aleatorio"), exports); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
__exportStar(require("./auditoria"), exports); var index_exports = {};
__exportStar(require("./cacheMemoria"), exports); module.exports = __toCommonJS(index_exports);
__exportStar(require("./constantes"), exports); __reExport(index_exports, require("./aleatorio"), module.exports);
__exportStar(require("./consulta"), exports); __reExport(index_exports, require("./auditoria"), module.exports);
__exportStar(require("./dayjs26"), exports); __reExport(index_exports, require("./cacheMemoria"), module.exports);
__exportStar(require("./ecosistema"), exports); __reExport(index_exports, require("./constantes"), module.exports);
__exportStar(require("./eLog"), exports); __reExport(index_exports, require("./consulta"), module.exports);
__exportStar(require("./extensoes"), exports); __reExport(index_exports, require("./dayjs26"), module.exports);
__exportStar(require("./extensoes"), exports); __reExport(index_exports, require("./ecosistema"), module.exports);
__exportStar(require("./filtroDelta"), exports); __reExport(index_exports, require("./eLog"), module.exports);
__exportStar(require("./local"), exports); __reExport(index_exports, require("./extensoes"), module.exports);
__exportStar(require("./postgres"), exports); __reExport(index_exports, require("./extensoes"), module.exports);
__exportStar(require("./produtos"), exports); __reExport(index_exports, require("./filtroDelta"), module.exports);
__exportStar(require("./situacoes"), exports); __reExport(index_exports, require("./local"), module.exports);
__exportStar(require("./testes-de-variaveis"), exports); __reExport(index_exports, require("./postgres"), module.exports);
__exportStar(require("./texto_busca"), exports); __reExport(index_exports, require("./produtos"), module.exports);
__exportStar(require("./tipagemRotas"), exports); __reExport(index_exports, require("./situacoes"), module.exports);
__exportStar(require("./tipagemRotas"), exports); __reExport(index_exports, require("./testes-de-variaveis"), module.exports);
__exportStar(require("./unidades_medida"), exports); __reExport(index_exports, require("./texto_busca"), module.exports);
__exportStar(require("./uuid"), exports); __reExport(index_exports, require("./tipagemRotas"), module.exports);
__exportStar(require("./variaveisComuns"), exports); __reExport(index_exports, require("./tipagemRotas"), module.exports);
__exportStar(require("./zCoordenadas"), exports); __reExport(index_exports, require("./unidades_medida"), module.exports);
__exportStar(require("./zDocumento"), exports); __reExport(index_exports, require("./uuid"), module.exports);
__exportStar(require("./zodCustomizados"), exports); __reExport(index_exports, require("./variaveisComuns"), module.exports);
__reExport(index_exports, require("./zCoordenadas"), module.exports);
__reExport(index_exports, require("./zDocumento"), module.exports);
__reExport(index_exports, require("./zodCustomizados"), module.exports);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
...require("./aleatorio"),
...require("./auditoria"),
...require("./cacheMemoria"),
...require("./constantes"),
...require("./consulta"),
...require("./dayjs26"),
...require("./ecosistema"),
...require("./eLog"),
...require("./extensoes"),
...require("./extensoes"),
...require("./filtroDelta"),
...require("./local"),
...require("./postgres"),
...require("./produtos"),
...require("./situacoes"),
...require("./testes-de-variaveis"),
...require("./texto_busca"),
...require("./tipagemRotas"),
...require("./tipagemRotas"),
...require("./unidades_medida"),
...require("./uuid"),
...require("./variaveisComuns"),
...require("./zCoordenadas"),
...require("./zDocumento"),
...require("./zodCustomizados")
});

View file

@ -1,56 +1,63 @@
"use strict"; "use strict";
var __importDefault = (this && this.__importDefault) || function (mod) { var __create = Object.create;
return (mod && mod.__esModule) ? mod : { "default": mod }; var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
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;
}; };
Object.defineProperty(exports, "__esModule", { value: true }); var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
const node_fs_1 = __importDefault(require("node:fs")); // If the importer is in node compatibility mode or this is not an ESM
const node_path_1 = __importDefault(require("node:path")); // file that has been converted to a CommonJS file using a Babel-
/** // compatible transform (i.e. "__esModule" has not been set), then set
* Mescla objetos recursivamente. // "default" to the CommonJS "module.exports" for node compatibility.
* - Adiciona chaves novas isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
* - Sobrescreve valores primitivos mod
* - Mescla objetos aninhados ));
*/ var import_node_fs = __toESM(require("node:fs"));
var import_node_path = __toESM(require("node:path"));
const mesclar = (entrada, novo) => { const mesclar = (entrada, novo) => {
const saida = { ...(entrada || {}) }; const saida = { ...entrada || {} };
for (const [k, v] of Object.entries(novo)) { for (const [k, v] of Object.entries(novo)) {
if (v && typeof v === "object" && !Array.isArray(v)) { if (v && typeof v === "object" && !Array.isArray(v)) {
saida[k] = mesclar(saida[k], v); saida[k] = mesclar(saida[k], v);
} } else {
else { saida[k] = v;
saida[k] = v;
}
} }
return saida; }
return saida;
}; };
/** Lê JSON ou retorna objeto vazio */
const abrirJson = (caminho) => { const abrirJson = (caminho) => {
try { try {
return JSON.parse(node_fs_1.default.readFileSync(caminho, "utf-8")); return JSON.parse(import_node_fs.default.readFileSync(caminho, "utf-8"));
} } catch {
catch { return {};
return {}; }
}
}; };
const settings_json = { const settings_json = {
"editor.defaultFormatter": "biomejs.biome", "editor.defaultFormatter": "biomejs.biome",
"[javascript]": { "editor.defaultFormatter": "biomejs.biome" }, "[javascript]": { "editor.defaultFormatter": "biomejs.biome" },
"[javascriptreact]": { "editor.defaultFormatter": "biomejs.biome" }, "[javascriptreact]": { "editor.defaultFormatter": "biomejs.biome" },
"[typescript]": { "editor.defaultFormatter": "biomejs.biome" }, "[typescript]": { "editor.defaultFormatter": "biomejs.biome" },
"[typescriptreact]": { "editor.defaultFormatter": "biomejs.biome" }, "[typescriptreact]": { "editor.defaultFormatter": "biomejs.biome" },
"[json]": { "editor.defaultFormatter": "biomejs.biome" }, "[json]": { "editor.defaultFormatter": "biomejs.biome" },
"[jsonc]": { "editor.defaultFormatter": "biomejs.biome" }, "[jsonc]": { "editor.defaultFormatter": "biomejs.biome" },
"[vue]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[vue]": { "editor.defaultFormatter": "esbenp.prettier-vscode" },
"editor.codeActionsOnSave": { "editor.codeActionsOnSave": {
"source.organizeImports.biome": "always", "source.organizeImports.biome": "always",
"source.fixAll.biome": "always", "source.fixAll.biome": "always"
}, }
}; };
const caminhoSeting = node_path_1.default.join(process.cwd(), ".vscode/settings.json"); const caminhoSeting = import_node_path.default.join(process.cwd(), ".vscode/settings.json");
// Garante a pasta .vscode import_node_fs.default.mkdirSync(import_node_path.default.dirname(caminhoSeting), { recursive: true });
node_fs_1.default.mkdirSync(node_path_1.default.dirname(caminhoSeting), { recursive: true });
// Mescla e grava
const atual = abrirJson(caminhoSeting); const atual = abrirJson(caminhoSeting);
const final = mesclar(atual, settings_json); const final = mesclar(atual, settings_json);
node_fs_1.default.writeFileSync(caminhoSeting, JSON.stringify(final, null, 2), "utf8"); import_node_fs.default.writeFileSync(caminhoSeting, JSON.stringify(final, null, 2), "utf8");
console.log(`✅ Configurações salvas em ${caminhoSeting}`); console.log(`\u2705 Configura\xE7\xF5es salvas em ${caminhoSeting}`);

View file

@ -1,35 +1,46 @@
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); var __defProp = Object.defineProperty;
exports.localValor = void 0; var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
/** var __getOwnPropNames = Object.getOwnPropertyNames;
* LocalStorage Tipado var __hasOwnProp = Object.prototype.hasOwnProperty;
* Lê ou grava um valor no localStorage, mantendo o tipo genérico <T>. var __export = (target, all) => {
*/ for (var name in all)
const localValor = (chave_, valor) => { __defProp(target, name, { get: all[name], enumerable: true });
const localStorage = "localStorage" in globalThis ? globalThis.localStorage : undefined;
if (typeof localStorage == "undefined")
return null;
const chave = typeof chave_ === "string" ? chave_ : encodeURIComponent(JSON.stringify(chave_));
try {
// Grava valor se fornecido
if (valor !== undefined) {
localStorage.setItem(chave, JSON.stringify(valor));
}
// Lê valor
const v2 = localStorage.getItem(chave);
if (v2 === null)
return null;
try {
return JSON.parse(v2);
}
catch {
// Caso o valor não seja JSON válido
return v2;
}
}
catch {
// Em caso de erro de acesso ao localStorage
return null;
}
}; };
exports.localValor = localValor; 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 local_exports = {};
__export(local_exports, {
localValor: () => localValor
});
module.exports = __toCommonJS(local_exports);
const localValor = (chave_, valor) => {
const localStorage = "localStorage" in globalThis ? globalThis.localStorage : void 0;
if (typeof localStorage == "undefined") return null;
const chave = typeof chave_ === "string" ? chave_ : encodeURIComponent(JSON.stringify(chave_));
try {
if (valor !== void 0) {
localStorage.setItem(chave, JSON.stringify(valor));
}
const v2 = localStorage.getItem(chave);
if (v2 === null) return null;
try {
return JSON.parse(v2);
} catch {
return v2;
}
} catch {
return null;
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
localValor
});

View file

@ -1,26 +1,47 @@
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); var __defProp = Object.defineProperty;
exports.objetoPg = exports.pgObjeto = exports.paraObjetoRegistroPg = void 0; var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
/** var __getOwnPropNames = Object.getOwnPropertyNames;
* Trata um objeto para ser imput para postgres var __hasOwnProp = Object.prototype.hasOwnProperty;
* @param entrada var __export = (target, all) => {
* @returns for (var name in all)
*/ __defProp(target, name, { get: all[name], enumerable: true });
const paraObjetoRegistroPg = (entrada) => {
try {
return Object.fromEntries(Object.entries(entrada).map(([k, v]) => [
k,
v === undefined || v == null
? v
: typeof v == "string" || typeof v == "number" || typeof v == "boolean"
? v
: JSON.stringify(v, null, 2),
]));
}
catch (error) {
throw new Error(`Erro na função paraObjetoRegistroPg: ${error.message} ${error.stack}`);
}
}; };
exports.paraObjetoRegistroPg = paraObjetoRegistroPg; var __copyProps = (to, from, except, desc) => {
exports.pgObjeto = exports.paraObjetoRegistroPg; if (from && typeof from === "object" || typeof from === "function") {
exports.objetoPg = exports.paraObjetoRegistroPg; 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 postgres_exports = {};
__export(postgres_exports, {
objetoPg: () => objetoPg,
paraObjetoRegistroPg: () => paraObjetoRegistroPg,
pgObjeto: () => pgObjeto
});
module.exports = __toCommonJS(postgres_exports);
const paraObjetoRegistroPg = (entrada) => {
try {
return Object.fromEntries(
Object.entries(entrada).map(([k, v]) => [
k,
v === void 0 || v == null ? v : typeof v == "string" || typeof v == "number" || typeof v == "boolean" ? v : JSON.stringify(v, null, 2)
])
);
} catch (error) {
throw new Error(
`Erro na fun\xE7\xE3o paraObjetoRegistroPg: ${error.message} ${error.stack}`
);
}
};
const pgObjeto = paraObjetoRegistroPg;
const objetoPg = paraObjetoRegistroPg;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
objetoPg,
paraObjetoRegistroPg,
pgObjeto
});

View file

@ -1,8 +1,32 @@
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); var __defProp = Object.defineProperty;
exports.Produtos = void 0; var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var Produtos; var __getOwnPropNames = Object.getOwnPropertyNames;
(function (Produtos) { var __hasOwnProp = Object.prototype.hasOwnProperty;
Produtos["e-licencie"] = "e-licencie"; var __export = (target, all) => {
Produtos["gov.e-licencie"] = "gov.e-licencie"; for (var name in all)
})(Produtos || (exports.Produtos = Produtos = {})); __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 produtos_exports = {};
__export(produtos_exports, {
Produtos: () => Produtos
});
module.exports = __toCommonJS(produtos_exports);
var Produtos = /* @__PURE__ */ ((Produtos2) => {
Produtos2["e-licencie"] = "e-licencie";
Produtos2["gov.e-licencie"] = "gov.e-licencie";
return Produtos2;
})(Produtos || {});
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Produtos
});

View file

@ -1,58 +1,77 @@
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); var __defProp = Object.defineProperty;
exports.tiposSituacoesElicencie = void 0; var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var tiposSituacoesElicencie; var __getOwnPropNames = Object.getOwnPropertyNames;
(function (tiposSituacoesElicencie) { var __hasOwnProp = Object.prototype.hasOwnProperty;
tiposSituacoesElicencie["modelo"] = "000_modelo"; var __export = (target, all) => {
tiposSituacoesElicencie["vencida"] = "100_vencida"; for (var name in all)
tiposSituacoesElicencie["expirado"] = "200_expirado"; __defProp(target, name, { get: all[name], enumerable: true });
tiposSituacoesElicencie["alerta"] = "300_alerta"; };
tiposSituacoesElicencie["protocoladafora"] = "350_protocoladafora"; var __copyProps = (to, from, except, desc) => {
tiposSituacoesElicencie["protocolada"] = "400_protocolada"; if (from && typeof from === "object" || typeof from === "function") {
tiposSituacoesElicencie["protocoladaApenas"] = "430_protocolada"; for (let key of __getOwnPropNames(from))
tiposSituacoesElicencie["protocolada_alteracao"] = "450_protocolada"; if (!__hasOwnProp.call(to, key) && key !== except)
tiposSituacoesElicencie["prazo"] = "500_prazo"; __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
tiposSituacoesElicencie["emitida"] = "515_emitida"; }
tiposSituacoesElicencie["valida"] = "518_valida"; return to;
tiposSituacoesElicencie["novo"] = "520_novo"; };
tiposSituacoesElicencie["recebido"] = "521_recebido"; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
tiposSituacoesElicencie["em_andamento"] = "530_em_andamento"; var situacoes_exports = {};
tiposSituacoesElicencie["aguardando"] = "530_aguardando"; __export(situacoes_exports, {
tiposSituacoesElicencie["aguardandoresposta"] = "540_aguardandoresposta"; tiposSituacoesElicencie: () => tiposSituacoesElicencie
tiposSituacoesElicencie["suspensaotemporaria"] = "540_suspensaotemporaria"; });
tiposSituacoesElicencie["cancelada"] = "550_cancelada"; module.exports = __toCommonJS(situacoes_exports);
tiposSituacoesElicencie["execucao"] = "560_execucao"; var tiposSituacoesElicencie = /* @__PURE__ */ ((tiposSituacoesElicencie2) => {
tiposSituacoesElicencie["pendente"] = "570_pendente"; tiposSituacoesElicencie2["modelo"] = "000_modelo";
tiposSituacoesElicencie["executadafora"] = "600_executadafora"; tiposSituacoesElicencie2["vencida"] = "100_vencida";
tiposSituacoesElicencie["executada"] = "700_executada"; tiposSituacoesElicencie2["expirado"] = "200_expirado";
tiposSituacoesElicencie["naoexecutada"] = "701_naoexecutada"; tiposSituacoesElicencie2["alerta"] = "300_alerta";
tiposSituacoesElicencie["concluida"] = "730_concluida"; tiposSituacoesElicencie2["protocoladafora"] = "350_protocoladafora";
tiposSituacoesElicencie["respondido_negado"] = "740_respondido_negado"; tiposSituacoesElicencie2["protocolada"] = "400_protocolada";
tiposSituacoesElicencie["respondido_aceito"] = "741_respondido_aceito"; tiposSituacoesElicencie2["protocoladaApenas"] = "430_protocolada";
tiposSituacoesElicencie["atendidoparcial"] = "742_atendidoparcial"; tiposSituacoesElicencie2["protocolada_alteracao"] = "450_protocolada";
tiposSituacoesElicencie["naoatendido"] = "743_naoatendido"; tiposSituacoesElicencie2["prazo"] = "500_prazo";
tiposSituacoesElicencie["atendido"] = "744_atendido"; tiposSituacoesElicencie2["emitida"] = "515_emitida";
tiposSituacoesElicencie["renovada"] = "760_renovada"; tiposSituacoesElicencie2["valida"] = "518_valida";
tiposSituacoesElicencie["finalizada"] = "800_finalizada"; tiposSituacoesElicencie2["novo"] = "520_novo";
tiposSituacoesElicencie["emitirnota"] = "101_emitirnota"; tiposSituacoesElicencie2["recebido"] = "521_recebido";
tiposSituacoesElicencie["faturaatrasada"] = "301_faturaatrasada"; tiposSituacoesElicencie2["em_andamento"] = "530_em_andamento";
tiposSituacoesElicencie["pagarfatura"] = "302_pagarfatura"; tiposSituacoesElicencie2["aguardando"] = "530_aguardando";
tiposSituacoesElicencie["aguardandoconfirmacao"] = "531_aguardandoconfirmacao"; tiposSituacoesElicencie2["aguardandoresposta"] = "540_aguardandoresposta";
tiposSituacoesElicencie["agendado"] = "701_agendado"; tiposSituacoesElicencie2["suspensaotemporaria"] = "540_suspensaotemporaria";
tiposSituacoesElicencie["faturapaga"] = "801_faturapaga"; tiposSituacoesElicencie2["cancelada"] = "550_cancelada";
tiposSituacoesElicencie["excluida"] = "999_excluida"; tiposSituacoesElicencie2["execucao"] = "560_execucao";
// situacoes outorgas tiposSituacoesElicencie2["pendente"] = "570_pendente";
// Requerido tiposSituacoesElicencie2["executadafora"] = "600_executadafora";
// Vigente tiposSituacoesElicencie2["executada"] = "700_executada";
// Em renovação tiposSituacoesElicencie2["naoexecutada"] = "701_naoexecutada";
// Arquivado tiposSituacoesElicencie2["concluida"] = "730_concluida";
tiposSituacoesElicencie["requerida"] = "401_requerida"; tiposSituacoesElicencie2["respondido_negado"] = "740_respondido_negado";
tiposSituacoesElicencie["vigente"] = "516_vigente"; tiposSituacoesElicencie2["respondido_aceito"] = "741_respondido_aceito";
tiposSituacoesElicencie["emrenovacao"] = "402_emrenovacao"; tiposSituacoesElicencie2["atendidoparcial"] = "742_atendidoparcial";
tiposSituacoesElicencie["arquivada"] = "801_arquivada"; tiposSituacoesElicencie2["naoatendido"] = "743_naoatendido";
tiposSituacoesElicencie["aguardando_sincronizacao"] = "999_aguardando_sincronizacao"; tiposSituacoesElicencie2["atendido"] = "744_atendido";
tiposSituacoesElicencie["nao_conforme"] = "710_nao_conforme"; tiposSituacoesElicencie2["renovada"] = "760_renovada";
tiposSituacoesElicencie["conforme"] = "720_conforme"; tiposSituacoesElicencie2["finalizada"] = "800_finalizada";
tiposSituacoesElicencie["nao_aplicavel"] = "730_nao_aplicavel"; tiposSituacoesElicencie2["emitirnota"] = "101_emitirnota";
tiposSituacoesElicencie["parcial"] = "715_parcial"; tiposSituacoesElicencie2["faturaatrasada"] = "301_faturaatrasada";
})(tiposSituacoesElicencie || (exports.tiposSituacoesElicencie = tiposSituacoesElicencie = {})); tiposSituacoesElicencie2["pagarfatura"] = "302_pagarfatura";
tiposSituacoesElicencie2["aguardandoconfirmacao"] = "531_aguardandoconfirmacao";
tiposSituacoesElicencie2["agendado"] = "701_agendado";
tiposSituacoesElicencie2["faturapaga"] = "801_faturapaga";
tiposSituacoesElicencie2["excluida"] = "999_excluida";
tiposSituacoesElicencie2["requerida"] = "401_requerida";
tiposSituacoesElicencie2["vigente"] = "516_vigente";
tiposSituacoesElicencie2["emrenovacao"] = "402_emrenovacao";
tiposSituacoesElicencie2["arquivada"] = "801_arquivada";
tiposSituacoesElicencie2["aguardando_sincronizacao"] = "999_aguardando_sincronizacao";
tiposSituacoesElicencie2["nao_conforme"] = "710_nao_conforme";
tiposSituacoesElicencie2["conforme"] = "720_conforme";
tiposSituacoesElicencie2["nao_aplicavel"] = "730_nao_aplicavel";
tiposSituacoesElicencie2["parcial"] = "715_parcial";
return tiposSituacoesElicencie2;
})(tiposSituacoesElicencie || {});
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
tiposSituacoesElicencie
});

View file

@ -1,8 +1,6 @@
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); var import_cacheMemoria = require("./cacheMemoria");
const cacheMemoria_1 = require("./cacheMemoria"); var import_texto_busca = require("./texto_busca");
const texto_busca_1 = require("./texto_busca"); console.log("Vari\xE1veis funcionando", import_texto_busca.texto_busca);
// node dist-back/teste.mjs (0, import_cacheMemoria.cacheM)(1, { Jaca: Promise.resolve() });
console.log("Variáveis funcionando", texto_busca_1.texto_busca); console.log("cache:", (0, import_cacheMemoria.cacheM)(1));
(0, cacheMemoria_1.cacheM)(1, { Jaca: Promise.resolve() });
console.log("cache:", (0, cacheMemoria_1.cacheM)(1));

View file

@ -1,18 +1,24 @@
"use strict"; "use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { var __defProp = Object.defineProperty;
if (k2 === undefined) k2 = k; var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var desc = Object.getOwnPropertyDescriptor(m, k); var __getOwnPropNames = Object.getOwnPropertyNames;
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { var __hasOwnProp = Object.prototype.hasOwnProperty;
desc = { enumerable: true, get: function() { return m[k]; } }; var __copyProps = (to, from, except, desc) => {
} if (from && typeof from === "object" || typeof from === "function") {
Object.defineProperty(o, k2, desc); for (let key of __getOwnPropNames(from))
}) : (function(o, m, k, k2) { if (!__hasOwnProp.call(to, key) && key !== except)
if (k2 === undefined) k2 = k; __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
o[k2] = m[k]; }
})); return to;
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
}; };
Object.defineProperty(exports, "__esModule", { value: true }); var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
__exportStar(require("./umaFuncao"), exports); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
__exportStar(require("./umaVariavel"), exports); 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

@ -1,5 +1,28 @@
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); var __defProp = Object.defineProperty;
exports.umaFuncao = void 0; var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
const umaFuncao = () => "Olá Mundo! (função)"; var __getOwnPropNames = Object.getOwnPropertyNames;
exports.umaFuncao = umaFuncao; 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 umaFuncao_exports = {};
__export(umaFuncao_exports, {
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
});

View file

@ -1,4 +1,28 @@
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); var __defProp = Object.defineProperty;
exports.umaVariavel = void 0; var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
exports.umaVariavel = "Olá Mundo! (variável)"; 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,23 +1,22 @@
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); var import_vitest = require("vitest");
const bun_test_1 = require("bun:test"); var import_tipagemRotas = require("../tipagemRotas");
const tipagemRotas_1 = require("../tipagemRotas"); (0, import_vitest.describe)("TipagemRotas", () => {
(0, bun_test_1.describe)("TipagemRotas", () => { (0, import_vitest.it)("deve montar _partesCaminho a partir de string ou array, normalizando barras", () => {
(0, bun_test_1.it)("deve montar _partesCaminho a partir de string ou array, normalizando barras", () => { const r1 = new import_tipagemRotas.TipagemRotas({ caminho: "aplicacao/func" });
const r1 = new tipagemRotas_1.TipagemRotas({ caminho: "aplicacao/func" }); (0, import_vitest.expect)(r1.caminho).toBe("/aplicacao/func");
(0, bun_test_1.expect)(r1.caminho).toBe("/aplicacao/func"); const r2 = new import_tipagemRotas.TipagemRotas({
const r2 = new tipagemRotas_1.TipagemRotas({ caminho: ["aplicacao", "func"]
caminho: ["aplicacao", "func"],
});
(0, bun_test_1.expect)(r2.caminho).toBe("/aplicacao/func");
const r3 = new tipagemRotas_1.TipagemRotas({ caminho: "/a//b///c/" });
(0, bun_test_1.expect)(r3.caminho).toBe("/a/b/c");
});
(0, bun_test_1.it)("Valores de entrada com mesmo valor dos valores de saída", () => {
const r1 = new tipagemRotas_1.TipagemRotas({ caminho: "aplicacao/func" });
const objetoEntrada = { idade: 21, nome: "João" };
const rota = r1.endereco(objetoEntrada);
const parametros = r1.parametros(rota);
(0, bun_test_1.expect)(parametros.nome).toBe(objetoEntrada.nome);
}); });
(0, import_vitest.expect)(r2.caminho).toBe("/aplicacao/func");
const r3 = new import_tipagemRotas.TipagemRotas({ caminho: "/a//b///c/" });
(0, import_vitest.expect)(r3.caminho).toBe("/a/b/c");
});
(0, import_vitest.it)("Valores de entrada com mesmo valor dos valores de sa\xEDda", () => {
const r1 = new import_tipagemRotas.TipagemRotas({ caminho: "aplicacao/func" });
const objetoEntrada = { idade: 21, nome: "Jo\xE3o" };
const rota = r1.endereco(objetoEntrada);
const parametros = r1.parametros(rota);
(0, import_vitest.expect)(parametros.nome).toBe(objetoEntrada.nome);
});
}); });

View file

@ -1,111 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const bun_test_1 = require("bun:test");
const filtroDelta_1 = require("../filtroDelta");
(0, bun_test_1.describe)("filtroDelta - validação de colunas", () => {
(0, bun_test_1.it)("deve validar nomes de colunas e propriedades contendo qualquer combinação de \\w, . e -", () => {
const colunasValidasCombinadas = [
"coluna-teste",
"dados.item-1",
"minha-tabela.meu-campo",
"uuid-550e8400-e29b-41d4-a716-446655440000",
"objeto-a.propriedade-b.campo_c",
"campo-1",
"parametro-a-b-c",
"coluna.",
".coluna",
"coluna..sub",
"a-b.c-d.e",
"-coluna-",
"..",
".",
"-",
"---",
"dados.item_1-x.teste.",
"prefixo..meio--fim",
];
for (const coluna of colunasValidasCombinadas) {
(0, bun_test_1.expect)(filtroDelta_1.regexColunaFiltroDelta.test(coluna)).toBe(true);
(0, bun_test_1.expect)(filtroDelta_1.zColunaFiltroDelta.parse(coluna)).toBe(coluna);
}
});
(0, bun_test_1.it)("deve validar nomes de colunas convencionais com letras, números e sublinhados", () => {
const colunasConvencionais = [
"nome",
"idade",
"usuario_id",
"_id",
"dados.propriedade",
"tabela.campo_123.sub_valor",
];
for (const coluna of colunasConvencionais) {
(0, bun_test_1.expect)(filtroDelta_1.regexColunaFiltroDelta.test(coluna)).toBe(true);
(0, bun_test_1.expect)(filtroDelta_1.zColunaFiltroDelta.parse(coluna)).toBe(coluna);
}
});
(0, bun_test_1.it)("deve rejeitar nomes de colunas inválidos", () => {
const colunasInvalidas = [
"",
"coluna com espaco",
"coluna;drop",
"coluna/sub",
"coluna@dominio",
"coluna#1",
"coluna$valor",
"coluna'teste'",
'coluna"teste"',
"(coluna)",
"coluna=1",
"coluna\nteste",
];
for (const coluna of colunasInvalidas) {
(0, bun_test_1.expect)(filtroDelta_1.regexColunaFiltroDelta.test(coluna)).toBe(false);
(0, bun_test_1.expect)(() => filtroDelta_1.zColunaFiltroDelta.parse(coluna)).toThrow("Coluna inválida");
}
});
(0, bun_test_1.it)("deve permitir criar filtro delta completo com colunas contendo hífen", () => {
const filtro = {
condicoes: [
{
id: "{c1}",
coluna: "dados-usuario.primeiro-nome",
operador: "=",
valor: "Luiz",
},
{
id: "{c2}",
coluna: "configuracao-sistema.status-ativo",
operador: "=",
valor: true,
},
],
formula: "{c1} E {c2}",
};
const resultado = filtroDelta_1.zFiltroDelta.parse(filtro);
(0, bun_test_1.expect)(resultado.condicoes).toHaveLength(2);
(0, bun_test_1.expect)(resultado.condicoes[0].coluna).toBe("dados-usuario.primeiro-nome");
(0, bun_test_1.expect)(resultado.condicoes[1].coluna).toBe("configuracao-sistema.status-ativo");
});
(0, bun_test_1.it)("deve funcionar com a fábrica iniciarFiltroDelta usando tipos de colunas com hífen", () => {
const { criarFiltroDelta } = (0, filtroDelta_1.iniciarFiltroDelta)();
const filtro = criarFiltroDelta({
condicoes: [
{
id: "{1}",
coluna: "item-id",
operador: "!=",
valor: "abc",
},
{
id: "{2}",
coluna: "parametros.taxa-padrao",
operador: ">=",
valor: 10,
},
],
formula: "{1} OU {2}",
});
(0, bun_test_1.expect)(filtro.condicoes[0].coluna).toBe("item-id");
(0, bun_test_1.expect)(filtro.condicoes[1].coluna).toBe("parametros.taxa-padrao");
});
});

View file

@ -1,14 +1,30 @@
"use strict"; "use strict";
/** gerar o texto de busca removendo caracteres especies e caixa alta */ var __defProp = Object.defineProperty;
Object.defineProperty(exports, "__esModule", { value: true }); var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
exports.texto_busca = void 0; var __getOwnPropNames = Object.getOwnPropertyNames;
const texto_busca = (...texto) => texto var __hasOwnProp = Object.prototype.hasOwnProperty;
.map((txt) => txt === null || txt === undefined var __export = (target, all) => {
? "" for (var name in all)
: String(txt) __defProp(target, name, { get: all[name], enumerable: true });
.normalize("NFD") };
.replace(/[\u0300-\u036f]/g, "") var __copyProps = (to, from, except, desc) => {
.replace(/\s+/g, " ") if (from && typeof from === "object" || typeof from === "function") {
.toLowerCase()) for (let key of __getOwnPropNames(from))
.join(" "); if (!__hasOwnProp.call(to, key) && key !== except)
exports.texto_busca = texto_busca; __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 texto_busca_exports = {};
__export(texto_busca_exports, {
texto_busca: () => texto_busca
});
module.exports = __toCommonJS(texto_busca_exports);
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(" ");
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
texto_busca
});

View file

@ -1,108 +1,116 @@
"use strict"; "use strict";
/** Gerar uma classe que facilita a gestão de rotas com a tipagem das querys var __defProp = Object.defineProperty;
* var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
* Definições: var __getOwnPropNames = Object.getOwnPropertyNames;
* var __hasOwnProp = Object.prototype.hasOwnProperty;
* caminho = "/aplicacao/funcionalidade" var __export = (target, all) => {
* for (var name in all)
* endereco = "http://localhost:3000/aplicacao/funcionalidade" __defProp(target, name, { get: all[name], enumerable: true });
* };
* parametros = {nome:"José"} var __copyProps = (to, from, except, desc) => {
*/ if (from && typeof from === "object" || typeof from === "function") {
Object.defineProperty(exports, "__esModule", { value: true }); for (let key of __getOwnPropNames(from))
exports.TipagemRotas = void 0; 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 tipagemRotas_exports = {};
__export(tipagemRotas_exports, {
TipagemRotas: () => TipagemRotas
});
module.exports = __toCommonJS(tipagemRotas_exports);
class TipagemRotas { class TipagemRotas {
/** Ao criar novo obijeto de tipagem de rota é necessário passar o caminho parcial /** Ao criar novo obijeto de tipagem de rota é necessário passar o caminho parcial
** export const mCaminho = new TipagemRotas<{q:string}>("aplicacao","funcionalidade") ** export const mCaminho = new TipagemRotas<{q:string}>("aplicacao","funcionalidade")
*/ */
constructor({ caminho, acaoIr, rotulo, }) { constructor({
this._partesCaminho = []; caminho,
this._acaoIr = acaoIr; acaoIr,
this._partesCaminho = (Array.isArray(caminho) ? caminho : [caminho]) rotulo
.filter(Boolean) }) {
.map((a) => String(a)) this._partesCaminho = [];
.flatMap((a) => a.split("/")) this._acaoIr = acaoIr;
.filter(Boolean); this._partesCaminho = (Array.isArray(caminho) ? caminho : [caminho]).filter(Boolean).map((a) => String(a)).flatMap((a) => a.split("/")).filter(Boolean);
this.rotulo = rotulo; this.rotulo = rotulo;
}
/** 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 win = typeof globalThis !== "undefined" && globalThis.window || void 0;
const url = new URL(win ? win.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), JSON.stringify(value));
} }
/** Retorna o caminho completo da rota url.hash = "";
** console.log(mCaminho.caminho) if (usarComoHash) {
** "/caminho" url.hash = `#${url.search}`;
*/ url.search = "";
get caminho() {
const ret = `/${this._partesCaminho.join("/")}`;
return ret;
} }
/** Define o caminho completo da rota return url.href;
** mCaminho.caminho = "/novoCaminho" }
** console.log(mCaminho.caminho) /** Vai para a url
** "/novoCaminho" ** mCaminho.ir({q:"query"})
** */ ** window.location.href = "http://localhost:3000/caminho?q=query"
set caminho(caminhoParcial) { */
this._partesCaminho = caminhoParcial.split("/").filter((parte) => parte); ir(query) {
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 });
}
} }
/** Retorna o caminho completo da rota com a query }
** console.log(mCaminho.resolve({q:"query"})) /** Retorna os parametros da url
** "http://localhost:3000/caminho?q=query" ** console.log(mCaminho.parametros())
*/ ** {q:"query"}
endereco(query, usarComoHash) { */
const win = (typeof globalThis !== "undefined" && globalThis.window) || undefined; parametros(urlEntrada) {
const url = new URL(win ? win.location.href : "http://localhost"); const url = urlEntrada ? new URL(urlEntrada) : new URL(
url.pathname = this.caminho; typeof globalThis !== "undefined" && globalThis.window ? globalThis.window.location.href : "http://localhost"
url.search = ""; );
const queryKeys = Object.entries(query); const query = url.searchParams;
for (const [key, value] of queryKeys) { let queryObj = Object.fromEntries(query.entries());
url.searchParams.set(String(key), JSON.stringify(value)); const hash = url.hash;
} if (hash) {
url.hash = ""; const hashObj = Object.fromEntries(new URLSearchParams(hash.slice(1)).entries());
if (usarComoHash) { queryObj = { ...queryObj, ...hashObj };
url.hash = `#${url.search}`;
url.search = "";
}
return url.href;
} }
/** Vai para a url for (const chave in queryObj) {
** mCaminho.ir({q:"query"}) try {
** window.location.href = "http://localhost:3000/caminho?q=query" queryObj[chave] = JSON.parse(queryObj[chave]);
*/ } catch {
ir(query) { console.log(`[${chave}|${queryObj[chave]}] n\xE3o \xE9 um json v\xE1lido.`);
if (this._acaoIr) { }
this._acaoIr(this.endereco({ ...query }));
}
else {
const win = (typeof globalThis !== "undefined" && globalThis.window) || undefined;
if (win) {
win.location.href = this.endereco({ ...query });
}
}
}
/** Retorna os parametros da url
** console.log(mCaminho.parametros())
** {q:"query"}
*/
parametros(urlEntrada) {
const url = urlEntrada
? new URL(urlEntrada)
: new URL(typeof globalThis !== "undefined" && globalThis.window
? globalThis.window.location.href
: "http://localhost");
const query = url.searchParams;
let queryObj = Object.fromEntries(query.entries());
// pegar hash
const hash = url.hash;
if (hash) {
const hashObj = Object.fromEntries(new URLSearchParams(hash.slice(1)).entries());
queryObj = { ...queryObj, ...hashObj };
}
for (const chave in queryObj) {
try {
queryObj[chave] = JSON.parse(queryObj[chave]);
}
catch {
console.log(`[${chave}|${queryObj[chave]}] não é um json válido.`);
}
}
return queryObj;
} }
return queryObj;
}
} }
exports.TipagemRotas = TipagemRotas; // Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
TipagemRotas
});

View file

@ -1,64 +1,82 @@
"use strict"; "use strict";
/** var __defProp = Object.defineProperty;
* Essa variável se conecta a tabela_lidades var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
* var __getOwnPropNames = Object.getOwnPropertyNames;
* onde sigla se conecta com sigla var __hasOwnProp = Object.prototype.hasOwnProperty;
* var __export = (target, all) => {
* Usuário terá mais opções de unidades, quando fazer o envio para o mtr, usar a opção fornecida pelo usuarios, caso não tenha for (var name in all)
* usar a normalizada __defProp(target, name, { get: all[name], enumerable: true });
*/ };
Object.defineProperty(exports, "__esModule", { value: true }); var __copyProps = (to, from, except, desc) => {
exports.unidades_medida = exports.siglas_unidades_medida = void 0; if (from && typeof from === "object" || typeof from === "function") {
var siglas_unidades_medida; for (let key of __getOwnPropNames(from))
(function (siglas_unidades_medida) { if (!__hasOwnProp.call(to, key) && key !== except)
siglas_unidades_medida["UN"] = "UN"; __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
siglas_unidades_medida["KG"] = "KG"; }
siglas_unidades_medida["TON"] = "TON"; return to;
siglas_unidades_medida["g"] = "g"; };
siglas_unidades_medida["M\u00B3"] = "M\u00B3"; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
siglas_unidades_medida["Lt"] = "Lt"; var unidades_medida_exports = {};
})(siglas_unidades_medida || (exports.siglas_unidades_medida = siglas_unidades_medida = {})); __export(unidades_medida_exports, {
exports.unidades_medida = [ siglas_unidades_medida: () => siglas_unidades_medida,
{ unidades_medida: () => unidades_medida
sigla_unidade: "KG", });
nome: "Quilograma", module.exports = __toCommonJS(unidades_medida_exports);
sigla_normalizada: "KG", var siglas_unidades_medida = /* @__PURE__ */ ((siglas_unidades_medida2) => {
normalizar: (valor) => valor, siglas_unidades_medida2["UN"] = "UN";
tipo: "massa", siglas_unidades_medida2["KG"] = "KG";
}, siglas_unidades_medida2["TON"] = "TON";
{ siglas_unidades_medida2["g"] = "g";
sigla_unidade: "g", siglas_unidades_medida2["M\xB3"] = "M\xB3";
nome: "Grama", siglas_unidades_medida2["Lt"] = "Lt";
sigla_normalizada: "KG", return siglas_unidades_medida2;
normalizar: (valor) => valor / 1000, })(siglas_unidades_medida || {});
tipo: "massa", const unidades_medida = [
}, {
{ sigla_unidade: "KG",
sigla_unidade: "TON", nome: "Quilograma",
nome: "Tonelada", sigla_normalizada: "KG",
sigla_normalizada: "KG", normalizar: (valor) => valor,
normalizar: (valor) => valor * 1000, tipo: "massa"
tipo: "massa", },
}, {
{ sigla_unidade: "g",
sigla_unidade: "Lt", nome: "Grama",
nome: "Litro", sigla_normalizada: "KG",
sigla_normalizada: "Lt", normalizar: (valor) => valor / 1e3,
normalizar: (valor) => valor, tipo: "massa"
tipo: "volume", },
}, {
{ sigla_unidade: "TON",
sigla_unidade: "M³", nome: "Tonelada",
nome: "Metro Cúbico", sigla_normalizada: "KG",
sigla_normalizada: "Lt", normalizar: (valor) => valor * 1e3,
normalizar: (valor) => valor * 1000, tipo: "massa"
tipo: "volume", },
}, {
{ sigla_unidade: "Lt",
sigla_unidade: "UN", nome: "Litro",
nome: "Unidade", sigla_normalizada: "Lt",
sigla_normalizada: "UN", normalizar: (valor) => valor,
normalizar: (valor) => valor, tipo: "volume"
tipo: "unidade", },
}, {
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"
}
]; ];
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
siglas_unidades_medida,
unidades_medida
});

View file

@ -1,50 +1,172 @@
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); var __defProp = Object.defineProperty;
exports.uuid = exports.uuidV4 = exports.uuidV3 = exports.validarUuid = exports.erUuid = void 0; var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
const uuid_1 = require("uuid"); var __getOwnPropNames = Object.getOwnPropertyNames;
/** var __hasOwnProp = Object.prototype.hasOwnProperty;
* Valida se uma string é um UUID válido (qualquer versão). var __export = (target, all) => {
* for (var name in all)
* @param valor - A string que será validada. __defProp(target, name, { get: all[name], enumerable: true });
* @returns booleano indicando se é um UUID válido. };
*/ var __copyProps = (to, from, except, desc) => {
exports.erUuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; if (from && typeof from === "object" || typeof from === "function") {
const validarUuid = (uuid) => { for (let key of __getOwnPropNames(from))
const retorno = exports.erUuid.test(String(uuid || "")); if (!__hasOwnProp.call(to, key) && key !== except)
return retorno; __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 uuid_exports = {};
__export(uuid_exports, {
erUuid: () => erUuid,
uuid: () => uuid,
uuidV3: () => uuidV3,
uuidV4: () => uuidV4,
validarUuid: () => validarUuid
});
module.exports = __toCommonJS(uuid_exports);
const erUuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const validarUuid = (uuid2) => {
return erUuid.test(String(uuid2 || ""));
};
const uuidV4 = () => globalThis.crypto.randomUUID();
const uuid = uuidV4;
const NIL_UUID = "00000000-0000-0000-0000-000000000000";
const rotL = (x, n) => x << n | x >>> 32 - n;
const md5 = (str) => {
const msg = new TextEncoder().encode(str);
const len = msg.length;
const bits = len * 8;
const padLen = len % 64 < 56 ? 56 - len % 64 : 120 - len % 64;
const padded = new Uint8Array(len + padLen + 8);
padded.set(msg);
padded[len] = 128;
const dv = new DataView(padded.buffer);
dv.setUint32(len + padLen, bits >>> 0, true);
dv.setUint32(len + padLen + 4, Math.floor(bits / 2 ** 32), true);
const T = Array.from(
{ length: 64 },
(_, i) => Math.abs(Math.sin(i + 1)) * 2 ** 32 >>> 0
);
const S = [
7,
12,
17,
22,
7,
12,
17,
22,
7,
12,
17,
22,
7,
12,
17,
22,
5,
9,
14,
20,
5,
9,
14,
20,
5,
9,
14,
20,
5,
9,
14,
20,
4,
11,
16,
23,
4,
11,
16,
23,
4,
11,
16,
23,
4,
11,
16,
23,
6,
10,
15,
21,
6,
10,
15,
21,
6,
10,
15,
21,
6,
10,
15,
21
];
let a0 = 1732584193, b0 = 4023233417, c0 = 2562383102, d0 = 271733878;
for (let off = 0; off < padded.length; off += 64) {
const M = [];
for (let j = 0; j < 16; j++) M[j] = dv.getUint32(off + j * 4, true);
let [A, B, C, D] = [a0, b0, c0, d0];
for (let i = 0; i < 64; i++) {
let F, g;
if (i < 16) {
F = B & C | ~B & D;
g = i;
} else if (i < 32) {
F = D & B | ~D & C;
g = (5 * i + 1) % 16;
} else if (i < 48) {
F = B ^ C ^ D;
g = (3 * i + 5) % 16;
} else {
F = C ^ (B | ~D);
g = 7 * i % 16;
}
F = F + A + T[i] + M[g] >>> 0;
A = D;
D = C;
C = B;
B = B + rotL(F, S[i]) >>> 0;
}
a0 = a0 + A >>> 0;
b0 = b0 + B >>> 0;
c0 = c0 + C >>> 0;
d0 = d0 + D >>> 0;
}
const toHexLE = (n) => {
let s = "";
for (let i = 0; i < 4; i++) s += (n >>> i * 8 & 255).toString(16).padStart(2, "0");
return s;
};
return toHexLE(a0) + toHexLE(b0) + toHexLE(c0) + toHexLE(d0);
};
const formatarUuidV3 = (hash) => {
const c = hash.slice(0, 32);
const v = (Number.parseInt(c[16], 16) & 3 | 8).toString(16);
return `${c.slice(0, 8)}-${c.slice(8, 12)}-3${c.slice(13, 16)}-${v}${c.slice(17, 20)}-${c.slice(20, 32)}`;
}; };
exports.validarUuid = validarUuid;
/**
* Gera um UUID determinístico (versão 3) com base em uma chave e um grupo (namespace).
*
* - Usa o algoritmo MD5 (RFC 4122).
* - Sempre retorna o mesmo UUID para a mesma combinação chave + grupo.
* - Caso o grupo não seja informado, usa o UUID "nil" como namespace.
*
* @param chave - Qualquer valor que será convertido em string para gerar o UUID (ex: número, string ou objeto).
* @param grupo - Opcional. Namespace para separar domínios diferentes de UUIDs.
* @returns UUID v3 (determinístico)
*/
const uuidV3 = (chave, grupo) => { const uuidV3 = (chave, grupo) => {
return (0, uuid_1.v3)( const namespace = grupo ? uuidV3(grupo) : NIL_UUID;
// Converte a chave para string (de forma segura) const input = typeof chave === "string" ? chave : typeof chave === "number" ? String(chave) : JSON.stringify(chave);
typeof chave === "string" return formatarUuidV3(md5(namespace + input));
? chave
: typeof chave === "number"
? String(chave)
: JSON.stringify(chave),
// Se um grupo foi fornecido, gera um UUID v3 recursivamente com base nele, senão usa NIL
grupo ? (0, exports.uuidV3)(grupo) : uuid_1.NIL);
}; };
exports.uuidV3 = uuidV3; // Annotate the CommonJS export names for ESM import in node:
/** 0 && (module.exports = {
* Gera um UUID v4 (aleatório, não determinístico). erUuid,
* uuid,
* - Usado quando unicidade é necessária, mas não se exige que seja previsível. uuidV3,
*/ uuidV4,
exports.uuidV4 = uuid_1.v4; validarUuid
/** });
* @deprecated Esta variável será descontinuada em versões futuras.
* Use a função `uuidV4()` diretamente.
*/
exports.uuid = exports.uuidV4;

View file

@ -1,14 +1,31 @@
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); var __defProp = Object.defineProperty;
exports.nomeVariavel = exports.esperar = void 0; 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 variaveisComuns_exports = {};
__export(variaveisComuns_exports, {
esperar: () => esperar,
nomeVariavel: () => nomeVariavel
});
module.exports = __toCommonJS(variaveisComuns_exports);
const esperar = (ms) => new Promise((resolve) => setTimeout(() => resolve(true), ms)); const esperar = (ms) => new Promise((resolve) => setTimeout(() => resolve(true), ms));
exports.esperar = esperar;
/**
* Usado para retronat o no de uma variável, deve ser usado dentro de um objeto
* const nomex = {a: 1, b: 2}
* nomeVariavel({nomex}) // retorna "nomex"
* @param v
* @returns
*/
const nomeVariavel = (v) => Object.keys(v).join("/"); const nomeVariavel = (v) => Object.keys(v).join("/");
exports.nomeVariavel = nomeVariavel; // Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
esperar,
nomeVariavel
});

View file

@ -1,17 +1,44 @@
"use strict"; "use strict";
/** var __create = Object.create;
* No futuro podemos melhorar este Zod para incluir mais formatos de coordenadas. var __defProp = Object.defineProperty;
* var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
*/ var __getOwnPropNames = Object.getOwnPropertyNames;
var __importDefault = (this && this.__importDefault) || function (mod) { var __getProtoOf = Object.getPrototypeOf;
return (mod && mod.__esModule) ? mod : { "default": mod }; var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
}; };
Object.defineProperty(exports, "__esModule", { value: true }); var __copyProps = (to, from, except, desc) => {
exports.zCoordenadas = void 0; if (from && typeof from === "object" || typeof from === "function") {
const zod_1 = __importDefault(require("zod")); for (let key of __getOwnPropNames(from))
exports.zCoordenadas = zod_1.default.object({ if (!__hasOwnProp.call(to, key) && key !== except)
formato: zod_1.default.literal("decimal").default("decimal"), __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
datum: zod_1.default.literal("EPSG:4326").default("EPSG:4326"), }
latitude: zod_1.default.number(), return to;
longitude: zod_1.default.number(), };
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 zCoordenadas_exports = {};
__export(zCoordenadas_exports, {
zCoordenadas: () => zCoordenadas
});
module.exports = __toCommonJS(zCoordenadas_exports);
var import_zod = __toESM(require("zod"));
const zCoordenadas = import_zod.default.object({
formato: import_zod.default.literal("decimal").default("decimal"),
datum: import_zod.default.literal("EPSG:4326").default("EPSG:4326"),
latitude: import_zod.default.number(),
longitude: import_zod.default.number()
});
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
zCoordenadas
}); });

View file

@ -1,55 +1,48 @@
"use strict"; "use strict";
var __importDefault = (this && this.__importDefault) || function (mod) { var __create = Object.create;
return (mod && mod.__esModule) ? mod : { "default": mod }; 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 });
}; };
Object.defineProperty(exports, "__esModule", { value: true }); var __copyProps = (to, from, except, desc) => {
exports.zDocumento = exports.zDocCpf = exports.zDocCnpj = void 0; if (from && typeof from === "object" || typeof from === "function") {
const zod_1 = __importDefault(require("zod")); for (let key of __getOwnPropNames(from))
/** if (!__hasOwnProp.call(to, key) && key !== except)
Resumo – CNPJ Alfanumérico (vigência a partir de julho de 2026) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
A Receita Federal passará a emitir CNPJs alfanuméricos para novas empresas a partir de julho de 2026. O objetivo é ampliar a quantidade de combinações disponíveis e evitar o esgotamento dos números atuais. return to;
};
O que muda? var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
O CNPJ continuará com 14 caracteres. // If the importer is in node compatibility mode or this is not an ESM
Os 12 primeiros caracteres poderão conter letras (A-Z) e números (0-9). // file that has been converted to a CommonJS file using a Babel-
Os 2 dígitos verificadores finais continuarão sendo numéricos. // compatible transform (i.e. "__esModule" has not been set), then set
Exemplo ilustrativo: // "default" to the CommonJS "module.exports" for node compatibility.
Atual: 00.000.000/0001-00 isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
Novo: A1.B2C.3D4/EF56-78 mod
Quem será afetado? ));
Empresas já existentes não terão seus CNPJs alterados. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
A mudança vale apenas para novas inscrições realizadas a partir de julho de 2026. var zDocumento_exports = {};
*/ __export(zDocumento_exports, {
zDocCnpj: () => zDocCnpj,
zDocCpf: () => zDocCpf,
zDocumento: () => zDocumento
});
module.exports = __toCommonJS(zDocumento_exports);
var import_zod = __toESM(require("zod"));
const regexCnpjNumerico = /^\d{2}\.\d{3}\.\d{3}\/\d{4}-\d{2}$/; const regexCnpjNumerico = /^\d{2}\.\d{3}\.\d{3}\/\d{4}-\d{2}$/;
/**
Como ler o novo CNPJ (estrutura)
Tomando como exemplo um CNPJ alfanumérico fictício:
12.ABC.345/0001-67
Como ler:
12.ABC.345 é a raiz (identificação da empresa)
0001 é o sufixo (estabelecimento, geralmente “0001” para matriz)
67 são os dígitos verificadores numéricos
Pontos de atenção:
Letras maiúsculas (não há diferenciação entre maiúscula e minúscula no sistema, mas convenção é maiúscula)
Não usar caracteres especiais: só letras de A a Z e números de 0 a 9
Pontos, barra e hífen mantidos como antes
*/
const regexCnpjAlfanumerico = /^[A-Z0-9]{2}\.[A-Z0-9]{3}\.[A-Z0-9]{3}\/[A-Z0-9]{4}-\d{2}$/i; const regexCnpjAlfanumerico = /^[A-Z0-9]{2}\.[A-Z0-9]{3}\.[A-Z0-9]{3}\/[A-Z0-9]{4}-\d{2}$/i;
const yyyymm = Number(new Date().toISOString().slice(0, 7).replace("-", "")); const yyyymm = Number((/* @__PURE__ */ new Date()).toISOString().slice(0, 7).replace("-", ""));
exports.zDocCnpj = zod_1.default const zDocCnpj = import_zod.default.string().regex(yyyymm < 202407 ? regexCnpjNumerico : regexCnpjAlfanumerico).describe("Documento (CNPJ) no formato XX.XXX.XXX/XXXX-XX");
.string() const zDocCpf = import_zod.default.string().regex(/^\d{3}\.\d{3}\.\d{3}-\d{2}$/).describe("Documento (CPF) no formato XXX.XXX.XXX-XX");
.regex(yyyymm < 202407 ? regexCnpjNumerico : regexCnpjAlfanumerico) const zDocumento = zDocCpf.or(zDocCnpj).describe("CPF ou CNPJ");
.describe("Documento (CNPJ) no formato XX.XXX.XXX/XXXX-XX"); // Annotate the CommonJS export names for ESM import in node:
exports.zDocCpf = zod_1.default 0 && (module.exports = {
.string() zDocCnpj,
.regex(/^\d{3}\.\d{3}\.\d{3}-\d{2}$/) zDocCpf,
.describe("Documento (CPF) no formato XXX.XXX.XXX-XX"); zDocumento
exports.zDocumento = exports.zDocCpf.or(exports.zDocCnpj).describe("CPF ou CNPJ"); });

View file

@ -1,40 +1,56 @@
"use strict"; "use strict";
var __importDefault = (this && this.__importDefault) || function (mod) { var __create = Object.create;
return (mod && mod.__esModule) ? mod : { "default": mod }; 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 });
}; };
Object.defineProperty(exports, "__esModule", { value: true }); var __copyProps = (to, from, except, desc) => {
exports.zNumeroInteiroPositivo = exports.zNumeroInteiro = exports.zNumeroPositivo = exports.zNumero = void 0; if (from && typeof from === "object" || typeof from === "function") {
const zod_1 = __importDefault(require("zod")); 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 zodCustomizados_exports = {};
__export(zodCustomizados_exports, {
zNumero: () => zNumero,
zNumeroInteiro: () => zNumeroInteiro,
zNumeroPositivo: () => zNumeroPositivo
});
module.exports = __toCommonJS(zodCustomizados_exports);
var import_zod = __toESM(require("zod"));
const zPreprocessarNumero = (p) => { const zPreprocessarNumero = (p) => {
if (typeof p === "number") if (typeof p === "number") return p;
return p; if (typeof p !== "string") return p;
if (typeof p !== "string") let p2 = p;
return p; if (p2.includes(",")) {
let p2 = p; p2 = p2.replace(/\./g, "").replace(",", ".");
if (p2.includes(",")) { }
// ponto de milhar → remove; vírgula decimal → troca por ponto p2 = p2.replace(/[^0-9.]/g, "");
p2 = p2.replace(/\./g, "").replace(",", "."); if (p2 == "") return null;
} return Number(p2);
// remove tudo que não seja dígito ou ponto decimal
p2 = p2.replace(/[^0-9.]/g, "");
if (p2 == "")
return null;
return Number(p2);
}; };
/** const zNumero = import_zod.default.preprocess(zPreprocessarNumero, import_zod.default.number());
* Schema numérico que aceita strings legadas e normaliza para `number`. const zNumeroPositivo = import_zod.default.preprocess(zPreprocessarNumero, import_zod.default.number().positive());
* const zNumeroInteiro = import_zod.default.preprocess(zPreprocessarNumero, import_zod.default.number().int());
* O campo **é** um número. O `preprocess` resolve compatibilidade com dados // Annotate the CommonJS export names for ESM import in node:
* antigos onde o frontend enviava strings formatadas (BR ou monetária). 0 && (module.exports = {
* zNumero,
* Formatos de entrada aceitos: zNumeroInteiro,
* - `10` → number direto zNumeroPositivo
* - `10.1` → ponto decimal });
* - `10,1` → vírgula decimal (BR)
* - `1.000,1` → milhar com ponto + vírgula decimal (BR)
* - `R$ 10,01` → prefixo monetário legado
*/
exports.zNumero = zod_1.default.preprocess(zPreprocessarNumero, zod_1.default.number());
exports.zNumeroPositivo = zod_1.default.preprocess(zPreprocessarNumero, zod_1.default.number().positive());
exports.zNumeroInteiro = zod_1.default.preprocess(zPreprocessarNumero, zod_1.default.number().int());
exports.zNumeroInteiroPositivo = zod_1.default.preprocess(zPreprocessarNumero, zod_1.default.number().int().positive());

View file

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

View file

@ -1 +0,0 @@
export {};

View file

@ -1,27 +0,0 @@
/** gerar uma função de cache para uso em memoria */
const _cache = {};
globalThis.cacheMemoria_cache = _cache;
export const cacheM = (chave, valor, validadeSeg) => {
// converte a chave e string
const txChave = typeof chave == "string"
? chave
: typeof chave == "number"
? String(chave)
: encodeURIComponent(JSON.stringify(chave));
const validade = validadeSeg && new Date().getTime() + validadeSeg * 1000;
if (valor !== undefined) {
_cache[txChave] = {
valor,
validade,
};
}
const busca = _cache[txChave];
if (busca?.validade && busca.validade < new Date().getTime()) {
return undefined;
}
return busca?.valor;
};
export const verCacheM = () => _cache;
export const cacheMemoria = cacheM;
/** para uso fixo dentro de uma função, trava a chave */
export const cacheMFixo = (chave) => (valor) => cacheM(chave, valor);

View file

@ -1,22 +0,0 @@
export const uuid_null = "00000000-0000-0000-0000-000000000000";
/** Colunas Presentes n maioria das tabelas */
export var camposComuns;
(function (camposComuns) {
camposComuns["codigo"] = "codigo";
camposComuns["excluido"] = "excluido";
camposComuns["data_hora_criacao"] = "data_hora_criacao";
camposComuns["data_hora_atualizacao"] = "data_hora_atualizacao";
camposComuns["codigo_usuario_criacao"] = "codigo_usuario_criacao";
camposComuns["codigo_usuario_atualizacao"] = "codigo_usuario_atualizacao";
camposComuns["versao"] = "versao";
})(camposComuns || (camposComuns = {}));
/** Palavras comumente usadas */
export var tx;
(function (tx) {
tx["token"] = "token";
})(tx || (tx = {}));
export var tipoUsuarioResiduos;
(function (tipoUsuarioResiduos) {
tipoUsuarioResiduos["Usuario"] = "usuario";
tipoUsuarioResiduos["Fornecedor"] = "fornecedor";
})(tipoUsuarioResiduos || (tipoUsuarioResiduos = {}));

View file

@ -1,20 +0,0 @@
import z from "zod";
export var operadores;
(function (operadores) {
operadores["="] = "=";
operadores["!="] = "!=";
operadores[">"] = ">";
operadores[">="] = ">=";
operadores["<"] = "<";
operadores["<="] = "<=";
operadores["like"] = "like";
operadores["in"] = "in";
operadores["isNull"] = "isNull";
})(operadores || (operadores = {}));
export const zOperadores = z.enum(["=", "!=", ">", ">=", "<", "<=", "like", "in", "isNull"]);
export const zFiltro = z.object({
coluna: z.string(),
valor: z.any(),
operador: zOperadores,
ou: z.boolean().optional(),
});

View file

@ -1,21 +0,0 @@
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";
export const definirDayjsbr = (dayjsEntrada) => {
dayjsEntrada.locale("pt-br");
dayjsEntrada.extend(utc);
dayjsEntrada.extend(timezone);
dayjsEntrada.extend(weekOfYear);
dayjsEntrada.extend(isSameOrBefore);
dayjsEntrada.extend(isSameOrAfter);
dayjsEntrada.extend(minMax);
dayjsEntrada.extend(relativeTime);
dayjsEntrada.extend(duration);
return dayjsEntrada;
};

View file

@ -1,70 +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.
*/
/**
* 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 { iniciarDayjsBr } from "p-comuns"
* import "dayjs/locale/pt-br" // Importante: importar o locale!
* export const dayjsbr = iniciarDayjsBr({
* dayjs,
* duration,
* isSameOrAfter,
* isSameOrBefore,
* minMax,
* relativeTime,
* timezone,
* utc,
* weekOfYear,
* })
* ```
*/
const iniciarDayjsBr = ({ dayjs, duration, isSameOrAfter, isSameOrBefore, minMax, relativeTime, timezone, utc, 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;
};
/**
* @deprecated Use iniciarDayjsBr em vez de definirDayjsBr. O método defineDayjsBr está obsoleto e será removido em futuras versões.
*/
const defineDayjsBr = iniciarDayjsBr;
export { defineDayjsBr, iniciarDayjsBr };

View file

@ -1,77 +0,0 @@
/** Níveis de severidade para o sistema de log estruturado. */
export var NivelLog;
(function (NivelLog) {
/** O mais baixo nível, ideal para rastreamento detalhado de fluxo e execução. */
NivelLog["RASTREAMENTO"] = "RASTREAMENTO";
/** Usado para informações que ajudam a entender o estado do sistema durante a execução. */
NivelLog["DEPURACAO"] = "DEPURACAO";
/** Informações gerais e eventos do sistema. */
NivelLog["INFORMACAO"] = "INFORMACAO";
/** Eventos inesperados, mas que não impedem o funcionamento do sistema. */
NivelLog["AVISO"] = "AVISO";
/** Erros que impactam o funcionamento do sistema, mas que podem ser recuperados. */
NivelLog["ERRO"] = "ERRO";
/** O nível mais alto de severidade, indicando falhas que requerem atenção imediata. */
NivelLog["CRITICO"] = "CRITICO";
})(NivelLog || (NivelLog = {}));
/** Detalhes de cada nível de log — peso para filtragem, emoji e método do console. */
export const NivelLogDetalhes = {
[NivelLog.RASTREAMENTO]: { peso: 1, rotulo: "Rastreamento", emoji: "🔍", metodo: "debug" },
[NivelLog.DEPURACAO]: { peso: 2, rotulo: "Depuração", emoji: "🐛", metodo: "debug" },
[NivelLog.INFORMACAO]: { peso: 3, rotulo: "Informação", emoji: "ℹ️", metodo: "info" },
[NivelLog.AVISO]: { peso: 4, rotulo: "Aviso", emoji: "⚠️", metodo: "warn" },
[NivelLog.ERRO]: { peso: 5, rotulo: "Erro", emoji: "❌", metodo: "error" },
[NivelLog.CRITICO]: { peso: 6, rotulo: "Crítico", emoji: "🔥", metodo: "error" },
};
/**
* Inicializa o sistema de log estruturado.
*
* @param opcoes.app - Identificador da aplicação/instância (ex: `"front:e-licencie:12345"`)
* @param opcoes.nivelMinimo - Nível mínimo para exibição no console (padrão: INFORMACAO)
* @param opcoes.arquivamento - Callback opcional para persistir/enviar as entradas de log
*
* @example
* ```ts
* const log = iniciarELog({ app: "front:e-licencie:12345" })
*
* log.info({ origem: "criarUsuario()", mensagem: "Usuário criado", dados: { id: "abc-123" } })
* // → ℹ️ [Informação] [front:e-licencie:12345] [criarUsuario()] Usuário criado
* ```
*/
export const iniciarELog = (opcoes) => {
const nivel = opcoes.nivelMinimo ?? NivelLog.INFORMACAO;
const pesoMinimo = NivelLogDetalhes[nivel].peso;
const emitir = (nivelLog, pr) => {
const config = NivelLogDetalhes[nivelLog];
if (config.peso < pesoMinimo)
return;
const entrada = {
timestamp: new Date().toISOString(),
nivel: nivelLog,
app: opcoes.app,
origem: pr.origem,
mensagem: pr.mensagem,
...(pr.dados !== undefined ? { dados: pr.dados } : {}),
};
console[config.metodo](`${config.emoji} [${config.rotulo}] [${opcoes.app}] [${pr.origem}] ${pr.mensagem}`, pr.dados !== undefined ? pr.dados : "");
if (opcoes.arquivamento) {
opcoes.arquivamento(entrada, { app: opcoes.app, nivelMinimo: nivel });
}
};
return {
rastreamento: (pr) => emitir(NivelLog.RASTREAMENTO, pr),
depuracao: (pr) => emitir(NivelLog.DEPURACAO, pr),
info: (pr) => emitir(NivelLog.INFORMACAO, pr),
aviso: (pr) => emitir(NivelLog.AVISO, pr),
erro: (pr) => emitir(NivelLog.ERRO, pr),
critico: (pr) => emitir(NivelLog.CRITICO, pr),
};
};
const _log = iniciarELog({
app: "testando",
nivelMinimo: NivelLog.INFORMACAO,
arquivamento: () => {
//
},
});
//log.aviso({ origem: "teste", mensagem: "teste" })

View file

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

View file

@ -1 +0,0 @@
export const link_paiol = "https://paiol.idz.one";

View file

@ -1,168 +0,0 @@
export 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ídeo",
mime: "video/mp4",
},
{
ext: "avi",
tipo: "vídeo",
mime: "video/x-msvideo",
},
{
ext: "mkv",
tipo: "vídeo",
mime: "video/x-matroska",
},
{
ext: "mov",
tipo: "vídeo",
mime: "video/quicktime",
},
{
ext: "wmv",
tipo: "vídeo",
mime: "video/x-ms-wmv",
},
{
ext: "flv",
tipo: "vídeo",
mime: "video/x-flv",
},
{
ext: "webm",
tipo: "vídeo",
mime: "video/webm",
},
{
ext: "3gp",
tipo: "vídeo",
mime: "video/3gpp",
},
{
ext: "mpeg",
tipo: "vídeo",
mime: "video/mpeg",
},
];
/**
* Função que retorna o tipo do arquivo
* @param nomeArquivo
* @returns
*/
export const tipoArquivo = (nomeArquivo) => {
// extenssão do arquivo
const extArquivo = String(nomeArquivo || "")
.toLocaleLowerCase()
.split(".")
.pop();
// procura a extensão do arquivo na lista de extensões
const extensao = extensoes.find((extensao) => extensao.ext === extArquivo);
// retorna o tipo do arquivo
return extensao?.tipo || "outros";
};

View file

@ -1,239 +0,0 @@
import z from "zod";
/**
* =============================================================================
* FILTRO DELTA (zFiltroDelta)
* =============================================================================
*
* OBJETIVO
* -----------------------------------------------------------------------------
* Novo sistema de filtros projetado para maior flexibilidade e geração segura
* de instruções SQL dinâmicas (WHERE).
*
* REGRAS IMPORTANTES (PARA IA)
* -----------------------------------------------------------------------------
* - O filtro é composto de duas partes obrigatórias: `condicoes` e `formula`.
* - Apenas referências aos `id`s das `condicoes` podem ser usadas na `formula`.
* - Não use sintaxe baseada em objetos aninhados para agrupamento (ex: { E: [], OU: [] }). Use fórmulas em string.
*
* 1) CONDIÇÕES (`condicoes`):
* Array de objetos contendo as definições isoladas de cada comparação.
* Exemplo:
* [
* { id: "{1}", coluna: "idade", operador: ">=", valor: 18 },
* { id: "{2}", coluna: "nome", operador: "like", valor: "%pa%" }
* ]
* - `id`: Deve SEMPRE seguir o formato {identificador}. Ex: `{c1}`, `{idade_min}`.
* - `coluna`: O nome da coluna ou um path JSONB válido (ex: `veiculo.ano`).
* - `operador`: Um dos valores do tipo `tipoOperadorFiltroDelta` (veja a constante).
*
* 2) FÓRMULA (`formula`):
* String que define a expressão lógica relacionando as condições através de seus `id`s.
* Operadores Lógicos Suportados (EM MAIÚSCULO):
* - `E` (AND)
* - `OU` (OR)
* - `NAO` (NOT)
* Suporta o agrupamento lógico usando parênteses `()`
* Exemplo válido: "({1} E NAO({2})) OU {3}"
*
* =============================================================================
*/
/**
* Operadores permitidos para comparação.
*/
export const zOperadorFiltroDelta = z.enum([">", "<", ">=", "<=", "=", "!=", "in", "like", "∩"]);
export const operadorFiltroDeltaDetalhes = {
">": {
rotulo: "Maior que",
descricao: "O valor de A deve ser maior que o valor de B",
},
"<": {
rotulo: "Menor que",
descricao: "O valor de A deve ser menor que o valor de B",
},
">=": {
rotulo: "Maior ou igual a",
descricao: "O valor de A deve ser maior ou igual ao valor de B",
},
"<=": {
rotulo: "Menor ou igual a",
descricao: "O valor de A deve ser menor ou igual ao valor de B",
},
"=": {
rotulo: "Igual a",
descricao: "O valor de A deve ser igual ao valor de B",
},
"!=": {
rotulo: "Diferente de",
descricao: "O valor de A deve ser diferente do valor de B",
},
in: {
rotulo: "Está em",
descricao: "O valor de A deve estar presente na coleção ou lista definida em B",
},
like: {
rotulo: "Contém",
descricao: "O valor de A deve conter o texto informado em B",
},
"∩": {
rotulo: "Interseção",
descricao: "A e B devem possuir pelo menos um elemento em comum",
},
};
/**
* Valida o identificador da condição.
*
* Formato esperado:
* {identificador} ou {identificador:sufixo}
*/
const regexIdCondicaoFiltroDelta = /^\{[\w:]+\}$/;
/**
* Valida nomes de colunas e caminhos jsonb.
* Permite letras, números, sublinhado (_), ponto (.) e hífen (-) em qualquer combinação.
*/
export const regexColunaFiltroDelta = /^[\w.-]+$/;
/**
* Coluna simples ou caminho aninhado de jsonb.
*/
export const zColunaFiltroDelta = z
.string()
.regex(regexColunaFiltroDelta, "Coluna inválida")
.describe("nome da coluna ou caminho aninhado do jsonb");
/**
* Estrutura individual de uma condição do filtro.
*/
export const zCondicaoFiltroDelta = z.object({
/**
* Identificador único da condição.
*
* Exemplo:
* {1}
*/
id: z
.string()
.describe("id da condição do filtro")
.regex(regexIdCondicaoFiltroDelta, "O id deve seguir o formato {identificador}"),
/**
* Nome da coluna ou caminho jsonb.
*/
coluna: zColunaFiltroDelta,
/**
* Operador da comparação.
*/
operador: zOperadorFiltroDelta,
/**
* Valor utilizado na comparação.
*/
valor: z.any().describe("valor de comparação"),
});
/**
* Verifica se a fórmula possui uma estrutura lógica válida.
*/
const formulaFiltroDeltaValida = (formula) => {
/**
* Extrai apenas os tokens permitidos:
* - referências de condição: {id} ou {id:sufixo}
* - operadores lógicos: E, OU
* - negação: NAO(...)
* - parênteses
*/
const tokensPermitidos = formula.match(/\{[\w:]+\}|\bNAO\b|\bE\b|\bOU\b|\(|\)/g) || [];
/**
* Reconstrói a fórmula usando apenas os tokens válidos.
*/
const formulaReconstruida = tokensPermitidos.join("");
/**
* Remove espaços para comparar o texto original com o texto reconstruído.
*/
const formulaOriginalSemEspacos = formula.replace(/\s+/g, "");
const formulaReconstruidaSemEspacos = formulaReconstruida.replace(/\s+/g, "");
/**
* Se forem diferentes, há conteúdo não permitido na fórmula.
*/
if (formulaOriginalSemEspacos !== formulaReconstruidaSemEspacos) {
return false;
}
/**
* Converte a fórmula para uma expressão JavaScript equivalente.
*
* NAO(x) → !x
* E → &&
* OU → ||
*/
const expressaoLogica = formula
.replace(/\{[\w:]+\}/g, "true")
.replace(/\bNAO\b/g, "!")
.replace(/\bE\b/g, "&&")
.replace(/\bOU\b/g, "||");
try {
/**
* Valida a ordem dos operadores, parênteses e estrutura lógica geral.
*/
new Function(`return (${expressaoLogica})`)();
return true;
}
catch {
return false;
}
};
/**
* Estrutura principal do filtro delta.
*/
export const zFiltroDelta = z
.object({
/**
* Lista de condições disponíveis.
*/
condicoes: z.array(zCondicaoFiltroDelta),
/**
* Fórmula lógica que combina as condições.
*/
formula: z.string().refine(formulaFiltroDeltaValida, {
message: "Fórmula inválida. Use apenas referências de condições {id} ou {id:sufixo}, operadores E/OU/NAO e parênteses.",
}),
})
.superRefine((value, ctx) => {
/**
* IDs das condições cadastradas.
*/
const idsCondicoes = new Set(value.condicoes.map((condicao) => condicao.id));
/**
* Referências usadas dentro da fórmula.
*/
const referenciasFormula = value.formula.match(/\{[\w:]+\}/g) || [];
/**
* Verifica se toda referência da fórmula existe em condicoes.
*/
for (const referencia of referenciasFormula) {
if (!idsCondicoes.has(referencia)) {
ctx.addIssue({
code: "custom",
path: ["formula"],
message: `A referência ${referencia} não existe em condicoes.`,
});
}
}
});
export const criarFiltroDelta = (filtro) => zFiltroDelta.parse(filtro);
/**
* Fábrica para criar filtros com colunas estritamente tipadas.
* Útil para autocompletar os nomes das colunas e garantir a estrutura no TypeScript.
*
* @example
* ```ts
* const { criarFiltroDelta } = iniciarFiltroDelta<"nome" | "idade" | "jsonb.propriedade">()
*
* const filtro = criarFiltroDelta({
* condicoes: [
* { id: "{c1}", coluna: "idade", operador: ">", valor: 18 },
* { id: "{c2}", coluna: "nome", operador: "=", valor: "luiz" },
* { id: "{c3}", coluna: "jsonb.propriedade", operador: "=", valor: "valor" },
* ],
* formula: "({c1} E {c2}) OU {c3}",
* })
* ```
*/
export const iniciarFiltroDelta = () => {
return {
criarFiltroDelta: criarFiltroDelta,
};
};

View file

@ -1,10 +0,0 @@
export const graficos_pilao = {
Condicionantes: {
grafico: "condicionantes-criadas",
titulo: "Condicionantes Criadas",
},
Licenças: {
grafico: "licencas-criadas",
titulo: "Licenças Criadas",
},
};

688
dist-front/index.d.mts Normal file
View file

@ -0,0 +1,688 @@
import z 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';
declare const aleatorio: (tamanho?: number) => string;
type TipoPayloadAuditoria = {
/** UUID do registro de auditoria */
codigo?: string | null;
/** UUID do usuario da acao (pode ser null se for processo do sistema que não registrou) */
usuario_criacao: string | null;
/** Timestamp ou data de criacao / execucao */
data_criacao: string | Date;
/** Nome exato da tabela no banco que originou o registro */
tabela_origem: string;
/** Código único (UUID) do registro na tabela original */
codigo_origem: string;
/** JSON contendo o snapshot das colunas novas / editadas */
novo: Record<string, any>;
/** JSON contendo o snapshot das colunas antes da edição */
anterior: Record<string, any>;
/** Hash ou controle de versao do item, usualmente preenchido por new.ver_seg */
__versao: string;
/** Tipo de operação que gerou a auditoria */
acao: "criar" | "atualizar" | "deletar" | string;
/** Versão do sistema no momento em que a ação ocorreu */
versao_sistema: string;
};
/** gerar uma função de cache para uso em memoria */
declare const cacheM: <T>(chave: any, valor?: T, validadeSeg?: number) => T | undefined;
declare const verCacheM: () => {
[k: string]: {
/** new Date().getTime() */
validade?: number | undefined;
valor: any;
} | undefined;
};
declare const cacheMemoria: <T>(chave: any, valor?: T, validadeSeg?: number) => T | undefined;
/** para uso fixo dentro de uma função, trava a chave */
declare const cacheMFixo: (chave: any) => <T>(valor?: T) => T | undefined;
declare const uuid_null = "00000000-0000-0000-0000-000000000000";
/** Colunas Presentes n maioria das tabelas */
declare enum camposComuns {
codigo = "codigo",
excluido = "excluido",
data_hora_criacao = "data_hora_criacao",
data_hora_atualizacao = "data_hora_atualizacao",
codigo_usuario_criacao = "codigo_usuario_criacao",
codigo_usuario_atualizacao = "codigo_usuario_atualizacao",
versao = "versao"
}
/** Palavras comumente usadas */
declare enum tx {
token = "token"
}
declare enum tipoUsuarioResiduos {
Usuario = "usuario",
Fornecedor = "fornecedor"
}
declare enum operadores {
"=" = "=",
"!=" = "!=",
">" = ">",
">=" = ">=",
"<" = "<",
"<=" = "<=",
like = "like",
in = "in",
isNull = "isNull",
notIn = "notIn"
}
type tipoFiltro = {
coluna: string;
valor: any;
operador: keyof typeof operadores | operadores;
ou?: boolean;
};
type interfaceConsulta = {
offset?: number;
limit?: number;
filtros?: tipoFiltro[];
ordem?: string;
ordemTipo?: "asc" | "desc";
colunas?: string[];
apenasConsulta?: boolean;
apenasContagem?: boolean;
};
declare const zOperadores: z.ZodEnum<{
"=": "=";
"!=": "!=";
">": ">";
">=": ">=";
"<": "<";
"<=": "<=";
like: "like";
in: "in";
isNull: "isNull";
notIn: "notIn";
}>;
declare const zFiltro: z.ZodObject<{
coluna: z.ZodString;
valor: z.ZodAny;
operador: z.ZodEnum<{
"=": "=";
"!=": "!=";
">": ">";
">=": ">=";
"<": "<";
"<=": "<=";
like: "like";
in: "in";
isNull: "isNull";
notIn: "notIn";
}>;
ou: z.ZodOptional<z.ZodBoolean>;
}, 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 { iniciarDayjsBr } from "p-comuns"
* import "dayjs/locale/pt-br" // Importante: importar o locale!
* export const dayjsbr = iniciarDayjsBr({
* dayjs,
* duration,
* isSameOrAfter,
* isSameOrBefore,
* minMax,
* relativeTime,
* timezone,
* utc,
* weekOfYear,
* })
* ```
*/
declare const iniciarDayjsBr: ({ 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;
/**
* @deprecated Use iniciarDayjsBr em vez de definirDayjsBr. O método defineDayjsBr está obsoleto e será removido em futuras versões.
*/
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";
/** Níveis de severidade para o sistema de log estruturado. */
declare enum NivelLog {
/** O mais baixo nível, ideal para rastreamento detalhado de fluxo e execução. */
RASTREAMENTO = "RASTREAMENTO",
/** Usado para informações que ajudam a entender o estado do sistema durante a execução. */
DEPURACAO = "DEPURACAO",
/** Informações gerais e eventos do sistema. */
INFORMACAO = "INFORMACAO",
/** Eventos inesperados, mas que não impedem o funcionamento do sistema. */
AVISO = "AVISO",
/** Erros que impactam o funcionamento do sistema, mas que podem ser recuperados. */
ERRO = "ERRO",
/** O nível mais alto de severidade, indicando falhas que requerem atenção imediata. */
CRITICO = "CRITICO"
}
type DetalheNivel = {
peso: number;
rotulo: string;
emoji: string;
metodo: "debug" | "info" | "warn" | "error";
};
/** Detalhes de cada nível de log — peso para filtragem, emoji e método do console. */
declare const NivelLogDetalhes: Record<NivelLog, DetalheNivel>;
/** Estrutura de uma entrada de log emitida pelo sistema. */
type EntradaLog = {
timestamp: string;
nivel: keyof typeof NivelLog;
/** Identificador da aplicação/instância (ex: "front:e-licencie:12345"). */
app: string;
/** Local no código de onde o log foi emitido (ex: "criarUsuario()"). */
origem: string;
mensagem: string;
dados?: unknown;
};
/** Interface pública do logger retornado por `iniciarELog`. */
type ELogger = {
rastreamento: (pr: {
origem: string;
mensagem: string;
dados?: unknown;
}) => void;
depuracao: (pr: {
origem: string;
mensagem: string;
dados?: unknown;
}) => void;
info: (pr: {
origem: string;
mensagem: string;
dados?: unknown;
}) => void;
aviso: (pr: {
origem: string;
mensagem: string;
dados?: unknown;
}) => void;
erro: (pr: {
origem: string;
mensagem: string;
dados?: unknown;
}) => void;
critico: (pr: {
origem: string;
mensagem: string;
dados?: unknown;
}) => void;
};
/** Opções de configuração do logger, disponíveis no callback de arquivamento. */
type OpoesELogger = {
app: string;
nivelMinimo: keyof typeof NivelLog;
};
/** Tipo do callback de arquivamento de logs. */
type ArquivamentoLog = (entrada: EntradaLog, opcoes: OpoesELogger) => void;
/**
* Inicializa o sistema de log estruturado.
*
* @param opcoes.app - Identificador da aplicação/instância (ex: `"front:e-licencie:12345"`)
* @param opcoes.nivelMinimo - Nível mínimo para exibição no console (padrão: INFORMACAO)
* @param opcoes.arquivamento - Callback opcional para persistir/enviar as entradas de log
*
* @example
* ```ts
* const log = iniciarELog({ app: "front:e-licencie:12345" })
*
* log.info({ origem: "criarUsuario()", mensagem: "Usuário criado", dados: { id: "abc-123" } })
* // → ℹ️ [Informação] [front:e-licencie:12345] [criarUsuario()] Usuário criado
* ```
*/
declare const iniciarELog: (opcoes: {
app: string;
nivelMinimo?: keyof typeof NivelLog;
arquivamento?: ArquivamentoLog;
}) => ELogger;
type tiposArquivo = "imagem" | "documento" | "vídeo" | "outros";
declare const extensoes: {
ext: string;
tipo: tiposArquivo;
mime: string;
}[];
/**
* Função que retorna o tipo do arquivo
* @param nomeArquivo
* @returns
*/
declare const tipoArquivo: (nomeArquivo: string | null | undefined) => tiposArquivo;
/**
* =============================================================================
* FILTRO DELTA (zFiltroDelta)
* =============================================================================
*
* OBJETIVO
* -----------------------------------------------------------------------------
* Novo sistema de filtros projetado para maior flexibilidade e geração segura
* de instruções SQL dinâmicas (WHERE).
*
* REGRAS IMPORTANTES (PARA IA)
* -----------------------------------------------------------------------------
* - O filtro é composto de duas partes obrigatórias: `condicoes` e `formula`.
* - Apenas referências aos `id`s das `condicoes` podem ser usadas na `formula`.
* - Não use sintaxe baseada em objetos aninhados para agrupamento (ex: { E: [], OU: [] }). Use fórmulas em string.
*
* 1) CONDIÇÕES (`condicoes`):
* Array de objetos contendo as definições isoladas de cada comparação.
* Exemplo:
* [
* { id: "{1}", coluna: "idade", operador: ">=", valor: 18 },
* { id: "{2}", coluna: "nome", operador: "like", valor: "%pa%" }
* ]
* - `id`: Deve SEMPRE seguir o formato {identificador}. Ex: `{c1}`, `{idade_min}`.
* - `coluna`: O nome da coluna ou um path JSONB válido (ex: `veiculo.ano`).
* - `operador`: Um dos valores do tipo `tipoOperadorFiltroDelta` (veja a constante).
*
* 2) FÓRMULA (`formula`):
* String que define a expressão lógica relacionando as condições através de seus `id`s.
* Operadores Lógicos Suportados (EM MAIÚSCULO):
* - `E` (AND)
* - `OU` (OR)
* - `NAO` (NOT)
* Suporta o agrupamento lógico usando parênteses `()`
* Exemplo válido: "({1} E NAO({2})) OU {3}"
*
* =============================================================================
*/
/**
* Operadores permitidos para comparação.
*/
declare const zOperadorFiltroDelta: z.ZodEnum<{
"=": "=";
"!=": "!=";
">": ">";
">=": ">=";
"<": "<";
"<=": "<=";
like: "like";
in: "in";
"\u2229": "∩";
}>;
declare const operadorFiltroDeltaDetalhes: Record<z.infer<typeof zOperadorFiltroDelta>, {
rotulo: string;
descricao: string;
}>;
/**
* Coluna simples ou caminho aninhado de jsonb.
*/
declare const zColunaFiltroDelta: z.ZodString;
/**
* Estrutura individual de uma condição do filtro.
*/
declare const zCondicaoFiltroDelta: z.ZodObject<{
id: z.ZodString;
coluna: z.ZodString;
operador: z.ZodEnum<{
"=": "=";
"!=": "!=";
">": ">";
">=": ">=";
"<": "<";
"<=": "<=";
like: "like";
in: "in";
"\u2229": "∩";
}>;
valor: z.ZodAny;
}, z.core.$strip>;
/**
* Estrutura principal do filtro delta.
*/
declare const zFiltroDelta: z.ZodObject<{
condicoes: z.ZodArray<z.ZodObject<{
id: z.ZodString;
coluna: z.ZodString;
operador: z.ZodEnum<{
"=": "=";
"!=": "!=";
">": ">";
">=": ">=";
"<": "<";
"<=": "<=";
like: "like";
in: "in";
"\u2229": "∩";
}>;
valor: z.ZodAny;
}, z.core.$strip>>;
formula: z.ZodString;
}, z.core.$strip>;
type tipoOperadorFiltroDelta = z.infer<typeof zOperadorFiltroDelta>;
type tipoColunaFiltroDelta = z.infer<typeof zColunaFiltroDelta>;
type tipoCondicaoFiltroDelta = z.infer<typeof zCondicaoFiltroDelta>;
type tipoFiltroDelta = z.infer<typeof zFiltroDelta>;
type tipoCondicaoFiltroDeltaTipado<T extends string> = tipoCondicaoFiltroDelta & {
coluna: T;
};
type tipoFiltroDeltaColunaTipada<T extends string> = {
condicoes: tipoCondicaoFiltroDeltaTipado<T>[];
formula: string;
};
declare const criarFiltroDelta: <T extends string>(filtro: tipoFiltroDeltaColunaTipada<T>) => tipoFiltroDeltaColunaTipada<T>;
/**
* Fábrica para criar filtros com colunas estritamente tipadas.
* Útil para autocompletar os nomes das colunas e garantir a estrutura no TypeScript.
*
* @example
* ```ts
* const { criarFiltroDelta } = iniciarFiltroDelta<"nome" | "idade" | "jsonb.propriedade">()
*
* const filtro = criarFiltroDelta({
* condicoes: [
* { id: "{c1}", coluna: "idade", operador: ">", valor: 18 },
* { id: "{c2}", coluna: "nome", operador: "=", valor: "luiz" },
* { id: "{c3}", coluna: "jsonb.propriedade", operador: "=", valor: "valor" },
* ],
* formula: "({c1} E {c2}) OU {c3}",
* })
* ```
*/
declare const iniciarFiltroDelta: <TColunas extends string>() => {
criarFiltroDelta: (filtro: tipoFiltroDeltaColunaTipada<TColunas>) => tipoFiltroDeltaColunaTipada<TColunas>;
};
/**
* LocalStorage Tipado
* Lê ou grava um valor no localStorage, mantendo o tipo genérico <T>.
*/
declare const localValor: <T>(chave_: string | any, valor?: T | null) => T | null;
/**
* Trata um objeto para ser imput para postgres
* @param entrada
* @returns
*/
declare const paraObjetoRegistroPg: (entrada: {
[k: string]: any;
}) => {
[k: string]: string | boolean | null | undefined | number;
};
declare const pgObjeto: (entrada: {
[k: string]: any;
}) => {
[k: string]: string | boolean | null | undefined | number;
};
declare const objetoPg: (entrada: {
[k: string]: any;
}) => {
[k: string]: string | boolean | null | undefined | number;
};
declare enum Produtos {
"e-licencie" = "e-licencie",
"gov.e-licencie" = "gov.e-licencie"
}
declare enum tiposSituacoesElicencie {
modelo = "000_modelo",
vencida = "100_vencida",
expirado = "200_expirado",
alerta = "300_alerta",
protocoladafora = "350_protocoladafora",
protocolada = "400_protocolada",
protocoladaApenas = "430_protocolada",
protocolada_alteracao = "450_protocolada",
prazo = "500_prazo",
emitida = "515_emitida",
valida = "518_valida",
novo = "520_novo",
recebido = "521_recebido",
em_andamento = "530_em_andamento",
aguardando = "530_aguardando",
aguardandoresposta = "540_aguardandoresposta",
suspensaotemporaria = "540_suspensaotemporaria",
cancelada = "550_cancelada",
execucao = "560_execucao",
pendente = "570_pendente",
executadafora = "600_executadafora",
executada = "700_executada",
naoexecutada = "701_naoexecutada",
concluida = "730_concluida",
respondido_negado = "740_respondido_negado",
respondido_aceito = "741_respondido_aceito",
atendidoparcial = "742_atendidoparcial",
naoatendido = "743_naoatendido",
atendido = "744_atendido",
renovada = "760_renovada",
finalizada = "800_finalizada",
emitirnota = "101_emitirnota",
faturaatrasada = "301_faturaatrasada",
pagarfatura = "302_pagarfatura",
aguardandoconfirmacao = "531_aguardandoconfirmacao",
agendado = "701_agendado",
faturapaga = "801_faturapaga",
excluida = "999_excluida",
requerida = "401_requerida",
vigente = "516_vigente",
emrenovacao = "402_emrenovacao",
arquivada = "801_arquivada",
aguardando_sincronizacao = "999_aguardando_sincronizacao",
nao_conforme = "710_nao_conforme",
conforme = "720_conforme",
nao_aplicavel = "730_nao_aplicavel",
parcial = "715_parcial"
}
declare const umaFuncao: () => string;
declare const umaVariavel = "Ol\u00E1 Mundo! (vari\u00E1vel)";
/** gerar o texto de busca removendo caracteres especies e caixa alta */
declare const texto_busca: (...texto: any[]) => string;
/** Gerar uma classe que facilita a gestão de rotas com a tipagem das querys
*
* Definições:
*
* caminho = "/aplicacao/funcionalidade"
*
* endereco = "http://localhost:3000/aplicacao/funcionalidade"
*
* parametros = {nome:"José"}
*/
declare class TipagemRotas<T extends {
[q: string]: any;
}> {
_partesCaminho: string[];
_acaoIr?: (endereco: string) => undefined;
rotulo: string | undefined;
/** 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, rotulo, }: {
caminho: (string | null | undefined)[] | string;
acaoIr?: undefined | ((endereco: string) => undefined);
/** Rotulo da página
* Inicio | Controle
*/
rotulo?: string;
});
/** Retorna o caminho completo da rota
** console.log(mCaminho.caminho)
** "/caminho"
*/
get caminho(): string;
/** Define o caminho completo da rota
** mCaminho.caminho = "/novoCaminho"
** console.log(mCaminho.caminho)
** "/novoCaminho"
** */
set caminho(caminhoParcial: string);
/** Retorna o caminho completo da rota com a query
** console.log(mCaminho.resolve({q:"query"}))
** "http://localhost:3000/caminho?q=query"
*/
endereco(query: T, usarComoHash?: boolean): string;
/** Vai para a url
** mCaminho.ir({q:"query"})
** window.location.href = "http://localhost:3000/caminho?q=query"
*/
ir(query: T): void;
/** Retorna os parametros da url
** console.log(mCaminho.parametros())
** {q:"query"}
*/
parametros(urlEntrada?: string): Partial<T>;
}
/**
* Essa variável se conecta a tabela_lidades
*
* onde sigla se conecta com sigla
*
* Usuário terá mais opções de unidades, quando fazer o envio para o mtr, usar a opção fornecida pelo usuarios, caso não tenha
* usar a normalizada
*/
declare enum siglas_unidades_medida {
UN = "UN",
KG = "KG",
TON = "TON",
g = "g",
"M³" = "M\u00B3",
Lt = "Lt"
}
declare const unidades_medida: {
sigla_unidade: keyof typeof siglas_unidades_medida;
nome: string;
sigla_normalizada: keyof typeof siglas_unidades_medida;
normalizar: (valor: number) => number;
tipo: "massa" | "volume" | "comprimento" | "unidade";
}[];
/**
* Valida se uma string é um UUID válido (qualquer versão).
*/
declare const erUuid: RegExp;
declare const validarUuid: (uuid: string | number | undefined | null) => boolean;
/**
* Gera um UUID v4 (aleatório, não determinístico).
* Usa `globalThis.crypto.randomUUID()` — disponível em Node 19+, Bun e browsers modernos.
*/
declare const uuidV4: () => string;
/**
* @deprecated Use uuidV4() diretamente.
*/
declare const uuid: () => string;
/**
* Gera um UUID determinístico (versão 3) com base em uma chave e um grupo (namespace).
* Implementação pura JS (MD5), sem dependência de Node.js — funciona em browser e server.
*
* @param chave - Valor a serializar (string, number ou objeto).
* @param grupo - Namespace opcional; se omitido, usa UUID nil.
*/
declare const uuidV3: (chave: unknown, grupo?: unknown) => string;
declare const esperar: (ms: number) => Promise<true>;
/**
* Usado para retronat o no de uma variável, deve ser usado dentro de um objeto
* const nomex = {a: 1, b: 2}
* nomeVariavel({nomex}) // retorna "nomex"
* @param v
* @returns
*/
declare const nomeVariavel: (v: {
[key: string]: any;
}) => string;
/**
* No futuro podemos melhorar este Zod para incluir mais formatos de coordenadas.
*
*/
declare const zCoordenadas: z.ZodObject<{
formato: z.ZodDefault<z.ZodLiteral<"decimal">>;
datum: z.ZodDefault<z.ZodLiteral<"EPSG:4326">>;
latitude: z.ZodNumber;
longitude: z.ZodNumber;
}, z.core.$strip>;
declare const zDocCnpj: z.ZodString;
declare const zDocCpf: z.ZodString;
declare const zDocumento: z.ZodUnion<[z.ZodString, z.ZodString]>;
/**
* Schema numérico que aceita strings legadas e normaliza para `number`.
*
* O campo **é** um número. O `preprocess` resolve compatibilidade com dados
* antigos onde o frontend enviava strings formatadas (BR ou monetária).
*
* Formatos de entrada aceitos:
* - `10` → number direto
* - `10.1` → ponto decimal
* - `10,1` → vírgula decimal (BR)
* - `1.000,1` → milhar com ponto + vírgula decimal (BR)
* - `R$ 10,01` → prefixo monetário legado
*/
declare const zNumero: z.ZodPreprocess<z.ZodNumber>;
declare const zNumeroPositivo: z.ZodPreprocess<z.ZodNumber>;
declare const zNumeroInteiro: z.ZodPreprocess<z.ZodNumber>;
export { type ArquivamentoLog, type ELogger, type EntradaLog, NivelLog, NivelLogDetalhes, type OpoesELogger, Produtos, TipagemRotas, type TipoPayloadAuditoria, aleatorio, cacheM, cacheMFixo, cacheMemoria, camposComuns, criarFiltroDelta, defineDayjsBr, erUuid, esperar, extensoes, iniciarDayjsBr, iniciarELog, iniciarFiltroDelta, type interfaceConsulta, link_paiol, localValor, nomeVariavel, objetoPg, operadorFiltroDeltaDetalhes, operadores, paraObjetoRegistroPg, pgObjeto, siglas_unidades_medida, texto_busca, tipoArquivo, type tipoColunaFiltroDelta, type tipoCondicaoFiltroDelta, type tipoCondicaoFiltroDeltaTipado, type tipoFiltro, type tipoFiltroDelta, type tipoFiltroDeltaColunaTipada, type tipoOperadorFiltroDelta, tipoUsuarioResiduos, tiposSituacoesElicencie, tx, umaFuncao, umaVariavel, unidades_medida, uuid, uuidV3, uuidV4, uuid_null, validarUuid, verCacheM, zColunaFiltroDelta, zCondicaoFiltroDelta, zCoordenadas, zDocCnpj, zDocCpf, zDocumento, zFiltro, zFiltroDelta, zNumero, zNumeroInteiro, zNumeroPositivo, zOperadorFiltroDelta, zOperadores };

View file

@ -1,25 +0,0 @@
export * from "./aleatorio";
export * from "./auditoria";
export * from "./cacheMemoria";
export * from "./constantes";
export * from "./consulta";
export * from "./dayjs26";
export * from "./ecosistema";
export * from "./eLog";
export * from "./extensoes";
export * from "./extensoes";
export * from "./filtroDelta";
export * from "./local";
export * from "./postgres";
export * from "./produtos";
export * from "./situacoes";
export * from "./testes-de-variaveis";
export * from "./texto_busca";
export * from "./tipagemRotas";
export * from "./tipagemRotas";
export * from "./unidades_medida";
export * from "./uuid";
export * from "./variaveisComuns";
export * from "./zCoordenadas";
export * from "./zDocumento";
export * from "./zodCustomizados";

1
dist-front/index.mjs Normal file

File diff suppressed because one or more lines are too long

View file

@ -1,51 +0,0 @@
import fs from "node:fs";
import path from "node:path";
/**
* Mescla objetos recursivamente.
* - Adiciona chaves novas
* - Sobrescreve valores primitivos
* - Mescla objetos aninhados
*/
const mesclar = (entrada, novo) => {
const saida = { ...(entrada || {}) };
for (const [k, v] of Object.entries(novo)) {
if (v && typeof v === "object" && !Array.isArray(v)) {
saida[k] = mesclar(saida[k], v);
}
else {
saida[k] = v;
}
}
return saida;
};
/** Lê JSON ou retorna objeto vazio */
const abrirJson = (caminho) => {
try {
return JSON.parse(fs.readFileSync(caminho, "utf-8"));
}
catch {
return {};
}
};
const settings_json = {
"editor.defaultFormatter": "biomejs.biome",
"[javascript]": { "editor.defaultFormatter": "biomejs.biome" },
"[javascriptreact]": { "editor.defaultFormatter": "biomejs.biome" },
"[typescript]": { "editor.defaultFormatter": "biomejs.biome" },
"[typescriptreact]": { "editor.defaultFormatter": "biomejs.biome" },
"[json]": { "editor.defaultFormatter": "biomejs.biome" },
"[jsonc]": { "editor.defaultFormatter": "biomejs.biome" },
"[vue]": { "editor.defaultFormatter": "esbenp.prettier-vscode" },
"editor.codeActionsOnSave": {
"source.organizeImports.biome": "always",
"source.fixAll.biome": "always",
},
};
const caminhoSeting = path.join(process.cwd(), ".vscode/settings.json");
// Garante a pasta .vscode
fs.mkdirSync(path.dirname(caminhoSeting), { recursive: true });
// Mescla e grava
const atual = abrirJson(caminhoSeting);
const final = mesclar(atual, settings_json);
fs.writeFileSync(caminhoSeting, JSON.stringify(final, null, 2), "utf8");
console.log(`✅ Configurações salvas em ${caminhoSeting}`);

View file

@ -1,31 +0,0 @@
/**
* LocalStorage Tipado
* Lê ou grava um valor no localStorage, mantendo o tipo genérico <T>.
*/
export const localValor = (chave_, valor) => {
const localStorage = "localStorage" in globalThis ? globalThis.localStorage : undefined;
if (typeof localStorage == "undefined")
return null;
const chave = typeof chave_ === "string" ? chave_ : encodeURIComponent(JSON.stringify(chave_));
try {
// Grava valor se fornecido
if (valor !== undefined) {
localStorage.setItem(chave, JSON.stringify(valor));
}
// Lê valor
const v2 = localStorage.getItem(chave);
if (v2 === null)
return null;
try {
return JSON.parse(v2);
}
catch {
// Caso o valor não seja JSON válido
return v2;
}
}
catch {
// Em caso de erro de acesso ao localStorage
return null;
}
};

View file

@ -1,22 +0,0 @@
/**
* Trata um objeto para ser imput para postgres
* @param entrada
* @returns
*/
export const paraObjetoRegistroPg = (entrada) => {
try {
return Object.fromEntries(Object.entries(entrada).map(([k, v]) => [
k,
v === undefined || v == null
? v
: typeof v == "string" || typeof v == "number" || typeof v == "boolean"
? v
: JSON.stringify(v, null, 2),
]));
}
catch (error) {
throw new Error(`Erro na função paraObjetoRegistroPg: ${error.message} ${error.stack}`);
}
};
export const pgObjeto = paraObjetoRegistroPg;
export const objetoPg = paraObjetoRegistroPg;

View file

@ -1,5 +0,0 @@
export var Produtos;
(function (Produtos) {
Produtos["e-licencie"] = "e-licencie";
Produtos["gov.e-licencie"] = "gov.e-licencie";
})(Produtos || (Produtos = {}));

View file

@ -1,55 +0,0 @@
export var tiposSituacoesElicencie;
(function (tiposSituacoesElicencie) {
tiposSituacoesElicencie["modelo"] = "000_modelo";
tiposSituacoesElicencie["vencida"] = "100_vencida";
tiposSituacoesElicencie["expirado"] = "200_expirado";
tiposSituacoesElicencie["alerta"] = "300_alerta";
tiposSituacoesElicencie["protocoladafora"] = "350_protocoladafora";
tiposSituacoesElicencie["protocolada"] = "400_protocolada";
tiposSituacoesElicencie["protocoladaApenas"] = "430_protocolada";
tiposSituacoesElicencie["protocolada_alteracao"] = "450_protocolada";
tiposSituacoesElicencie["prazo"] = "500_prazo";
tiposSituacoesElicencie["emitida"] = "515_emitida";
tiposSituacoesElicencie["valida"] = "518_valida";
tiposSituacoesElicencie["novo"] = "520_novo";
tiposSituacoesElicencie["recebido"] = "521_recebido";
tiposSituacoesElicencie["em_andamento"] = "530_em_andamento";
tiposSituacoesElicencie["aguardando"] = "530_aguardando";
tiposSituacoesElicencie["aguardandoresposta"] = "540_aguardandoresposta";
tiposSituacoesElicencie["suspensaotemporaria"] = "540_suspensaotemporaria";
tiposSituacoesElicencie["cancelada"] = "550_cancelada";
tiposSituacoesElicencie["execucao"] = "560_execucao";
tiposSituacoesElicencie["pendente"] = "570_pendente";
tiposSituacoesElicencie["executadafora"] = "600_executadafora";
tiposSituacoesElicencie["executada"] = "700_executada";
tiposSituacoesElicencie["naoexecutada"] = "701_naoexecutada";
tiposSituacoesElicencie["concluida"] = "730_concluida";
tiposSituacoesElicencie["respondido_negado"] = "740_respondido_negado";
tiposSituacoesElicencie["respondido_aceito"] = "741_respondido_aceito";
tiposSituacoesElicencie["atendidoparcial"] = "742_atendidoparcial";
tiposSituacoesElicencie["naoatendido"] = "743_naoatendido";
tiposSituacoesElicencie["atendido"] = "744_atendido";
tiposSituacoesElicencie["renovada"] = "760_renovada";
tiposSituacoesElicencie["finalizada"] = "800_finalizada";
tiposSituacoesElicencie["emitirnota"] = "101_emitirnota";
tiposSituacoesElicencie["faturaatrasada"] = "301_faturaatrasada";
tiposSituacoesElicencie["pagarfatura"] = "302_pagarfatura";
tiposSituacoesElicencie["aguardandoconfirmacao"] = "531_aguardandoconfirmacao";
tiposSituacoesElicencie["agendado"] = "701_agendado";
tiposSituacoesElicencie["faturapaga"] = "801_faturapaga";
tiposSituacoesElicencie["excluida"] = "999_excluida";
// situacoes outorgas
// Requerido
// Vigente
// Em renovação
// Arquivado
tiposSituacoesElicencie["requerida"] = "401_requerida";
tiposSituacoesElicencie["vigente"] = "516_vigente";
tiposSituacoesElicencie["emrenovacao"] = "402_emrenovacao";
tiposSituacoesElicencie["arquivada"] = "801_arquivada";
tiposSituacoesElicencie["aguardando_sincronizacao"] = "999_aguardando_sincronizacao";
tiposSituacoesElicencie["nao_conforme"] = "710_nao_conforme";
tiposSituacoesElicencie["conforme"] = "720_conforme";
tiposSituacoesElicencie["nao_aplicavel"] = "730_nao_aplicavel";
tiposSituacoesElicencie["parcial"] = "715_parcial";
})(tiposSituacoesElicencie || (tiposSituacoesElicencie = {}));

View file

@ -1,6 +0,0 @@
import { cacheM } from "./cacheMemoria";
import { texto_busca } from "./texto_busca";
// node dist-back/teste.mjs
console.log("Variáveis funcionando", texto_busca);
cacheM(1, { Jaca: Promise.resolve() });
console.log("cache:", cacheM(1));

View file

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

View file

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

View file

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

View file

@ -1,21 +0,0 @@
import { describe, expect, it } from "bun:test";
import { TipagemRotas } from "../tipagemRotas";
describe("TipagemRotas", () => {
it("deve montar _partesCaminho a partir de string ou array, normalizando barras", () => {
const r1 = new TipagemRotas({ caminho: "aplicacao/func" });
expect(r1.caminho).toBe("/aplicacao/func");
const r2 = new TipagemRotas({
caminho: ["aplicacao", "func"],
});
expect(r2.caminho).toBe("/aplicacao/func");
const r3 = new TipagemRotas({ caminho: "/a//b///c/" });
expect(r3.caminho).toBe("/a/b/c");
});
it("Valores de entrada com mesmo valor dos valores de saída", () => {
const r1 = new TipagemRotas({ caminho: "aplicacao/func" });
const objetoEntrada = { idade: 21, nome: "João" };
const rota = r1.endereco(objetoEntrada);
const parametros = r1.parametros(rota);
expect(parametros.nome).toBe(objetoEntrada.nome);
});
});

View file

@ -1,109 +0,0 @@
import { describe, expect, it } from "bun:test";
import { iniciarFiltroDelta, regexColunaFiltroDelta, zColunaFiltroDelta, zFiltroDelta, } from "../filtroDelta";
describe("filtroDelta - validação de colunas", () => {
it("deve validar nomes de colunas e propriedades contendo qualquer combinação de \\w, . e -", () => {
const colunasValidasCombinadas = [
"coluna-teste",
"dados.item-1",
"minha-tabela.meu-campo",
"uuid-550e8400-e29b-41d4-a716-446655440000",
"objeto-a.propriedade-b.campo_c",
"campo-1",
"parametro-a-b-c",
"coluna.",
".coluna",
"coluna..sub",
"a-b.c-d.e",
"-coluna-",
"..",
".",
"-",
"---",
"dados.item_1-x.teste.",
"prefixo..meio--fim",
];
for (const coluna of colunasValidasCombinadas) {
expect(regexColunaFiltroDelta.test(coluna)).toBe(true);
expect(zColunaFiltroDelta.parse(coluna)).toBe(coluna);
}
});
it("deve validar nomes de colunas convencionais com letras, números e sublinhados", () => {
const colunasConvencionais = [
"nome",
"idade",
"usuario_id",
"_id",
"dados.propriedade",
"tabela.campo_123.sub_valor",
];
for (const coluna of colunasConvencionais) {
expect(regexColunaFiltroDelta.test(coluna)).toBe(true);
expect(zColunaFiltroDelta.parse(coluna)).toBe(coluna);
}
});
it("deve rejeitar nomes de colunas inválidos", () => {
const colunasInvalidas = [
"",
"coluna com espaco",
"coluna;drop",
"coluna/sub",
"coluna@dominio",
"coluna#1",
"coluna$valor",
"coluna'teste'",
'coluna"teste"',
"(coluna)",
"coluna=1",
"coluna\nteste",
];
for (const coluna of colunasInvalidas) {
expect(regexColunaFiltroDelta.test(coluna)).toBe(false);
expect(() => zColunaFiltroDelta.parse(coluna)).toThrow("Coluna inválida");
}
});
it("deve permitir criar filtro delta completo com colunas contendo hífen", () => {
const filtro = {
condicoes: [
{
id: "{c1}",
coluna: "dados-usuario.primeiro-nome",
operador: "=",
valor: "Luiz",
},
{
id: "{c2}",
coluna: "configuracao-sistema.status-ativo",
operador: "=",
valor: true,
},
],
formula: "{c1} E {c2}",
};
const resultado = zFiltroDelta.parse(filtro);
expect(resultado.condicoes).toHaveLength(2);
expect(resultado.condicoes[0].coluna).toBe("dados-usuario.primeiro-nome");
expect(resultado.condicoes[1].coluna).toBe("configuracao-sistema.status-ativo");
});
it("deve funcionar com a fábrica iniciarFiltroDelta usando tipos de colunas com hífen", () => {
const { criarFiltroDelta } = iniciarFiltroDelta();
const filtro = criarFiltroDelta({
condicoes: [
{
id: "{1}",
coluna: "item-id",
operador: "!=",
valor: "abc",
},
{
id: "{2}",
coluna: "parametros.taxa-padrao",
operador: ">=",
valor: 10,
},
],
formula: "{1} OU {2}",
});
expect(filtro.condicoes[0].coluna).toBe("item-id");
expect(filtro.condicoes[1].coluna).toBe("parametros.taxa-padrao");
});
});

View file

@ -1,10 +0,0 @@
/** gerar o texto de busca removendo caracteres especies e caixa alta */
export const texto_busca = (...texto) => texto
.map((txt) => txt === null || txt === undefined
? ""
: String(txt)
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "")
.replace(/\s+/g, " ")
.toLowerCase())
.join(" ");

View file

@ -1,104 +0,0 @@
/** Gerar uma classe que facilita a gestão de rotas com a tipagem das querys
*
* Definições:
*
* caminho = "/aplicacao/funcionalidade"
*
* endereco = "http://localhost:3000/aplicacao/funcionalidade"
*
* parametros = {nome:"José"}
*/
export 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, rotulo, }) {
this._partesCaminho = [];
this._acaoIr = acaoIr;
this._partesCaminho = (Array.isArray(caminho) ? caminho : [caminho])
.filter(Boolean)
.map((a) => String(a))
.flatMap((a) => a.split("/"))
.filter(Boolean);
this.rotulo = rotulo;
}
/** 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 win = (typeof globalThis !== "undefined" && globalThis.window) || undefined;
const url = new URL(win ? win.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), JSON.stringify(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 {
const win = (typeof globalThis !== "undefined" && globalThis.window) || undefined;
if (win) {
win.location.href = this.endereco({ ...query });
}
}
}
/** Retorna os parametros da url
** console.log(mCaminho.parametros())
** {q:"query"}
*/
parametros(urlEntrada) {
const url = urlEntrada
? new URL(urlEntrada)
: new URL(typeof globalThis !== "undefined" && globalThis.window
? globalThis.window.location.href
: "http://localhost");
const query = url.searchParams;
let queryObj = Object.fromEntries(query.entries());
// pegar hash
const hash = url.hash;
if (hash) {
const hashObj = Object.fromEntries(new URLSearchParams(hash.slice(1)).entries());
queryObj = { ...queryObj, ...hashObj };
}
for (const chave in queryObj) {
try {
queryObj[chave] = JSON.parse(queryObj[chave]);
}
catch {
console.log(`[${chave}|${queryObj[chave]}] não é um json válido.`);
}
}
return queryObj;
}
}

View file

@ -1,61 +0,0 @@
/**
* Essa variável se conecta a tabela_lidades
*
* onde sigla se conecta com sigla
*
* Usuário terá mais opções de unidades, quando fazer o envio para o mtr, usar a opção fornecida pelo usuarios, caso não tenha
* usar a normalizada
*/
export var siglas_unidades_medida;
(function (siglas_unidades_medida) {
siglas_unidades_medida["UN"] = "UN";
siglas_unidades_medida["KG"] = "KG";
siglas_unidades_medida["TON"] = "TON";
siglas_unidades_medida["g"] = "g";
siglas_unidades_medida["M\u00B3"] = "M\u00B3";
siglas_unidades_medida["Lt"] = "Lt";
})(siglas_unidades_medida || (siglas_unidades_medida = {}));
export 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 / 1000,
tipo: "massa",
},
{
sigla_unidade: "TON",
nome: "Tonelada",
sigla_normalizada: "KG",
normalizar: (valor) => valor * 1000,
tipo: "massa",
},
{
sigla_unidade: "Lt",
nome: "Litro",
sigla_normalizada: "Lt",
normalizar: (valor) => valor,
tipo: "volume",
},
{
sigla_unidade: "M³",
nome: "Metro Cúbico",
sigla_normalizada: "Lt",
normalizar: (valor) => valor * 1000,
tipo: "volume",
},
{
sigla_unidade: "UN",
nome: "Unidade",
sigla_normalizada: "UN",
normalizar: (valor) => valor,
tipo: "unidade",
},
];

View file

@ -1,45 +0,0 @@
import { NIL, v3, v4 } from "uuid";
/**
* Valida se uma string é um UUID válido (qualquer versão).
*
* @param valor - A string que será validada.
* @returns booleano indicando se é um UUID válido.
*/
export const erUuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
export const validarUuid = (uuid) => {
const retorno = erUuid.test(String(uuid || ""));
return retorno;
};
/**
* Gera um UUID determinístico (versão 3) com base em uma chave e um grupo (namespace).
*
* - Usa o algoritmo MD5 (RFC 4122).
* - Sempre retorna o mesmo UUID para a mesma combinação chave + grupo.
* - Caso o grupo não seja informado, usa o UUID "nil" como namespace.
*
* @param chave - Qualquer valor que será convertido em string para gerar o UUID (ex: número, string ou objeto).
* @param grupo - Opcional. Namespace para separar domínios diferentes de UUIDs.
* @returns UUID v3 (determinístico)
*/
export const uuidV3 = (chave, grupo) => {
return v3(
// Converte a chave para string (de forma segura)
typeof chave === "string"
? chave
: typeof chave === "number"
? String(chave)
: JSON.stringify(chave),
// Se um grupo foi fornecido, gera um UUID v3 recursivamente com base nele, senão usa NIL
grupo ? uuidV3(grupo) : NIL);
};
/**
* Gera um UUID v4 (aleatório, não determinístico).
*
* - Usado quando unicidade é necessária, mas não se exige que seja previsível.
*/
export const uuidV4 = v4;
/**
* @deprecated Esta variável será descontinuada em versões futuras.
* Use a função `uuidV4()` diretamente.
*/
export const uuid = uuidV4;

View file

@ -1,9 +0,0 @@
export const esperar = (ms) => new Promise((resolve) => setTimeout(() => resolve(true), ms));
/**
* Usado para retronat o no de uma variável, deve ser usado dentro de um objeto
* const nomex = {a: 1, b: 2}
* nomeVariavel({nomex}) // retorna "nomex"
* @param v
* @returns
*/
export const nomeVariavel = (v) => Object.keys(v).join("/");

View file

@ -1,11 +0,0 @@
/**
* No futuro podemos melhorar este Zod para incluir mais formatos de coordenadas.
*
*/
import z from "zod";
export const zCoordenadas = z.object({
formato: z.literal("decimal").default("decimal"),
datum: z.literal("EPSG:4326").default("EPSG:4326"),
latitude: z.number(),
longitude: z.number(),
});

View file

@ -1,49 +0,0 @@
import z from "zod";
/**
Resumo – CNPJ Alfanumérico (vigência a partir de julho de 2026)
A Receita Federal passará a emitir CNPJs alfanuméricos para novas empresas a partir de julho de 2026. O objetivo é ampliar a quantidade de combinações disponíveis e evitar o esgotamento dos números atuais.
O que muda?
O CNPJ continuará com 14 caracteres.
Os 12 primeiros caracteres poderão conter letras (A-Z) e números (0-9).
Os 2 dígitos verificadores finais continuarão sendo numéricos.
Exemplo ilustrativo:
Atual: 00.000.000/0001-00
Novo: A1.B2C.3D4/EF56-78
Quem será afetado?
Empresas já existentes não terão seus CNPJs alterados.
A mudança vale apenas para novas inscrições realizadas a partir de julho de 2026.
*/
const regexCnpjNumerico = /^\d{2}\.\d{3}\.\d{3}\/\d{4}-\d{2}$/;
/**
Como ler o novo CNPJ (estrutura)
Tomando como exemplo um CNPJ alfanumérico fictício:
12.ABC.345/0001-67
Como ler:
12.ABC.345 é a raiz (identificação da empresa)
0001 é o sufixo (estabelecimento, geralmente “0001” para matriz)
67 são os dígitos verificadores numéricos
Pontos de atenção:
Letras maiúsculas (não há diferenciação entre maiúscula e minúscula no sistema, mas convenção é maiúscula)
Não usar caracteres especiais: só letras de A a Z e números de 0 a 9
Pontos, barra e hífen mantidos como antes
*/
const regexCnpjAlfanumerico = /^[A-Z0-9]{2}\.[A-Z0-9]{3}\.[A-Z0-9]{3}\/[A-Z0-9]{4}-\d{2}$/i;
const yyyymm = Number(new Date().toISOString().slice(0, 7).replace("-", ""));
export const zDocCnpj = z
.string()
.regex(yyyymm < 202407 ? regexCnpjNumerico : regexCnpjAlfanumerico)
.describe("Documento (CNPJ) no formato XX.XXX.XXX/XXXX-XX");
export const zDocCpf = z
.string()
.regex(/^\d{3}\.\d{3}\.\d{3}-\d{2}$/)
.describe("Documento (CPF) no formato XXX.XXX.XXX-XX");
export const zDocumento = zDocCpf.or(zDocCnpj).describe("CPF ou CNPJ");

View file

@ -1,34 +0,0 @@
import z from "zod";
const zPreprocessarNumero = (p) => {
if (typeof p === "number")
return p;
if (typeof p !== "string")
return p;
let p2 = p;
if (p2.includes(",")) {
// ponto de milhar → remove; vírgula decimal → troca por ponto
p2 = p2.replace(/\./g, "").replace(",", ".");
}
// remove tudo que não seja dígito ou ponto decimal
p2 = p2.replace(/[^0-9.]/g, "");
if (p2 == "")
return null;
return Number(p2);
};
/**
* Schema numérico que aceita strings legadas e normaliza para `number`.
*
* O campo **é** um número. O `preprocess` resolve compatibilidade com dados
* antigos onde o frontend enviava strings formatadas (BR ou monetária).
*
* Formatos de entrada aceitos:
* - `10` → number direto
* - `10.1` → ponto decimal
* - `10,1` → vírgula decimal (BR)
* - `1.000,1` → milhar com ponto + vírgula decimal (BR)
* - `R$ 10,01` → prefixo monetário legado
*/
export const zNumero = z.preprocess(zPreprocessarNumero, z.number());
export const zNumeroPositivo = z.preprocess(zPreprocessarNumero, z.number().positive());
export const zNumeroInteiro = z.preprocess(zPreprocessarNumero, z.number().int());
export const zNumeroInteiroPositivo = z.preprocess(zPreprocessarNumero, z.number().int().positive());

View file

@ -1,22 +1,23 @@
{ {
"name": "p-comuns", "name": "p-comuns",
"version": "0.362.0", "version": "0.355.0",
"description": "", "description": "",
"main": "./dist-front/index.js", "main": "./dist-front/index.mjs",
"module": "./dist-front/index.js", "module": "./dist-front/index.mjs",
"types": "./src/index.ts", "types": "./dist-front/index.d.mts",
"exports": { "exports": {
".": { ".": {
"types": "./src/index.ts", "types": "./dist-front/index.d.mts",
"import": "./dist-front/index.js", "import": "./dist-front/index.mjs",
"require": "./dist-back/index.js" "require": "./dist-back/index.js"
} }
}, },
"scripts": { "scripts": {
"biome": "biome check --write", "biome": "pnpm exec biome check --write",
"check": "bun run biome && bun x tsc --noEmit", "check": "pnpm run biome && npx tsc --noEmit",
"build": "npm --no-git-tag-version version minor && bun run biome && bun x tsc -p tsconfig-back.json && bun x tsc -p tsconfig-front.json", "build": "npm --no-git-tag-version version minor && pnpm run biome && tsup --config ./tsup/tsup.config.ts && pnpm run pacote",
"teste": "bun test", "teste": "npx vitest run src/testes/TipagemRotas.test.ts",
"pacote": "npm pack && npm pack && mv $(npm pack --silent) pacote.tgz",
"postinstall": "node ./scripts/atualizar-biome.js" "postinstall": "node ./scripts/atualizar-biome.js"
}, },
"author": { "author": {
@ -27,13 +28,15 @@
"license": "ISC", "license": "ISC",
"dependencies": {}, "dependencies": {},
"devDependencies": { "devDependencies": {
"@biomejs/biome": "^2",
"@types/bun": "^1.4.2",
"@types/node": "^22",
"dayjs": "^1.11.18",
"typescript": "^7",
"uuid": "^11.1.0", "uuid": "^11.1.0",
"zod": "4.4.3" "zod": "4.4.3",
"dayjs": "^1.11.18",
"@biomejs/biome": "2.4.12",
"@types/node": "^22",
"tsup": "8.5.1",
"typescript": "^6",
"unbuild": "^3.6.1",
"vitest": "^3.2.4"
}, },
"peerDependencies": { "peerDependencies": {
"dayjs": "^1.11.18", "dayjs": "^1.11.18",

BIN
pacote.tgz Normal file

Binary file not shown.

2744
pnpm-lock.yaml generated Executable file

File diff suppressed because it is too large Load diff

View file

@ -10,6 +10,7 @@ export enum operadores {
like = "like", like = "like",
in = "in", in = "in",
isNull = "isNull", isNull = "isNull",
notIn = "notIn",
} }
export type tipoFiltro = { export type tipoFiltro = {
@ -30,7 +31,18 @@ export type interfaceConsulta = {
apenasContagem?: boolean apenasContagem?: boolean
} }
export const zOperadores = z.enum(["=", "!=", ">", ">=", "<", "<=", "like", "in", "isNull"]) export const zOperadores = z.enum([
"=",
"!=",
">",
">=",
"<",
"<=",
"like",
"in",
"isNull",
"notIn",
])
export const zFiltro = z.object({ export const zFiltro = z.object({
coluna: z.string(), coluna: z.string(),

View file

@ -96,9 +96,8 @@ const regexIdCondicaoFiltroDelta = /^\{[\w:]+\}$/
/** /**
* Valida nomes de colunas e caminhos jsonb. * Valida nomes de colunas e caminhos jsonb.
* Permite letras, números, sublinhado (_), ponto (.) e hífen (-) em qualquer combinação.
*/ */
export const regexColunaFiltroDelta = /^[\w.-]+$/ const regexColunaFiltroDelta = /^\w+(\.\w+)*$/
/** /**
* Coluna simples ou caminho aninhado de jsonb. * Coluna simples ou caminho aninhado de jsonb.

View file

@ -1,4 +1,4 @@
import { describe, expect, it } from "bun:test" import { describe, expect, it } from "vitest"
import { TipagemRotas } from "../tipagemRotas" import { TipagemRotas } from "../tipagemRotas"
describe("TipagemRotas", () => { describe("TipagemRotas", () => {

View file

@ -1,127 +0,0 @@
import { describe, expect, it } from "bun:test"
import {
iniciarFiltroDelta,
regexColunaFiltroDelta,
zColunaFiltroDelta,
zFiltroDelta,
} from "../filtroDelta"
describe("filtroDelta - validação de colunas", () => {
it("deve validar nomes de colunas e propriedades contendo qualquer combinação de \\w, . e -", () => {
const colunasValidasCombinadas = [
"coluna-teste",
"dados.item-1",
"minha-tabela.meu-campo",
"uuid-550e8400-e29b-41d4-a716-446655440000",
"objeto-a.propriedade-b.campo_c",
"campo-1",
"parametro-a-b-c",
"coluna.",
".coluna",
"coluna..sub",
"a-b.c-d.e",
"-coluna-",
"..",
".",
"-",
"---",
"dados.item_1-x.teste.",
"prefixo..meio--fim",
]
for (const coluna of colunasValidasCombinadas) {
expect(regexColunaFiltroDelta.test(coluna)).toBe(true)
expect(zColunaFiltroDelta.parse(coluna)).toBe(coluna)
}
})
it("deve validar nomes de colunas convencionais com letras, números e sublinhados", () => {
const colunasConvencionais = [
"nome",
"idade",
"usuario_id",
"_id",
"dados.propriedade",
"tabela.campo_123.sub_valor",
]
for (const coluna of colunasConvencionais) {
expect(regexColunaFiltroDelta.test(coluna)).toBe(true)
expect(zColunaFiltroDelta.parse(coluna)).toBe(coluna)
}
})
it("deve rejeitar nomes de colunas inválidos", () => {
const colunasInvalidas = [
"",
"coluna com espaco",
"coluna;drop",
"coluna/sub",
"coluna@dominio",
"coluna#1",
"coluna$valor",
"coluna'teste'",
'coluna"teste"',
"(coluna)",
"coluna=1",
"coluna\nteste",
]
for (const coluna of colunasInvalidas) {
expect(regexColunaFiltroDelta.test(coluna)).toBe(false)
expect(() => zColunaFiltroDelta.parse(coluna)).toThrow("Coluna inválida")
}
})
it("deve permitir criar filtro delta completo com colunas contendo hífen", () => {
const filtro = {
condicoes: [
{
id: "{c1}",
coluna: "dados-usuario.primeiro-nome",
operador: "=" as const,
valor: "Luiz",
},
{
id: "{c2}",
coluna: "configuracao-sistema.status-ativo",
operador: "=" as const,
valor: true,
},
],
formula: "{c1} E {c2}",
}
const resultado = zFiltroDelta.parse(filtro)
expect(resultado.condicoes).toHaveLength(2)
expect(resultado.condicoes[0].coluna).toBe("dados-usuario.primeiro-nome")
expect(resultado.condicoes[1].coluna).toBe("configuracao-sistema.status-ativo")
})
it("deve funcionar com a fábrica iniciarFiltroDelta usando tipos de colunas com hífen", () => {
type Colunas = "item-id" | "parametros.taxa-padrao"
const { criarFiltroDelta } = iniciarFiltroDelta<Colunas>()
const filtro = criarFiltroDelta({
condicoes: [
{
id: "{1}",
coluna: "item-id",
operador: "!=",
valor: "abc",
},
{
id: "{2}",
coluna: "parametros.taxa-padrao",
operador: ">=",
valor: 10,
},
],
formula: "{1} OU {2}",
})
expect(filtro.condicoes[0].coluna).toBe("item-id")
expect(filtro.condicoes[1].coluna).toBe("parametros.taxa-padrao")
})
})

View file

@ -1,52 +1,130 @@
import { NIL, v3, v4 } from "uuid"
/** /**
* Valida se uma string é um UUID válido (qualquer versão). * Valida se uma string é um UUID válido (qualquer versão).
*
* @param valor - A string que será validada.
* @returns booleano indicando se é um UUID válido.
*/ */
export const erUuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i export const erUuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
export const validarUuid = (uuid: string | number | undefined | null) => { export const validarUuid = (uuid: string | number | undefined | null) => {
const retorno = erUuid.test(String(uuid || "")) return erUuid.test(String(uuid || ""))
return retorno }
// ── UUID v4 ──────────────────────────────────────────────────────────────────
// Usa Web Crypto API (globalThis.crypto), disponível em Node 19+, Bun e browsers.
/**
* Gera um UUID v4 (aleatório, não determinístico).
* Usa `globalThis.crypto.randomUUID()` — disponível em Node 19+, Bun e browsers modernos.
*/
export const uuidV4 = (): string => globalThis.crypto.randomUUID()
/**
* @deprecated Use uuidV4() diretamente.
*/
export const uuid = uuidV4
// ── UUID v3 (MD5 determinístico) ──────────────────────────────────────────────
// Implementação pura sem dependência de Node.js para compatibilidade front+back.
const NIL_UUID = "00000000-0000-0000-0000-000000000000"
// Rotação de 32 bits à esquerda
const rotL = (x: number, n: number) => (x << n) | (x >>> (32 - n))
// MD5 — implementação pura JS compatível com browser e Node
const md5 = (str: string): string => {
const msg = new TextEncoder().encode(str)
const len = msg.length
const bits = len * 8
// Padding
const padLen = len % 64 < 56 ? 56 - (len % 64) : 120 - (len % 64)
const padded = new Uint8Array(len + padLen + 8)
padded.set(msg)
padded[len] = 0x80
const dv = new DataView(padded.buffer)
dv.setUint32(len + padLen, bits >>> 0, true)
dv.setUint32(len + padLen + 4, Math.floor(bits / 2 ** 32), true)
// Tabela de senos
const T: number[] = Array.from(
{ length: 64 },
(_, i) => (Math.abs(Math.sin(i + 1)) * 2 ** 32) >>> 0,
)
const S = [
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4,
11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6,
10, 15, 21,
]
let a0 = 0x67452301,
b0 = 0xefcdab89,
c0 = 0x98badcfe,
d0 = 0x10325476
for (let off = 0; off < padded.length; off += 64) {
const M: number[] = []
for (let j = 0; j < 16; j++) M[j] = dv.getUint32(off + j * 4, true)
let [A, B, C, D] = [a0, b0, c0, d0]
for (let i = 0; i < 64; i++) {
let F: number, g: number
if (i < 16) {
F = (B & C) | (~B & D)
g = i
} else if (i < 32) {
F = (D & B) | (~D & C)
g = (5 * i + 1) % 16
} else if (i < 48) {
F = B ^ C ^ D
g = (3 * i + 5) % 16
} else {
F = C ^ (B | ~D)
g = (7 * i) % 16
}
F = (F + A + T[i] + M[g]) >>> 0
A = D
D = C
C = B
B = (B + rotL(F, S[i])) >>> 0
}
a0 = (a0 + A) >>> 0
b0 = (b0 + B) >>> 0
c0 = (c0 + C) >>> 0
d0 = (d0 + D) >>> 0
}
const toHexLE = (n: number) => {
let s = ""
for (let i = 0; i < 4; i++) s += ((n >>> (i * 8)) & 0xff).toString(16).padStart(2, "0")
return s
}
return toHexLE(a0) + toHexLE(b0) + toHexLE(c0) + toHexLE(d0)
}
const formatarUuidV3 = (hash: string): string => {
const c = hash.slice(0, 32)
const v = ((Number.parseInt(c[16], 16) & 0x3) | 0x8).toString(16)
return `${c.slice(0, 8)}-${c.slice(8, 12)}-3${c.slice(13, 16)}-${v}${c.slice(17, 20)}-${c.slice(20, 32)}`
} }
/** /**
* Gera um UUID determinístico (versão 3) com base em uma chave e um grupo (namespace). * Gera um UUID determinístico (versão 3) com base em uma chave e um grupo (namespace).
* Implementação pura JS (MD5), sem dependência de Node.js — funciona em browser e server.
* *
* - Usa o algoritmo MD5 (RFC 4122). * @param chave - Valor a serializar (string, number ou objeto).
* - Sempre retorna o mesmo UUID para a mesma combinação chave + grupo. * @param grupo - Namespace opcional; se omitido, usa UUID nil.
* - Caso o grupo não seja informado, usa o UUID "nil" como namespace.
*
* @param chave - Qualquer valor que será convertido em string para gerar o UUID (ex: número, string ou objeto).
* @param grupo - Opcional. Namespace para separar domínios diferentes de UUIDs.
* @returns UUID v3 (determinístico)
*/ */
export const uuidV3 = (chave: any, grupo?: any): string => { export const uuidV3 = (chave: unknown, grupo?: unknown): string => {
return v3( const namespace = grupo ? uuidV3(grupo) : NIL_UUID
// Converte a chave para string (de forma segura) const input =
typeof chave === "string" typeof chave === "string"
? chave ? chave
: typeof chave === "number" : typeof chave === "number"
? String(chave) ? String(chave)
: JSON.stringify(chave), : JSON.stringify(chave)
return formatarUuidV3(md5(namespace + input))
// Se um grupo foi fornecido, gera um UUID v3 recursivamente com base nele, senão usa NIL
grupo ? uuidV3(grupo) : NIL,
)
} }
/**
* Gera um UUID v4 (aleatório, não determinístico).
*
* - Usado quando unicidade é necessária, mas não se exige que seja previsível.
*/
export const uuidV4 = v4
/**
* @deprecated Esta variável será descontinuada em versões futuras.
* Use a função `uuidV4()` diretamente.
*/
export const uuid = uuidV4

View file

@ -37,5 +37,3 @@ export const zNumero = z.preprocess(zPreprocessarNumero, z.number())
export const zNumeroPositivo = z.preprocess(zPreprocessarNumero, z.number().positive()) export const zNumeroPositivo = z.preprocess(zPreprocessarNumero, z.number().positive())
export const zNumeroInteiro = z.preprocess(zPreprocessarNumero, z.number().int()) export const zNumeroInteiro = z.preprocess(zPreprocessarNumero, z.number().int())
export const zNumeroInteiroPositivo = z.preprocess(zPreprocessarNumero, z.number().int().positive())

View file

@ -1,7 +1,7 @@
{ {
"extends": "./tsconfig", "extends": "./tsconfig",
"compilerOptions": { "compilerOptions": {
"outDir": "./dist-back", "outDir": "./dist-require",
"module": "commonjs" "module": "commonjs"
} }
} }

View file

@ -1,8 +1,7 @@
{ {
"extends": "./tsconfig", "extends": "./tsconfig",
"compilerOptions": { "compilerOptions": {
"outDir": "./dist-front", "outDir": "./dist-import",
"module": "ESNext", "module": "ES6"
"moduleResolution": "bundler"
} }
} }

View file

@ -18,7 +18,7 @@
"rootDir": "./src" /* Define a pasta raiz para os arquivos de origem. */, "rootDir": "./src" /* Define a pasta raiz para os arquivos de origem. */,
/* Emissão */ /* Emissão */
"declaration": false /* Não gera arquivos .d.ts. */, "declaration": true /* Gera arquivos .d.ts para os arquivos TypeScript. */,
/* Interoperabilidade de Módulos */ /* Interoperabilidade de Módulos */
"forceConsistentCasingInFileNames": true /* Garante consistência na diferenciação entre maiúsculas e minúsculas em nomes de arquivos. */, "forceConsistentCasingInFileNames": true /* Garante consistência na diferenciação entre maiúsculas e minúsculas em nomes de arquivos. */,
@ -26,9 +26,8 @@
/* Verificação de Tipos */ /* Verificação de Tipos */
"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. */,
// // IA manter "ignoreDeprecations": "6.0",
"ignoreDeprecations": "6.0"
"types": ["node", "bun"]
}, },
"include": [ "include": [
"src/**/*" "src/**/*"

14
tsup/como usar.md Executable 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": "./dist-front/index.d.mts",,
"exports": {
".": {
"types": "./dist-front/index.d.mts",,
"import": "./dist-front/index.mjs",
"require": "./dist-back/index.js"
}
},

29
tsup/tsup.config.back.ts Executable file
View file

@ -0,0 +1,29 @@
// tsup.config.ts (Configuração Ajustada para Back-end)
import { defineConfig, type Options } from "tsup"
// Definimos as opções em uma constante para clareza, como você fez.
// Exportamos para que possam ser reutilizadas ou inspecionadas.
export const tsup_config_back: Options = {
/** 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
platform: "node",
outExtension: () => ({ js: ".js" }),
loader: {
".svg": "text",
".md": "text",
},
}
// Exporta a configuração padrão usando defineConfig
export default defineConfig(tsup_config_back)

View file

@ -0,0 +1,10 @@
// tsup.config.ts (Configuração Ajustada para Back-end)
import { defineConfig, type Options } from "tsup"
import { tsup_config_front } from "./tsup.config.front"
tsup_config_front. noExternal= [/./]
export {tsup_config_front}
// Exporta a configuração padrão usando defineConfig
export default defineConfig(tsup_config_front)

29
tsup/tsup.config.front.ts Executable file
View file

@ -0,0 +1,29 @@
// tsup.config.ts (Configuração Ajustada para Back-end)
import { defineConfig, type Options } from "tsup"
// Definimos as opções em uma constante para clareza, como você fez.
// Exportamos para que possam ser reutilizadas ou inspecionadas.
export const tsup_config_front: Options = {
entry: ["src/index.ts"], // 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: true, // ESSENCIAL: Mantém a estrutura de arquivos e pastas original
splitting: false, // Desnecessário quando bundle é false
dts: true, // 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: true, // Recomendado para builds de produção
platform: "browser",
external: ['dayjs', 'cross-fetch', 'uuid', 'zod'],
outExtension: () => ({ js: ".mjs" }),
shims: false,
loader: {
".svg": "text",
".md": "text",
},
}
// Exporta a configuração padrão usando defineConfig
export default defineConfig(tsup_config_front)

7
tsup/tsup.config.interno.ts Executable file
View file

@ -0,0 +1,7 @@
// tsup.config.ts (Configuração Ajustada para Back-end)
import { defineConfig } from "tsup"
import { tsup_config_back } from "./tsup.config.back"
import { tsup_config_front } from "./tsup.config.front.interno"
// Exporta a configuração padrão usando defineConfig
export default defineConfig([tsup_config_back, tsup_config_front])

7
tsup/tsup.config.ts Executable file
View file

@ -0,0 +1,7 @@
// tsup.config.ts (Configuração Ajustada para Back-end)
import { defineConfig } from "tsup"
import { tsup_config_back } from "./tsup.config.back"
import { tsup_config_front } from "./tsup.config.front"
// Exporta a configuração padrão usando defineConfig
export default defineConfig([tsup_config_back, tsup_config_front])