@kashdao/cli 0.1.0
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/CHANGELOG.md +78 -0
- package/CONTRIBUTING.md +159 -0
- package/LICENSE +21 -0
- package/README.md +868 -0
- package/SECURITY.md +110 -0
- package/dist/account-AVFLEM5D.js +90 -0
- package/dist/account-AVFLEM5D.js.map +1 -0
- package/dist/auth-GUJCVKTD.js +239 -0
- package/dist/auth-GUJCVKTD.js.map +1 -0
- package/dist/chunk-BN2CUM42.js +9 -0
- package/dist/chunk-BN2CUM42.js.map +1 -0
- package/dist/chunk-BRK7KJ4O.js +154 -0
- package/dist/chunk-BRK7KJ4O.js.map +1 -0
- package/dist/chunk-KMBMQIZ7.js +393 -0
- package/dist/chunk-KMBMQIZ7.js.map +1 -0
- package/dist/chunk-LBIRQHX5.js +133 -0
- package/dist/chunk-LBIRQHX5.js.map +1 -0
- package/dist/chunk-MIXOZU2S.js +366 -0
- package/dist/chunk-MIXOZU2S.js.map +1 -0
- package/dist/chunk-QJMF73M5.js +129 -0
- package/dist/chunk-QJMF73M5.js.map +1 -0
- package/dist/chunk-UZNSYATZ.js +680 -0
- package/dist/chunk-UZNSYATZ.js.map +1 -0
- package/dist/chunk-VIADBYFY.js +94 -0
- package/dist/chunk-VIADBYFY.js.map +1 -0
- package/dist/chunk-YHCG2SUC.js +159 -0
- package/dist/chunk-YHCG2SUC.js.map +1 -0
- package/dist/chunk-YJX3JJ4M.js +174 -0
- package/dist/chunk-YJX3JJ4M.js.map +1 -0
- package/dist/client-IOM55ZCS.js +14 -0
- package/dist/client-IOM55ZCS.js.map +1 -0
- package/dist/completion-ZZGX5BQC.js +100 -0
- package/dist/completion-ZZGX5BQC.js.map +1 -0
- package/dist/config-XJL5TSYK.js +690 -0
- package/dist/config-XJL5TSYK.js.map +1 -0
- package/dist/config-store-3ZSYGXMQ.js +44 -0
- package/dist/config-store-3ZSYGXMQ.js.map +1 -0
- package/dist/docs-MDKKSJDC.js +102 -0
- package/dist/docs-MDKKSJDC.js.map +1 -0
- package/dist/eoa-IQ72EIHR.js +551 -0
- package/dist/eoa-IQ72EIHR.js.map +1 -0
- package/dist/errors-WMZIEGQI.js +18 -0
- package/dist/errors-WMZIEGQI.js.map +1 -0
- package/dist/explain-H4EH3KH3.js +165 -0
- package/dist/explain-H4EH3KH3.js.map +1 -0
- package/dist/global-options-XOLJUPTT.js +18 -0
- package/dist/global-options-XOLJUPTT.js.map +1 -0
- package/dist/health-VZEIII74.js +98 -0
- package/dist/health-VZEIII74.js.map +1 -0
- package/dist/help-footer-GTANVDNP.js +43 -0
- package/dist/help-footer-GTANVDNP.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +251 -0
- package/dist/index.js.map +1 -0
- package/dist/intro-PQQTYWR7.js +41 -0
- package/dist/intro-PQQTYWR7.js.map +1 -0
- package/dist/markets-C37JZDPE.js +295 -0
- package/dist/markets-C37JZDPE.js.map +1 -0
- package/dist/output-VCBZ3FM7.js +22 -0
- package/dist/output-VCBZ3FM7.js.map +1 -0
- package/dist/portfolio-2AEPIJIG.js +115 -0
- package/dist/portfolio-2AEPIJIG.js.map +1 -0
- package/dist/protocol-XEQXF2GW.js +1572 -0
- package/dist/protocol-XEQXF2GW.js.map +1 -0
- package/dist/quote-I4DVJ7ZB.js +144 -0
- package/dist/quote-I4DVJ7ZB.js.map +1 -0
- package/dist/schema-PIFQ65TS.js +410 -0
- package/dist/schema-PIFQ65TS.js.map +1 -0
- package/dist/setup-USZ6IODD.js +260 -0
- package/dist/setup-USZ6IODD.js.map +1 -0
- package/dist/stdin-YW2CEQXU.js +28 -0
- package/dist/stdin-YW2CEQXU.js.map +1 -0
- package/dist/trace-IZBYTUFO.js +103 -0
- package/dist/trace-IZBYTUFO.js.map +1 -0
- package/dist/trade-IIZSEXEI.js +586 -0
- package/dist/trade-IIZSEXEI.js.map +1 -0
- package/dist/version-JDK3PEP5.js +117 -0
- package/dist/version-JDK3PEP5.js.map +1 -0
- package/dist/version-check-TDCION37.js +138 -0
- package/dist/version-check-TDCION37.js.map +1 -0
- package/dist/webhooks-PTVRKICZ.js +680 -0
- package/dist/webhooks-PTVRKICZ.js.map +1 -0
- package/dist/with-retry-4FIZG3A7.js +223 -0
- package/dist/with-retry-4FIZG3A7.js.map +1 -0
- package/package.json +99 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/webhooks/index.ts","../src/commands/webhooks/list.ts","../src/commands/webhooks/redeliver.ts","../src/commands/webhooks/replay.ts","../src/commands/webhooks/rotate-secret.ts","../src/commands/webhooks/verify.ts"],"sourcesContent":["/**\n * `kash webhooks` — manage webhook delivery for the authenticating\n * API key.\n */\n\nimport { Command } from 'commander';\n\nimport { listWebhookEventsCommand } from './list.js';\nimport { redeliverCommand } from './redeliver.js';\nimport { replayWebhookCommand } from './replay.js';\nimport { rotateSecretCommand } from './rotate-secret.js';\nimport { verifyWebhookCommand } from './verify.js';\n\nexport const webhooksCommand = new Command('webhooks')\n .description('Manage webhook delivery, signing secrets, and signature verification.')\n .addCommand(listWebhookEventsCommand)\n .addCommand(rotateSecretCommand)\n .addCommand(redeliverCommand)\n .addCommand(verifyWebhookCommand)\n .addCommand(replayWebhookCommand);\n","/**\n * `kash webhooks list` — paginated listing of webhook delivery events\n * for the authenticating key.\n *\n * Wraps `GET /v1/webhooks/events` (DX6). The same shape that surfaces\n * inline on a trade resource's `webhookDelivery` field is now also\n * accessible as a flat feed — useful for auditing what shipped and\n * triaging delivery failures without N trade lookups.\n *\n * Filter shape mirrors the SDK: `--status` accepts a comma-separated\n * list of derived statuses or can be repeated. Both forms collapse to\n * the same comma-string the server expects.\n *\n * Flag conventions mirror `kash markets list` and `kash trade list`:\n * `-l/-c/-a` short forms for `--limit/--cursor/--all`, default page\n * size 20, `--ndjson` streaming for AI-agent consumption.\n */\n\nimport { Command } from 'commander';\n\nimport { CliValidationError, toCliError } from '../../errors.js';\nimport { buildClient } from '../../utils/client.js';\nimport { parsePositiveInt, readGlobals } from '../../utils/global-options.js';\nimport { log, print, printJson, style, writeNdjson } from '../../utils/output.js';\n\nimport type { WebhookEventResource } from '@kashdao/sdk';\n\nconst STATUS_VALUES = ['none', 'pending', 'delivered', 'retrying', 'failed'] as const;\ntype StatusValue = (typeof STATUS_VALUES)[number];\n\ntype ListOptions = {\n readonly limit?: string;\n readonly cursor?: string;\n readonly status?: readonly StatusValue[];\n readonly all?: boolean;\n readonly ndjson?: boolean;\n};\n\nexport const listWebhookEventsCommand = new Command('list')\n .description('List recent webhook delivery events for the calling key.')\n .option('-l, --limit <n>', 'page size (1-100)', '20')\n .option('-c, --cursor <cursor>', 'opaque cursor from a previous response')\n .option('-a, --all', 'walk every page (subject to --limit per page)', false)\n .option(\n '--ndjson',\n 'stream results as newline-delimited JSON (one record per line); implies --all'\n )\n // Note: we deliberately do NOT use Commander's `.choices()` here.\n // Commander validates each variadic entry against the choices list\n // BEFORE our normaliser runs, so `--status failed,retrying` (a\n // single comma-string entry) gets rejected as not matching any\n // choice. The normaliser below splits commas first and then\n // validates, so both shapes (`--status failed,retrying` and\n // `--status failed --status retrying`) work.\n .option(\n '--status <status...>',\n `filter by derived status (one of: ${STATUS_VALUES.join(', ')}); repeat or comma-separate`\n )\n .addHelpText(\n 'after',\n `\nExamples:\n $ kash webhooks list\n $ kash webhooks list --status failed --status retrying\n $ kash webhooks list --status failed,retrying -l 100\n $ kash webhooks list --all --json | jq '.[] | select(.status == \"failed\")'\n $ kash webhooks list --ndjson | while read -r line; do echo \"$line\" | jq -r .id; done\n`\n )\n .action(async (opts: ListOptions, cmd: Command) => {\n const globals = readGlobals(cmd);\n\n const limit = opts.limit === undefined ? 20 : parsePositiveInt(opts.limit, 'limit');\n if (limit < 1 || limit > 100) {\n throw new CliValidationError('--limit must be between 1 and 100.', undefined, 'limit');\n }\n\n // `--status failed,retrying` (single comma-string) and\n // `--status failed --status retrying` (repeated) both reach us\n // as an array; flatten + split + dedupe so the SDK call is uniform.\n const status = normaliseStatus(opts.status);\n\n try {\n const { client } = await buildClient({ requireAuth: true, globals });\n const page = await client.webhooks.list({\n limit,\n ...(opts.cursor === undefined ? {} : { cursor: opts.cursor }),\n ...(status === undefined ? {} : { status }),\n });\n\n if (opts.ndjson === true) {\n // Stream every record as one line of NDJSON to stdout. Avoids\n // buffering the full result set — the agent reads as we go.\n for await (const event of page) {\n writeNdjson(event);\n }\n return;\n }\n\n if (opts.all === true) {\n const collected: WebhookEventResource[] = [];\n for await (const event of page) collected.push(event);\n if (globals.json) {\n // Canonical `{data, pagination, count}` — see markets/list.ts\n // for rationale. Same shape across single-page and walked\n // modes lets agents pin to one schema.\n printJson({\n data: collected,\n pagination: { hasMore: false, cursor: null },\n count: collected.length,\n });\n return;\n }\n renderRows(collected);\n return;\n }\n\n // Default: first page only.\n if (globals.json) {\n printJson({\n data: page.data,\n pagination: page.pagination,\n count: page.data.length,\n });\n return;\n }\n renderRows(page.data);\n if (page.pagination.hasMore && page.pagination.cursor) {\n log.detail('Next page', `--cursor ${page.pagination.cursor}`);\n }\n } catch (cause) {\n throw toCliError(cause);\n }\n });\n\nfunction renderRows(rows: readonly WebhookEventResource[]): void {\n if (rows.length === 0) {\n print(style.dim(' (no webhook events)'));\n return;\n }\n print('');\n for (const row of rows) {\n const statusBadge = renderStatus(row.status);\n const tradeCol = row.tradeRequestId ? row.tradeRequestId.slice(0, 8) : style.dim('—');\n print(\n ` ${statusBadge} ${style.dim(row.id.slice(0, 8))} ` +\n `${row.eventType.padEnd(28)} trade=${tradeCol} ` +\n `attempts=${String(row.delivery.attempts).padStart(2)} ` +\n `${style.dim(row.emittedAt)}`\n );\n }\n print('');\n}\n\nfunction normaliseStatus(raw: ListOptions['status']): readonly StatusValue[] | undefined {\n if (!raw || raw.length === 0) return undefined;\n // Each element may itself be comma-separated. Flatten, dedupe, and\n // validate. We throw on unknown statuses (instead of silently\n // dropping them) so a typo like `--status faild` surfaces as\n // INVALID_INPUT rather than a confusing empty result set.\n const seen = new Set<StatusValue>();\n for (const entry of raw) {\n for (const piece of entry.split(',')) {\n const trimmed = piece.trim();\n if (trimmed.length === 0) continue;\n if (!(STATUS_VALUES as readonly string[]).includes(trimmed)) {\n throw new CliValidationError(\n `Unknown --status \"${trimmed}\".`,\n `Allowed: ${STATUS_VALUES.join(', ')}.`,\n 'status'\n );\n }\n seen.add(trimmed as StatusValue);\n }\n }\n return seen.size === 0 ? undefined : [...seen];\n}\n\nfunction renderStatus(status: WebhookEventResource['status']): string {\n switch (status) {\n case 'delivered':\n return style.success('✓ delivered');\n case 'failed':\n return style.error('✗ failed ');\n case 'retrying':\n return style.warn('⟳ retrying ');\n case 'pending':\n return style.dim('… pending ');\n case 'none':\n return style.dim('· none ');\n default: {\n // Exhaustiveness guard — if a new status is added to the\n // union, TS surfaces the missing case here at compile time\n // rather than the function silently returning `undefined`.\n const _exhaustive: never = status;\n return _exhaustive;\n }\n }\n}\n","/**\n * `kash webhooks redeliver <eventId>` — re-queue an existing webhook\n * for delivery. Useful when a downstream receiver was offline.\n */\n\nimport { Command } from 'commander';\n\nimport { CliValidationError, toCliError } from '../../errors.js';\nimport { buildClient } from '../../utils/client.js';\nimport { formatDate, shortId } from '../../utils/formatting.js';\nimport { readGlobals } from '../../utils/global-options.js';\nimport { log, print, printJson, style } from '../../utils/output.js';\n\n/**\n * Event ID shape: a UUID v1/v3/v4/v5 — matches what\n * `WebhookEventResourceSchema.id` (`z.string().uuid()`) accepts. We\n * pre-flight the shape so a typo (a trade id with surrounding\n * quotes, a partial paste, the wrong field) surfaces as\n * `INVALID_INPUT` before we burn an API round-trip.\n */\nconst EVENT_ID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nexport const redeliverCommand = new Command('redeliver')\n .description('Re-queue a webhook event for delivery.')\n .argument('<eventId>', 'webhook event UUID')\n .addHelpText(\n 'after',\n `\nExamples:\n $ kash webhooks redeliver 99999999-9999-9999-9999-999999999999\n $ kash webhooks redeliver \"$(kash webhooks list --json --quiet | jq -r '.data[0].id')\"\n`\n )\n .action(async (eventId: string, _opts, cmd: Command) => {\n const globals = readGlobals(cmd);\n if (!EVENT_ID_REGEX.test(eventId)) {\n throw new CliValidationError(\n `<eventId> must be a UUID.`,\n `Got \"${eventId}\". Look up the id in \\`kash webhooks list --json --quiet | jq -r '.data[].id'\\`.`,\n 'eventId'\n );\n }\n let event;\n try {\n const { client } = await buildClient({ requireAuth: true, globals });\n event = await client.webhooks.redeliver(eventId);\n } catch (cause) {\n throw toCliError(cause);\n }\n\n if (globals.json) {\n printJson(event);\n return;\n }\n\n // All labels are padded to 16 chars so the values line up in a\n // visually consistent column. Show the FULL event id (not a\n // shortId) so the operator can correlate against logs / docs\n // without re-running `kash webhooks list`.\n log.success(`Re-delivery queued for ${event.id}.`);\n print(` ${style.dim('Event id ')} ${event.id}`);\n print(` ${style.dim('Event type ')} ${event.eventType}`);\n print(` ${style.dim('Emitted at ')} ${formatDate(event.emittedAt)}`);\n print(` ${style.dim('Attempts ')} ${String(event.deliveryAttempts)}`);\n if (event.lastDeliveredAt) {\n print(` ${style.dim('Last delivered ')} ${formatDate(event.lastDeliveredAt)}`);\n }\n // Also keep `shortId` available for CI logs that don't want the\n // full UUID — surface as a hint, not the primary value.\n log.detail('Short id', shortId(event.id));\n });\n","/**\n * `kash webhooks replay <body-file> --target <url> --secret <s>` —\n * sign a captured webhook payload with a local secret and POST it to\n * a target URL. Pairs with `kash webhooks verify` for round-trip\n * testing against a development tunnel (ngrok, cloudflared) or a\n * local server.\n *\n * **Why a built-in.** The signing format is `t=<unix-ms>,v1=<hex>`\n * (Stripe-compatible). Replicating the HMAC + header construction in\n * shell + jq is tedious and error-prone; this command does it\n * deterministically.\n *\n * **Privacy.** The body is read verbatim and forwarded — `kash\n * webhooks replay` is intentionally a thin wrapper over\n * `fetch(target)`, NOT an event reformatter. If your captured payload\n * contains PII, redact it locally before passing it in.\n *\n * **Custom timestamp.** Defaults to `Date.now()`. Pass `--timestamp-ms`\n * to replay an old payload — useful for testing the receiver's\n * replay-window enforcement (e.g. \"does my server reject deliveries\n * older than 5 minutes?\").\n */\n\nimport { createHmac } from 'node:crypto';\nimport { readFile } from 'node:fs/promises';\n\nimport { Command } from 'commander';\n\nimport { CliError, CliValidationError, toCliError } from '../../errors.js';\nimport { parsePositiveInt, readGlobals } from '../../utils/global-options.js';\nimport { log, print, printJson, style } from '../../utils/output.js';\n\ntype ReplayOptions = {\n target: string;\n secret?: string;\n secretFile?: string;\n secretEnv?: string;\n timestampMs?: string;\n signatureHeader?: string;\n timeoutMs?: string;\n dryRun?: boolean;\n refusePrivateAddresses?: boolean;\n};\n\nconst SIGNATURE_HEADER_DEFAULT = 'X-Kash-Signature';\n\nexport const replayWebhookCommand = new Command('replay')\n .description('Re-sign a captured webhook payload and POST it to a target URL.')\n .argument('[body]', 'path to a JSON body file (omit or pass \"-\" for stdin)')\n .requiredOption('-t, --target <url>', 'destination URL (e.g. ngrok tunnel or localhost endpoint)')\n .option('-s, --secret <secret>', 'webhook signing secret (overrides KASH_WEBHOOK_SECRET)')\n .option(\n '--secret-file <path>',\n 'read the signing secret from a file (preferred — keeps the value out of argv and env)'\n )\n .option(\n '--secret-env <name>',\n 'read the signing secret from this environment variable (default: KASH_WEBHOOK_SECRET)'\n )\n .option(\n '--timestamp-ms <ms>',\n 'unix-ms timestamp for the signature header (default: current time)'\n )\n .option(\n '--signature-header <name>',\n `override the signature header name (default: ${SIGNATURE_HEADER_DEFAULT})`\n )\n .option('--timeout-ms <ms>', 'fetch timeout (default 10000)')\n .option(\n '--dry-run',\n 'compute the signature header and inspect the would-be POST without sending it'\n )\n .option(\n '--refuse-private-addresses',\n 'hard-fail (instead of warning) when --target is a loopback / private / link-local address — recommended for CI'\n )\n .addHelpText(\n 'after',\n `\nExamples:\n # Auto-reads KASH_WEBHOOK_SECRET (matches \\`kash webhooks verify\\`).\n $ KASH_WEBHOOK_SECRET=whsec_… kash webhooks replay payload.json -t http://localhost:3000/webhook\n\n # Explicit secret file (preferred — keeps the value out of argv/env).\n $ kash webhooks replay payload.json -t http://localhost:3000/webhook --secret-file ~/.kash/webhook.secret\n\n # Pipe captured payload from stdin.\n $ cat payload.json | kash webhooks replay - -t … -s whsec_…\n\n # CI guardrails: refuse private targets + inspect the signed bytes\n # before sending.\n $ kash webhooks replay payload.json -t https://api.example.com --secret-file s.txt --refuse-private-addresses\n $ kash webhooks replay payload.json -t https://api.example.com --secret-file s.txt --dry-run --json\n\nNotes:\n - The signature format is \\`t=<unix-ms>,v1=<hex-hmac-sha256>\\` —\n Stripe-compatible. The receiver verifies via \\`kash webhooks verify\\`\n or the SDK's \\`webhooks.verifySignature\\`.\n - Defaults the timestamp to \\`Date.now()\\`. Pass \\`--timestamp-ms\\`\n with an old timestamp to test the receiver's replay-window\n rejection (the SDK's default is 5 min).\n - Secret resolution order: --secret > --secret-file > --secret-env\n > KASH_WEBHOOK_SECRET. --secret-file is preferred — it keeps the\n value out of argv (where \\`ps\\` could see it) and out of env (where\n a child process would inherit it).\n - --dry-run is safe to run anywhere — it never opens a network\n socket. Use it to inspect the signature header before pointing\n a fresh receiver at production traffic.\n`\n )\n .action(async (body: string | undefined, options: ReplayOptions, cmd: Command) => {\n const globals = readGlobals(cmd);\n try {\n // Resolve secret: --secret > --secret-file > --secret-env > KASH_WEBHOOK_SECRET.\n // Refuse if all are missing/empty.\n const secret = await resolveSecret(options);\n\n // Resolve target (URL validation + private-address policy). The\n // policy is hard-refuse when --refuse-private-addresses is set\n // (recommended for CI), otherwise warn-only (the historical\n // default — needed for local-tunnel testing).\n const targetUrl = validateTarget(options.target, {\n refusePrivate: options.refusePrivateAddresses === true,\n });\n\n // Read the body verbatim. We sign whatever bytes the user\n // captured — bit-exact match is what the receiver's verifier\n // expects.\n const rawBody = await readBody(body);\n\n const timestampMs = options.timestampMs\n ? parsePositiveInt(options.timestampMs, 'timestamp-ms')\n : Date.now();\n const timeoutMs = options.timeoutMs\n ? parsePositiveInt(options.timeoutMs, 'timeout-ms')\n : 10_000;\n\n // Compute HMAC: `t=<ms>,v1=<hex>` over the canonical\n // `<timestamp>.<body>` payload. Same shape `verifySignature`\n // checks against.\n const headerName = options.signatureHeader ?? SIGNATURE_HEADER_DEFAULT;\n const headerValue = computeSignatureHeader(rawBody, secret, timestampMs);\n\n // --dry-run short-circuit: emit the would-be POST envelope and\n // return without opening a network socket. Useful for previewing\n // the signature against a fresh receiver before pointing real\n // traffic at it.\n if (options.dryRun === true) {\n if (globals.json) {\n printJson({\n targetUrl,\n headerName,\n headerValue,\n timestampMs,\n bodyBytes: Buffer.byteLength(rawBody, 'utf8'),\n dryRun: true,\n });\n return;\n }\n print('');\n log.success('Dry run — signature computed, no request sent.');\n print(` ${style.dim('Target ')} ${targetUrl}`);\n print(` ${style.dim('Header ')} ${headerName}: ${headerValue}`);\n print(` ${style.dim('Body ')} ${String(Buffer.byteLength(rawBody, 'utf8'))} bytes`);\n log.info('Re-run without --dry-run to send.');\n return;\n }\n\n // POST. Use `fetch` (Node 22+ ships it). Bound by a timeout so\n // a wedged target doesn't hang the CLI.\n const result = await deliver({\n targetUrl,\n body: rawBody,\n headerName,\n headerValue,\n timeoutMs,\n });\n\n if (globals.json) {\n printJson({\n targetUrl,\n headerName,\n headerValue,\n timestampMs,\n status: result.status,\n ok: result.ok,\n durationMs: result.durationMs,\n responseBody: result.body,\n });\n return;\n }\n\n // Human mode: brief result + the response body for inspection.\n print('');\n if (result.ok) {\n log.success(`Delivered in ${String(result.durationMs)}ms — HTTP ${String(result.status)}.`);\n } else {\n log.error(\n `Receiver returned HTTP ${String(result.status)} (after ${String(result.durationMs)}ms).`\n );\n }\n print(` ${style.dim('Target ')} ${targetUrl}`);\n print(` ${style.dim('Header ')} ${headerName}: ${headerValue}`);\n if (result.body.length > 0) {\n print('');\n print(style.dim('--- Response body ---'));\n print(result.body);\n }\n } catch (cause) {\n throw toCliError(cause);\n }\n });\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nasync function resolveSecret(options: ReplayOptions): Promise<string> {\n // Resolution order matches `kash webhooks verify` so the two\n // commands are interchangeable from the operator's POV:\n // 1. --secret (explicit; convenient but lands in argv)\n // 2. --secret-file (preferred — value never crosses argv/env)\n // 3. --secret-env <NAME> (read from named env var)\n // 4. KASH_WEBHOOK_SECRET (default env, no flag needed)\n if (options.secret !== undefined) return options.secret;\n if (options.secretFile !== undefined) {\n try {\n const raw = await readFile(options.secretFile, 'utf8');\n // Strip a trailing newline that text editors append; secrets\n // never include leading/trailing whitespace.\n return raw.trim();\n } catch {\n throw new CliValidationError(\n `--secret-file: failed to read ${options.secretFile}.`,\n 'Verify the file exists and is readable.',\n 'secret-file'\n );\n }\n }\n if (options.secretEnv !== undefined) {\n const value = process.env[options.secretEnv];\n if (!value || value.length === 0) {\n throw new CliError(`--secret-env ${options.secretEnv} is not set or empty.`, {\n code: 'INVALID_INPUT',\n recoverable: true,\n suggestion: `Set ${options.secretEnv}=<webhook-secret> before re-running.`,\n });\n }\n return value;\n }\n const fromEnv = process.env['KASH_WEBHOOK_SECRET'];\n if (fromEnv !== undefined && fromEnv.length > 0) return fromEnv;\n throw new CliValidationError(\n 'A signing secret is required.',\n 'Pass --secret-file (preferred), --secret, --secret-env <NAME>, or set KASH_WEBHOOK_SECRET.',\n 'secret'\n );\n}\n\nfunction validateTarget(raw: string, policy: { refusePrivate: boolean }): string {\n let url: URL;\n try {\n url = new URL(raw);\n } catch {\n throw new CliValidationError(\n '--target must be a valid URL.',\n `Got \"${raw}\". Include the scheme (http:// or https://).`,\n 'target'\n );\n }\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n throw new CliValidationError(\n `--target must use http:// or https:// (got \"${url.protocol}\").`,\n undefined,\n 'target'\n );\n }\n // SSRF guard: by default warn when the target host is a loopback /\n // private / link-local address. `kash webhooks replay` is a\n // developer tool, not a server, so the risk is bounded — but a\n // misconfigured run against `169.254.169.254` (cloud metadata\n // service) or a VPN-bound private range can still exfiltrate\n // sensitive data through the signed POST body. The default warn\n // (instead of refuse) preserves local-tunnel testing (the common\n // case: `localhost:3000`, `127.0.0.1:3000`).\n //\n // CI runs and production-flavoured tests should pass\n // `--refuse-private-addresses` to upgrade the warning to a hard\n // failure — the policy parameter does that.\n if (policy.refusePrivate && isPrivateAddress(url)) {\n throw new CliValidationError(\n `--target points at a private address (${url.hostname}) and --refuse-private-addresses is set.`,\n 'Drop the flag to allow private targets, or change --target to a public URL.',\n 'target'\n );\n }\n warnIfPrivateAddress(url);\n return url.toString();\n}\n\n/**\n * Best-effort literal-IP-shape check. Matches:\n *\n * - IPv4 loopback (127/8 — silent, expected for dev tunnels)\n * - IPv4 link-local (169.254/16 — louder warning; cloud metadata\n * services live here)\n * - IPv4 private ranges (10/8, 172.16/12, 192.168/16)\n * - IPv6 loopback (::1)\n * - IPv6 link-local (fe80::/10)\n * - IPv6 unique local (fc00::/7, which covers fc00:: and fd00::)\n *\n * Hostnames are intentionally NOT resolved here — full DNS resolution\n * would couple this CLI command to an async resolver and add a\n * network round-trip on every replay. That means cloud metadata\n * hostnames like `metadata.google.internal` are NOT caught (they\n * resolve to `169.254.169.254` only at request time); operators\n * relying on hostname-based aliases for sensitive endpoints must\n * audit their `--target` values themselves. The literal-IP check\n * here catches the most common foot-gun: a copy-pasted\n * `169.254.169.254` or private-range URL.\n *\n * The IPv4 octet regex bounds octets to 0–255 explicitly so a\n * pathological host like `999.999.999.999` (which `URL` happily\n * accepts as a hostname string) does not silently coerce into a\n * matching octet via `parseInt`.\n */\nexport function warnIfPrivateAddress(url: URL): void {\n // `url.hostname` keeps the surrounding [...] for IPv6 literals\n // (per the WHATWG URL spec — Node, browsers, and the URL standard\n // all agree). Strip them for the prefix matching below so the\n // regexes deal with bare hex hextets.\n const rawHost = url.hostname;\n const host = rawHost.startsWith('[') && rawHost.endsWith(']') ? rawHost.slice(1, -1) : rawHost;\n\n // IPv6 loopback.\n if (host === '::1') {\n emitPrivateWarning(rawHost);\n return;\n }\n\n // Localhost name (and `*.localhost` per RFC 6761) — silent.\n if (host === 'localhost' || host.endsWith('.localhost')) return;\n\n // IPv6 link-local (fe80::/10) — first 10 bits are 1111 1110 10.\n // The leading hextet `fexx` ranges from fe80 to febf. The textual\n // prefix is therefore `fe` followed by one of `8`, `9`, `a`, `b`,\n // followed by any hex digit, followed by either `:` (short form,\n // e.g. `fe80::1`) or another hex digit then `:` (full form,\n // e.g. `fe80:0:…`). Match case-insensitively.\n if (/^fe[89ab][0-9a-f]{0,2}:/i.test(host)) {\n emitLinkLocalWarning(rawHost);\n return;\n }\n\n // IPv6 unique-local (fc00::/7) — first 7 bits are 1111 110, so any\n // address whose leading hextet starts with `fc` or `fd`. Allow up\n // to two more hex digits before the `:` separator (covers `fc::`,\n // `fc1::`, `fcab::`, `fd00::`, etc.).\n if (/^f[cd][0-9a-f]{0,2}:/i.test(host)) {\n emitPrivateWarning(rawHost);\n return;\n }\n\n // IPv4 octet match — bounded 0..255 so `999.999.999.999` doesn't\n // silently match. `URL` accepts these strings as hostnames, so the\n // bound matters.\n const ipv4 =\n /^(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)$/.exec(\n host\n );\n if (!ipv4) return; // hostname (no DNS check — see jsdoc)\n const [, a, b] = ipv4;\n const oct1 = Number.parseInt(a!, 10);\n const oct2 = Number.parseInt(b!, 10);\n if (oct1 === 127) return; // loopback — expected for `127.0.0.1` etc.\n if (oct1 === 10) {\n emitPrivateWarning(host);\n return;\n }\n if (oct1 === 172 && oct2 >= 16 && oct2 <= 31) {\n emitPrivateWarning(host);\n return;\n }\n if (oct1 === 192 && oct2 === 168) {\n emitPrivateWarning(host);\n return;\n }\n if (oct1 === 169 && oct2 === 254) {\n emitLinkLocalWarning(host);\n return;\n }\n}\n\n/**\n * Pure predicate version of {@link warnIfPrivateAddress} — same set\n * of literal-IP shapes (loopback, link-local, RFC1918 private,\n * IPv6 ::1 / fe80::/10 / fc00::/7), but returns a boolean instead of\n * writing to stderr. Used by the `--refuse-private-addresses` policy\n * to hard-fail the run; the warn-only path stays as before.\n *\n * Hostnames that aren't literal IPs are treated as \"not private\"\n * (same documented limitation as the warning function — no DNS).\n */\nexport function isPrivateAddress(url: URL): boolean {\n const rawHost = url.hostname;\n const host = rawHost.startsWith('[') && rawHost.endsWith(']') ? rawHost.slice(1, -1) : rawHost;\n\n if (host === '::1') return true;\n if (host === 'localhost' || host.endsWith('.localhost')) return true;\n if (/^fe[89ab][0-9a-f]{0,2}:/i.test(host)) return true;\n if (/^f[cd][0-9a-f]{0,2}:/i.test(host)) return true;\n\n const ipv4 =\n /^(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)$/.exec(\n host\n );\n if (!ipv4) return false;\n const oct1 = Number.parseInt(ipv4[1]!, 10);\n const oct2 = Number.parseInt(ipv4[2]!, 10);\n if (oct1 === 127) return true; // loopback\n if (oct1 === 10) return true;\n if (oct1 === 172 && oct2 >= 16 && oct2 <= 31) return true;\n if (oct1 === 192 && oct2 === 168) return true;\n if (oct1 === 169 && oct2 === 254) return true; // link-local\n return false;\n}\n\nfunction emitLinkLocalWarning(host: string): void {\n // Worth a louder warning since link-local is the textbook SSRF\n // target — AWS / GCP / Azure metadata services live here.\n process.stderr.write(\n `\\u26a0 --target points at a link-local address (${host}). This range hosts cloud metadata services. Verify the target is intentional.\\n`\n );\n}\n\nfunction emitPrivateWarning(host: string): void {\n process.stderr.write(\n `\\u26a0 --target points at a private address (${host}). Verify this is your dev tunnel and not an internal service.\\n`\n );\n}\n\nasync function readBody(file: string | undefined): Promise<string> {\n if (file !== undefined && file !== '-') {\n let raw: string;\n try {\n raw = await readFile(file, 'utf8');\n } catch (cause) {\n throw new CliError(`Failed to read ${file}.`, {\n code: 'CONFIGURATION',\n recoverable: true,\n suggestion: 'Verify the path exists and is readable.',\n cause,\n });\n }\n // Strip the BOM here too — the file branch is the more common\n // case when operators are testing with captured payloads dropped\n // by Notepad or VSCode-with-utf8bom.\n const { stripBom } = await import('../../utils/stdin.js');\n return stripBom(raw);\n }\n // Stdin.\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n if (typeof chunk === 'string') chunks.push(Buffer.from(chunk));\n else if (chunk instanceof Buffer) chunks.push(chunk);\n else chunks.push(Buffer.from(chunk as Uint8Array));\n }\n if (chunks.length === 0) {\n throw new CliValidationError(\n 'No input received on stdin.',\n 'Pass a file path or pipe a webhook body into stdin.'\n );\n }\n // Strip a leading UTF-8 BOM. Notepad / VSCode-with-utf8bom and many\n // Windows tools prepend U+FEFF; without the strip the receiver\n // would HMAC-verify a body that starts with the BOM, but its own\n // JSON.parse would fail (BOM isn't valid leading whitespace in\n // JSON). Strip on read so the signature matches the parsed body.\n const { stripBom } = await import('../../utils/stdin.js');\n return stripBom(Buffer.concat(chunks).toString('utf8'));\n}\n\n/**\n * Build the Stripe-compatible signature header. Format is exactly\n * `t=<unix-ms>,v1=<hex-hmac-sha256>` — same shape the SDK's\n * `parseSignatureHeader` accepts. We replicate the math here rather\n * than reaching into the SDK's private helpers (which aren't\n * exported); the impl is small and the algorithm is stable.\n */\nexport function computeSignatureHeader(body: string, secret: string, timestampMs: number): string {\n const payload = `${String(timestampMs)}.${body}`;\n const hex = createHmac('sha256', secret).update(payload).digest('hex');\n return `t=${String(timestampMs)},v1=${hex}`;\n}\n\ntype DeliveryResult = {\n readonly status: number;\n readonly ok: boolean;\n readonly body: string;\n readonly durationMs: number;\n};\n\nasync function deliver(args: {\n readonly targetUrl: string;\n readonly body: string;\n readonly headerName: string;\n readonly headerValue: string;\n readonly timeoutMs: number;\n}): Promise<DeliveryResult> {\n const start = Date.now();\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), args.timeoutMs);\n\n // The CLI is a published-to-npm public package that intentionally\n // has zero `@kashdao/*` runtime deps beyond `@kashdao/sdk` and\n // `@kashdao/protocol-sdk` (enforced by sync-to-public-mirror.ts).\n // Pulling in `@kashdao/http-client` would break that invariant.\n // The webhook replay is to a USER-supplied URL (already SSRF-guarded\n // by `--refuse-private-addresses` upstream of this call); the call\n // is one-shot, has a caller-set timeout via AbortController, and\n // propagates failures explicitly via `DeliveryResult`.\n try {\n const response = await /* eslint-disable-line @kashdao/no-bare-fetch */ fetch(args.targetUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n [args.headerName]: args.headerValue,\n },\n body: args.body,\n signal: controller.signal,\n });\n const responseBody = await response.text();\n return {\n status: response.status,\n ok: response.ok,\n body: responseBody,\n durationMs: Date.now() - start,\n };\n } catch (cause) {\n // Timeout detection. `AbortError` covers most cases, but Node's\n // fetch can surface a header-stage timeout via `cause.cause` with\n // an UND_ERR_HEADERS_TIMEOUT-style code in which `name` is not\n // `AbortError`. The AbortController is the authoritative signal:\n // if we triggered it, this is a timeout regardless of the error's\n // visible shape.\n const wasAborted = controller.signal.aborted;\n const looksLikeAbort = cause instanceof Error && cause.name === 'AbortError';\n if (wasAborted || looksLikeAbort) {\n throw new CliError(`Delivery timed out after ${String(args.timeoutMs)}ms.`, {\n code: 'TIMEOUT',\n recoverable: true,\n suggestion: 'Raise --timeout-ms or check the target endpoint is responsive.',\n cause,\n });\n }\n throw new CliError(\n `Delivery failed: ${cause instanceof Error ? cause.message : String(cause)}`,\n {\n code: 'NETWORK',\n recoverable: true,\n suggestion: 'Verify the target URL is reachable from this machine.',\n cause,\n }\n );\n } finally {\n clearTimeout(timer);\n }\n}\n","/**\n * `kash webhooks rotate-secret` — rotate the signing secret for the\n * authenticating API key. The plaintext secret is returned ONCE.\n *\n * This is a destructive operation: the current secret is invalidated\n * immediately on success. Interactive callers (TTY, not --json, not\n * --quiet) get a confirmation prompt to prevent one-keystroke prod\n * webhook breakage. CI / scripted callers can bypass with `--yes`,\n * which is also what `--json --quiet` implies (no TTY for prompting,\n * caller knows what it's doing).\n */\n\nimport readline from 'node:readline/promises';\n\nimport { Command } from 'commander';\n\nimport { toCliError } from '../../errors.js';\nimport { buildClient } from '../../utils/client.js';\nimport { formatDate } from '../../utils/formatting.js';\nimport { readGlobals } from '../../utils/global-options.js';\nimport { log, print, printJson, style } from '../../utils/output.js';\n\ntype RotateOptions = {\n yes?: boolean;\n};\n\nexport const rotateSecretCommand = new Command('rotate-secret')\n .description('Rotate the webhook signing secret for the current API key.')\n .option('-y, --yes', 'skip the interactive confirmation (required for --json --quiet)')\n .addHelpText(\n 'after',\n `\nExamples:\n $ kash webhooks rotate-secret # interactive confirm\n $ kash webhooks rotate-secret --yes # skip confirm\n $ kash webhooks rotate-secret --yes --json --quiet | jq -r '.secret' > new-secret.txt\n\nNotes:\n This invalidates your current webhook secret immediately. Receivers\n that haven't been updated will start failing signature verification\n on the next event. Have your secret-store update plan ready before\n confirming.\n`\n )\n .action(async (options: RotateOptions, cmd: Command) => {\n const globals = readGlobals(cmd);\n\n const interactive = process.stdin.isTTY && !globals.quiet && !globals.json;\n const confirmed = options.yes === true || !interactive ? true : await confirm();\n if (!confirmed) {\n log.info('Aborted.');\n return;\n }\n\n let secret;\n try {\n const { client } = await buildClient({ requireAuth: true, globals });\n secret = await client.webhooks.rotateSecret();\n } catch (cause) {\n throw toCliError(cause);\n }\n\n if (globals.json) {\n printJson(secret);\n return;\n }\n\n log.warn('Webhook secret rotated. The new secret is shown ONCE.');\n print('');\n print(` ${style.bold('Secret')}: ${secret.secret}`);\n print(` ${style.dim('Rotated at ')}: ${formatDate(secret.rotatedAt)}`);\n print(` ${style.dim('Previous valid until')}: ${formatDate(secret.previousRetainedUntil)}`);\n print('');\n log.info('Store this secret in your webhook receiver immediately.');\n });\n\nasync function confirm(): Promise<boolean> {\n const rl = readline.createInterface({ input: process.stdin, output: process.stderr });\n try {\n const answer = await rl.question(\n 'This will invalidate your current webhook secret. Continue? [y/N] '\n );\n return answer.trim().toLowerCase().startsWith('y');\n } finally {\n rl.close();\n }\n}\n","/**\n * `kash webhooks verify` — offline HMAC-SHA256 signature verification.\n *\n * Wraps the SDK's `webhooks.verifySignature` so an operator\n * debugging webhook delivery can ad-hoc verify a captured payload\n * against the signing secret. Useful when:\n *\n * - A webhook receiver rejected an event and the operator wants to\n * confirm whether the signature was actually valid.\n * - An agent pipes a captured webhook through `kash webhooks\n * verify --quiet --json` to check authenticity before acting.\n *\n * Reads the body from `--body-file <path>` (recommended — preserves\n * exact bytes) or `--body <string>` (convenient for short payloads).\n * Reads the secret from `--secret <value>`, `--secret-file <path>`,\n * or `KASH_WEBHOOK_SECRET` env. The signature comes from the captured\n * `X-Kash-Signature` header value.\n */\n\nimport { readFile } from 'node:fs/promises';\n\nimport { Command } from 'commander';\n\nimport { CliValidationError, toCliError } from '../../errors.js';\nimport { buildClient } from '../../utils/client.js';\nimport { parsePositiveInt, readGlobals } from '../../utils/global-options.js';\nimport { log, print, printJson, style } from '../../utils/output.js';\n\ntype VerifyOptions = {\n signature: string;\n body?: string;\n bodyFile?: string;\n secret?: string;\n secretFile?: string;\n toleranceMs?: string;\n};\n\nexport const verifyWebhookCommand = new Command('verify')\n .description('Verify a captured X-Kash-Signature against the raw body and secret.')\n .requiredOption('-s, --signature <header>', 'the X-Kash-Signature header value (e.g. \"t=…,v1=…\")')\n .option('--body <string>', 'raw request body as a string (use --body-file for binary-safe input)')\n .option('--body-file <path>', 'path to a file containing the raw request body')\n .option('--secret <value>', 'webhook signing secret (overrides KASH_WEBHOOK_SECRET)')\n .option(\n '--secret-file <path>',\n 'read secret from a file (preferred over --secret on shared shells)'\n )\n .option(\n '--tolerance-ms <n>',\n 'replay-window tolerance in milliseconds (default 300000 = 5 minutes)'\n )\n .addHelpText(\n 'after',\n `\nExamples:\n $ kash webhooks verify --signature \"t=…,v1=…\" --body-file event.json\n $ kash webhooks verify -s \"$SIG\" --body \"$BODY\" --secret-file ~/.kash/webhook.secret --json\n`\n )\n .action(async (options: VerifyOptions, cmd: Command) => {\n const globals = readGlobals(cmd);\n\n if (options.body !== undefined && options.bodyFile !== undefined) {\n throw new CliValidationError('Pass exactly one of --body or --body-file.', undefined, 'body');\n }\n if (options.body === undefined && options.bodyFile === undefined) {\n throw new CliValidationError('--body or --body-file is required.', undefined, 'body');\n }\n if (options.secret !== undefined && options.secretFile !== undefined) {\n throw new CliValidationError(\n 'Pass at most one of --secret or --secret-file.',\n undefined,\n 'secret'\n );\n }\n\n const body =\n options.body !== undefined\n ? options.body\n : await readFileChecked(options.bodyFile!, 'body-file');\n const secret = await resolveSecret(options);\n const toleranceMs =\n options.toleranceMs === undefined\n ? undefined\n : parsePositiveInt(options.toleranceMs, 'tolerance-ms');\n\n let result;\n try {\n const { client } = await buildClient({ globals });\n result = await client.webhooks.verifySignature(body, options.signature, secret, {\n ...(toleranceMs === undefined ? {} : { toleranceMs }),\n });\n } catch (cause) {\n throw toCliError(cause);\n }\n\n if (globals.json) {\n printJson(result);\n return;\n }\n if (result.valid) {\n print(`${style.success('✓')} Signature is valid.`);\n } else {\n log.error(`Signature is INVALID: ${result.reason}`);\n }\n });\n\nasync function readFileChecked(path: string, flag: string): Promise<string> {\n try {\n return await readFile(path, 'utf8');\n } catch (cause) {\n throw new CliValidationError(\n `Failed to read ${flag} ${path}: ${(cause as Error).message}`,\n 'Verify the path exists and is readable.',\n flag\n );\n }\n}\n\nasync function resolveSecret(options: VerifyOptions): Promise<string> {\n if (options.secret !== undefined) return options.secret;\n if (options.secretFile !== undefined) {\n const raw = await readFileChecked(options.secretFile, 'secret-file');\n // Strip a trailing newline that text editors append; secrets\n // never include leading/trailing whitespace.\n return raw.trim();\n }\n const fromEnv = process.env['KASH_WEBHOOK_SECRET'];\n if (fromEnv !== undefined && fromEnv.length > 0) return fromEnv;\n throw new CliValidationError(\n 'Webhook secret not provided.',\n 'Pass --secret-file (preferred), --secret, or set KASH_WEBHOOK_SECRET.',\n 'secret'\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,SAAS,WAAAA,gBAAe;;;ACaxB,SAAS,eAAe;AASxB,IAAM,gBAAgB,CAAC,QAAQ,WAAW,aAAa,YAAY,QAAQ;AAWpE,IAAM,2BAA2B,IAAI,QAAQ,MAAM,EACvD,YAAY,0DAA0D,EACtE,OAAO,mBAAmB,qBAAqB,IAAI,EACnD,OAAO,yBAAyB,wCAAwC,EACxE,OAAO,aAAa,iDAAiD,KAAK,EAC1E;AAAA,EACC;AAAA,EACA;AACF,EAQC;AAAA,EACC;AAAA,EACA,qCAAqC,cAAc,KAAK,IAAI,CAAC;AAC/D,EACC;AAAA,EACC;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQF,EACC,OAAO,OAAO,MAAmB,QAAiB;AACjD,QAAM,UAAU,YAAY,GAAG;AAE/B,QAAM,QAAQ,KAAK,UAAU,SAAY,KAAK,iBAAiB,KAAK,OAAO,OAAO;AAClF,MAAI,QAAQ,KAAK,QAAQ,KAAK;AAC5B,UAAM,IAAI,mBAAmB,sCAAsC,QAAW,OAAO;AAAA,EACvF;AAKA,QAAM,SAAS,gBAAgB,KAAK,MAAM;AAE1C,MAAI;AACF,UAAM,EAAE,OAAO,IAAI,MAAM,YAAY,EAAE,aAAa,MAAM,QAAQ,CAAC;AACnE,UAAM,OAAO,MAAM,OAAO,SAAS,KAAK;AAAA,MACtC;AAAA,MACA,GAAI,KAAK,WAAW,SAAY,CAAC,IAAI,EAAE,QAAQ,KAAK,OAAO;AAAA,MAC3D,GAAI,WAAW,SAAY,CAAC,IAAI,EAAE,OAAO;AAAA,IAC3C,CAAC;AAED,QAAI,KAAK,WAAW,MAAM;AAGxB,uBAAiB,SAAS,MAAM;A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command","Command","resolveSecret","readFile","Command"]}
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
parsePositiveInt,
|
|
4
|
+
readGlobals
|
|
5
|
+
} from "./chunk-LBIRQHX5.js";
|
|
6
|
+
import {
|
|
7
|
+
log,
|
|
8
|
+
style
|
|
9
|
+
} from "./chunk-VIADBYFY.js";
|
|
10
|
+
import "./chunk-MIXOZU2S.js";
|
|
11
|
+
import {
|
|
12
|
+
CliError,
|
|
13
|
+
toCliError
|
|
14
|
+
} from "./chunk-UZNSYATZ.js";
|
|
15
|
+
|
|
16
|
+
// src/commands/with-retry.ts
|
|
17
|
+
import { spawn } from "child_process";
|
|
18
|
+
import { Command } from "commander";
|
|
19
|
+
var RETRYABLE_CODES = /* @__PURE__ */ new Set([
|
|
20
|
+
"RATE_LIMITED",
|
|
21
|
+
"NETWORK",
|
|
22
|
+
"TIMEOUT",
|
|
23
|
+
"MAINTENANCE",
|
|
24
|
+
"SERVER_ERROR"
|
|
25
|
+
]);
|
|
26
|
+
var TERMINAL_CODES = /* @__PURE__ */ new Set([
|
|
27
|
+
"INVALID_INPUT",
|
|
28
|
+
"AUTH_REQUIRED",
|
|
29
|
+
"INSUFFICIENT_SCOPE",
|
|
30
|
+
"NOT_FOUND",
|
|
31
|
+
"CONFLICT",
|
|
32
|
+
"CONFIGURATION",
|
|
33
|
+
"DIRECT_CONFIG_MISSING",
|
|
34
|
+
"SIGNER_FAILED"
|
|
35
|
+
]);
|
|
36
|
+
var withRetryCommand = new Command("with-retry").description("Re-run a kash command on recoverable failures (rate limits, transient errors).").option("--max-attempts <n>", "maximum total attempts including the first (default 5)", "5").option(
|
|
37
|
+
"--initial-delay-ms <n>",
|
|
38
|
+
"starting backoff when the envelope has no retryAfterMs (default 1000)",
|
|
39
|
+
"1000"
|
|
40
|
+
).option("--max-delay-ms <n>", "cap on the per-attempt wait (default 30000)", "30000").option(
|
|
41
|
+
"--retry-without-json",
|
|
42
|
+
"retry even when the inner command did not emit --json (no envelope to discriminate terminal from transient \u2014 opt in if you trust the inner command failed transiently)"
|
|
43
|
+
).allowUnknownOption().argument("<command...>", "kash command + args; pass after `--` to disambiguate").addHelpText(
|
|
44
|
+
"after",
|
|
45
|
+
`
|
|
46
|
+
Examples:
|
|
47
|
+
$ kash with-retry --max-attempts 5 -- markets list --status ACTIVE --json
|
|
48
|
+
$ kash with-retry -- trade buy <id> --outcome 0 --amount 10 \\
|
|
49
|
+
--auto-idempotency-key --json --quiet
|
|
50
|
+
$ kash with-retry --max-attempts 3 -- health --json --quiet
|
|
51
|
+
|
|
52
|
+
Notes:
|
|
53
|
+
- The wrapped command MUST come after \`--\` so its flags don't collide
|
|
54
|
+
with with-retry's own.
|
|
55
|
+
- When the wrapped command emits --json, the error envelope's
|
|
56
|
+
\`code\` / \`recoverable\` / \`retryAfterMs\` drive the retry. Recoverable
|
|
57
|
+
codes (RATE_LIMITED, NETWORK, TIMEOUT, MAINTENANCE, SERVER_ERROR)
|
|
58
|
+
retry; terminal codes (INVALID_INPUT, AUTH_REQUIRED, NOT_FOUND, \u2026)
|
|
59
|
+
fail fast.
|
|
60
|
+
- Without --json on the inner command, we DO NOT retry by default \u2014
|
|
61
|
+
no envelope means we can't tell INVALID_INPUT from a transient
|
|
62
|
+
NETWORK error, and retrying validation 5\xD7 wastes time. Pass
|
|
63
|
+
--retry-without-json to force exponential backoff regardless.
|
|
64
|
+
`
|
|
65
|
+
).action(async (commandArgs, options, cmd) => {
|
|
66
|
+
const globals = readGlobals(cmd);
|
|
67
|
+
const maxAttempts = options.maxAttempts ? parsePositiveInt(options.maxAttempts, "max-attempts") : 5;
|
|
68
|
+
const initialDelay = options.initialDelayMs ? parsePositiveInt(options.initialDelayMs, "initial-delay-ms") : 1e3;
|
|
69
|
+
const maxDelay = options.maxDelayMs ? parsePositiveInt(options.maxDelayMs, "max-delay-ms") : 3e4;
|
|
70
|
+
if (commandArgs.length === 0) {
|
|
71
|
+
throw new CliError("with-retry needs a command to run.", {
|
|
72
|
+
code: "INVALID_INPUT",
|
|
73
|
+
recoverable: true,
|
|
74
|
+
suggestion: "Pass the kash command after `--`, e.g. `kash with-retry -- health --json --quiet`."
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
try {
|
|
78
|
+
await runWithRetry(commandArgs, {
|
|
79
|
+
maxAttempts,
|
|
80
|
+
initialDelay,
|
|
81
|
+
maxDelay,
|
|
82
|
+
humanMode: !globals.json,
|
|
83
|
+
retryWithoutJson: options.retryWithoutJson === true
|
|
84
|
+
});
|
|
85
|
+
} catch (cause) {
|
|
86
|
+
throw toCliError(cause);
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
async function runWithRetry(args, opts) {
|
|
90
|
+
for (let attempt = 1; attempt <= opts.maxAttempts; attempt++) {
|
|
91
|
+
const result = await runOnce(args);
|
|
92
|
+
if (result.exitCode === 0) {
|
|
93
|
+
if (result.stdout) process.stdout.write(result.stdout);
|
|
94
|
+
process.exit(0);
|
|
95
|
+
}
|
|
96
|
+
const envelope = parseErrorEnvelope(result.stdout) ?? parseErrorEnvelope(result.stderr);
|
|
97
|
+
const code = envelope?.error.code;
|
|
98
|
+
const recoverable = decideRetry(code, envelope?.error.recoverable, {
|
|
99
|
+
retryWithoutJson: opts.retryWithoutJson
|
|
100
|
+
});
|
|
101
|
+
if (!recoverable || attempt === opts.maxAttempts) {
|
|
102
|
+
if (result.stdout) process.stdout.write(result.stdout);
|
|
103
|
+
if (opts.humanMode) {
|
|
104
|
+
const reason = !recoverable ? "non-recoverable error" : "max attempts exhausted";
|
|
105
|
+
log.error(`with-retry: ${reason} after attempt ${String(attempt)} (${code ?? "unknown"}).`);
|
|
106
|
+
}
|
|
107
|
+
process.exit(result.exitCode);
|
|
108
|
+
}
|
|
109
|
+
const wait = computeWait(envelope?.error.retryAfterMs, attempt, opts);
|
|
110
|
+
if (opts.humanMode) {
|
|
111
|
+
process.stderr.write(
|
|
112
|
+
`${style.dim(
|
|
113
|
+
`with-retry: attempt ${String(attempt)}/${String(opts.maxAttempts)} failed (${code ?? "unknown"}); retrying in ${String(wait)}ms\u2026`
|
|
114
|
+
)}
|
|
115
|
+
`
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
await sleep(wait);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
async function runOnce(args) {
|
|
122
|
+
return await new Promise((resolve, reject) => {
|
|
123
|
+
const node = process.execPath;
|
|
124
|
+
const entry = process.argv[1];
|
|
125
|
+
if (!entry) {
|
|
126
|
+
reject(new Error("with-retry: cannot determine kash entry path."));
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
const child = spawn(node, [entry, ...args], {
|
|
130
|
+
// stdin: 'ignore' (NOT 'inherit'). With inherit, an inner
|
|
131
|
+
// command that prompts for input (`kash auth set-key` without
|
|
132
|
+
// --from-stdin, an interactive `kash setup`) would silently
|
|
133
|
+
// hang on retry — the prompt waits for input but the parent's
|
|
134
|
+
// stdin has already been consumed (or is non-interactive in
|
|
135
|
+
// the CI case). A retry loop should never be holding an
|
|
136
|
+
// interactive prompt; if the inner command needs stdin, the
|
|
137
|
+
// user runs it directly. `kash with-retry` is for commands
|
|
138
|
+
// that read auth/config from env or pre-set state.
|
|
139
|
+
// stdout + stderr stay piped so we can capture and re-emit.
|
|
140
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
141
|
+
// Inherit env so the child sees KASH_API_KEY, KASH_PROFILE, etc.
|
|
142
|
+
env: process.env
|
|
143
|
+
});
|
|
144
|
+
let stdout = "";
|
|
145
|
+
child.stdout.on("data", (chunk) => {
|
|
146
|
+
stdout += chunk.toString("utf8");
|
|
147
|
+
});
|
|
148
|
+
let stderr = "";
|
|
149
|
+
child.stderr.on("data", (chunk) => {
|
|
150
|
+
const text = chunk.toString("utf8");
|
|
151
|
+
stderr += text;
|
|
152
|
+
process.stderr.write(text);
|
|
153
|
+
});
|
|
154
|
+
child.on("error", (err) => reject(err));
|
|
155
|
+
child.on("exit", (exitCode, signal) => {
|
|
156
|
+
const code = exitCode ?? (signal === null ? 1 : 128);
|
|
157
|
+
resolve({ exitCode: code, stdout, stderr });
|
|
158
|
+
});
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
function parseErrorEnvelope(stderr) {
|
|
162
|
+
const lines = stderr.split("\n").filter((l) => l.trim().startsWith("{"));
|
|
163
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
164
|
+
try {
|
|
165
|
+
const parsed = JSON.parse(lines[i]);
|
|
166
|
+
if (typeof parsed === "object" && parsed !== null && "error" in parsed && typeof parsed.error === "object") {
|
|
167
|
+
const error = parsed.error;
|
|
168
|
+
if (typeof error.code === "string") {
|
|
169
|
+
return {
|
|
170
|
+
error: {
|
|
171
|
+
code: error.code,
|
|
172
|
+
...typeof error.recoverable === "boolean" ? { recoverable: error.recoverable } : {},
|
|
173
|
+
...typeof error.retryAfterMs === "number" ? { retryAfterMs: error.retryAfterMs } : {}
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
} catch {
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
const trimmed = stderr.trim();
|
|
182
|
+
if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
|
|
183
|
+
try {
|
|
184
|
+
const parsed = JSON.parse(trimmed);
|
|
185
|
+
if (parsed.error && typeof parsed.error.code === "string") {
|
|
186
|
+
return {
|
|
187
|
+
error: {
|
|
188
|
+
code: parsed.error.code,
|
|
189
|
+
...typeof parsed.error.recoverable === "boolean" ? { recoverable: parsed.error.recoverable } : {},
|
|
190
|
+
...typeof parsed.error.retryAfterMs === "number" ? { retryAfterMs: parsed.error.retryAfterMs } : {}
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
} catch {
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
return void 0;
|
|
198
|
+
}
|
|
199
|
+
function decideRetry(code, envelopeRecoverable, options = { retryWithoutJson: false }) {
|
|
200
|
+
if (code === void 0) {
|
|
201
|
+
return options.retryWithoutJson;
|
|
202
|
+
}
|
|
203
|
+
if (RETRYABLE_CODES.has(code)) return true;
|
|
204
|
+
if (TERMINAL_CODES.has(code)) return false;
|
|
205
|
+
return envelopeRecoverable ?? true;
|
|
206
|
+
}
|
|
207
|
+
function computeWait(retryAfterMs, attempt, opts) {
|
|
208
|
+
if (retryAfterMs !== void 0 && retryAfterMs > 0) {
|
|
209
|
+
return Math.min(retryAfterMs, opts.maxDelay);
|
|
210
|
+
}
|
|
211
|
+
const exp = opts.initialDelay * 2 ** (attempt - 1);
|
|
212
|
+
return Math.min(exp, opts.maxDelay);
|
|
213
|
+
}
|
|
214
|
+
function sleep(ms) {
|
|
215
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
216
|
+
}
|
|
217
|
+
export {
|
|
218
|
+
computeWait,
|
|
219
|
+
decideRetry,
|
|
220
|
+
parseErrorEnvelope,
|
|
221
|
+
withRetryCommand
|
|
222
|
+
};
|
|
223
|
+
//# sourceMappingURL=with-retry-4FIZG3A7.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/with-retry.ts"],"sourcesContent":["/**\n * `kash with-retry [opts] -- <command> [args...]` — wrap any kash\n * command in a retry loop driven by the structured error envelope.\n *\n * **Why a built-in.** The `examples/trade-replay.sh` recipe shows the\n * pattern, but every agent / CI script ends up reimplementing it\n * slightly differently. Promoting it to a first-class command means:\n * - Idempotency-key handling is consistent (the inner command's\n * own --auto-idempotency-key / --idempotency-key still applies;\n * retries are at the CLI-invocation level so the inner command's\n * guarantees stay intact).\n * - `recoverable`/`retryAfterMs` from the error envelope drive the\n * wait — same logic that powers the SDK's own retries, surfaced\n * to scripts.\n *\n * **Mechanics.** Spawns the same kash binary as a child process,\n * forwards stdout/stderr live (so the user sees progress), and\n * captures stderr to parse the `CliErrorEnvelope` when the inner\n * command fails. If the inner command emitted `--json`, we get\n * structured `code` / `recoverable` / `retryAfterMs` and use them.\n * Otherwise we fall back to a fixed exponential schedule.\n *\n * Bare success (exit 0) returns immediately. Non-recoverable failure\n * also returns immediately — there's no point retrying an\n * `INVALID_INPUT` or `AUTH_REQUIRED`. Recoverable failure\n * (`RATE_LIMITED`, `NETWORK`, `TIMEOUT`, `MAINTENANCE`, `SERVER_ERROR`)\n * triggers the next attempt up to `--max-attempts`.\n */\n\nimport { spawn } from 'node:child_process';\n\nimport { Command } from 'commander';\n\nimport { CliError, toCliError } from '../errors.js';\nimport { parsePositiveInt, readGlobals } from '../utils/global-options.js';\nimport { log, style } from '../utils/output.js';\n\ntype WithRetryOptions = {\n maxAttempts?: string;\n initialDelayMs?: string;\n maxDelayMs?: string;\n retryWithoutJson?: boolean;\n};\n\n/** Codes whose envelopes are worth retrying. Mirrors the SDK's policy. */\nconst RETRYABLE_CODES: ReadonlySet<string> = new Set([\n 'RATE_LIMITED',\n 'NETWORK',\n 'TIMEOUT',\n 'MAINTENANCE',\n 'SERVER_ERROR',\n]);\n\n/** Codes that are explicitly NOT worth retrying — fail fast. */\nconst TERMINAL_CODES: ReadonlySet<string> = new Set([\n 'INVALID_INPUT',\n 'AUTH_REQUIRED',\n 'INSUFFICIENT_SCOPE',\n 'NOT_FOUND',\n 'CONFLICT',\n 'CONFIGURATION',\n 'DIRECT_CONFIG_MISSING',\n 'SIGNER_FAILED',\n]);\n\nexport const withRetryCommand = new Command('with-retry')\n .description('Re-run a kash command on recoverable failures (rate limits, transient errors).')\n .option('--max-attempts <n>', 'maximum total attempts including the first (default 5)', '5')\n .option(\n '--initial-delay-ms <n>',\n 'starting backoff when the envelope has no retryAfterMs (default 1000)',\n '1000'\n )\n .option('--max-delay-ms <n>', 'cap on the per-attempt wait (default 30000)', '30000')\n .option(\n '--retry-without-json',\n 'retry even when the inner command did not emit --json (no envelope to discriminate ' +\n 'terminal from transient — opt in if you trust the inner command failed transiently)'\n )\n // Allow unknown options to flow through as positional args so the\n // wrapped command's flags don't get parsed by Commander as our own.\n .allowUnknownOption()\n .argument('<command...>', 'kash command + args; pass after `--` to disambiguate')\n .addHelpText(\n 'after',\n `\nExamples:\n $ kash with-retry --max-attempts 5 -- markets list --status ACTIVE --json\n $ kash with-retry -- trade buy <id> --outcome 0 --amount 10 \\\\\n --auto-idempotency-key --json --quiet\n $ kash with-retry --max-attempts 3 -- health --json --quiet\n\nNotes:\n - The wrapped command MUST come after \\`--\\` so its flags don't collide\n with with-retry's own.\n - When the wrapped command emits --json, the error envelope's\n \\`code\\` / \\`recoverable\\` / \\`retryAfterMs\\` drive the retry. Recoverable\n codes (RATE_LIMITED, NETWORK, TIMEOUT, MAINTENANCE, SERVER_ERROR)\n retry; terminal codes (INVALID_INPUT, AUTH_REQUIRED, NOT_FOUND, …)\n fail fast.\n - Without --json on the inner command, we DO NOT retry by default —\n no envelope means we can't tell INVALID_INPUT from a transient\n NETWORK error, and retrying validation 5× wastes time. Pass\n --retry-without-json to force exponential backoff regardless.\n`\n )\n .action(async (commandArgs: string[], options: WithRetryOptions, cmd: Command) => {\n const globals = readGlobals(cmd);\n\n const maxAttempts = options.maxAttempts\n ? parsePositiveInt(options.maxAttempts, 'max-attempts')\n : 5;\n const initialDelay = options.initialDelayMs\n ? parsePositiveInt(options.initialDelayMs, 'initial-delay-ms')\n : 1_000;\n const maxDelay = options.maxDelayMs\n ? parsePositiveInt(options.maxDelayMs, 'max-delay-ms')\n : 30_000;\n\n if (commandArgs.length === 0) {\n throw new CliError('with-retry needs a command to run.', {\n code: 'INVALID_INPUT',\n recoverable: true,\n suggestion:\n 'Pass the kash command after `--`, e.g. `kash with-retry -- health --json --quiet`.',\n });\n }\n\n try {\n await runWithRetry(commandArgs, {\n maxAttempts,\n initialDelay,\n maxDelay,\n humanMode: !globals.json,\n retryWithoutJson: options.retryWithoutJson === true,\n });\n } catch (cause) {\n throw toCliError(cause);\n }\n });\n\ntype RunOptions = {\n readonly maxAttempts: number;\n readonly initialDelay: number;\n readonly maxDelay: number;\n readonly humanMode: boolean;\n readonly retryWithoutJson: boolean;\n};\n\nasync function runWithRetry(args: readonly string[], opts: RunOptions): Promise<void> {\n for (let attempt = 1; attempt <= opts.maxAttempts; attempt++) {\n const result = await runOnce(args);\n\n if (result.exitCode === 0) {\n // Success — replay captured stdout (stderr was already streamed\n // live by runOnce). The inner command's JSON / table output is\n // what the user wants on the success path.\n if (result.stdout) process.stdout.write(result.stdout);\n process.exit(0);\n }\n\n // Non-zero exit — the JSON error envelope (if --json was set on\n // the inner command) lives on stdout. Fall back to stderr for\n // commands that route errors that way.\n const envelope = parseErrorEnvelope(result.stdout) ?? parseErrorEnvelope(result.stderr);\n const code = envelope?.error.code;\n const recoverable = decideRetry(code, envelope?.error.recoverable, {\n retryWithoutJson: opts.retryWithoutJson,\n });\n\n if (!recoverable || attempt === opts.maxAttempts) {\n // Final attempt failed (or non-recoverable). Replay captured\n // stdout — that's where the JSON envelope lives in --json mode\n // and any successful prefix lives in human mode. Stderr already\n // streamed live during the attempt, so don't double-print it.\n if (result.stdout) process.stdout.write(result.stdout);\n if (opts.humanMode) {\n const reason = !recoverable ? 'non-recoverable error' : 'max attempts exhausted';\n log.error(`with-retry: ${reason} after attempt ${String(attempt)} (${code ?? 'unknown'}).`);\n }\n process.exit(result.exitCode);\n }\n\n // Recoverable — compute wait and retry. Drop the inner output\n // for failed-but-retried attempts so the user only sees the\n // final outcome.\n const wait = computeWait(envelope?.error.retryAfterMs, attempt, opts);\n if (opts.humanMode) {\n process.stderr.write(\n `${style.dim(\n `with-retry: attempt ${String(attempt)}/${String(opts.maxAttempts)} failed (${code ?? 'unknown'}); retrying in ${String(wait)}ms…`\n )}\\n`\n );\n }\n await sleep(wait);\n }\n}\n\ntype RunResult = {\n readonly exitCode: number;\n readonly stdout: string;\n readonly stderr: string;\n};\n\n/**\n * Spawn the kash CLI as a child process. Captures both stdout and\n * stderr — stdout because that's where the JSON error envelope lives\n * (via `printJson`); stderr because human-mode error rendering goes\n * there. We replay the captured streams to the user only after the\n * retry decision is made, to avoid showing transient failures.\n */\nasync function runOnce(args: readonly string[]): Promise<RunResult> {\n return await new Promise((resolve, reject) => {\n // process.argv[1] points at `dist/index.js` (or the published\n // bin's entry). Re-invoking via `process.execPath` avoids relying\n // on the shell `kash` lookup, which may not be on PATH for the\n // child (e.g. when `kash` was invoked via npx).\n const node = process.execPath;\n const entry = process.argv[1];\n if (!entry) {\n reject(new Error('with-retry: cannot determine kash entry path.'));\n return;\n }\n\n const child = spawn(node, [entry, ...args], {\n // stdin: 'ignore' (NOT 'inherit'). With inherit, an inner\n // command that prompts for input (`kash auth set-key` without\n // --from-stdin, an interactive `kash setup`) would silently\n // hang on retry — the prompt waits for input but the parent's\n // stdin has already been consumed (or is non-interactive in\n // the CI case). A retry loop should never be holding an\n // interactive prompt; if the inner command needs stdin, the\n // user runs it directly. `kash with-retry` is for commands\n // that read auth/config from env or pre-set state.\n // stdout + stderr stay piped so we can capture and re-emit.\n stdio: ['ignore', 'pipe', 'pipe'],\n // Inherit env so the child sees KASH_API_KEY, KASH_PROFILE, etc.\n env: process.env,\n });\n\n let stdout = '';\n child.stdout.on('data', (chunk: Buffer) => {\n stdout += chunk.toString('utf8');\n });\n\n let stderr = '';\n child.stderr.on('data', (chunk: Buffer) => {\n const text = chunk.toString('utf8');\n stderr += text;\n // Stream stderr through live too — the inner command's progress\n // logs (spinners, retries) shouldn't get held back. The final\n // envelope at the very end is what we'll re-parse.\n process.stderr.write(text);\n });\n\n child.on('error', (err) => reject(err));\n child.on('exit', (exitCode, signal) => {\n // A signal-killed child gets exitCode null. Map to a non-zero\n // sentinel so the retry loop treats it as a failure.\n const code = exitCode ?? (signal === null ? 1 : 128);\n resolve({ exitCode: code, stdout, stderr });\n });\n });\n}\n\n/**\n * Look for a `CliErrorEnvelope` in the captured stderr. Robust to\n * non-JSON stderr (e.g. interleaved log lines) — scans for the last\n * line that parses as JSON with the `{ ok: false, error: { code } }`\n * shape.\n */\nexport function parseErrorEnvelope(\n stderr: string\n): { error: { code: string; recoverable?: boolean; retryAfterMs?: number } } | undefined {\n // Search from the end backwards — the envelope is emitted last.\n const lines = stderr.split('\\n').filter((l) => l.trim().startsWith('{'));\n for (let i = lines.length - 1; i >= 0; i--) {\n try {\n const parsed = JSON.parse(lines[i]!) as unknown;\n if (\n typeof parsed === 'object' &&\n parsed !== null &&\n 'error' in parsed &&\n typeof (parsed as { error?: unknown }).error === 'object'\n ) {\n const error = (\n parsed as { error: { code?: unknown; recoverable?: unknown; retryAfterMs?: unknown } }\n ).error;\n if (typeof error.code === 'string') {\n return {\n error: {\n code: error.code,\n ...(typeof error.recoverable === 'boolean' ? { recoverable: error.recoverable } : {}),\n ...(typeof error.retryAfterMs === 'number'\n ? { retryAfterMs: error.retryAfterMs }\n : {}),\n },\n };\n }\n }\n } catch {\n // Not JSON — skip.\n }\n }\n // The envelope is also commonly pretty-printed across multiple lines.\n // Try parsing the entire stderr as JSON if the multi-line scan fails.\n const trimmed = stderr.trim();\n if (trimmed.startsWith('{') && trimmed.endsWith('}')) {\n try {\n const parsed = JSON.parse(trimmed) as {\n error?: { code?: unknown; recoverable?: unknown; retryAfterMs?: unknown };\n };\n if (parsed.error && typeof parsed.error.code === 'string') {\n return {\n error: {\n code: parsed.error.code,\n ...(typeof parsed.error.recoverable === 'boolean'\n ? { recoverable: parsed.error.recoverable }\n : {}),\n ...(typeof parsed.error.retryAfterMs === 'number'\n ? { retryAfterMs: parsed.error.retryAfterMs }\n : {}),\n },\n };\n }\n } catch {\n // ignore\n }\n }\n return undefined;\n}\n\n/**\n * Decide whether to retry based on the envelope. Sources of truth, in\n * order:\n * 1. Explicit allow-list of retryable codes — wins.\n * 2. Explicit deny-list of terminal codes — fails fast.\n * 3. The envelope's own `recoverable: boolean` — fallback for codes\n * we don't have a strong opinion about.\n * 4. No envelope at all (non-JSON inner command, or stdout that\n * doesn't parse) — DO NOT retry by default. Without an envelope\n * we can't tell INVALID_INPUT (terminal) from a transient\n * NETWORK timeout, and retrying validation errors 5× wastes\n * time and confuses operators. Users who want unconditional\n * retries can pass `--retry-without-json`.\n *\n * The \"no-envelope = no-retry\" default is the safe one. The previous\n * behaviour (assume-retryable) caused `with-retry -- trade buy <bad-id>\n * --outcome 0 --amount 10` to retry 5× on INVALID_INPUT — observable\n * confusion in the wild.\n */\nexport function decideRetry(\n code: string | undefined,\n envelopeRecoverable: boolean | undefined,\n options: { retryWithoutJson: boolean } = { retryWithoutJson: false }\n): boolean {\n if (code === undefined) {\n // No envelope. Caller's policy wins.\n return options.retryWithoutJson;\n }\n if (RETRYABLE_CODES.has(code)) return true;\n if (TERMINAL_CODES.has(code)) return false;\n return envelopeRecoverable ?? true;\n}\n\n/**\n * Wait time for the next attempt. Server-driven `retryAfterMs` wins;\n * otherwise exponential (initial * 2^(attempt-1), capped at maxDelay).\n */\nexport function computeWait(\n retryAfterMs: number | undefined,\n attempt: number,\n opts: { initialDelay: number; maxDelay: number }\n): number {\n if (retryAfterMs !== undefined && retryAfterMs > 0) {\n return Math.min(retryAfterMs, opts.maxDelay);\n }\n const exp = opts.initialDelay * 2 ** (attempt - 1);\n return Math.min(exp, opts.maxDelay);\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA6BA,SAAS,aAAa;AAEtB,SAAS,eAAe;AAcxB,IAAM,kBAAuC,oBAAI,IAAI;AAAA,EACnD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAGD,IAAM,iBAAsC,oBAAI,IAAI;AAAA,EAClD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAEM,IAAM,mBAAmB,IAAI,QAAQ,YAAY,EACrD,YAAY,gFAAgF,EAC5F,OAAO,sBAAsB,0DAA0D,GAAG,EAC1F;AAAA,EACC;AAAA,EACA;AAAA,EACA;AACF,E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AAO;AAGjC,UAAI,OAAO,SAAS,OAAO,OAAO,MAAM,SAAS,UAAU;AACzD,eAAO;AAAA,UACL,OAAO;AAAA,YACL,MAAM,OAAO,MAAM;AAAA,YACnB,GAAI,OAAO,OAAO,MAAM,gBAAgB,YACpC,EAAE,aAAa,OAAO,MAAM,YAAY,IACxC,CAAC;AAAA,YACL,GAAI,OAAO,OAAO,MAAM,iBAAiB,WACrC,EAAE,cAAc,OAAO,MAAM,aAAa,IAC1C,CAAC;AAAA,UACP;AAAA,QACF;AAAA,MACF;AAAA,IACF,QAAQ;AAAA,IAER;AAAA,EACF;AACA,SAAO;AACT;AAqBO,SAAS,YACd,MACA,qBACA,UAAyC,EAAE,kBAAkB,MAAM,GAC1D;AACT,MAAI,SAAS,QAAW;AAEtB,WAAO,QAAQ;AAAA,EACjB;AACA,MAAI,gBAAgB,IAAI,IAAI,EAAG,QAAO;AACtC,MAAI,eAAe,IAAI,IAAI,EAAG,QAAO;AACrC,SAAO,uBAAuB;AAChC;AAMO,SAAS,YACd,cACA,SACA,MACQ;AACR,MAAI,iBAAiB,UAAa,eAAe,GAAG;AAClD,WAAO,KAAK,IAAI,cAAc,KAAK,QAAQ;AAAA,EAC7C;AACA,QAAM,MAAM,KAAK,eAAe,MAAM,UAAU;AAChD,SAAO,KAAK,IAAI,KAAK,KAAK,QAAQ;AACpC;AAEA,SAAS,MAAM,IAA2B;AACxC,SAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;","names":[]}
|
package/package.json
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@kashdao/cli",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Official non-custodial command-line interface for the Kash prediction-market protocol. Wraps @kashdao/sdk (Kash-orchestrated mode) and @kashdao/protocol-sdk (self-orchestrated mode).",
|
|
5
|
+
"private": false,
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"import": {
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"default": "./dist/index.js"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"./package.json": "./package.json"
|
|
17
|
+
},
|
|
18
|
+
"//": "Public CLI — intentional override of the workspace 'private: true' rule. Published to npm as @kashdao/cli. See SECURITY.md and README.md 'Stability promise' for the publish + support policy.",
|
|
19
|
+
"author": {
|
|
20
|
+
"name": "KashDAO",
|
|
21
|
+
"email": "engineering@kash.bot",
|
|
22
|
+
"url": "https://kash.bot"
|
|
23
|
+
},
|
|
24
|
+
"bin": {
|
|
25
|
+
"kash": "./dist/index.js"
|
|
26
|
+
},
|
|
27
|
+
"bugs": "https://github.com/KashDAO/cli/issues",
|
|
28
|
+
"dependencies": {
|
|
29
|
+
"@inquirer/prompts": "^7.2.1",
|
|
30
|
+
"chalk": "^5.4.1",
|
|
31
|
+
"cli-table3": "^0.6.5",
|
|
32
|
+
"commander": "^13.1.0",
|
|
33
|
+
"omelette": "^0.4.17",
|
|
34
|
+
"ora": "^8.2.0",
|
|
35
|
+
"viem": "^2.45.0",
|
|
36
|
+
"zod": "^3.25.76",
|
|
37
|
+
"zod-to-json-schema": "^3.25.0",
|
|
38
|
+
"@kashdao/sdk": "0.1.0",
|
|
39
|
+
"@kashdao/protocol-sdk": "0.1.0"
|
|
40
|
+
},
|
|
41
|
+
"devDependencies": {
|
|
42
|
+
"@types/node": "^25.0.3",
|
|
43
|
+
"@types/omelette": "^0.4.5",
|
|
44
|
+
"tsup": "^8.5.1",
|
|
45
|
+
"tsx": "^4.21.0",
|
|
46
|
+
"typescript": "^5.9.3",
|
|
47
|
+
"vitest": "^4.0.16",
|
|
48
|
+
"@kashdao/vitest-config": "1.1.0",
|
|
49
|
+
"@kashdao/config-typescript": "1.0.0",
|
|
50
|
+
"@kashdao/eslint-config": "1.0.0"
|
|
51
|
+
},
|
|
52
|
+
"engines": {
|
|
53
|
+
"node": ">=22.0.0"
|
|
54
|
+
},
|
|
55
|
+
"files": [
|
|
56
|
+
"dist",
|
|
57
|
+
"README.md",
|
|
58
|
+
"CHANGELOG.md",
|
|
59
|
+
"CONTRIBUTING.md",
|
|
60
|
+
"SECURITY.md",
|
|
61
|
+
"LICENSE"
|
|
62
|
+
],
|
|
63
|
+
"homepage": "https://github.com/KashDAO/cli#readme",
|
|
64
|
+
"keywords": [
|
|
65
|
+
"cli",
|
|
66
|
+
"command-line",
|
|
67
|
+
"developer-tools",
|
|
68
|
+
"erc-4337",
|
|
69
|
+
"kash",
|
|
70
|
+
"kashdao",
|
|
71
|
+
"prediction-markets",
|
|
72
|
+
"sdk",
|
|
73
|
+
"typescript",
|
|
74
|
+
"web3"
|
|
75
|
+
],
|
|
76
|
+
"license": "MIT",
|
|
77
|
+
"publishConfig": {
|
|
78
|
+
"access": "public",
|
|
79
|
+
"registry": "https://registry.npmjs.org/"
|
|
80
|
+
},
|
|
81
|
+
"repository": "KashDAO/cli.git",
|
|
82
|
+
"sideEffects": false,
|
|
83
|
+
"scripts": {
|
|
84
|
+
"build": "pnpm gen:api-error-bundle && tsup",
|
|
85
|
+
"clean": "rm -rf dist docs tsconfig.tsbuildinfo src/api-error-bundle.generated.ts",
|
|
86
|
+
"dev": "pnpm gen:api-error-bundle && tsup --watch",
|
|
87
|
+
"docs": "pnpm build && node scripts/generate-docs.mjs",
|
|
88
|
+
"gen:api-error-bundle": "tsx scripts/build-api-error-bundle.ts",
|
|
89
|
+
"lint": "NODE_OPTIONS='--max-old-space-size=2048' eslint src --ext .ts",
|
|
90
|
+
"lint:fix": "NODE_OPTIONS='--max-old-space-size=2048' eslint src --ext .ts --fix",
|
|
91
|
+
"sbom": "npm sbom --sbom-format=cyclonedx > sbom.cyclonedx.json",
|
|
92
|
+
"start": "node dist/index.js",
|
|
93
|
+
"test": "pnpm gen:api-error-bundle && vitest run --reporter=dot --no-coverage",
|
|
94
|
+
"test:coverage": "pnpm gen:api-error-bundle && vitest run --coverage",
|
|
95
|
+
"test:unit": "pnpm gen:api-error-bundle && vitest run --reporter=dot --no-coverage",
|
|
96
|
+
"test:watch": "pnpm gen:api-error-bundle && vitest --reporter=dot",
|
|
97
|
+
"typecheck": "pnpm gen:api-error-bundle && tsc --noEmit"
|
|
98
|
+
}
|
|
99
|
+
}
|