pinga-cli 0.0.0 → 0.2.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/dist/config.js ADDED
@@ -0,0 +1,93 @@
1
+ import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { CliError } from "./errors.js";
4
+ export const DEFAULT_PROFILE = "default";
5
+ const PROFILE_NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
6
+ /**
7
+ * Onde fica o arquivo de configuração:
8
+ * - Windows: `%APPDATA%\pinga\config.json`;
9
+ * - demais: `$XDG_CONFIG_HOME/pinga/config.json`, com `~/.config` como padrão.
10
+ *
11
+ * `PINGA_CONFIG_DIR` troca o diretório inteiro (testes, CI, mais de uma conta na mesma máquina).
12
+ */
13
+ export function configPath(io) {
14
+ // O sistema vem do `Io`, não do módulo `path` nativo: assim o cálculo é o mesmo em qualquer máquina.
15
+ const paths = io.platform === "win32" ? path.win32 : path.posix;
16
+ const override = io.env["PINGA_CONFIG_DIR"];
17
+ if (override)
18
+ return paths.join(override, "config.json");
19
+ if (io.platform === "win32") {
20
+ const appData = io.env["APPDATA"] || paths.join(io.homedir, "AppData", "Roaming");
21
+ return paths.join(appData, "pinga", "config.json");
22
+ }
23
+ const xdg = io.env["XDG_CONFIG_HOME"];
24
+ const base = xdg && paths.isAbsolute(xdg) ? xdg : paths.join(io.homedir, ".config");
25
+ return paths.join(base, "pinga", "config.json");
26
+ }
27
+ export function assertProfileName(name) {
28
+ if (!PROFILE_NAME.test(name)) {
29
+ throw new CliError(`Nome de perfil inválido: "${name}". Use letras, números, "-" e "_" (até 64 caracteres).`);
30
+ }
31
+ return name;
32
+ }
33
+ export async function readConfig(file) {
34
+ let text;
35
+ try {
36
+ text = await readFile(file, "utf8");
37
+ }
38
+ catch (error) {
39
+ if (isNotFound(error))
40
+ return { profiles: {} };
41
+ throw new CliError(`Não consegui ler ${file}: ${describe(error)}`);
42
+ }
43
+ let parsed;
44
+ try {
45
+ parsed = JSON.parse(text);
46
+ }
47
+ catch {
48
+ throw new CliError(`${file} não é um JSON válido. Corrija o arquivo ou apague-o e rode \`pinga login\` de novo.`);
49
+ }
50
+ if (!isRecord(parsed) || (parsed["profiles"] !== undefined && !isRecord(parsed["profiles"]))) {
51
+ throw new CliError(`${file} não tem o formato esperado ({ "profiles": { ... } }).`);
52
+ }
53
+ const profiles = {};
54
+ for (const [name, value] of Object.entries((parsed["profiles"] ?? {}))) {
55
+ if (!isRecord(value))
56
+ continue;
57
+ profiles[name] = {
58
+ api_key: typeof value["api_key"] === "string" ? value["api_key"] : undefined,
59
+ base_url: typeof value["base_url"] === "string" ? value["base_url"] : undefined,
60
+ };
61
+ }
62
+ return { profiles };
63
+ }
64
+ /**
65
+ * Grava com permissão `0600` (diretório `0700`): o arquivo guarda a API key em texto puro, como o
66
+ * `~/.aws/credentials` e o `~/.npmrc`. A escrita é atômica (arquivo temporário + rename), então um
67
+ * Ctrl+C no meio não deixa a configuração pela metade.
68
+ */
69
+ export async function writeConfig(file, config) {
70
+ const dir = path.dirname(file);
71
+ await mkdir(dir, { recursive: true, mode: 0o700 });
72
+ const temp = `${file}.${process.pid}.tmp`;
73
+ const body = `${JSON.stringify(config, null, 2)}\n`;
74
+ try {
75
+ await writeFile(temp, body, { mode: 0o600 });
76
+ // `mode` do writeFile passa pela umask; o chmod garante 0600 mesmo assim.
77
+ await chmod(temp, 0o600);
78
+ await rename(temp, file);
79
+ }
80
+ catch (error) {
81
+ await rm(temp, { force: true });
82
+ throw new CliError(`Não consegui gravar ${file}: ${describe(error)}`);
83
+ }
84
+ }
85
+ function isNotFound(error) {
86
+ return isRecord(error) && error["code"] === "ENOENT";
87
+ }
88
+ function describe(error) {
89
+ return error instanceof Error ? error.message : String(error);
90
+ }
91
+ function isRecord(value) {
92
+ return typeof value === "object" && value !== null && !Array.isArray(value);
93
+ }
@@ -0,0 +1,100 @@
1
+ import { DEFAULT_BASE_URL, Pinga } from "@pinga/sdk";
2
+ import { assertProfileName, configPath, DEFAULT_PROFILE, readConfig } from "./config.js";
3
+ import { CliError, redact } from "./errors.js";
4
+ import { VERSION } from "./version.js";
5
+ /** Estado de uma execução: perfil escolhido, formato de saída e acesso ao cliente da API. */
6
+ export class Context {
7
+ io;
8
+ json;
9
+ profile;
10
+ configFile;
11
+ #baseUrlFlag;
12
+ /** Chaves conhecidas nesta execução, para a redação de toda saída. */
13
+ #secrets = [];
14
+ #shortSecrets = [];
15
+ #config;
16
+ constructor(io, flags) {
17
+ this.io = io;
18
+ this.json = flags.json;
19
+ this.profile = assertProfileName(flags.profile ?? io.env["PINGA_PROFILE"] ?? DEFAULT_PROFILE);
20
+ this.configFile = configPath(io);
21
+ this.#baseUrlFlag = flags.baseUrl;
22
+ const envKey = io.env["PINGA_API_KEY"];
23
+ if (envKey)
24
+ this.#secrets.push(envKey);
25
+ }
26
+ /**
27
+ * `anyLength`: redige mesmo se for curto (segredo de webhook informado pelo usuário). Sem ele,
28
+ * vale o mínimo de 8 caracteres do `redact`, para não mutilar a saída com trechos comuns.
29
+ */
30
+ rememberSecret(secret, options = {}) {
31
+ if (options.anyLength)
32
+ this.#shortSecrets.push(secret);
33
+ else
34
+ this.#secrets.push(secret);
35
+ }
36
+ async config() {
37
+ if (this.#config === undefined) {
38
+ this.#config = await readConfig(this.configFile);
39
+ for (const profile of Object.values(this.#config.profiles)) {
40
+ if (profile.api_key)
41
+ this.#secrets.push(profile.api_key);
42
+ }
43
+ }
44
+ return this.#config;
45
+ }
46
+ /** `--base-url` > `PINGA_BASE_URL` > `base_url` do perfil > produção. */
47
+ async baseUrl() {
48
+ if (this.#baseUrlFlag)
49
+ return this.#baseUrlFlag;
50
+ const fromEnv = this.io.env["PINGA_BASE_URL"];
51
+ if (fromEnv)
52
+ return fromEnv;
53
+ const config = await this.config();
54
+ return config.profiles[this.profile]?.base_url ?? DEFAULT_BASE_URL;
55
+ }
56
+ /** `PINGA_API_KEY` no ambiente tem precedência sobre o perfil do arquivo de configuração. */
57
+ async credentials() {
58
+ const baseUrl = await this.baseUrl();
59
+ const fromEnv = this.io.env["PINGA_API_KEY"];
60
+ if (fromEnv)
61
+ return { apiKey: fromEnv, baseUrl, source: "env" };
62
+ const config = await this.config();
63
+ const apiKey = config.profiles[this.profile]?.api_key;
64
+ if (apiKey)
65
+ return { apiKey, baseUrl, source: "profile" };
66
+ const hint = this.profile === DEFAULT_PROFILE ? "pinga login" : `pinga login --profile ${this.profile}`;
67
+ throw new CliError(`Nenhuma API key para o perfil "${this.profile}". Rode \`${hint}\` ou defina PINGA_API_KEY.`);
68
+ }
69
+ createClient(apiKey, baseUrl) {
70
+ this.rememberSecret(apiKey);
71
+ return new Pinga({
72
+ apiKey,
73
+ baseUrl,
74
+ fetch: this.io.fetch,
75
+ defaultHeaders: { "User-Agent": `pinga-cli/${VERSION}` },
76
+ });
77
+ }
78
+ async client() {
79
+ const { apiKey, baseUrl } = await this.credentials();
80
+ return this.createClient(apiKey, baseUrl);
81
+ }
82
+ /** Escreve uma linha no stdout, já redigida. */
83
+ out(text = "") {
84
+ this.io.stdout.write(`${redact(text, this.#secrets, this.#shortSecrets)}\n`);
85
+ }
86
+ /** Escreve uma linha no stderr, já redigida. Avisos e progresso, nunca o resultado. */
87
+ err(text = "") {
88
+ this.io.stderr.write(`${redact(text, this.#secrets, this.#shortSecrets)}\n`);
89
+ }
90
+ /** Resultado em `--json`: um documento JSON no stdout. */
91
+ outJson(value) {
92
+ this.out(JSON.stringify(value, null, 2));
93
+ }
94
+ errJson(value) {
95
+ this.err(JSON.stringify(value, null, 2));
96
+ }
97
+ redact(text) {
98
+ return redact(text, this.#secrets, this.#shortSecrets);
99
+ }
100
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,48 @@
1
+ /** Erro de uso: flag desconhecida, argumento faltando, combinação inválida. Sai com código 2. */
2
+ export class UsageError extends Error {
3
+ constructor(message) {
4
+ super(message);
5
+ this.name = "UsageError";
6
+ }
7
+ }
8
+ /** Erro do próprio CLI, sem resposta da API (configuração, arquivo, entrada). Sai com código 1. */
9
+ export class CliError extends Error {
10
+ constructor(message) {
11
+ super(message);
12
+ this.name = "CliError";
13
+ }
14
+ }
15
+ /**
16
+ * Falha que o comando já relatou na própria saída (ex.: `templates push` com um template recusado
17
+ * entre vários). Só muda o código de saída para 1; o despachante não imprime mais nada.
18
+ */
19
+ export class ReportedFailure extends Error {
20
+ constructor() {
21
+ super("falha já relatada");
22
+ this.name = "ReportedFailure";
23
+ }
24
+ }
25
+ export const ExitCode = {
26
+ Ok: 0,
27
+ Failure: 1,
28
+ Usage: 2,
29
+ };
30
+ const API_KEY_PATTERN = /pg_(live|test)_[A-Za-z0-9]+/g;
31
+ /**
32
+ * Segunda barreira contra vazar a API key: todo texto que sai do CLI passa por aqui. A primeira é
33
+ * nunca pôr a chave numa mensagem; esta pega o que escapar (ex.: um erro de terceiro que ecoe a URL
34
+ * ou o header).
35
+ */
36
+ export function redact(text, secrets = [], anyLength = []) {
37
+ let result = text.replace(API_KEY_PATTERN, "pg_$1_[redacted]");
38
+ for (const secret of secrets) {
39
+ if (secret.length >= 8)
40
+ result = result.split(secret).join("[redacted]");
41
+ }
42
+ // Mais longos primeiro, para um segredo que contém outro não sair parcialmente redigido.
43
+ for (const secret of [...anyLength].sort((a, b) => b.length - a.length)) {
44
+ if (secret.length > 0)
45
+ result = result.split(secret).join("[redacted]");
46
+ }
47
+ return result;
48
+ }
package/dist/format.js ADDED
@@ -0,0 +1,24 @@
1
+ /** Tabela em colunas alinhadas, sem bordas — fácil de ler e de passar por `grep`/`awk`. */
2
+ export function table(headers, rawRows) {
3
+ const rows = rawRows.map((row) => row.map(clean));
4
+ const widths = headers.map((header, index) => Math.max(header.length, ...rows.map((row) => (row[index] ?? "").length)));
5
+ const render = (cells) => cells
6
+ .map((cell, index) => (index === cells.length - 1 ? cell : cell.padEnd(widths[index] ?? 0)))
7
+ .join(" ")
8
+ .trimEnd();
9
+ return [render(headers), ...rows.map(render)].join("\n");
10
+ }
11
+ /** Quebras de linha e tabs numa célula desalinhariam a tabela. */
12
+ function clean(value) {
13
+ return value.replace(/[\r\n\t]+/g, " ");
14
+ }
15
+ /** Controles C0/C1, DEL, zero-width, separadores de linha e bidi que mexeriam no terminal. */
16
+ const UNSAFE = /[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u2028-\u202e\u2060-\u206f\ufeff]/g;
17
+ /** Slug para saída comum: igual ao original, mas com caracteres perigosos como `\uXXXX`. */
18
+ export function escapeSlug(slug) {
19
+ return slug.replace(UNSAFE, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
20
+ }
21
+ /** Slug entre aspas para mensagens de erro; escapa o que `JSON.stringify` deixa passar (DEL, C1, bidi...). */
22
+ export function quoteSlug(slug) {
23
+ return escapeSlug(JSON.stringify(slug));
24
+ }
package/dist/io.js ADDED
@@ -0,0 +1,3 @@
1
+ // Tudo o que o CLI toca no mundo de fora passa por aqui: processo, terminal, ambiente e rede.
2
+ // Os testes trocam cada peça por uma falsa e rodam o CLI inteiro em memória.
3
+ export {};
package/dist/main.js ADDED
@@ -0,0 +1,190 @@
1
+ import { parseArgs } from "node:util";
2
+ import { login, logout } from "./commands/auth.js";
3
+ import { deliveriesGet, deliveriesList } from "./commands/deliveries.js";
4
+ import { emailsSend } from "./commands/emails.js";
5
+ import { domainsCheck } from "./commands/domains.js";
6
+ import { templatesPull, templatesPush } from "./commands/templates.js";
7
+ import { webhooksVerify } from "./commands/webhooks.js";
8
+ import { Context } from "./context.js";
9
+ import { ExitCode, redact, UsageError } from "./errors.js";
10
+ import { renderError } from "./render-error.js";
11
+ import { VERSION } from "./version.js";
12
+ export const COMMANDS = [
13
+ login,
14
+ logout,
15
+ emailsSend,
16
+ deliveriesList,
17
+ deliveriesGet,
18
+ templatesPull,
19
+ templatesPush,
20
+ domainsCheck,
21
+ webhooksVerify,
22
+ ];
23
+ const GLOBAL_OPTIONS = {
24
+ profile: { type: "string", short: "p" },
25
+ "base-url": { type: "string" },
26
+ json: { type: "boolean" },
27
+ help: { type: "boolean", short: "h" },
28
+ version: { type: "boolean", short: "v" },
29
+ };
30
+ const GLOBAL_HELP = `Opções globais:
31
+ -p, --profile <nome> perfil do arquivo de configuração (padrão: PINGA_PROFILE ou "default")
32
+ --base-url <url> URL da API (padrão: PINGA_BASE_URL, o do perfil ou https://api.pinga.api.br)
33
+ --json saída em JSON no stdout; em erro, o JSON do erro vai para o stderr
34
+ -h, --help mostra a ajuda`;
35
+ const ENVIRONMENT_HELP = `Ambiente:
36
+ PINGA_API_KEY API key; tem precedência sobre o arquivo de configuração
37
+ PINGA_PROFILE perfil padrão
38
+ PINGA_BASE_URL URL da API
39
+ PINGA_CONFIG_DIR diretório do config.json (padrão: ~/.config/pinga; %APPDATA%\\pinga no Windows)
40
+ PINGA_WEBHOOK_SECRET segredo para \`pinga webhooks verify\``;
41
+ /**
42
+ * Executa o CLI e devolve o código de saída: `0` sucesso, `1` falha (API, rede, configuração),
43
+ * `2` erro de uso.
44
+ */
45
+ export async function main(argv, io) {
46
+ const { words, command, rest } = splitCommand(argv);
47
+ const wantsJson = argv.includes("--json");
48
+ let ctx;
49
+ try {
50
+ if (!command) {
51
+ if (words.length === 0) {
52
+ const flags = parseFlags(GLOBAL_OPTIONS, rest);
53
+ if (flags.values["version"]) {
54
+ io.stdout.write(`pinga ${VERSION}\n`);
55
+ return ExitCode.Ok;
56
+ }
57
+ io.stdout.write(`${rootHelp()}\n`);
58
+ return flags.values["help"] ? ExitCode.Ok : ExitCode.Usage;
59
+ }
60
+ if (words[0] === "help") {
61
+ const target = findCommand(words.slice(1));
62
+ io.stdout.write(`${target ? commandHelp(target) : groupHelp(words[1])}\n`);
63
+ return ExitCode.Ok;
64
+ }
65
+ const group = words[0];
66
+ if (words.length === 1 && COMMANDS.some((candidate) => candidate.name[0] === group)) {
67
+ io.stdout.write(`${groupHelp(group)}\n`);
68
+ return rest.includes("--help") || rest.includes("-h") ? ExitCode.Ok : ExitCode.Usage;
69
+ }
70
+ throw new UsageError(`Comando desconhecido: ${words.join(" ")}. Rode \`pinga --help\`.`);
71
+ }
72
+ const parsed = parseFlags({ ...GLOBAL_OPTIONS, ...command.options }, rest);
73
+ if (parsed.values["help"]) {
74
+ io.stdout.write(`${commandHelp(command)}\n`);
75
+ return ExitCode.Ok;
76
+ }
77
+ const { min, max, names } = command.positionals;
78
+ if (parsed.positionals.length < min || parsed.positionals.length > max) {
79
+ const expected = max === 0 ? "nenhum argumento" : `${names ?? "argumentos"}`;
80
+ throw new UsageError(`\`pinga ${command.name.join(" ")}\` espera ${expected}. Rode com --help.`);
81
+ }
82
+ ctx = new Context(io, {
83
+ profile: stringValue(parsed.values["profile"]),
84
+ baseUrl: stringValue(parsed.values["base-url"]),
85
+ json: parsed.values["json"] === true,
86
+ });
87
+ await command.run(ctx, parsed.values, parsed.positionals);
88
+ return ExitCode.Ok;
89
+ }
90
+ catch (error) {
91
+ const rendered = renderError(error);
92
+ if (rendered.reported)
93
+ return rendered.exitCode;
94
+ const scrub = (text) => (ctx ? ctx.redact(text) : redact(text, [io.env["PINGA_API_KEY"] ?? ""]));
95
+ if (wantsJson) {
96
+ io.stderr.write(`${scrub(JSON.stringify(rendered.json, null, 2))}\n`);
97
+ }
98
+ else {
99
+ io.stderr.write(`${scrub(rendered.lines.join("\n"))}\n`);
100
+ }
101
+ return rendered.exitCode;
102
+ }
103
+ }
104
+ /**
105
+ * Acha o comando no começo da linha. As opções globais podem vir antes dele
106
+ * (`pinga --profile prod deliveries list`), por isso elas e o valor delas são pulados. Tudo depois do
107
+ * nome do comando fica para o `parseArgs`, já com as opções daquele comando: só ele sabe se `--html`
108
+ * leva valor (em `emails send` leva; em `deliveries get`, não).
109
+ */
110
+ function splitCommand(argv) {
111
+ const words = [];
112
+ const leading = [];
113
+ let index = 0;
114
+ while (index < argv.length && !findCommand(words)) {
115
+ const token = argv[index];
116
+ if (token.startsWith("-") && token !== "-") {
117
+ const option = globalOption(token);
118
+ if (!option)
119
+ break;
120
+ leading.push(token);
121
+ if (option.type === "string" && !token.includes("=") && index + 1 < argv.length) {
122
+ leading.push(argv[index + 1]);
123
+ index += 1;
124
+ }
125
+ }
126
+ else {
127
+ words.push(token);
128
+ }
129
+ index += 1;
130
+ }
131
+ return { words, command: findCommand(words), rest: [...leading, ...argv.slice(index)] };
132
+ }
133
+ function globalOption(token) {
134
+ const options = GLOBAL_OPTIONS;
135
+ if (token.startsWith("--"))
136
+ return options[token.slice(2).split("=")[0]];
137
+ return Object.values(options).find((option) => option.short === token.slice(1));
138
+ }
139
+ function findCommand(words) {
140
+ return COMMANDS.find((command) => command.name.length === words.length && command.name.every((part, index) => words[index] === part));
141
+ }
142
+ function parseFlags(options, args) {
143
+ try {
144
+ const { values, positionals } = parseArgs({ args, options, allowPositionals: true, strict: true });
145
+ return { values: values, positionals };
146
+ }
147
+ catch (error) {
148
+ // Mensagens do parseArgs vêm em inglês; reescreve as comuns.
149
+ const message = error instanceof Error ? error.message : String(error);
150
+ const unknown = /Unknown option '([^']+)'/.exec(message);
151
+ if (unknown)
152
+ throw new UsageError(`Opção desconhecida: ${unknown[1]}. Rode com --help.`);
153
+ const missing = /Option '([^']+?)(?: <value>)?' argument missing/.exec(message);
154
+ if (missing)
155
+ throw new UsageError(`${missing[1]?.replace(/^-\w, /, "")} precisa de um valor.`);
156
+ throw new UsageError(message);
157
+ }
158
+ }
159
+ function stringValue(value) {
160
+ return typeof value === "string" && value.length > 0 ? value : undefined;
161
+ }
162
+ function rootHelp() {
163
+ const width = Math.max(...COMMANDS.map((command) => command.name.join(" ").length));
164
+ const lines = COMMANDS.map((command) => ` ${command.name.join(" ").padEnd(width)} ${command.summary}`);
165
+ return `pinga ${VERSION} — CLI da Pinga (https://docs.pinga.api.br/cli)
166
+
167
+ Uso: pinga <comando> [opções]
168
+
169
+ Comandos:
170
+ ${lines.join("\n")}
171
+
172
+ ${GLOBAL_HELP}
173
+
174
+ ${ENVIRONMENT_HELP}
175
+
176
+ Rode \`pinga <comando> --help\` para as opções de cada comando.`;
177
+ }
178
+ function groupHelp(group) {
179
+ const commands = COMMANDS.filter((command) => command.name[0] === group);
180
+ if (commands.length === 0)
181
+ return rootHelp();
182
+ const width = Math.max(...commands.map((command) => command.name.join(" ").length));
183
+ return `Uso: pinga ${group} <subcomando> [opções]
184
+
185
+ Subcomandos:
186
+ ${commands.map((command) => ` ${command.name.join(" ").padEnd(width)} ${command.summary}`).join("\n")}`;
187
+ }
188
+ function commandHelp(command) {
189
+ return `${command.help}\n\n${GLOBAL_HELP}`;
190
+ }
package/dist/prompt.js ADDED
@@ -0,0 +1,86 @@
1
+ import { CliError } from "./errors.js";
2
+ const CTRL_C = "\u0003";
3
+ const CTRL_D = "\u0004";
4
+ const BACKSPACE = "\u007f";
5
+ const BACKSPACE_ALT = "\b";
6
+ /**
7
+ * Lê um segredo.
8
+ *
9
+ * - Terminal: modo raw, sem eco. O prompt vai para o stderr, para não sujar o stdout de quem redireciona.
10
+ * - Sem terminal (pipe, CI): lê a primeira linha da entrada padrão, ex.:
11
+ * `printf '%s' "$PINGA_KEY" | pinga login`.
12
+ */
13
+ export async function readSecret(stdin, stderr, prompt) {
14
+ if (stdin.isTTY && typeof stdin.setRawMode === "function") {
15
+ return readFromTerminal(stdin, stderr, prompt);
16
+ }
17
+ return readFirstLine(stdin);
18
+ }
19
+ function readFromTerminal(stdin, stderr, prompt) {
20
+ stderr.write(prompt);
21
+ stdin.setEncoding?.("utf8");
22
+ stdin.setRawMode?.(true);
23
+ stdin.resume?.();
24
+ return new Promise((resolve, reject) => {
25
+ let value = "";
26
+ const finish = (error) => {
27
+ stdin.removeListener("data", onData);
28
+ stdin.setRawMode?.(false);
29
+ stdin.pause?.();
30
+ stderr.write("\n");
31
+ if (error)
32
+ reject(error);
33
+ else
34
+ resolve(value);
35
+ };
36
+ const onData = (chunk) => {
37
+ const text = typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8");
38
+ for (const char of text) {
39
+ if (char === "\r" || char === "\n" || char === CTRL_D) {
40
+ finish();
41
+ return;
42
+ }
43
+ if (char === CTRL_C) {
44
+ finish(new CliError("Cancelado."));
45
+ return;
46
+ }
47
+ if (char === BACKSPACE || char === BACKSPACE_ALT) {
48
+ value = value.slice(0, -1);
49
+ continue;
50
+ }
51
+ // Ignora sequências de controle (setas etc.): numa chave só entram caracteres imprimíveis.
52
+ if (char >= " ")
53
+ value += char;
54
+ }
55
+ };
56
+ stdin.on("data", onData);
57
+ });
58
+ }
59
+ async function readFirstLine(stdin) {
60
+ let buffer = "";
61
+ for await (const chunk of stdin) {
62
+ buffer += typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8");
63
+ const newline = buffer.search(/\r?\n/);
64
+ if (newline >= 0)
65
+ return buffer.slice(0, newline);
66
+ }
67
+ return buffer;
68
+ }
69
+ /**
70
+ * Lê a entrada padrão inteira como bytes, sem decodificar: um caractere multibyte partido entre
71
+ * chunks, ou um byte que não é UTF-8, chega intacto (`webhooks verify` assina sobre os bytes).
72
+ */
73
+ export async function readAllBytes(stdin) {
74
+ const chunks = [];
75
+ for await (const chunk of stdin)
76
+ chunks.push(typeof chunk === "string" ? Buffer.from(chunk, "utf8") : Buffer.from(chunk));
77
+ return new Uint8Array(Buffer.concat(chunks));
78
+ }
79
+ /** Lê a entrada padrão inteira (`--html-file -`). */
80
+ export async function readAll(stdin) {
81
+ let buffer = "";
82
+ for await (const chunk of stdin) {
83
+ buffer += typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8");
84
+ }
85
+ return buffer;
86
+ }
@@ -0,0 +1,77 @@
1
+ import { PingaError } from "@pinga/sdk";
2
+ import { CliError, ExitCode, ReportedFailure, UsageError } from "./errors.js";
3
+ /**
4
+ * Traduz qualquer falha para a saída do CLI. Erro da API mostra `title`, `detail` e `trace_id` do
5
+ * Problem Details, mais as listas de validação, que é o que o usuário precisa para corrigir o pedido
6
+ * ou abrir chamado.
7
+ */
8
+ export function renderError(error) {
9
+ if (error instanceof ReportedFailure) {
10
+ return { exitCode: ExitCode.Failure, lines: [], json: { error: {} }, reported: true };
11
+ }
12
+ if (error instanceof UsageError) {
13
+ return {
14
+ exitCode: ExitCode.Usage,
15
+ lines: [`Erro: ${error.message}`],
16
+ json: { error: { type: "usage_error", message: error.message } },
17
+ };
18
+ }
19
+ if (error instanceof PingaError) {
20
+ return renderApiError(error);
21
+ }
22
+ if (error instanceof CliError) {
23
+ return {
24
+ exitCode: ExitCode.Failure,
25
+ lines: [`Erro: ${error.message}`],
26
+ json: { error: { type: "cli_error", message: error.message } },
27
+ };
28
+ }
29
+ const message = error instanceof Error ? error.message : String(error);
30
+ return {
31
+ exitCode: ExitCode.Failure,
32
+ lines: [`Erro inesperado: ${message}`],
33
+ json: { error: { type: "unexpected_error", message } },
34
+ };
35
+ }
36
+ function renderApiError(error) {
37
+ const lines = [];
38
+ const title = error.title ?? error.type;
39
+ lines.push(error.status > 0 ? `Erro: ${title} (HTTP ${error.status})` : `Erro: ${title}`);
40
+ if (error.detail)
41
+ lines.push(` ${error.detail}`);
42
+ const errors = error.errors;
43
+ if (Array.isArray(errors)) {
44
+ for (const item of errors) {
45
+ const where = item.line != null ? ` (linha ${item.line}${item.column != null ? `, coluna ${item.column}` : ""})` : "";
46
+ lines.push(` - ${item.stage ? `${item.stage}: ` : ""}${item.message ?? ""}${where}`);
47
+ }
48
+ }
49
+ else if (errors && typeof errors === "object") {
50
+ for (const [field, messages] of Object.entries(errors)) {
51
+ for (const message of messages)
52
+ lines.push(` - ${field}: ${message}`);
53
+ }
54
+ }
55
+ for (const item of error.variableErrors ?? []) {
56
+ const name = item.name ?? item.field ?? "?";
57
+ lines.push(` - variável ${name}: ${item.message ?? item.reason ?? item.code ?? "inválida"}`);
58
+ }
59
+ if (error.traceId)
60
+ lines.push(` trace_id: ${error.traceId}`);
61
+ return {
62
+ exitCode: ExitCode.Failure,
63
+ lines,
64
+ json: {
65
+ error: {
66
+ type: error.type,
67
+ status: error.status,
68
+ title: error.title ?? null,
69
+ detail: error.detail ?? null,
70
+ trace_id: error.traceId ?? null,
71
+ code: error.code ?? null,
72
+ errors: error.errors ?? null,
73
+ variable_errors: error.variableErrors ?? null,
74
+ },
75
+ },
76
+ };
77
+ }