@thecodecodex/tools 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Douglas Capeletti
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,45 @@
1
- # Temporary Holding Version
1
+ # @thecodecodex/tools
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Lógica pura das ferramentas do [thecodecodex.com](https://thecodecodex.com/pt/tools/): finanças brasileiras (CLT, PJ,
4
+ juros compostos, férias), CPF/CNPJ, fatura em PDF, PDF Studio, conversor de tabelas, diff, regex, JWT, hash, UUID e
5
+ outras, além do script de terminal [`cli.js`](https://thecodecodex.com/cli.js) e do catálogo de skills de IA.
6
+
7
+ Sem DOM nem framework: as mesmas funções rodam no navegador (site), no Node/Deno/Bun (`cli.js`) e nos testes.
8
+
9
+ ## Uso
10
+
11
+ ```sh
12
+ pnpm add @thecodecodex/tools
13
+ ```
14
+
15
+ O pacote publica o código-fonte TypeScript (ESM), para ser consumido por um bundler (Vite, esbuild, Astro) ou pelo Deno.
16
+
17
+ ```ts
18
+ import { isValidCpf } from "@thecodecodex/tools/br/cpf"
19
+ import { cltYear } from "@thecodecodex/tools/finance/clt"
20
+ import { convertTable } from "@thecodecodex/tools/table-convert"
21
+ ```
22
+
23
+ Indicadores de mercado (CDI, IPCA, poupança, câmbio) não vêm embutidos: carregue-os antes de usar
24
+ `@thecodecodex/tools/market` ou os comandos de terminal que dependem deles.
25
+
26
+ ```ts
27
+ import { setMarketData } from "@thecodecodex/tools/market"
28
+ setMarketData(data) // { fetchedAt, source, series: { cdi, ipca12m, savingsMonthly, usd, eur, gbp, cad } }
29
+ ```
30
+
31
+ ## Desenvolvimento
32
+
33
+ - `pnpm check`: tipos, lint e testes (Vitest, ao lado do código em `src/**/*.test.ts`)
34
+ - Skills de IA ficam em `skills/<nome>/` (formato [Agent Skills](https://agentskills.io/specification)); depois de
35
+ editar, rode `pnpm skills:build` para regenerar `src/skills.json` (um teste falha se ficar desatualizado)
36
+ - Nova ferramenta: a lógica e o comando de terminal (`src/cli/tools.ts`, com os mesmos parâmetros da URL no site)
37
+
38
+ ## Publicação
39
+
40
+ Atualize `version` no `package.json`, faça o commit e envie a tag correspondente (`git tag v0.2.0 && git push --tags`):
41
+ o workflow `publish.yml` roda os testes e publica no npm com provenance.
42
+
43
+ ## Licença
44
+
45
+ MIT
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@thecodecodex/tools",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Lógica das ferramentas do thecodecodex.com (finanças BR, CPF/CNPJ, PDF, regex, JWT e mais) e o script de terminal cli.js",
5
+ "license": "MIT",
6
+ "author": "Douglas Capeletti",
7
+ "homepage": "https://thecodecodex.com/pt/tools/",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/douglas-capeletti/thecodecodex-tools.git"
11
+ },
12
+ "bugs": "https://github.com/douglas-capeletti/thecodecodex-tools/issues",
13
+ "type": "module",
14
+ "sideEffects": false,
15
+ "exports": {
16
+ "./random": "./src/random/index.ts",
17
+ "./table-convert": "./src/table-convert/index.ts",
18
+ "./skills.json": "./src/skills.json",
19
+ "./*": "./src/*.ts"
20
+ },
21
+ "files": [
22
+ "src",
23
+ "!src/**/*.test.ts",
24
+ "!src/**/*.fixture.*",
25
+ "!src/**/fixtures",
26
+ "!src/test-setup.ts"
27
+ ],
28
+ "scripts": {
29
+ "check": "tsc && eslint && vitest run",
30
+ "test": "vitest run",
31
+ "lint": "eslint",
32
+ "skills:build": "node scripts/build-skills.mjs",
33
+ "prepublishOnly": "pnpm check"
34
+ },
35
+ "dependencies": {
36
+ "pdf-lib": "^1.17.1"
37
+ },
38
+ "devDependencies": {
39
+ "@stylistic/eslint-plugin": "^2.13.0",
40
+ "@types/node": "^22.20.5",
41
+ "eslint": "^9.39.4",
42
+ "globals": "^15.15.0",
43
+ "typescript": "^5.9.3",
44
+ "typescript-eslint": "^8.59.0",
45
+ "vitest": "^5.0.5"
46
+ },
47
+ "packageManager": "pnpm@12.14.0"
48
+ }
package/src/base64.ts ADDED
@@ -0,0 +1,36 @@
1
+ // Codificação de texto UTF-8 (acentos e emojis) — btoa/atob puros só aceitam Latin-1
2
+ export type Codec = "base64" | "base64url" | "url"
3
+ export type Direction = "encode" | "decode"
4
+
5
+ function bytesToBase64(bytes: Uint8Array): string {
6
+ let binary = ""
7
+ bytes.forEach((b) => (binary += String.fromCharCode(b)))
8
+ return btoa(binary)
9
+ }
10
+
11
+ function base64ToBytes(value: string): Uint8Array {
12
+ const binary = atob(value)
13
+ return Uint8Array.from(binary, (char) => char.charCodeAt(0))
14
+ }
15
+
16
+ export function encode(text: string, codec: Codec): string {
17
+ if (codec === "url") return encodeURIComponent(text)
18
+ const base64 = bytesToBase64(new TextEncoder().encode(text))
19
+ return codec === "base64url" ? base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "") : base64
20
+ }
21
+
22
+ export function decode(text: string, codec: Codec): string {
23
+ if (codec === "url") return decodeURIComponent(text.replace(/\+/g, " "))
24
+ let value = text.trim().replace(/\s/g, "")
25
+ if (codec === "base64url") value = value.replace(/-/g, "+").replace(/_/g, "/")
26
+ value = value.padEnd(value.length + ((4 - (value.length % 4)) % 4), "=")
27
+ return new TextDecoder("utf-8", { fatal: true }).decode(base64ToBytes(value))
28
+ }
29
+
30
+ export function convert(text: string, codec: Codec, direction: Direction): { ok: true, value: string } | { ok: false } {
31
+ try {
32
+ return { ok: true, value: direction === "encode" ? encode(text, codec) : decode(text, codec) }
33
+ } catch {
34
+ return { ok: false }
35
+ }
36
+ }
package/src/br/cnpj.ts ADDED
@@ -0,0 +1,55 @@
1
+ import { secureRandom, type Random } from "../random/index"
2
+
3
+ // CNPJ alfanumérico (IN RFB nº 2.229/2024): raiz e ordem aceitam [0-9A-Z]; os dígitos verificadores
4
+ // seguem numéricos. Cada caractere vale (código ASCII − 48), então o cálculo é o mesmo do CNPJ numérico.
5
+ const ALPHANUMERIC = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
6
+ const WEIGHTS = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
7
+
8
+ function charValue(char: string): number {
9
+ return char.charCodeAt(0) - 48
10
+ }
11
+
12
+ function checkDigit(chars: string): number {
13
+ const weights = WEIGHTS.slice(WEIGHTS.length - chars.length)
14
+ const sum = [...chars].reduce((acc, char, i) => acc + charValue(char) * (weights[i] ?? 0), 0)
15
+ const rest = sum % 11
16
+ return rest < 2 ? 0 : 11 - rest
17
+ }
18
+
19
+ export function cnpjCheckDigits(base: string): string {
20
+ const first = checkDigit(base)
21
+ const second = checkDigit(base + first)
22
+ return `${first}${second}`
23
+ }
24
+
25
+ export type CnpjKind = "numeric" | "alphanumeric"
26
+
27
+ export function generateCnpj({ kind = "numeric", branch = "0001", random = secureRandom }: { kind?: CnpjKind, branch?: string, random?: Random } = {}): string {
28
+ const alphabet = kind === "alphanumeric" ? ALPHANUMERIC : ALPHANUMERIC.slice(0, 10)
29
+ let root: string
30
+ do {
31
+ root = Array.from({ length: 8 }, () => alphabet[random(alphabet.length)]).join("")
32
+ // garante ao menos uma letra no alfanumérico, senão é só um CNPJ numérico
33
+ } while (/^(.)\1+$/.test(root) || (kind === "alphanumeric" && !/[A-Z]/.test(root)))
34
+ const base = root + branch
35
+ return base + cnpjCheckDigits(base)
36
+ }
37
+
38
+ export function stripCnpj(value: string): string {
39
+ return value.toUpperCase().replace(/[^0-9A-Z]/g, "")
40
+ }
41
+
42
+ export function formatCnpj(value: string): string {
43
+ const chars = stripCnpj(value)
44
+ return chars.length === 14 ? chars.replace(/(.{2})(.{3})(.{3})(.{4})(.{2})/, "$1.$2.$3/$4-$5") : value
45
+ }
46
+
47
+ export function isValidCnpj(value: string): boolean {
48
+ const chars = stripCnpj(value)
49
+ if (!/^[0-9A-Z]{12}\d{2}$/.test(chars) || /^(.)\1+$/.test(chars)) return false
50
+ return cnpjCheckDigits(chars.slice(0, 12)) === chars.slice(12)
51
+ }
52
+
53
+ export function cnpjKind(value: string): CnpjKind {
54
+ return /[A-Z]/.test(stripCnpj(value).slice(0, 12)) ? "alphanumeric" : "numeric"
55
+ }
package/src/br/cpf.ts ADDED
@@ -0,0 +1,61 @@
1
+ import { secureRandom, type Random } from "../random/index"
2
+
3
+ // O 9º dígito do CPF indica a região fiscal de emissão
4
+ export const CPF_REGIONS: Record<string, number> = {
5
+ RS: 0,
6
+ DF: 1, GO: 1, MS: 1, MT: 1, TO: 1,
7
+ AC: 2, AM: 2, AP: 2, PA: 2, RO: 2, RR: 2,
8
+ CE: 3, MA: 3, PI: 3,
9
+ AL: 4, PB: 4, PE: 4, RN: 4,
10
+ BA: 5, SE: 5,
11
+ MG: 6,
12
+ ES: 7, RJ: 7,
13
+ SP: 8,
14
+ PR: 9, SC: 9,
15
+ }
16
+
17
+ function checkDigit(digits: number[]): number {
18
+ const weightStart = digits.length + 1
19
+ const sum = digits.reduce((acc, digit, i) => acc + digit * (weightStart - i), 0)
20
+ const rest = sum % 11
21
+ return rest < 2 ? 0 : 11 - rest
22
+ }
23
+
24
+ export function cpfCheckDigits(base: string): string {
25
+ const digits = [...base].map(Number)
26
+ const first = checkDigit(digits)
27
+ const second = checkDigit([...digits, first])
28
+ return `${first}${second}`
29
+ }
30
+
31
+ export function generateCpf({ uf, random = secureRandom }: { uf?: string | undefined, random?: Random } = {}): string {
32
+ const region = uf ? CPF_REGIONS[uf] : undefined
33
+ let base: string
34
+ do {
35
+ base = Array.from({ length: 8 }, () => random(10)).join("") + String(region ?? random(10))
36
+ } while (/^(\d)\1+$/.test(base))
37
+ return base + cpfCheckDigits(base)
38
+ }
39
+
40
+ export function stripCpf(value: string): string {
41
+ return value.replace(/\D/g, "")
42
+ }
43
+
44
+ export function formatCpf(value: string): string {
45
+ const digits = stripCpf(value)
46
+ return digits.length === 11 ? digits.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, "$1.$2.$3-$4") : value
47
+ }
48
+
49
+ export function isValidCpf(value: string): boolean {
50
+ const digits = stripCpf(value)
51
+ // sequências repetidas (111.111.111-11) passam no cálculo mas são inválidas
52
+ if (digits.length !== 11 || /^(\d)\1+$/.test(digits)) return false
53
+ return cpfCheckDigits(digits.slice(0, 9)) === digits.slice(9)
54
+ }
55
+
56
+ export function cpfRegion(value: string): string[] {
57
+ const digits = stripCpf(value)
58
+ if (digits.length < 9) return []
59
+ const region = Number(digits[8])
60
+ return Object.entries(CPF_REGIONS).filter(([, r]) => r === region).map(([uf]) => uf)
61
+ }
@@ -0,0 +1,93 @@
1
+ // Ponto de entrada de thecodecodex.com/cli.js. Uso:
2
+ // deno run "https://thecodecodex.com/cli.js?tool=net-salary&bruto=8000"
3
+ // curl -s https://thecodecodex.com/cli.js | node --input-type=module - net-salary bruto=8000
4
+ // Parâmetros: da query string da URL do script (Deno) e/ou argumentos (`tool chave=valor` ou `--chave valor`).
5
+ import { TOOLS, type Params } from "./tools"
6
+
7
+ declare const Deno: { args: string[], stdout: { write(data: Uint8Array): Promise<number> }, exit(code: number): never } | undefined
8
+ declare const process: { argv: string[], stdout: { write(data: Uint8Array | string): boolean }, exitCode?: number } | undefined
9
+
10
+ export const SITE = "https://thecodecodex.com"
11
+
12
+ export function parseArgs(url: string, args: string[]): { tool: string | undefined, params: Params } {
13
+ const params = new URLSearchParams(url.includes("?") ? url.slice(url.indexOf("?") + 1) : "")
14
+ let tool = params.get("tool") ?? undefined
15
+ params.delete("tool")
16
+ for (let i = 0; i < args.length; i++) {
17
+ const arg = args[i] ?? ""
18
+ if (arg.startsWith("--")) {
19
+ const [key, inline] = arg.slice(2).split(/=(.*)/s)
20
+ const value = inline ?? (args[i + 1] && !args[i + 1]?.startsWith("--") ? args[++i] : "1")
21
+ if (key === "tool") tool = value
22
+ else if (key) params.set(key, value ?? "")
23
+ } else if (arg.includes("=")) {
24
+ const [key = "", value = ""] = arg.split(/=(.*)/s)
25
+ if (key === "tool") tool = value
26
+ else params.set(key, value)
27
+ } else if (!tool) tool = arg
28
+ }
29
+ return { tool, params }
30
+ }
31
+
32
+ export function help(): unknown {
33
+ return {
34
+ usage: [`deno run "${SITE}/cli.js?tool=<ferramenta>&<parametro>=<valor>"`, `curl -s ${SITE}/cli.js | node --input-type=module - <ferramenta> <parametro>=<valor>`],
35
+ note: "Os parâmetros são os mesmos da URL da ferramenta no site: copie o link de compartilhamento e troque o endereço.",
36
+ tools: Object.fromEntries(Object.entries(TOOLS).map(([name, tool]) => [name, { description: tool.description, params: Object.fromEntries(tool.params.map((p) => [p.name, `${p.description} (padrão: ${p.default || "—"})`])) }])),
37
+ }
38
+ }
39
+
40
+ export type ExecuteResult = { text: string, write?: FileToWrite[] } | { bytes: Uint8Array }
41
+ export interface FileToWrite {
42
+ path: string
43
+ content: string
44
+ }
45
+
46
+ export async function execute(tool: string | undefined, params: Params): Promise<ExecuteResult> {
47
+ if (!tool || tool === "help") return { text: JSON.stringify(help(), null, 2) }
48
+ const definition = TOOLS[tool]
49
+ if (!definition) throw new Error(`Ferramenta desconhecida: ${tool}. Rode sem parâmetros para ver a lista.`)
50
+ const output = await definition.run(params)
51
+ if ("pdf" in output) return { bytes: output.pdf }
52
+ if ("file" in output) return { bytes: output.file }
53
+ if ("text" in output) return { text: output.text }
54
+ const text = JSON.stringify({ tool, input: Object.fromEntries(params), result: output.json }, null, 2)
55
+ return "write" in output ? { text, write: output.write } : { text }
56
+ }
57
+
58
+ // Grava arquivos com node:fs (Node, Bun e Deno entendem o prefixo node:; no Deno exige --allow-write).
59
+ // Import dinâmico com especificador em variável: o bundle "neutral" não tenta resolver módulos do Node.
60
+ interface NodeFs {
61
+ mkdir(path: string, options: { recursive: boolean }): Promise<unknown>
62
+ writeFile(path: string, data: string): Promise<void>
63
+ }
64
+ async function writeFiles(files: FileToWrite[]) {
65
+ const fsModule = "node:fs/promises"
66
+ const fs = (await import(/* @vite-ignore */ fsModule)) as NodeFs
67
+ for (const file of files) {
68
+ const folder = file.path.slice(0, Math.max(file.path.lastIndexOf("/"), 0))
69
+ if (folder) await fs.mkdir(folder, { recursive: true })
70
+ await fs.writeFile(file.path, file.content)
71
+ }
72
+ }
73
+
74
+ export async function main() {
75
+ const isDeno = typeof Deno !== "undefined"
76
+ const args = isDeno ? Deno.args : (process?.argv.slice(2) ?? []).filter((a) => a !== "-")
77
+ const write = async (data: Uint8Array | string) => {
78
+ const bytes = typeof data === "string" ? new TextEncoder().encode(`${data}\n`) : data
79
+ if (isDeno) await Deno.stdout.write(bytes)
80
+ else process?.stdout.write(bytes)
81
+ }
82
+ try {
83
+ const { tool, params } = parseArgs(import.meta.url, args)
84
+ const result = await execute(tool, params)
85
+ if ("write" in result && result.write) await writeFiles(result.write)
86
+ await write("text" in result ? result.text : result.bytes)
87
+ } catch (error) {
88
+ await write(JSON.stringify({ error: error instanceof Error ? error.message : String(error) }, null, 2))
89
+ if (isDeno) Deno.exit(1)
90
+ else if (process) process.exitCode = 1
91
+ }
92
+ }
93
+