@01.software/cli 0.8.0 → 0.9.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/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/mcp/{chunk-45ZCPS57.js → chunk-GJOQ4SE2.js} +895 -657
- package/dist/mcp/chunk-GJOQ4SE2.js.map +1 -0
- package/dist/mcp/http.js +28 -23
- package/dist/mcp/http.js.map +1 -1
- package/dist/mcp/stdio.js +1 -1
- package/dist/mcp/vercel.js +911 -680
- package/package.json +3 -3
- package/dist/mcp/chunk-45ZCPS57.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -241,7 +241,7 @@ var CLI_I18N_KO = {
|
|
|
241
241
|
PassApiKey: "`--api-key <token>` \uC635\uC158\uC744 \uC804\uB2EC\uD558\uAC70\uB098,",
|
|
242
242
|
SetEnvVars: "`SOFTWARE_PUBLISHABLE_KEY` / `SOFTWARE_SECRET_KEY` \uD658\uACBD \uBCC0\uC218\uB97C \uC124\uC815\uD558\uC138\uC694.",
|
|
243
243
|
InvalidApiKeyFormat: "API \uD0A4 \uD615\uC2DD\uC774 \uC62C\uBC14\uB974\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4. `sk01_` \uB610\uB294 `pat01_` \uD1A0\uD070\uC774 \uD544\uC694\uD569\uB2C8\uB2E4.",
|
|
244
|
-
|
|
244
|
+
RetiredHexCredentialsRejected: "\uC774\uC804 hex \uC790\uACA9 \uC99D\uBA85\uC740 \uB354 \uC774\uC0C1 \uD5C8\uC6A9\uB418\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4 \u2014 `01 login`\uC73C\uB85C \uB2E4\uC2DC \uC778\uC99D\uD558\uC138\uC694.",
|
|
245
245
|
InvalidJsonObject: "`--{{label}}` \uC778\uC790\uB294 JSON \uAC1D\uCCB4\uC5EC\uC57C \uD569\uB2C8\uB2E4.",
|
|
246
246
|
InvalidJsonArray: "`--{{label}}` \uC778\uC790\uB294 JSON \uBC30\uC5F4\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4.",
|
|
247
247
|
InvalidJsonValue: "`--{{label}}` \uC778\uC790\uC758 JSON \uD615\uC2DD\uC774 \uC62C\uBC14\uB974\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4: {{value}}",
|
|
@@ -273,7 +273,7 @@ var CLI_I18N_EN = {
|
|
|
273
273
|
PassApiKey: "pass `--api-key <token>`, or",
|
|
274
274
|
SetEnvVars: "set `SOFTWARE_PUBLISHABLE_KEY` and `SOFTWARE_SECRET_KEY` environment variables.",
|
|
275
275
|
InvalidApiKeyFormat: "Invalid API key format. Expected `sk01_` or `pat01_` token.",
|
|
276
|
-
|
|
276
|
+
RetiredHexCredentialsRejected: "Retired hex credentials are no longer accepted \u2014 run `01 login` to re-authenticate.",
|
|
277
277
|
InvalidJsonObject: "--{{label}} must be a JSON object.",
|
|
278
278
|
InvalidJsonArray: "--{{label}} must be a JSON array.",
|
|
279
279
|
InvalidJsonValue: "Invalid JSON for --{{label}}: {{value}}",
|
|
@@ -477,7 +477,7 @@ function resolveClient(apiKeyFlag) {
|
|
|
477
477
|
code: "credential_invalid",
|
|
478
478
|
detail: {
|
|
479
479
|
message: t("InvalidApiKeyFormat"),
|
|
480
|
-
suggestion: t("
|
|
480
|
+
suggestion: t("RetiredHexCredentialsRejected")
|
|
481
481
|
}
|
|
482
482
|
});
|
|
483
483
|
}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/lib/client.ts","../src/lib/credentials.ts","../src/lib/output.ts","../src/lib/api-error.ts","../src/lib/i18n.ts","../src/commands/crud.ts","../src/lib/parse.ts","../src/commands/order.ts","../src/commands/return.ts","../src/commands/cart.ts","../src/commands/stock.ts","../src/commands/transaction.ts","../src/commands/auth.ts","../src/commands/schema.ts","../src/commands/mcp.ts"],"sourcesContent":["import { createRequire } from 'node:module'\nimport { Command } from 'commander'\nimport { resolveClient } from './lib/client.js'\nimport { exitWithError } from './lib/output.js'\nimport { setLocale, type Locale } from './lib/i18n.js'\nimport { registerCrudCommands } from './commands/crud.js'\nimport { registerOrderCommands } from './commands/order.js'\nimport { registerReturnCommands } from './commands/return.js'\nimport { registerCartCommands } from './commands/cart.js'\nimport { registerStockCommands } from './commands/stock.js'\nimport { registerTransactionCommands } from './commands/transaction.js'\nimport { registerAuthCommands } from './commands/auth.js'\nimport { registerSchemaCommands } from './commands/schema.js'\nimport { registerMcpCommands } from './commands/mcp.js'\n\nconst require = createRequire(import.meta.url)\nconst { version } = require('../package.json') as { version: string }\n\nconst program = new Command()\n\nprogram\n .name('01')\n .description('CLI for the 01.software platform')\n .version(version)\n .option('--api-key <key>', 'API key (sk01_... or pat01_... token)')\n .option('--format <format>', 'Output format: json, table, or ndjson')\n .option('--lang <locale>', 'Force locale (ko or en)')\n\nconst getFormat = () =>\n (program.opts().format ?? process.env.OUTPUT_FORMAT ?? 'json') as string\n\n// Surface the explicit `--lang` flag (when supplied) so the i18n table\n// detection in `lib/i18n.ts` honours it before falling back to LC_ALL/LANG.\n// Also pin OUTPUT_FORMAT into the env so `exitWithError(e)` calls inside\n// command bodies pick up the format without threading it through every\n// call site.\nprogram.hook('preAction', () => {\n const lang = program.opts().lang as string | undefined\n if (lang === 'ko' || lang === 'en') setLocale(lang as Locale)\n process.env.OUTPUT_FORMAT = getFormat()\n})\n\nprocess.on('unhandledRejection', (err) => {\n exitWithError(err, { format: getFormat() })\n})\n\nconst getClient = () =>\n resolveClient(program.opts().apiKey as string | undefined)\n\nregisterCrudCommands(program, getClient, getFormat)\nregisterOrderCommands(program, getClient, getFormat)\nregisterReturnCommands(program, getClient, getFormat)\nregisterCartCommands(program, getClient, getFormat)\nregisterStockCommands(program, getClient, getFormat)\nregisterTransactionCommands(program, getClient, getFormat)\nregisterSchemaCommands(program, getClient, getFormat)\nregisterMcpCommands(program)\nregisterAuthCommands(program)\n\nprogram.parse()\n","import {\n CollectionClient,\n ServerCommerceClient,\n} from '@01.software/sdk'\nimport { loadCredentials, loadLocalCredentials } from './credentials.js'\nimport { exitWithError } from './output.js'\nimport { t } from './i18n.js'\n\nexport interface ResolvedClient {\n collections: CollectionClient\n commerce: ServerCommerceClient\n publishableKey: string\n secretKey: string\n}\n\n/**\n * Accepted opaque bearer token prefixes.\n * - `sk01_` = tenant-level API key (created in Console > Settings > API Keys)\n * - `pat01_` = user-level Personal Access Token\n * Legacy hex HMAC secrets from the pre-2026-04 auth system are rejected.\n */\nfunction isValidBearerToken(secret: string): boolean {\n return secret.startsWith('sk01_') || secret.startsWith('pat01_')\n}\n\n/**\n * Resolve credentials in priority order:\n * 1. `--api-key <token>` flag (overrides secretKey only; publishableKey still\n * comes from env/credentials)\n * 2. `SOFTWARE_PUBLISHABLE_KEY` + `SOFTWARE_SECRET_KEY` env vars\n * 3. Local project credentials (`./01software/credentials.json`)\n * 4. Global user credentials (`~/.01software/credentials.json`)\n */\nexport function resolveClient(apiKeyFlag?: string): ResolvedClient {\n let publishableKey: string | undefined = process.env.SOFTWARE_PUBLISHABLE_KEY\n let secretKey: string | undefined =\n apiKeyFlag ?? process.env.SOFTWARE_SECRET_KEY\n\n if (!publishableKey || !secretKey) {\n const local = loadLocalCredentials()\n if (local) {\n publishableKey = publishableKey ?? local.publishableKey\n secretKey = secretKey ?? local.secretKey\n }\n }\n\n if (!publishableKey || !secretKey) {\n const stored = loadCredentials()\n if (stored) {\n publishableKey = publishableKey ?? stored.publishableKey\n secretKey = secretKey ?? stored.secretKey\n }\n }\n\n if (!publishableKey || !secretKey) {\n exitWithError({\n type: 'permission',\n code: 'credential_invalid',\n detail: {\n message: t('AuthenticationRequired'),\n steps: [\n t('RunLoginToAuthenticate'),\n t('PassApiKey'),\n t('SetEnvVars'),\n ],\n },\n })\n }\n\n if (!isValidBearerToken(secretKey)) {\n exitWithError({\n type: 'permission',\n code: 'credential_invalid',\n detail: {\n message: t('InvalidApiKeyFormat'),\n suggestion: t('LegacyHexCredentialsRejected'),\n },\n })\n }\n\n const serverOptions = { publishableKey, secretKey }\n\n return {\n collections: new CollectionClient(\n publishableKey,\n secretKey,\n undefined,\n undefined,\n undefined,\n ),\n commerce: new ServerCommerceClient(serverOptions),\n publishableKey,\n secretKey,\n }\n}\n","import {\n existsSync,\n mkdirSync,\n readFileSync,\n writeFileSync,\n unlinkSync,\n appendFileSync,\n} from 'node:fs'\nimport { join } from 'node:path'\nimport { homedir } from 'node:os'\n\nexport interface StoredCredentials {\n publishableKey: string\n /** Opaque bearer token — tenant API key (sk01_...) or PAT (pat01_...) */\n secretKey: string\n tenantId?: string\n tenantName: string\n storedAt: string\n}\n\nexport interface TenantInfo {\n id: string\n name: string\n}\n\nconst DIR_NAME = '.01software'\nconst FILE_NAME = 'credentials.json'\nconst TENANTS_FILE = 'tenants.json'\n\n// ---------------------------------------------------------------------------\n// Global credentials (~/.01software/credentials.json)\n// ---------------------------------------------------------------------------\n\nexport function getCredentialsPath(): string {\n return join(homedir(), DIR_NAME, FILE_NAME)\n}\n\nexport function loadCredentials(): StoredCredentials | null {\n return loadCredentialsFrom(getCredentialsPath())\n}\n\nexport function saveCredentials(\n creds: Omit<StoredCredentials, 'storedAt'>,\n): void {\n const dir = join(homedir(), DIR_NAME)\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true, mode: 0o700 })\n }\n\n const filePath = getCredentialsPath()\n const data: StoredCredentials = {\n ...creds,\n storedAt: new Date().toISOString(),\n }\n writeFileSync(filePath, JSON.stringify(data, null, 2), {\n encoding: 'utf-8',\n mode: 0o600,\n })\n}\n\nexport function deleteCredentials(): boolean {\n const filePath = getCredentialsPath()\n if (!existsSync(filePath)) return false\n\n unlinkSync(filePath)\n return true\n}\n\n// ---------------------------------------------------------------------------\n// Local credentials (./01software/credentials.json)\n// ---------------------------------------------------------------------------\n\nexport function getLocalCredentialsPath(): string {\n return join(process.cwd(), DIR_NAME, FILE_NAME)\n}\n\nexport function loadLocalCredentials(): StoredCredentials | null {\n return loadCredentialsFrom(getLocalCredentialsPath())\n}\n\nexport function saveLocalCredentials(\n creds: Omit<StoredCredentials, 'storedAt'>,\n): void {\n const dir = join(process.cwd(), DIR_NAME)\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true, mode: 0o700 })\n }\n\n const filePath = getLocalCredentialsPath()\n const data: StoredCredentials = {\n ...creds,\n storedAt: new Date().toISOString(),\n }\n writeFileSync(filePath, JSON.stringify(data, null, 2), {\n encoding: 'utf-8',\n mode: 0o600,\n })\n\n // Ensure .01software/ is in .gitignore\n ensureGitignore()\n}\n\n// ---------------------------------------------------------------------------\n// Tenant list cache (~/.01software/tenants.json)\n// ---------------------------------------------------------------------------\n\nexport function saveTenantList(tenants: TenantInfo[]): void {\n const dir = join(homedir(), DIR_NAME)\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true, mode: 0o700 })\n }\n\n const filePath = join(homedir(), DIR_NAME, TENANTS_FILE)\n writeFileSync(filePath, JSON.stringify(tenants, null, 2), {\n encoding: 'utf-8',\n mode: 0o600,\n })\n}\n\nexport function loadTenantList(): TenantInfo[] | null {\n const filePath = join(homedir(), DIR_NAME, TENANTS_FILE)\n if (!existsSync(filePath)) return null\n\n try {\n const raw = readFileSync(filePath, 'utf-8')\n const data = JSON.parse(raw)\n if (!Array.isArray(data)) return null\n const valid = data.filter(\n (t): t is TenantInfo =>\n typeof t?.id === 'string' && typeof t?.name === 'string',\n )\n return valid.length > 0 ? valid : null\n } catch {\n return null\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction loadCredentialsFrom(filePath: string): StoredCredentials | null {\n if (!existsSync(filePath)) return null\n\n try {\n const raw = readFileSync(filePath, 'utf-8')\n const data = JSON.parse(raw) as StoredCredentials\n if (!data.publishableKey || !data.secretKey) return null\n return data\n } catch {\n return null\n }\n}\n\nfunction ensureGitignore(): void {\n const gitignorePath = join(process.cwd(), '.gitignore')\n const entry = '.01software/'\n\n if (existsSync(gitignorePath)) {\n const content = readFileSync(gitignorePath, 'utf-8')\n if (content.includes(entry)) return\n appendFileSync(gitignorePath, `\\n${entry}\\n`, 'utf-8')\n } else {\n writeFileSync(gitignorePath, `${entry}\\n`, 'utf-8')\n }\n}\n","import pc from 'picocolors'\nimport {\n type AdminError,\n classifyError,\n adminErrorExitCode,\n} from './api-error.js'\nimport { CLI_I18N_KO, t } from './i18n.js'\n\n// Build a Set of valid i18n keys for fast lookup when localizing AdminError\n// codes. Reused below to choose between localized and fallback rendering.\nconst CLI_I18N_KEYS: readonly string[] = Object.keys(CLI_I18N_KO)\n\nexport function printJson(data: unknown): void {\n console.log(JSON.stringify(data, null, 2))\n}\n\nexport function printTable(data: unknown): void {\n if (Array.isArray(data)) {\n if (data.length === 0) {\n console.log(pc.dim(t('Empty')))\n return\n }\n const keys = Object.keys(data[0] as Record<string, unknown>)\n const widths = keys.map((k) =>\n Math.max(\n k.length,\n ...data.map(\n (row) => String((row as Record<string, unknown>)[k] ?? '').length,\n ),\n ),\n )\n\n // Header\n console.log(keys.map((k, i) => k.padEnd(widths[i]!)).join(' '))\n console.log(keys.map((_, i) => '-'.repeat(widths[i]!)).join(' '))\n\n // Rows\n for (const row of data) {\n console.log(\n keys\n .map((k, i) =>\n String((row as Record<string, unknown>)[k] ?? '').padEnd(\n widths[i]!,\n ),\n )\n .join(' '),\n )\n }\n } else if (data && typeof data === 'object') {\n const entries = Object.entries(data as Record<string, unknown>)\n const maxKey = Math.max(...entries.map(([k]) => k.length))\n for (const [key, value] of entries) {\n const display =\n typeof value === 'object' ? JSON.stringify(value) : String(value)\n console.log(`${pc.bold(key.padEnd(maxKey))} ${display}`)\n }\n } else {\n console.log(String(data))\n }\n}\n\nfunction printNdjson(data: unknown): void {\n if (Array.isArray(data)) {\n data.forEach((item) => console.log(JSON.stringify(item)))\n } else if (\n data &&\n typeof data === 'object' &&\n 'docs' in (data as Record<string, unknown>)\n ) {\n const { docs, ...meta } = data as {\n docs: unknown[]\n [key: string]: unknown\n }\n ;(docs as unknown[]).forEach((doc) => console.log(JSON.stringify(doc)))\n if (Object.keys(meta).length > 0)\n console.log(JSON.stringify({ _meta: meta }))\n } else {\n console.log(JSON.stringify(data))\n }\n}\n\nexport function printResult(data: unknown, format: string): void {\n if (format === 'ndjson') {\n printNdjson(data)\n } else if (format === 'table') {\n // For find responses with docs array, print the docs as table\n if (\n data &&\n typeof data === 'object' &&\n 'docs' in (data as Record<string, unknown>)\n ) {\n const resp = data as {\n docs: unknown[]\n totalDocs: number\n page: number\n totalPages: number\n }\n printTable(resp.docs)\n console.log(\n pc.dim(\n `\\n${t('Total', { n: resp.totalDocs })} | ${t('PageOf', {\n page: resp.page,\n total: resp.totalPages,\n })}`,\n ),\n )\n return\n }\n printTable(data)\n } else {\n printJson(data)\n }\n}\n\n/**\n * Map an unknown error → CLI exit code per `docs/packages/cli-exit-codes.md`.\n *\n * Routes through `classifyError()` (the AdminError discriminated union is\n * the canonical source). The legacy SDK-error-name + HTTP-status heuristic\n * lives inside `classifyError` so existing thrown values keep their\n * historical mapping. The `unknown` code → exit 1 fallback is encoded in\n * `adminErrorExitCode` itself.\n */\nexport function getExitCode(error: unknown): number {\n return adminErrorExitCode(classifyError(error))\n}\n\nexport interface ErrorPrintOptions {\n format?: string\n}\n\n/**\n * Resolve the active output format. The entry point (`index.ts`) sets\n * `process.env.OUTPUT_FORMAT` from `--format` / fallback so command bodies\n * can call `exitWithError(e)` without threading the format through every\n * call site. Explicit `options.format` always wins.\n */\nfunction resolveFormat(options: ErrorPrintOptions): string {\n return options.format ?? process.env.OUTPUT_FORMAT ?? 'json'\n}\n\n/**\n * Render an error to the user. With `--format json` (or\n * `OUTPUT_FORMAT=json`), serialize the AdminError discriminated union to\n * stdout per the contract in `docs/packages/cli-exit-codes.md`. Otherwise\n * print a localized one-line message + supporting metadata to stderr.\n */\nexport function printError(\n error: unknown,\n options: ErrorPrintOptions = {},\n): void {\n const adminError = classifyError(error)\n\n // Per docs/packages/cli-exit-codes.md: ALWAYS emit a one-line human\n // message on stderr before exiting non-zero. Under `--format json` the\n // AdminError JSON is ALSO serialized to stdout so scripts can parse it.\n const knownKey = CLI_I18N_KEYS.includes(adminError.code)\n ? (adminError.code as Parameters<typeof t>[0])\n : null\n const localized = knownKey ? t(knownKey) : null\n const rawErr =\n error && typeof error === 'object'\n ? (error as Record<string, unknown>)\n : null\n const rawMessage =\n rawErr && typeof rawErr.message === 'string' ? rawErr.message : ''\n const stringErr = typeof error === 'string' ? error : ''\n const detailMessage =\n rawErr &&\n rawErr.detail &&\n typeof rawErr.detail === 'object' &&\n typeof (rawErr.detail as Record<string, unknown>).message === 'string'\n ? String((rawErr.detail as Record<string, unknown>).message)\n : ''\n // Headline: prefer the most specific human-readable text on hand —\n // raw `message` (most common SDK shape), then a string-error directly,\n // then `detail.message`, then the localized AdminError-code translation,\n // then the bare code.\n const headline =\n rawMessage || stringErr || detailMessage || localized || adminError.code\n\n console.error(pc.red(`Error: ${headline}`))\n // Surface the raw `code`/`status` (when present and distinct) so callers\n // who throw SDK errors with proprietary codes don't lose them in the\n // human-readable rendering. The AdminError type/code is always emitted\n // — that's the canonical contract.\n if (\n rawErr &&\n typeof rawErr.code === 'string' &&\n rawErr.code !== adminError.code\n ) {\n console.error(pc.dim(`Code: ${rawErr.code}`))\n } else {\n console.error(pc.dim(`Code: ${adminError.code}`))\n }\n if (rawErr && typeof rawErr.status === 'number') {\n console.error(pc.dim(`Status: ${rawErr.status}`))\n }\n console.error(pc.dim(`Type: ${adminError.type}`))\n\n if (adminError.type === 'degraded' && typeof adminError.retryAfter === 'number') {\n console.error(pc.yellow(`Retry after: ${adminError.retryAfter}s`))\n }\n if (rawErr && typeof rawErr.suggestion === 'string') {\n console.error(pc.yellow(rawErr.suggestion))\n }\n\n if (resolveFormat(options) === 'json') {\n console.log(JSON.stringify(adminError))\n }\n}\n\nexport function exitWithError(\n error: unknown,\n options: ErrorPrintOptions = {},\n): never {\n printError(error, options)\n process.exit(getExitCode(error))\n}\n","// Mirror of `apps/console/src/lib/api-error.ts` (Spec §12.1).\n//\n// Kept as a hand-mirrored copy rather than an import because the CLI ships\n// to npm as a standalone package that cannot reach into apps/console at\n// runtime. Drift is locked by `apps/console/scripts/check-i18n-parity.ts`\n// (P7) which asserts every code listed in the console source has a matching\n// CLI translation entry.\n\nexport type ValidationCode = string\n\nexport type PermissionCode =\n | 'tenant_mismatch'\n | 'account_suspended'\n | 'feature_disabled'\n | 'role_denied'\n | 'credential_invalid'\n | 'pat_tenant_unpinned'\n | 'publishable_key_mismatch'\n | 'scope_denied'\n\nexport type DegradedCode =\n | 'redis_unavailable'\n | 'provider_unavailable'\n | 'rate_limited'\n\nexport type NetworkCode =\n | 'upstream_timeout'\n | 'upstream_5xx'\n | 'dns_failure'\n\nexport type AdminErrorCode =\n | PermissionCode\n | DegradedCode\n | NetworkCode\n | ValidationCode\n\nexport type AdminError =\n | {\n type: 'validation'\n code: ValidationCode\n field?: string\n detail?: Record<string, unknown>\n }\n | {\n type: 'permission'\n code: PermissionCode\n detail?: Record<string, unknown>\n }\n | {\n type: 'degraded'\n code: DegradedCode\n retryAfter?: number\n detail?: Record<string, unknown>\n }\n | {\n type: 'network'\n code: NetworkCode\n detail?: Record<string, unknown>\n }\n\nconst PERMISSION_CODES: readonly PermissionCode[] = [\n 'tenant_mismatch',\n 'account_suspended',\n 'feature_disabled',\n 'role_denied',\n 'credential_invalid',\n 'pat_tenant_unpinned',\n 'publishable_key_mismatch',\n 'scope_denied',\n]\n\nconst DEGRADED_CODES: readonly DegradedCode[] = [\n 'redis_unavailable',\n 'provider_unavailable',\n 'rate_limited',\n]\n\nconst NETWORK_CODES: readonly NetworkCode[] = [\n 'upstream_timeout',\n 'upstream_5xx',\n 'dns_failure',\n]\n\nfunction isPermissionCode(code: string): code is PermissionCode {\n return (PERMISSION_CODES as readonly string[]).includes(code)\n}\n\nfunction isDegradedCode(code: string): code is DegradedCode {\n return (DEGRADED_CODES as readonly string[]).includes(code)\n}\n\nfunction isNetworkCode(code: string): code is NetworkCode {\n return (NETWORK_CODES as readonly string[]).includes(code)\n}\n\n/**\n * Classify an unknown thrown / rejected value into the AdminError union.\n * Heuristic mirrors `apps/console/src/lib/api-error.ts:classifyError`:\n * 1. Object with `code: string` matching a known literal → typed bucket.\n * 2. Object with explicit `type` matching a union tag → trusted as-is.\n * 3. Anything else → `validation` / `unknown`.\n *\n * Additional heuristic (CLI-only): SDK error names + HTTP status fall\n * through to a sensible AdminError so existing thrown values continue to\n * classify even before callers migrate to literal codes.\n */\nexport function classifyError(err: unknown): AdminError {\n if (err && typeof err === 'object') {\n const obj = err as Record<string, unknown>\n\n if (typeof obj.code === 'string') {\n const code = obj.code\n if (isPermissionCode(code)) {\n return { type: 'permission', code }\n }\n if (isDegradedCode(code)) {\n const out: AdminError = { type: 'degraded', code }\n if (typeof obj.retryAfter === 'number') {\n out.retryAfter = obj.retryAfter\n }\n return out\n }\n if (isNetworkCode(code)) {\n return { type: 'network', code }\n }\n }\n\n if (obj.type === 'validation' && typeof obj.code === 'string') {\n const out: AdminError = { type: 'validation', code: obj.code }\n if (typeof obj.field === 'string') out.field = obj.field\n if (obj.detail && typeof obj.detail === 'object') {\n out.detail = obj.detail as Record<string, unknown>\n }\n return out\n }\n\n // CLI fallback: SDK error names + HTTP status (kept for back-compat).\n const name = typeof obj.name === 'string' ? obj.name : undefined\n const status = typeof obj.status === 'number' ? obj.status : undefined\n if (name === 'ConfigError' || status === 401) {\n return { type: 'permission', code: 'credential_invalid' }\n }\n if (\n name === 'NetworkError' ||\n name === 'TimeoutError' ||\n status === 408 ||\n status === 503\n ) {\n return { type: 'network', code: 'upstream_timeout' }\n }\n if (name === 'GoneError' || status === 404) {\n return {\n type: 'validation',\n code: 'not_found',\n detail:\n typeof obj.message === 'string' ? { message: obj.message } : undefined,\n }\n }\n if (name === 'UsageLimitError' || status === 429) {\n const out: AdminError = { type: 'degraded', code: 'rate_limited' }\n if (typeof obj.retryAfter === 'number') out.retryAfter = obj.retryAfter\n return out\n }\n if (name === 'ValidationError' || status === 400 || status === 422) {\n return {\n type: 'validation',\n code: 'invalid_argument',\n detail:\n typeof obj.message === 'string' ? { message: obj.message } : undefined,\n }\n }\n }\n\n return {\n type: 'validation',\n code: 'unknown',\n detail: { message: err instanceof Error ? err.message : String(err) },\n }\n}\n\n/**\n * Map AdminError → CLI exit code per `docs/packages/cli-exit-codes.md`.\n * permission → 2\n * validation → 3 (`not_found` → 5; `unknown` → 1)\n * network → 4\n * degraded → 6 (`rate_limited`; provider_unavailable /\n * redis_unavailable keep 4 as the canonical \"upstream\n * failure\")\n *\n * Exit code 1 is reserved for the \"we don't know\" bucket (matching the\n * shell-script contract). The `unknown` validation code is the explicit\n * channel for that — `classifyError` routes anything it cannot identify\n * here.\n */\nexport function adminErrorExitCode(err: AdminError): number {\n if (err.code === 'unknown') return 1\n switch (err.type) {\n case 'permission':\n return 2\n case 'validation':\n return err.code === 'not_found' ? 5 : 3\n case 'network':\n return 4\n case 'degraded':\n return err.code === 'rate_limited' ? 6 : 4\n }\n}\n\nexport const ADMIN_ERROR_CODES = {\n permission: PERMISSION_CODES,\n degraded: DEGRADED_CODES,\n network: NETWORK_CODES,\n} as const\n","// CLI i18n table — mirrors `apps/console/src/lib/i18n/admin.ts` AdminError\n// code coverage so a single check (`apps/console/scripts/check-i18n-parity.ts`)\n// can verify the CLI carries every code with both KO and EN translations.\n//\n// Locale resolution:\n// 1. CLI `--lang <ko|en>` (resolved by the entry point and exported via\n// `setLocale`).\n// 2. `LANG` / `LC_ALL` environment variables — anything starting with\n// `ko` (`ko_KR.UTF-8`, `ko-KR`, …) → ko; else en.\n// 3. Default `en`.\n\nexport const CLI_I18N_KO = {\n // CLI-surface microcopy\n AuthenticationRequired: '인증이 필요합니다',\n RunLoginToAuthenticate: '`01 login` 명령으로 브라우저 인증을 진행하거나,',\n PassApiKey: '`--api-key <token>` 옵션을 전달하거나,',\n SetEnvVars:\n '`SOFTWARE_PUBLISHABLE_KEY` / `SOFTWARE_SECRET_KEY` 환경 변수를 설정하세요.',\n InvalidApiKeyFormat:\n 'API 키 형식이 올바르지 않습니다. `sk01_` 또는 `pat01_` 토큰이 필요합니다.',\n LegacyHexCredentialsRejected:\n '레거시 hex 자격 증명은 더 이상 허용되지 않습니다 — `01 login`으로 다시 인증하세요.',\n InvalidJsonObject: '`--{{label}}` 인자는 JSON 객체여야 합니다.',\n InvalidJsonArray: '`--{{label}}` 인자는 JSON 배열이어야 합니다.',\n InvalidJsonValue: '`--{{label}}` 인자의 JSON 형식이 올바르지 않습니다: {{value}}',\n Empty: '(없음)',\n Total: '총 {{n}}개',\n PageOf: '{{page}} / {{total}} 페이지',\n\n // AdminError code translations (mirrors apps/console admin.ts).\n tenant_mismatch: '권한이 없는 테넌트',\n account_suspended: '계정이 정지되었습니다',\n feature_disabled: '이 기능이 비활성화되었습니다',\n role_denied: '권한이 부족합니다',\n credential_invalid: '자격 증명이 유효하지 않습니다',\n pat_tenant_unpinned: 'PAT 토큰의 테넌트가 고정되지 않았습니다',\n publishable_key_mismatch: '공개 키가 일치하지 않습니다',\n scope_denied: '범위 권한이 없습니다',\n redis_unavailable: '캐시가 일시적으로 사용 불가합니다',\n provider_unavailable: '외부 공급자가 응답하지 않습니다',\n rate_limited: '요청이 너무 많습니다 — 잠시 후 다시 시도하세요',\n upstream_timeout: '응답 시간이 초과되었습니다',\n upstream_5xx: '외부 서비스 오류',\n dns_failure: '네트워크 연결 오류',\n not_found: '리소스를 찾을 수 없습니다',\n invalid_argument: '인자가 올바르지 않습니다',\n unknown: '알 수 없는 오류',\n} as const\n\nexport type CliI18nKey = keyof typeof CLI_I18N_KO\n\nexport const CLI_I18N_EN: Record<CliI18nKey, string> = {\n AuthenticationRequired: 'Authentication required',\n RunLoginToAuthenticate:\n 'Run `01 login` to authenticate via browser, or',\n PassApiKey: 'pass `--api-key <token>`, or',\n SetEnvVars:\n 'set `SOFTWARE_PUBLISHABLE_KEY` and `SOFTWARE_SECRET_KEY` environment variables.',\n InvalidApiKeyFormat:\n 'Invalid API key format. Expected `sk01_` or `pat01_` token.',\n LegacyHexCredentialsRejected:\n 'Legacy hex credentials are no longer accepted — run `01 login` to re-authenticate.',\n InvalidJsonObject: '--{{label}} must be a JSON object.',\n InvalidJsonArray: '--{{label}} must be a JSON array.',\n InvalidJsonValue: 'Invalid JSON for --{{label}}: {{value}}',\n Empty: '(empty)',\n Total: '{{n}} total',\n PageOf: 'page {{page}}/{{total}}',\n\n tenant_mismatch: 'Tenant access denied',\n account_suspended: 'Your account has been suspended',\n feature_disabled: 'This feature is disabled',\n role_denied: 'Insufficient role permissions',\n credential_invalid: 'Invalid credentials',\n pat_tenant_unpinned: 'PAT token tenant is not pinned',\n publishable_key_mismatch: 'Publishable key mismatch',\n scope_denied: 'Scope permission denied',\n redis_unavailable: 'Cache temporarily unavailable',\n provider_unavailable: 'Upstream provider unavailable',\n rate_limited: 'Too many requests — please try again shortly',\n upstream_timeout: 'Upstream request timed out',\n upstream_5xx: 'Upstream service error',\n dns_failure: 'Network connection error',\n not_found: 'Resource not found',\n invalid_argument: 'Invalid argument',\n unknown: 'Unknown error',\n}\n\nexport type Locale = 'ko' | 'en'\n\nlet activeLocale: Locale | null = null\n\nexport function detectLocale(): Locale {\n if (activeLocale) return activeLocale\n const raw =\n process.env.LC_ALL ?? process.env.LANG ?? process.env.LANGUAGE ?? ''\n return raw.toLowerCase().startsWith('ko') ? 'ko' : 'en'\n}\n\nexport function setLocale(locale: Locale | null | undefined): void {\n activeLocale = locale ?? null\n}\n\nexport function t(\n key: CliI18nKey,\n vars?: Record<string, string | number>,\n): string {\n const table = detectLocale() === 'ko' ? CLI_I18N_KO : CLI_I18N_EN\n let s: string = table[key]\n if (vars) {\n for (const [k, v] of Object.entries(vars)) {\n // Use a global regex (escape user-supplied key) instead of\n // String.prototype.replaceAll so we keep working on tsconfig\n // targets older than ES2021. Keys are statically declared above so\n // metacharacter escaping is defense-in-depth.\n const escaped = k.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n s = s.replace(new RegExp(`\\\\{\\\\{${escaped}\\\\}\\\\}`, 'g'), String(v))\n }\n }\n return s\n}\n","import { readFileSync } from 'node:fs'\nimport { basename } from 'node:path'\nimport { Command } from 'commander'\nimport { COLLECTIONS } from '@01.software/sdk'\nimport type { ApiQueryOptions } from '@01.software/sdk'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\nimport { parseJson } from '../lib/parse.js'\n\nfunction readFileAsBlob(filePath: string): { blob: Blob; filename: string } {\n const buffer = readFileSync(filePath)\n return { blob: new Blob([buffer]), filename: basename(filePath) }\n}\n\nfunction validateCollection(name: string): string {\n if (!(COLLECTIONS as readonly string[]).includes(name)) {\n const normalized = name.replace(/-/g, '').toLowerCase()\n const suggestions = COLLECTIONS.filter((c) => {\n const cn = c.replace(/-/g, '').toLowerCase()\n return (\n cn.startsWith(normalized) ||\n normalized.startsWith(cn) ||\n (normalized.length >= 3 && cn.includes(normalized))\n )\n }).slice(0, 5)\n const hint =\n suggestions.length > 0\n ? `Did you mean: ${suggestions.join(', ')}?`\n : 'Run \"01 --help\" for available collections.'\n throw new Error(`Unknown collection \"${name}\". ${hint}`)\n }\n return name\n}\n\nfunction parseSelect(input: string): Record<string, boolean> {\n return Object.fromEntries(input.split(',').map((f) => [f.trim(), true]))\n}\n\nexport function registerCrudCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n program\n .command('query <collection>')\n .description('Query documents from a collection')\n .option('--where <json>', 'Filter conditions (JSON)')\n .option('--limit <n>', 'Max results', (v: string) => parseInt(v, 10))\n .option('--page <n>', 'Page number', (v: string) => parseInt(v, 10))\n .option('--sort <field>', 'Sort field (prefix with - for descending)')\n .option(\n '--depth <n>',\n 'Relationship depth (0 = no population)',\n (v: string) => parseInt(v, 10),\n )\n .option('--select <fields>', 'Comma-separated fields to select')\n .action(async (collection: string, opts) => {\n try {\n const col = validateCollection(collection)\n const client = getClient()\n const options: Record<string, unknown> = {}\n if (opts.where) options.where = parseJson(opts.where, 'where')\n if (opts.limit) options.limit = opts.limit\n if (opts.page) options.page = opts.page\n if (opts.sort) options.sort = opts.sort\n if (opts.depth != null) options.depth = opts.depth\n if (opts.select) options.select = parseSelect(opts.select)\n const result = await client.collections\n .from(col as (typeof COLLECTIONS)[number])\n .find(options)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('get <collection> <id>')\n .description('Get a document by ID')\n .option(\n '--depth <n>',\n 'Relationship depth (0 = no population)',\n (v: string) => parseInt(v, 10),\n )\n .option('--select <fields>', 'Comma-separated fields to select')\n .action(async (collection: string, id: string, opts) => {\n try {\n const col = validateCollection(collection)\n const client = getClient()\n const options: Record<string, unknown> = {}\n if (opts.depth != null) options.depth = opts.depth\n if (opts.select) options.select = parseSelect(opts.select)\n const result = await client.collections\n .from(col as (typeof COLLECTIONS)[number])\n .findById(id, options)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('create <collection>')\n .description('Create a new document')\n .requiredOption('--data <json>', 'Document data (JSON)')\n .option('--file <path>', 'File to upload (for upload collections)')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (collection: string, opts) => {\n try {\n const col = validateCollection(collection)\n const data = parseJson(opts.data, 'data')\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'create',\n collection: col,\n data,\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n let fileOpts: { file: Blob; filename: string } | undefined\n if (opts.file) {\n const { blob, filename } = readFileAsBlob(opts.file)\n fileOpts = { file: blob, filename }\n }\n const result = await client.collections\n .from(col as (typeof COLLECTIONS)[number])\n .create(data, fileOpts)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('update <collection> <id>')\n .description('Update a document by ID')\n .requiredOption('--data <json>', 'Document data (JSON)')\n .option('--file <path>', 'File to upload (for upload collections)')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (collection: string, id: string, opts) => {\n try {\n const col = validateCollection(collection)\n const data = parseJson(opts.data, 'data')\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'update',\n collection: col,\n id,\n data,\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n let fileOpts: { file: Blob; filename: string } | undefined\n if (opts.file) {\n const { blob, filename } = readFileAsBlob(opts.file)\n fileOpts = { file: blob, filename }\n }\n const result = await client.collections\n .from(col as (typeof COLLECTIONS)[number])\n .update(id, data, fileOpts)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('delete <collection> <id>')\n .description('Delete a document by ID')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (collection: string, id: string, opts) => {\n try {\n const col = validateCollection(collection)\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'delete',\n collection: col,\n id,\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.collections\n .from(col as (typeof COLLECTIONS)[number])\n .remove(id)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('update-many <collection>')\n .description('Update multiple documents matching a filter')\n .requiredOption('--where <json>', 'Filter conditions (JSON)')\n .requiredOption('--data <json>', 'Update data (JSON)')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (collection: string, opts) => {\n try {\n const col = validateCollection(collection)\n const where = parseJson(opts.where, 'where') as ApiQueryOptions['where']\n const data = parseJson(opts.data, 'data')\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'update-many',\n collection: col,\n where,\n data,\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.collections\n .from(col as (typeof COLLECTIONS)[number])\n .updateMany(where, data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('delete-many <collection>')\n .description('Delete multiple documents matching a filter')\n .requiredOption('--where <json>', 'Filter conditions (JSON)')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (collection: string, opts) => {\n try {\n const col = validateCollection(collection)\n const where = parseJson(opts.where, 'where') as ApiQueryOptions['where']\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'delete-many',\n collection: col,\n where,\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.collections\n .from(col as (typeof COLLECTIONS)[number])\n .removeMany(where)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { exitWithError } from './output.js'\nimport { t } from './i18n.js'\n\n/**\n * Spec §12.1 / Plan P8 track 7: throw an AdminError-shaped object so\n * `exitWithError` can render it correctly under `--format json` and exit\n * with code 3 (validation). The `code` literal `invalid_argument` is\n * already in the validation bucket per `api-error.ts`.\n */\nfunction failArg(label: string, value: string, expectedKind: 'object' | 'array' | 'value'): never {\n const message =\n expectedKind === 'object'\n ? t('InvalidJsonObject', { label })\n : expectedKind === 'array'\n ? t('InvalidJsonArray', { label })\n : t('InvalidJsonValue', { label, value })\n exitWithError({\n type: 'validation',\n code: 'invalid_argument',\n field: label,\n // `message` is read by `printError` for the stderr headline so the\n // user sees the label/value in the one-line summary; `detail` carries\n // the structured fields for `--format json` consumers.\n message,\n detail: { message, value, field: label },\n })\n}\n\nexport function parseJson(\n value: string,\n label: string,\n options: { format?: string } = {},\n): Record<string, unknown> {\n let parsed: unknown\n try {\n parsed = JSON.parse(value)\n } catch {\n return failArg(label, value, 'value')\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n return failArg(label, value, 'object')\n }\n void options\n return parsed as Record<string, unknown>\n}\n\nexport function parseJsonArray(\n value: string,\n label: string,\n options: { format?: string } = {},\n): unknown[] {\n let parsed: unknown\n try {\n parsed = JSON.parse(value)\n } catch {\n return failArg(label, value, 'value')\n }\n if (!Array.isArray(parsed)) {\n return failArg(label, value, 'array')\n }\n void options\n return parsed\n}\n","import { Command } from 'commander'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\nimport { parseJson, parseJsonArray } from '../lib/parse.js'\n\nexport function registerOrderCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const order = program.command('order').description('Order management')\n\n order\n .command('create')\n .description('Create a new order')\n .option('--payment-id <id>', 'Payment ID')\n .requiredOption('--order-number <num>', 'Order number')\n .requiredOption('--email <email>', 'Customer email')\n .option('--customer <id>', 'Customer ID')\n .option('--name <name>', 'Customer name')\n .option('--phone <phone>', 'Customer phone')\n .requiredOption('--shipping-address <json>', 'Shipping address (JSON)')\n .requiredOption('--products <json>', 'Order products array (JSON)')\n .requiredOption('--total-amount <n>', 'Total amount', parseFloat)\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (opts) => {\n try {\n const shippingAddress = parseJson(\n opts.shippingAddress,\n 'shipping-address',\n )\n const orderItems = parseJsonArray(opts.products, 'products')\n const data = {\n pgPaymentId: opts.paymentId,\n orderNumber: opts.orderNumber,\n customerSnapshot: {\n email: opts.email,\n name: opts.name,\n phone: opts.phone,\n },\n customer: opts.customer,\n shippingAddress,\n orderItems,\n totalAmount: opts.totalAmount,\n }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'order create', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.orders.create({\n ...data,\n orderItems: orderItems as Parameters<\n typeof client.commerce.orders.create\n >[0]['orderItems'],\n })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n order\n .command('get <orderNumber>')\n .description('Get an order by order number')\n .action(async (orderNumber: string) => {\n try {\n const client = getClient()\n const { docs: [order] } = await client.collections.from('orders').find({ where: { orderNumber: { equals: orderNumber } }, limit: 1, depth: 1 })\n if (!order) throw new Error('Order not found')\n printResult(order, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n order\n .command('update <orderNumber>')\n .description('Update order status')\n .requiredOption('--status <status>', 'New status')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (orderNumber: string, opts) => {\n try {\n const data = { orderNumber, status: opts.status }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'order update', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.orders.update(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n order\n .command('checkout')\n .description('Convert a cart to an order')\n .requiredOption('--cart-id <id>', 'Cart ID')\n .option('--payment-id <id>', 'Payment ID (optional for free orders)')\n .requiredOption('--order-number <num>', 'Order number')\n .requiredOption('--customer <json>', 'Customer snapshot (JSON)')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (opts) => {\n try {\n const customerSnapshot = parseJson(opts.customer, 'customer')\n const data = {\n cartId: opts.cartId,\n pgPaymentId: opts.paymentId,\n orderNumber: opts.orderNumber,\n customerSnapshot,\n }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'order checkout', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.orders.checkout({\n ...data,\n customerSnapshot: customerSnapshot as Parameters<\n typeof client.commerce.orders.checkout\n >[0]['customerSnapshot'],\n })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n order\n .command('fulfill <orderNumber>')\n .description('Create a fulfillment for an order')\n .requiredOption('--items <json>', 'Fulfillment items array (JSON)')\n .option('--carrier <name>', 'Shipping carrier')\n .option('--tracking-number <num>', 'Tracking number')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (orderNumber: string, opts) => {\n try {\n const items = parseJsonArray(opts.items, 'items')\n const data = {\n orderNumber,\n items,\n carrier: opts.carrier,\n trackingNumber: opts.trackingNumber,\n }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'order fulfill', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.orders.createFulfillment({\n ...data,\n items: items as Parameters<\n typeof client.commerce.orders.createFulfillment\n >[0]['items'],\n })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { Command } from 'commander'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\nimport { parseJsonArray } from '../lib/parse.js'\n\nexport function registerReturnCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const ret = program.command('return').description('Return management')\n\n ret\n .command('create <orderNumber>')\n .description('Create a return request')\n .requiredOption('--products <json>', 'Return products array (JSON)')\n .requiredOption('--refund-amount <n>', 'Refund amount', parseFloat)\n .option(\n '--reason <reason>',\n 'Return reason (change_of_mind, defective, wrong_delivery, damaged, other)',\n )\n .option('--reason-detail <text>', 'Detailed reason')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (orderNumber: string, opts) => {\n try {\n const returnItems = parseJsonArray(opts.products, 'products')\n const data = {\n orderNumber,\n returnItems,\n refundAmount: opts.refundAmount,\n reason: opts.reason,\n reasonDetail: opts.reasonDetail,\n }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'return create', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.orders.createReturn({\n ...data,\n returnItems: returnItems as Parameters<\n typeof client.commerce.orders.createReturn\n >[0]['returnItems'],\n })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n ret\n .command('update <returnId>')\n .description('Update return status')\n .requiredOption(\n '--status <status>',\n 'New status (processing, approved, rejected, completed)',\n )\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (returnId: string, opts) => {\n try {\n const data = { returnId, status: opts.status }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'return update', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.orders.updateReturn(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n ret\n .command('refund <orderNumber>')\n .description('Return with refund')\n .requiredOption('--products <json>', 'Return products array (JSON)')\n .requiredOption('--refund-amount <n>', 'Refund amount', parseFloat)\n .requiredOption('--payment-id <id>', 'Payment ID')\n .option('--reason <reason>', 'Return reason')\n .option('--reason-detail <text>', 'Detailed reason')\n .option('--refund-receipt-url <url>', 'Refund receipt URL')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (orderNumber: string, opts) => {\n try {\n const returnItems = parseJsonArray(opts.products, 'products')\n const data = {\n orderNumber,\n returnItems,\n refundAmount: opts.refundAmount,\n pgPaymentId: opts.paymentId,\n reason: opts.reason,\n reasonDetail: opts.reasonDetail,\n refundReceiptUrl: opts.refundReceiptUrl,\n }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'return refund', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.orders.returnWithRefund({\n ...data,\n returnItems: returnItems as Parameters<\n typeof client.commerce.orders.returnWithRefund\n >[0]['returnItems'],\n })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { Command } from 'commander'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\n\nexport function registerCartCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const cart = program.command('cart').description('Cart management')\n\n cart\n .command('add <cartId>')\n .description('Add an item to cart')\n .requiredOption('--product <id>', 'Product ID')\n .requiredOption('--variant <id>', 'Variant ID')\n .requiredOption('--option <id>', 'Option ID')\n .requiredOption('--quantity <n>', 'Quantity', (v: string) =>\n parseInt(v, 10),\n )\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (cartId: string, opts) => {\n try {\n const data = {\n cartId,\n product: opts.product,\n variant: opts.variant,\n option: opts.option,\n quantity: opts.quantity,\n }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'cart add', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.cart.addItem(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n cart\n .command('update <cartItemId>')\n .description('Update cart item quantity')\n .requiredOption('--quantity <n>', 'New quantity', (v: string) =>\n parseInt(v, 10),\n )\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (cartItemId: string, opts) => {\n try {\n const data = { cartItemId, quantity: opts.quantity }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'cart update', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.cart.updateItem(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n cart\n .command('remove <cartItemId>')\n .description('Remove an item from cart')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (cartItemId: string, opts) => {\n try {\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'cart remove',\n data: { cartItemId },\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.cart.removeItem({ cartItemId })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { Command } from 'commander'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\nimport { parseJsonArray } from '../lib/parse.js'\n\nexport function registerStockCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const stock = program.command('stock').description('Stock management')\n\n stock\n .command('check')\n .description('Check stock availability')\n .requiredOption(\n '--items <json>',\n 'Items to check (JSON array of { optionId, quantity })',\n )\n .action(async (opts) => {\n try {\n const client = getClient()\n const items = parseJsonArray(opts.items, 'items') as Parameters<\n typeof client.commerce.product.stockCheck\n >[0]['items']\n const result = await client.commerce.product.stockCheck({ items })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { Command } from 'commander'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\n\nexport function registerTransactionCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const tx = program\n .command('transaction')\n .description('Transaction management')\n\n tx.command('update')\n .description('Update transaction status')\n .requiredOption('--payment-id <id>', 'Payment ID')\n .requiredOption(\n '--status <status>',\n 'New status (pending, paid, failed, canceled)',\n )\n .requiredOption('--payment-method <method>', 'Payment method')\n .requiredOption('--receipt-url <url>', 'Receipt URL')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (opts) => {\n try {\n const data = {\n pgPaymentId: opts.paymentId,\n status: opts.status,\n paymentMethod: opts.paymentMethod,\n receiptUrl: opts.receiptUrl,\n }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'transaction update', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.orders.updateTransaction(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { randomBytes } from 'node:crypto'\nimport { createServer } from 'node:http'\nimport { execFile, exec } from 'node:child_process'\nimport { platform } from 'node:os'\nimport { URL } from 'node:url'\nimport type { Command } from 'commander'\nimport pc from 'picocolors'\nimport {\n loadCredentials,\n saveCredentials,\n deleteCredentials,\n getCredentialsPath,\n loadLocalCredentials,\n saveLocalCredentials,\n getLocalCredentialsPath,\n loadTenantList,\n saveTenantList,\n type TenantInfo,\n} from '../lib/credentials.js'\n\nconst WEB_URL = process.env.SOFTWARE_WEB_URL || 'https://01.software'\nconst TIMEOUT_MS = 3 * 60 * 1000 // 3 minutes\n\nfunction escapeHtml(s: string): string {\n return s\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n}\n\nfunction openBrowser(url: string): void {\n const os = platform()\n\n const onError = () => {\n console.log(\n pc.yellow(\n `Could not open browser automatically. Open this URL manually:\\n${url}`,\n ),\n )\n }\n\n if (os === 'win32') {\n exec(`start \"\" \"${url}\"`, (err) => {\n if (err) onError()\n })\n } else {\n const cmd = os === 'darwin' ? 'open' : 'xdg-open'\n execFile(cmd, [url], (err) => {\n if (err) onError()\n })\n }\n}\n\nconst PAGE_STYLE = `*{margin:0;box-sizing:border-box}\nbody{font-family:system-ui,-apple-system,sans-serif;display:flex;justify-content:center;align-items:center;min-height:100vh;background:#fff;color:#252525}\n@media(prefers-color-scheme:dark){body{background:#252525;color:#f5f5f5}}\n.card{text-align:center;padding:2rem 2.5rem;border-radius:10px;max-width:380px;width:100%}\n.icon{width:40px;height:40px;margin:0 auto 1rem;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:1.25rem}\n.icon.ok{background:rgba(0,0,0,.05);color:#252525}\n.icon.err{background:rgba(220,38,38,.08);color:#dc2626}\n@media(prefers-color-scheme:dark){.icon.ok{background:rgba(255,255,255,.08);color:#f5f5f5}}\nh1{font-size:.875rem;font-weight:600;margin-bottom:.375rem}\np{font-size:.75rem;color:#737373;line-height:1.5}`\n\nconst SUCCESS_HTML = `<!DOCTYPE html>\n<html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width\"><title>CLI Login</title>\n<style>${PAGE_STYLE}</style>\n</head><body><div class=\"card\"><div class=\"icon ok\">\\u2713</div><h1>Authenticated</h1><p>You can close this tab and return to the terminal.</p></div></body></html>`\n\nconst ERROR_HTML = (msg: string) => `<!DOCTYPE html>\n<html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width\"><title>CLI Login Error</title>\n<style>${PAGE_STYLE}</style>\n</head><body><div class=\"card\"><div class=\"icon err\">!</div><h1>Authentication failed</h1><p>${escapeHtml(msg)}</p></div></body></html>`\n\ninterface ExchangeResponse {\n publishableKey: string\n secretKey: string\n tenantName: string\n tenantId: string\n tenants?: TenantInfo[]\n}\n\nasync function exchangeCode(code: string): Promise<ExchangeResponse | null> {\n const url = `${WEB_URL}/api/cli/exchange`\n try {\n const res = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ code }),\n })\n if (!res.ok) {\n const body = await res.text().catch(() => '')\n console.error(\n pc.red(\n `Exchange failed: HTTP ${res.status} from ${url}${body ? ` — ${body.slice(0, 200)}` : ''}`,\n ),\n )\n return null\n }\n const data = (await res.json()) as Partial<ExchangeResponse>\n if (\n typeof data.publishableKey !== 'string' ||\n typeof data.secretKey !== 'string' ||\n typeof data.tenantName !== 'string' ||\n typeof data.tenantId !== 'string'\n ) {\n console.error(pc.red(`Exchange failed: malformed response from ${url}`))\n return null\n }\n return {\n publishableKey: data.publishableKey,\n secretKey: data.secretKey,\n tenantName: data.tenantName,\n tenantId: data.tenantId,\n tenants: Array.isArray(data.tenants)\n ? data.tenants.filter(\n (t): t is TenantInfo =>\n typeof (t as TenantInfo)?.id === 'string' &&\n typeof (t as TenantInfo)?.name === 'string',\n )\n : undefined,\n }\n } catch (err) {\n console.error(\n pc.red(\n `Exchange request to ${url} failed: ${err instanceof Error ? err.message : String(err)}`,\n ),\n )\n return null\n }\n}\n\n/**\n * Start a local HTTP server that receives the OAuth-style redirect callback\n * from the browser. The browser top-level-navigates to\n * http://127.0.0.1:{port}/callback?code={encryptedCode}&state={state}\n * and the CLI exchanges the opaque code with the web API to receive the\n * actual credentials server-to-server. This path has no CORS or PNA\n * preflight because the browser never issues a subresource fetch.\n */\nfunction startAuthServer(options: {\n state: string\n saveFn: (creds: {\n publishableKey: string\n secretKey: string\n tenantId?: string\n tenantName: string\n }) => void\n}): Promise<{ port: number; cleanup: (exitCode?: number) => void }> {\n return new Promise((resolve, reject) => {\n const server = createServer((req, res) => {\n if (!req.url) {\n res.writeHead(400).end()\n return\n }\n\n const url = new URL(req.url, `http://localhost`)\n\n if (url.pathname !== '/callback' || req.method !== 'GET') {\n res.writeHead(404).end()\n return\n }\n\n const error = url.searchParams.get('error')\n if (error) {\n res\n .writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', Connection: 'close' })\n .end(ERROR_HTML(error))\n console.error(pc.red(`Login failed: ${error}`))\n cleanup(2)\n return\n }\n\n const code = url.searchParams.get('code')\n const receivedState = url.searchParams.get('state')\n\n if (!code || !receivedState) {\n res\n .writeHead(400, { 'Content-Type': 'text/html; charset=utf-8', Connection: 'close' })\n .end(ERROR_HTML('Missing code or state. Start over with \"01 login\".'))\n cleanup(2)\n return\n }\n\n if (receivedState !== options.state) {\n res\n .writeHead(403, { 'Content-Type': 'text/html; charset=utf-8', Connection: 'close' })\n .end(ERROR_HTML('State mismatch. Start over with \"01 login\".'))\n console.error(pc.red('Login failed: state mismatch.'))\n cleanup(2)\n return\n }\n\n exchangeCode(code).then((creds) => {\n if (!creds) {\n res\n .writeHead(400, { 'Content-Type': 'text/html; charset=utf-8', Connection: 'close' })\n .end(ERROR_HTML('Invalid or expired code. Start over with \"01 login\".'))\n console.error(pc.red('Login failed: code exchange failed.'))\n cleanup(2)\n return\n }\n\n options.saveFn({\n publishableKey: creds.publishableKey,\n secretKey: creds.secretKey,\n tenantId: creds.tenantId,\n tenantName: creds.tenantName,\n })\n\n if (creds.tenants && creds.tenants.length > 0) {\n saveTenantList(creds.tenants)\n }\n\n console.log(pc.green(`\\nLogged in successfully!`))\n console.log(pc.dim(`Tenant: ${creds.tenantName}`))\n\n res\n .writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', Connection: 'close' })\n .end(SUCCESS_HTML)\n cleanup(0)\n })\n })\n\n let timeout: ReturnType<typeof setTimeout>\n let completed = false\n\n function cleanup(exitCode = 0) {\n if (completed) return\n completed = true\n clearTimeout(timeout)\n server.closeAllConnections?.()\n server.close(() => process.exit(exitCode))\n }\n\n server.listen(0, '127.0.0.1', () => {\n const addr = server.address()\n if (!addr || typeof addr === 'string') {\n reject(new Error('Failed to start local server.'))\n return\n }\n\n timeout = setTimeout(() => {\n console.error(\n pc.red('\\nLogin timed out (3 minutes). Please try again.'),\n )\n cleanup(4)\n }, TIMEOUT_MS)\n\n resolve({ port: addr.port, cleanup })\n })\n\n server.on('error', (err) => {\n reject(err)\n })\n })\n}\n\nexport function registerAuthCommands(program: Command): void {\n program\n .command('login')\n .description('Login via browser and store credentials')\n .action(async () => {\n const state = randomBytes(32).toString('hex')\n\n try {\n const { port } = await startAuthServer({\n state,\n saveFn: (creds) => {\n saveCredentials(creds)\n console.log(pc.dim(`Credentials saved to ${getCredentialsPath()}`))\n },\n })\n\n const params = new URLSearchParams({ port: String(port), state })\n const loginUrl = `${WEB_URL}/cli-auth?${params.toString()}`\n\n console.log(pc.dim('Opening browser for login...'))\n console.log(pc.dim(`If the browser does not open, visit:\\n${loginUrl}`))\n openBrowser(loginUrl)\n } catch (err) {\n console.error(\n pc.red(\n `Server error: ${err instanceof Error ? err.message : String(err)}`,\n ),\n )\n process.exit(4)\n }\n })\n\n program\n .command('logout')\n .description('Remove stored credentials')\n .action(() => {\n const deleted = deleteCredentials()\n if (deleted) {\n console.log(pc.green('Logged out. Credentials removed.'))\n } else {\n console.log(pc.dim('No stored credentials found.'))\n }\n })\n\n program\n .command('whoami')\n .description('Show current authentication status')\n .action(() => {\n // Check local credentials first\n const localCreds = loadLocalCredentials()\n const globalCreds = loadCredentials()\n const creds = localCreds || globalCreds\n const isLocal = !!localCreds\n\n if (!creds) {\n console.log(pc.dim('Not logged in. Run \"01 login\" to authenticate.'))\n return\n }\n\n const masked =\n creds.publishableKey.length > 8\n ? creds.publishableKey.slice(0, 4) + '...' + creds.publishableKey.slice(-4)\n : '****'\n\n const scope = isLocal ? pc.cyan(' (local)') : ''\n console.log(`Tenant: ${pc.bold(creds.tenantName)}${scope}`)\n console.log(`Publishable Key: ${pc.dim(masked)}`)\n console.log(`Stored at: ${pc.dim(creds.storedAt)}`)\n console.log(\n `File: ${pc.dim(isLocal ? getLocalCredentialsPath() : getCredentialsPath())}`,\n )\n })\n\n // -------------------------------------------------------------------------\n // tenant subcommands\n // -------------------------------------------------------------------------\n const tenant = program\n .command('tenant')\n .description('Manage tenant switching')\n\n tenant\n .command('list')\n .description('Show cached tenant list')\n .action(() => {\n const tenants = loadTenantList()\n if (!tenants || tenants.length === 0) {\n console.log(pc.dim('No cached tenants. Run \"01 login\" first.'))\n return\n }\n\n // Determine active tenant\n const localCreds = loadLocalCredentials()\n const globalCreds = loadCredentials()\n const activeCreds = localCreds || globalCreds\n const activeId = activeCreds?.tenantId\n const activeName = activeCreds?.tenantName\n\n console.log(pc.bold('Cached tenants:\\n'))\n for (const t of tenants) {\n const active = (activeId ? t.id === activeId : t.name === activeName)\n ? pc.green(' *')\n : ''\n console.log(` ${t.name}${active}`)\n }\n console.log()\n if (activeName) {\n const scope = localCreds ? '(local)' : '(global)'\n console.log(pc.dim(`* active ${scope}`))\n }\n })\n\n tenant\n .command('use <name>')\n .description('Switch to a different tenant via browser')\n .option('--local', 'Save credentials locally in the current project')\n .action(async (name: string, opts: { local?: boolean }) => {\n const tenants = loadTenantList()\n if (!tenants || tenants.length === 0) {\n console.error(pc.red('No cached tenants. Run \"01 login\" first.'))\n process.exit(2)\n }\n\n const match = tenants.find(\n (t) => t.name.toLowerCase() === name.toLowerCase(),\n )\n if (!match) {\n console.error(pc.red(`Tenant \"${name}\" not found in cache.`))\n console.error(\n pc.dim(`Available: ${tenants.map((t) => t.name).join(', ')}`),\n )\n process.exit(3)\n }\n\n const state = randomBytes(32).toString('hex')\n const isLocal = !!opts.local\n\n try {\n const { port } = await startAuthServer({\n state,\n saveFn: (creds) => {\n if (isLocal) {\n saveLocalCredentials(creds)\n console.log(\n pc.dim(`Credentials saved to ${getLocalCredentialsPath()}`),\n )\n } else {\n saveCredentials(creds)\n console.log(\n pc.dim(`Credentials saved to ${getCredentialsPath()}`),\n )\n }\n },\n })\n\n const params = new URLSearchParams({\n port: String(port),\n state,\n tenantId: match.id,\n })\n const loginUrl = `${WEB_URL}/cli-auth?${params.toString()}`\n\n console.log(pc.dim(`Switching to tenant \"${match.name}\"...`))\n console.log(pc.dim(`If the browser does not open, visit:\\n${loginUrl}`))\n openBrowser(loginUrl)\n } catch (err) {\n console.error(\n pc.red(\n `Server error: ${err instanceof Error ? err.message : String(err)}`,\n ),\n )\n process.exit(4)\n }\n })\n}\n","import { Command } from 'commander'\nimport { COLLECTIONS } from '@01.software/sdk'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\n\ndeclare const __DEFAULT_API_URL__: string\n\nfunction getApiUrl(): string {\n return (\n process.env.SOFTWARE_API_URL ||\n process.env.NEXT_PUBLIC_SOFTWARE_API_URL ||\n __DEFAULT_API_URL__\n ).replace(/\\/$/, '')\n}\n\nexport function registerSchemaCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const schema = program\n .command('schema')\n .description('Collection schema introspection')\n\n schema\n .command('list')\n .description('List available collections')\n .action(() => {\n printResult(COLLECTIONS, getFormat())\n })\n\n schema\n .command('show <collection>')\n .description('Show collection field schema')\n .action(async (collection: string) => {\n try {\n if (!(COLLECTIONS as readonly string[]).includes(collection)) {\n const normalized = collection.replace(/-/g, '').toLowerCase()\n const suggestions = (COLLECTIONS as readonly string[])\n .filter((c) => {\n const cn = c.replace(/-/g, '').toLowerCase()\n return (\n cn.startsWith(normalized) ||\n normalized.startsWith(cn) ||\n (normalized.length >= 3 && cn.includes(normalized))\n )\n })\n .slice(0, 5)\n const hint =\n suggestions.length > 0\n ? `Did you mean: ${suggestions.join(', ')}?`\n : 'Run \"01 schema list\" for available collections.'\n throw new Error(`Unknown collection \"${collection}\". ${hint}`)\n }\n const client = getClient()\n const baseUrl = getApiUrl()\n\n const url = `${baseUrl}/api/tenants/schema/${encodeURIComponent(collection)}`\n const response = await fetch(url, {\n headers: {\n 'X-Publishable-Key': client.publishableKey,\n Authorization: `Bearer ${client.secretKey}`,\n },\n })\n\n if (!response.ok) {\n const body = await response\n .json()\n .catch(() => ({ error: response.statusText }))\n const err = new Error(\n (body as { error?: string }).error || `HTTP ${response.status}`,\n )\n Object.assign(err, { status: response.status })\n throw err\n }\n\n const result = await response.json()\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { resolve, dirname } from 'node:path'\nimport { existsSync } from 'node:fs'\nimport { spawn } from 'node:child_process'\nimport { fileURLToPath } from 'node:url'\nimport type { Command } from 'commander'\nimport { resolveClient } from '../lib/client.js'\nimport { exitWithError } from '../lib/output.js'\n\nconst __dirname = dirname(fileURLToPath(import.meta.url))\n\n/**\n * Locate the MCP stdio entry point.\n * Resolve order:\n * 1. Packaged MCP server copied into packages/cli/dist/mcp/stdio.js\n * 2. Monorepo MCP build output: apps/mcp/dist/stdio.js\n * 3. Legacy xmcp output: apps/mcp/.xmcp/stdio.js\n */\nexport function findStdioEntry(baseDir = __dirname): string | null {\n const packaged = resolve(baseDir, 'mcp/stdio.js')\n if (existsSync(packaged)) return packaged\n\n const roots = ['../../../..', '../../..', '../..']\n const entries = ['apps/mcp/dist/stdio.js', 'apps/mcp/.xmcp/stdio.js']\n\n for (const entry of entries) {\n for (const root of roots) {\n const candidate = resolve(baseDir, root, entry)\n if (existsSync(candidate)) return candidate\n }\n }\n\n return null\n}\n\nexport function createMcpEnv(\n baseEnv: NodeJS.ProcessEnv,\n client: { publishableKey: string; secretKey: string },\n): NodeJS.ProcessEnv {\n const env: NodeJS.ProcessEnv = {\n ...baseEnv,\n SOFTWARE_PUBLISHABLE_KEY: client.publishableKey,\n SOFTWARE_SECRET_KEY: client.secretKey,\n }\n\n delete env.SOFTWARE_TENANT_ID\n\n return env\n}\n\nexport function registerMcpCommands(program: Command) {\n program\n .command('mcp')\n .description('Start MCP server over stdio')\n .action(() => {\n // 1. Validate credentials before spawning (exits with code 2 if missing)\n const client = resolveClient(program.opts().apiKey as string | undefined)\n\n // 2. Find stdio.js entry point\n const stdioEntry = findStdioEntry()\n if (!stdioEntry) {\n exitWithError(\n new Error(\n 'MCP server not found. Ensure apps/mcp is built (pnpm --filter mcp build).',\n ),\n )\n }\n\n // 3. Spawn stdio process (inherits env with SOFTWARE_PUBLISHABLE_KEY + SOFTWARE_SECRET_KEY)\n const child = spawn(process.execPath, [stdioEntry], {\n env: createMcpEnv(process.env, client),\n stdio: ['inherit', 'inherit', 'inherit'],\n })\n\n child.on('error', (err) => {\n exitWithError(new Error(`Failed to start MCP server: ${err.message}`))\n })\n\n child.on('exit', (code) => {\n process.exit(code ?? 0)\n })\n })\n}\n"],"mappings":";;;AAAA,SAAS,qBAAqB;AAC9B,SAAS,eAAe;;;ACDxB;AAAA,EACE;AAAA,EACA;AAAA,OACK;;;ACHP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,YAAY;AACrB,SAAS,eAAe;AAgBxB,IAAM,WAAW;AACjB,IAAM,YAAY;AAClB,IAAM,eAAe;AAMd,SAAS,qBAA6B;AAC3C,SAAO,KAAK,QAAQ,GAAG,UAAU,SAAS;AAC5C;AAEO,SAAS,kBAA4C;AAC1D,SAAO,oBAAoB,mBAAmB,CAAC;AACjD;AAEO,SAAS,gBACd,OACM;AACN,QAAM,MAAM,KAAK,QAAQ,GAAG,QAAQ;AACpC,MAAI,CAAC,WAAW,GAAG,GAAG;AACpB,cAAU,KAAK,EAAE,WAAW,MAAM,MAAM,IAAM,CAAC;AAAA,EACjD;AAEA,QAAM,WAAW,mBAAmB;AACpC,QAAM,OAA0B;AAAA,IAC9B,GAAG;AAAA,IACH,WAAU,oBAAI,KAAK,GAAE,YAAY;AAAA,EACnC;AACA,gBAAc,UAAU,KAAK,UAAU,MAAM,MAAM,CAAC,GAAG;AAAA,IACrD,UAAU;AAAA,IACV,MAAM;AAAA,EACR,CAAC;AACH;AAEO,SAAS,oBAA6B;AAC3C,QAAM,WAAW,mBAAmB;AACpC,MAAI,CAAC,WAAW,QAAQ,EAAG,QAAO;AAElC,aAAW,QAAQ;AACnB,SAAO;AACT;AAMO,SAAS,0BAAkC;AAChD,SAAO,KAAK,QAAQ,IAAI,GAAG,UAAU,SAAS;AAChD;AAEO,SAAS,uBAAiD;AAC/D,SAAO,oBAAoB,wBAAwB,CAAC;AACtD;AAEO,SAAS,qBACd,OACM;AACN,QAAM,MAAM,KAAK,QAAQ,IAAI,GAAG,QAAQ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SAAS,WAAW,SAAS;AACpD,qBAAqB,SAAS,WAAW,SAAS;AAClD,sBAAsB,SAAS,WAAW,SAAS;AACnD,4BAA4B,SAAS,WAAW,SAAS;AACzD,uBAAuB,SAAS,WAAW,SAAS;AACpD,oBAAoB,OAAO;AAC3B,qBAAqB,OAAO;AAE5B,QAAQ,MAAM;","names":["t","readFileSync","readFileSync","program","getClient","getFormat","program","getClient","getFormat","order","program","getClient","getFormat","program","getClient","getFormat","program","getClient","getFormat","program","getClient","getFormat","pc","pc","t","resolve","program","COLLECTIONS","program","getClient","getFormat","COLLECTIONS","existsSync","existsSync","program","require"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/lib/client.ts","../src/lib/credentials.ts","../src/lib/output.ts","../src/lib/api-error.ts","../src/lib/i18n.ts","../src/commands/crud.ts","../src/lib/parse.ts","../src/commands/order.ts","../src/commands/return.ts","../src/commands/cart.ts","../src/commands/stock.ts","../src/commands/transaction.ts","../src/commands/auth.ts","../src/commands/schema.ts","../src/commands/mcp.ts"],"sourcesContent":["import { createRequire } from 'node:module'\nimport { Command } from 'commander'\nimport { resolveClient } from './lib/client.js'\nimport { exitWithError } from './lib/output.js'\nimport { setLocale, type Locale } from './lib/i18n.js'\nimport { registerCrudCommands } from './commands/crud.js'\nimport { registerOrderCommands } from './commands/order.js'\nimport { registerReturnCommands } from './commands/return.js'\nimport { registerCartCommands } from './commands/cart.js'\nimport { registerStockCommands } from './commands/stock.js'\nimport { registerTransactionCommands } from './commands/transaction.js'\nimport { registerAuthCommands } from './commands/auth.js'\nimport { registerSchemaCommands } from './commands/schema.js'\nimport { registerMcpCommands } from './commands/mcp.js'\n\nconst require = createRequire(import.meta.url)\nconst { version } = require('../package.json') as { version: string }\n\nconst program = new Command()\n\nprogram\n .name('01')\n .description('CLI for the 01.software platform')\n .version(version)\n .option('--api-key <key>', 'API key (sk01_... or pat01_... token)')\n .option('--format <format>', 'Output format: json, table, or ndjson')\n .option('--lang <locale>', 'Force locale (ko or en)')\n\nconst getFormat = () =>\n (program.opts().format ?? process.env.OUTPUT_FORMAT ?? 'json') as string\n\n// Surface the explicit `--lang` flag (when supplied) so the i18n table\n// detection in `lib/i18n.ts` honours it before falling back to LC_ALL/LANG.\n// Also pin OUTPUT_FORMAT into the env so `exitWithError(e)` calls inside\n// command bodies pick up the format without threading it through every\n// call site.\nprogram.hook('preAction', () => {\n const lang = program.opts().lang as string | undefined\n if (lang === 'ko' || lang === 'en') setLocale(lang as Locale)\n process.env.OUTPUT_FORMAT = getFormat()\n})\n\nprocess.on('unhandledRejection', (err) => {\n exitWithError(err, { format: getFormat() })\n})\n\nconst getClient = () =>\n resolveClient(program.opts().apiKey as string | undefined)\n\nregisterCrudCommands(program, getClient, getFormat)\nregisterOrderCommands(program, getClient, getFormat)\nregisterReturnCommands(program, getClient, getFormat)\nregisterCartCommands(program, getClient, getFormat)\nregisterStockCommands(program, getClient, getFormat)\nregisterTransactionCommands(program, getClient, getFormat)\nregisterSchemaCommands(program, getClient, getFormat)\nregisterMcpCommands(program)\nregisterAuthCommands(program)\n\nprogram.parse()\n","import {\n CollectionClient,\n ServerCommerceClient,\n} from '@01.software/sdk'\nimport { loadCredentials, loadLocalCredentials } from './credentials.js'\nimport { exitWithError } from './output.js'\nimport { t } from './i18n.js'\n\nexport interface ResolvedClient {\n collections: CollectionClient\n commerce: ServerCommerceClient\n publishableKey: string\n secretKey: string\n}\n\n/**\n * Accepted opaque bearer token prefixes.\n * - `sk01_` = tenant-level API key (created in Console > Settings > API Keys)\n * - `pat01_` = user-level Personal Access Token\n * Hex HMAC secrets from the pre-2026-04 auth system are rejected.\n */\nfunction isValidBearerToken(secret: string): boolean {\n return secret.startsWith('sk01_') || secret.startsWith('pat01_')\n}\n\n/**\n * Resolve credentials in priority order:\n * 1. `--api-key <token>` flag (overrides secretKey only; publishableKey still\n * comes from env/credentials)\n * 2. `SOFTWARE_PUBLISHABLE_KEY` + `SOFTWARE_SECRET_KEY` env vars\n * 3. Local project credentials (`./01software/credentials.json`)\n * 4. Global user credentials (`~/.01software/credentials.json`)\n */\nexport function resolveClient(apiKeyFlag?: string): ResolvedClient {\n let publishableKey: string | undefined = process.env.SOFTWARE_PUBLISHABLE_KEY\n let secretKey: string | undefined =\n apiKeyFlag ?? process.env.SOFTWARE_SECRET_KEY\n\n if (!publishableKey || !secretKey) {\n const local = loadLocalCredentials()\n if (local) {\n publishableKey = publishableKey ?? local.publishableKey\n secretKey = secretKey ?? local.secretKey\n }\n }\n\n if (!publishableKey || !secretKey) {\n const stored = loadCredentials()\n if (stored) {\n publishableKey = publishableKey ?? stored.publishableKey\n secretKey = secretKey ?? stored.secretKey\n }\n }\n\n if (!publishableKey || !secretKey) {\n exitWithError({\n type: 'permission',\n code: 'credential_invalid',\n detail: {\n message: t('AuthenticationRequired'),\n steps: [\n t('RunLoginToAuthenticate'),\n t('PassApiKey'),\n t('SetEnvVars'),\n ],\n },\n })\n }\n\n if (!isValidBearerToken(secretKey)) {\n exitWithError({\n type: 'permission',\n code: 'credential_invalid',\n detail: {\n message: t('InvalidApiKeyFormat'),\n suggestion: t('RetiredHexCredentialsRejected'),\n },\n })\n }\n\n const serverOptions = { publishableKey, secretKey }\n\n return {\n collections: new CollectionClient(\n publishableKey,\n secretKey,\n undefined,\n undefined,\n undefined,\n ),\n commerce: new ServerCommerceClient(serverOptions),\n publishableKey,\n secretKey,\n }\n}\n","import {\n existsSync,\n mkdirSync,\n readFileSync,\n writeFileSync,\n unlinkSync,\n appendFileSync,\n} from 'node:fs'\nimport { join } from 'node:path'\nimport { homedir } from 'node:os'\n\nexport interface StoredCredentials {\n publishableKey: string\n /** Opaque bearer token — tenant API key (sk01_...) or PAT (pat01_...) */\n secretKey: string\n tenantId?: string\n tenantName: string\n storedAt: string\n}\n\nexport interface TenantInfo {\n id: string\n name: string\n}\n\nconst DIR_NAME = '.01software'\nconst FILE_NAME = 'credentials.json'\nconst TENANTS_FILE = 'tenants.json'\n\n// ---------------------------------------------------------------------------\n// Global credentials (~/.01software/credentials.json)\n// ---------------------------------------------------------------------------\n\nexport function getCredentialsPath(): string {\n return join(homedir(), DIR_NAME, FILE_NAME)\n}\n\nexport function loadCredentials(): StoredCredentials | null {\n return loadCredentialsFrom(getCredentialsPath())\n}\n\nexport function saveCredentials(\n creds: Omit<StoredCredentials, 'storedAt'>,\n): void {\n const dir = join(homedir(), DIR_NAME)\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true, mode: 0o700 })\n }\n\n const filePath = getCredentialsPath()\n const data: StoredCredentials = {\n ...creds,\n storedAt: new Date().toISOString(),\n }\n writeFileSync(filePath, JSON.stringify(data, null, 2), {\n encoding: 'utf-8',\n mode: 0o600,\n })\n}\n\nexport function deleteCredentials(): boolean {\n const filePath = getCredentialsPath()\n if (!existsSync(filePath)) return false\n\n unlinkSync(filePath)\n return true\n}\n\n// ---------------------------------------------------------------------------\n// Local credentials (./01software/credentials.json)\n// ---------------------------------------------------------------------------\n\nexport function getLocalCredentialsPath(): string {\n return join(process.cwd(), DIR_NAME, FILE_NAME)\n}\n\nexport function loadLocalCredentials(): StoredCredentials | null {\n return loadCredentialsFrom(getLocalCredentialsPath())\n}\n\nexport function saveLocalCredentials(\n creds: Omit<StoredCredentials, 'storedAt'>,\n): void {\n const dir = join(process.cwd(), DIR_NAME)\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true, mode: 0o700 })\n }\n\n const filePath = getLocalCredentialsPath()\n const data: StoredCredentials = {\n ...creds,\n storedAt: new Date().toISOString(),\n }\n writeFileSync(filePath, JSON.stringify(data, null, 2), {\n encoding: 'utf-8',\n mode: 0o600,\n })\n\n // Ensure .01software/ is in .gitignore\n ensureGitignore()\n}\n\n// ---------------------------------------------------------------------------\n// Tenant list cache (~/.01software/tenants.json)\n// ---------------------------------------------------------------------------\n\nexport function saveTenantList(tenants: TenantInfo[]): void {\n const dir = join(homedir(), DIR_NAME)\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true, mode: 0o700 })\n }\n\n const filePath = join(homedir(), DIR_NAME, TENANTS_FILE)\n writeFileSync(filePath, JSON.stringify(tenants, null, 2), {\n encoding: 'utf-8',\n mode: 0o600,\n })\n}\n\nexport function loadTenantList(): TenantInfo[] | null {\n const filePath = join(homedir(), DIR_NAME, TENANTS_FILE)\n if (!existsSync(filePath)) return null\n\n try {\n const raw = readFileSync(filePath, 'utf-8')\n const data = JSON.parse(raw)\n if (!Array.isArray(data)) return null\n const valid = data.filter(\n (t): t is TenantInfo =>\n typeof t?.id === 'string' && typeof t?.name === 'string',\n )\n return valid.length > 0 ? valid : null\n } catch {\n return null\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction loadCredentialsFrom(filePath: string): StoredCredentials | null {\n if (!existsSync(filePath)) return null\n\n try {\n const raw = readFileSync(filePath, 'utf-8')\n const data = JSON.parse(raw) as StoredCredentials\n if (!data.publishableKey || !data.secretKey) return null\n return data\n } catch {\n return null\n }\n}\n\nfunction ensureGitignore(): void {\n const gitignorePath = join(process.cwd(), '.gitignore')\n const entry = '.01software/'\n\n if (existsSync(gitignorePath)) {\n const content = readFileSync(gitignorePath, 'utf-8')\n if (content.includes(entry)) return\n appendFileSync(gitignorePath, `\\n${entry}\\n`, 'utf-8')\n } else {\n writeFileSync(gitignorePath, `${entry}\\n`, 'utf-8')\n }\n}\n","import pc from 'picocolors'\nimport {\n type AdminError,\n classifyError,\n adminErrorExitCode,\n} from './api-error.js'\nimport { CLI_I18N_KO, t } from './i18n.js'\n\n// Build a Set of valid i18n keys for fast lookup when localizing AdminError\n// codes. Reused below to choose between localized and fallback rendering.\nconst CLI_I18N_KEYS: readonly string[] = Object.keys(CLI_I18N_KO)\n\nexport function printJson(data: unknown): void {\n console.log(JSON.stringify(data, null, 2))\n}\n\nexport function printTable(data: unknown): void {\n if (Array.isArray(data)) {\n if (data.length === 0) {\n console.log(pc.dim(t('Empty')))\n return\n }\n const keys = Object.keys(data[0] as Record<string, unknown>)\n const widths = keys.map((k) =>\n Math.max(\n k.length,\n ...data.map(\n (row) => String((row as Record<string, unknown>)[k] ?? '').length,\n ),\n ),\n )\n\n // Header\n console.log(keys.map((k, i) => k.padEnd(widths[i]!)).join(' '))\n console.log(keys.map((_, i) => '-'.repeat(widths[i]!)).join(' '))\n\n // Rows\n for (const row of data) {\n console.log(\n keys\n .map((k, i) =>\n String((row as Record<string, unknown>)[k] ?? '').padEnd(\n widths[i]!,\n ),\n )\n .join(' '),\n )\n }\n } else if (data && typeof data === 'object') {\n const entries = Object.entries(data as Record<string, unknown>)\n const maxKey = Math.max(...entries.map(([k]) => k.length))\n for (const [key, value] of entries) {\n const display =\n typeof value === 'object' ? JSON.stringify(value) : String(value)\n console.log(`${pc.bold(key.padEnd(maxKey))} ${display}`)\n }\n } else {\n console.log(String(data))\n }\n}\n\nfunction printNdjson(data: unknown): void {\n if (Array.isArray(data)) {\n data.forEach((item) => console.log(JSON.stringify(item)))\n } else if (\n data &&\n typeof data === 'object' &&\n 'docs' in (data as Record<string, unknown>)\n ) {\n const { docs, ...meta } = data as {\n docs: unknown[]\n [key: string]: unknown\n }\n ;(docs as unknown[]).forEach((doc) => console.log(JSON.stringify(doc)))\n if (Object.keys(meta).length > 0)\n console.log(JSON.stringify({ _meta: meta }))\n } else {\n console.log(JSON.stringify(data))\n }\n}\n\nexport function printResult(data: unknown, format: string): void {\n if (format === 'ndjson') {\n printNdjson(data)\n } else if (format === 'table') {\n // For find responses with docs array, print the docs as table\n if (\n data &&\n typeof data === 'object' &&\n 'docs' in (data as Record<string, unknown>)\n ) {\n const resp = data as {\n docs: unknown[]\n totalDocs: number\n page: number\n totalPages: number\n }\n printTable(resp.docs)\n console.log(\n pc.dim(\n `\\n${t('Total', { n: resp.totalDocs })} | ${t('PageOf', {\n page: resp.page,\n total: resp.totalPages,\n })}`,\n ),\n )\n return\n }\n printTable(data)\n } else {\n printJson(data)\n }\n}\n\n/**\n * Map an unknown error → CLI exit code per `docs/packages/cli-exit-codes.md`.\n *\n * Routes through `classifyError()` (the AdminError discriminated union is\n * the canonical source). The SDK-error-name + HTTP-status heuristic lives\n * inside `classifyError` so existing thrown values keep their mapping.\n * The `unknown` code → exit 1 fallback is encoded in\n * `adminErrorExitCode` itself.\n */\nexport function getExitCode(error: unknown): number {\n return adminErrorExitCode(classifyError(error))\n}\n\nexport interface ErrorPrintOptions {\n format?: string\n}\n\n/**\n * Resolve the active output format. The entry point (`index.ts`) sets\n * `process.env.OUTPUT_FORMAT` from `--format` / fallback so command bodies\n * can call `exitWithError(e)` without threading the format through every\n * call site. Explicit `options.format` always wins.\n */\nfunction resolveFormat(options: ErrorPrintOptions): string {\n return options.format ?? process.env.OUTPUT_FORMAT ?? 'json'\n}\n\n/**\n * Render an error to the user. With `--format json` (or\n * `OUTPUT_FORMAT=json`), serialize the AdminError discriminated union to\n * stdout per the contract in `docs/packages/cli-exit-codes.md`. Otherwise\n * print a localized one-line message + supporting metadata to stderr.\n */\nexport function printError(\n error: unknown,\n options: ErrorPrintOptions = {},\n): void {\n const adminError = classifyError(error)\n\n // Per docs/packages/cli-exit-codes.md: ALWAYS emit a one-line human\n // message on stderr before exiting non-zero. Under `--format json` the\n // AdminError JSON is ALSO serialized to stdout so scripts can parse it.\n const knownKey = CLI_I18N_KEYS.includes(adminError.code)\n ? (adminError.code as Parameters<typeof t>[0])\n : null\n const localized = knownKey ? t(knownKey) : null\n const rawErr =\n error && typeof error === 'object'\n ? (error as Record<string, unknown>)\n : null\n const rawMessage =\n rawErr && typeof rawErr.message === 'string' ? rawErr.message : ''\n const stringErr = typeof error === 'string' ? error : ''\n const detailMessage =\n rawErr &&\n rawErr.detail &&\n typeof rawErr.detail === 'object' &&\n typeof (rawErr.detail as Record<string, unknown>).message === 'string'\n ? String((rawErr.detail as Record<string, unknown>).message)\n : ''\n // Headline: prefer the most specific human-readable text on hand —\n // raw `message` (most common SDK shape), then a string-error directly,\n // then `detail.message`, then the localized AdminError-code translation,\n // then the bare code.\n const headline =\n rawMessage || stringErr || detailMessage || localized || adminError.code\n\n console.error(pc.red(`Error: ${headline}`))\n // Surface the raw `code`/`status` (when present and distinct) so callers\n // who throw SDK errors with proprietary codes don't lose them in the\n // human-readable rendering. The AdminError type/code is always emitted\n // — that's the canonical contract.\n if (\n rawErr &&\n typeof rawErr.code === 'string' &&\n rawErr.code !== adminError.code\n ) {\n console.error(pc.dim(`Code: ${rawErr.code}`))\n } else {\n console.error(pc.dim(`Code: ${adminError.code}`))\n }\n if (rawErr && typeof rawErr.status === 'number') {\n console.error(pc.dim(`Status: ${rawErr.status}`))\n }\n console.error(pc.dim(`Type: ${adminError.type}`))\n\n if (adminError.type === 'degraded' && typeof adminError.retryAfter === 'number') {\n console.error(pc.yellow(`Retry after: ${adminError.retryAfter}s`))\n }\n if (rawErr && typeof rawErr.suggestion === 'string') {\n console.error(pc.yellow(rawErr.suggestion))\n }\n\n if (resolveFormat(options) === 'json') {\n console.log(JSON.stringify(adminError))\n }\n}\n\nexport function exitWithError(\n error: unknown,\n options: ErrorPrintOptions = {},\n): never {\n printError(error, options)\n process.exit(getExitCode(error))\n}\n","// Mirror of `apps/console/src/lib/api-error.ts` (Spec §12.1).\n//\n// Kept as a hand-mirrored copy rather than an import because the CLI ships\n// to npm as a standalone package that cannot reach into apps/console at\n// runtime. Drift is locked by `apps/console/scripts/check-i18n-parity.ts`,\n// which asserts every code listed in the console source has a matching CLI\n// translation entry.\n\nexport type ValidationCode = string\n\nexport type PermissionCode =\n | 'tenant_mismatch'\n | 'account_suspended'\n | 'feature_disabled'\n | 'role_denied'\n | 'credential_invalid'\n | 'pat_tenant_unpinned'\n | 'publishable_key_mismatch'\n | 'scope_denied'\n\nexport type DegradedCode =\n | 'redis_unavailable'\n | 'provider_unavailable'\n | 'rate_limited'\n\nexport type NetworkCode =\n | 'upstream_timeout'\n | 'upstream_5xx'\n | 'dns_failure'\n\nexport type AdminErrorCode =\n | PermissionCode\n | DegradedCode\n | NetworkCode\n | ValidationCode\n\nexport type AdminError =\n | {\n type: 'validation'\n code: ValidationCode\n field?: string\n detail?: Record<string, unknown>\n }\n | {\n type: 'permission'\n code: PermissionCode\n detail?: Record<string, unknown>\n }\n | {\n type: 'degraded'\n code: DegradedCode\n retryAfter?: number\n detail?: Record<string, unknown>\n }\n | {\n type: 'network'\n code: NetworkCode\n detail?: Record<string, unknown>\n }\n\nconst PERMISSION_CODES: readonly PermissionCode[] = [\n 'tenant_mismatch',\n 'account_suspended',\n 'feature_disabled',\n 'role_denied',\n 'credential_invalid',\n 'pat_tenant_unpinned',\n 'publishable_key_mismatch',\n 'scope_denied',\n]\n\nconst DEGRADED_CODES: readonly DegradedCode[] = [\n 'redis_unavailable',\n 'provider_unavailable',\n 'rate_limited',\n]\n\nconst NETWORK_CODES: readonly NetworkCode[] = [\n 'upstream_timeout',\n 'upstream_5xx',\n 'dns_failure',\n]\n\nfunction isPermissionCode(code: string): code is PermissionCode {\n return (PERMISSION_CODES as readonly string[]).includes(code)\n}\n\nfunction isDegradedCode(code: string): code is DegradedCode {\n return (DEGRADED_CODES as readonly string[]).includes(code)\n}\n\nfunction isNetworkCode(code: string): code is NetworkCode {\n return (NETWORK_CODES as readonly string[]).includes(code)\n}\n\n/**\n * Classify an unknown thrown / rejected value into the AdminError union.\n * Heuristic mirrors `apps/console/src/lib/api-error.ts:classifyError`:\n * 1. Object with `code: string` matching a known literal → typed bucket.\n * 2. Object with explicit `type` matching a union tag → trusted as-is.\n * 3. Anything else → `validation` / `unknown`.\n *\n * Additional heuristic (CLI-only): SDK error names + HTTP status fall\n * through to a sensible AdminError so existing thrown values continue to\n * classify even before callers migrate to literal codes.\n */\nexport function classifyError(err: unknown): AdminError {\n if (err && typeof err === 'object') {\n const obj = err as Record<string, unknown>\n\n if (typeof obj.code === 'string') {\n const code = obj.code\n if (isPermissionCode(code)) {\n return { type: 'permission', code }\n }\n if (isDegradedCode(code)) {\n const out: AdminError = { type: 'degraded', code }\n if (typeof obj.retryAfter === 'number') {\n out.retryAfter = obj.retryAfter\n }\n return out\n }\n if (isNetworkCode(code)) {\n return { type: 'network', code }\n }\n }\n\n if (obj.type === 'validation' && typeof obj.code === 'string') {\n const out: AdminError = { type: 'validation', code: obj.code }\n if (typeof obj.field === 'string') out.field = obj.field\n if (obj.detail && typeof obj.detail === 'object') {\n out.detail = obj.detail as Record<string, unknown>\n }\n return out\n }\n\n // CLI fallback: SDK error names + HTTP status.\n const name = typeof obj.name === 'string' ? obj.name : undefined\n const status = typeof obj.status === 'number' ? obj.status : undefined\n if (name === 'ConfigError' || status === 401) {\n return { type: 'permission', code: 'credential_invalid' }\n }\n if (\n name === 'NetworkError' ||\n name === 'TimeoutError' ||\n status === 408 ||\n status === 503\n ) {\n return { type: 'network', code: 'upstream_timeout' }\n }\n if (name === 'GoneError' || status === 404) {\n return {\n type: 'validation',\n code: 'not_found',\n detail:\n typeof obj.message === 'string' ? { message: obj.message } : undefined,\n }\n }\n if (name === 'UsageLimitError' || status === 429) {\n const out: AdminError = { type: 'degraded', code: 'rate_limited' }\n if (typeof obj.retryAfter === 'number') out.retryAfter = obj.retryAfter\n return out\n }\n if (name === 'ValidationError' || status === 400 || status === 422) {\n return {\n type: 'validation',\n code: 'invalid_argument',\n detail:\n typeof obj.message === 'string' ? { message: obj.message } : undefined,\n }\n }\n }\n\n return {\n type: 'validation',\n code: 'unknown',\n detail: { message: err instanceof Error ? err.message : String(err) },\n }\n}\n\n/**\n * Map AdminError → CLI exit code per `docs/packages/cli-exit-codes.md`.\n * permission → 2\n * validation → 3 (`not_found` → 5; `unknown` → 1)\n * network → 4\n * degraded → 6 (`rate_limited`; provider_unavailable /\n * redis_unavailable keep 4 as the canonical \"upstream\n * failure\")\n *\n * Exit code 1 is reserved for the \"we don't know\" bucket (matching the\n * shell-script contract). The `unknown` validation code is the explicit\n * channel for that — `classifyError` routes anything it cannot identify\n * here.\n */\nexport function adminErrorExitCode(err: AdminError): number {\n if (err.code === 'unknown') return 1\n switch (err.type) {\n case 'permission':\n return 2\n case 'validation':\n return err.code === 'not_found' ? 5 : 3\n case 'network':\n return 4\n case 'degraded':\n return err.code === 'rate_limited' ? 6 : 4\n }\n}\n\nexport const ADMIN_ERROR_CODES = {\n permission: PERMISSION_CODES,\n degraded: DEGRADED_CODES,\n network: NETWORK_CODES,\n} as const\n","// CLI i18n table — mirrors `apps/console/src/lib/i18n/admin.ts` AdminError\n// code coverage so a single check (`apps/console/scripts/check-i18n-parity.ts`)\n// can verify the CLI carries every code with both KO and EN translations.\n//\n// Locale resolution:\n// 1. CLI `--lang <ko|en>` (resolved by the entry point and exported via\n// `setLocale`).\n// 2. `LANG` / `LC_ALL` environment variables — anything starting with\n// `ko` (`ko_KR.UTF-8`, `ko-KR`, …) → ko; else en.\n// 3. Default `en`.\n\nexport const CLI_I18N_KO = {\n // CLI-surface microcopy\n AuthenticationRequired: '인증이 필요합니다',\n RunLoginToAuthenticate: '`01 login` 명령으로 브라우저 인증을 진행하거나,',\n PassApiKey: '`--api-key <token>` 옵션을 전달하거나,',\n SetEnvVars:\n '`SOFTWARE_PUBLISHABLE_KEY` / `SOFTWARE_SECRET_KEY` 환경 변수를 설정하세요.',\n InvalidApiKeyFormat:\n 'API 키 형식이 올바르지 않습니다. `sk01_` 또는 `pat01_` 토큰이 필요합니다.',\n RetiredHexCredentialsRejected:\n '이전 hex 자격 증명은 더 이상 허용되지 않습니다 — `01 login`으로 다시 인증하세요.',\n InvalidJsonObject: '`--{{label}}` 인자는 JSON 객체여야 합니다.',\n InvalidJsonArray: '`--{{label}}` 인자는 JSON 배열이어야 합니다.',\n InvalidJsonValue: '`--{{label}}` 인자의 JSON 형식이 올바르지 않습니다: {{value}}',\n Empty: '(없음)',\n Total: '총 {{n}}개',\n PageOf: '{{page}} / {{total}} 페이지',\n\n // AdminError code translations (mirrors apps/console admin.ts).\n tenant_mismatch: '권한이 없는 테넌트',\n account_suspended: '계정이 정지되었습니다',\n feature_disabled: '이 기능이 비활성화되었습니다',\n role_denied: '권한이 부족합니다',\n credential_invalid: '자격 증명이 유효하지 않습니다',\n pat_tenant_unpinned: 'PAT 토큰의 테넌트가 고정되지 않았습니다',\n publishable_key_mismatch: '공개 키가 일치하지 않습니다',\n scope_denied: '범위 권한이 없습니다',\n redis_unavailable: '캐시가 일시적으로 사용 불가합니다',\n provider_unavailable: '외부 공급자가 응답하지 않습니다',\n rate_limited: '요청이 너무 많습니다 — 잠시 후 다시 시도하세요',\n upstream_timeout: '응답 시간이 초과되었습니다',\n upstream_5xx: '외부 서비스 오류',\n dns_failure: '네트워크 연결 오류',\n not_found: '리소스를 찾을 수 없습니다',\n invalid_argument: '인자가 올바르지 않습니다',\n unknown: '알 수 없는 오류',\n} as const\n\nexport type CliI18nKey = keyof typeof CLI_I18N_KO\n\nexport const CLI_I18N_EN: Record<CliI18nKey, string> = {\n AuthenticationRequired: 'Authentication required',\n RunLoginToAuthenticate:\n 'Run `01 login` to authenticate via browser, or',\n PassApiKey: 'pass `--api-key <token>`, or',\n SetEnvVars:\n 'set `SOFTWARE_PUBLISHABLE_KEY` and `SOFTWARE_SECRET_KEY` environment variables.',\n InvalidApiKeyFormat:\n 'Invalid API key format. Expected `sk01_` or `pat01_` token.',\n RetiredHexCredentialsRejected:\n 'Retired hex credentials are no longer accepted — run `01 login` to re-authenticate.',\n InvalidJsonObject: '--{{label}} must be a JSON object.',\n InvalidJsonArray: '--{{label}} must be a JSON array.',\n InvalidJsonValue: 'Invalid JSON for --{{label}}: {{value}}',\n Empty: '(empty)',\n Total: '{{n}} total',\n PageOf: 'page {{page}}/{{total}}',\n\n tenant_mismatch: 'Tenant access denied',\n account_suspended: 'Your account has been suspended',\n feature_disabled: 'This feature is disabled',\n role_denied: 'Insufficient role permissions',\n credential_invalid: 'Invalid credentials',\n pat_tenant_unpinned: 'PAT token tenant is not pinned',\n publishable_key_mismatch: 'Publishable key mismatch',\n scope_denied: 'Scope permission denied',\n redis_unavailable: 'Cache temporarily unavailable',\n provider_unavailable: 'Upstream provider unavailable',\n rate_limited: 'Too many requests — please try again shortly',\n upstream_timeout: 'Upstream request timed out',\n upstream_5xx: 'Upstream service error',\n dns_failure: 'Network connection error',\n not_found: 'Resource not found',\n invalid_argument: 'Invalid argument',\n unknown: 'Unknown error',\n}\n\nexport type Locale = 'ko' | 'en'\n\nlet activeLocale: Locale | null = null\n\nexport function detectLocale(): Locale {\n if (activeLocale) return activeLocale\n const raw =\n process.env.LC_ALL ?? process.env.LANG ?? process.env.LANGUAGE ?? ''\n return raw.toLowerCase().startsWith('ko') ? 'ko' : 'en'\n}\n\nexport function setLocale(locale: Locale | null | undefined): void {\n activeLocale = locale ?? null\n}\n\nexport function t(\n key: CliI18nKey,\n vars?: Record<string, string | number>,\n): string {\n const table = detectLocale() === 'ko' ? CLI_I18N_KO : CLI_I18N_EN\n let s: string = table[key]\n if (vars) {\n for (const [k, v] of Object.entries(vars)) {\n // Use a global regex (escape user-supplied key) instead of\n // String.prototype.replaceAll so we keep working on tsconfig\n // targets older than ES2021. Keys are statically declared above so\n // metacharacter escaping is defense-in-depth.\n const escaped = k.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n s = s.replace(new RegExp(`\\\\{\\\\{${escaped}\\\\}\\\\}`, 'g'), String(v))\n }\n }\n return s\n}\n","import { readFileSync } from 'node:fs'\nimport { basename } from 'node:path'\nimport { Command } from 'commander'\nimport { COLLECTIONS } from '@01.software/sdk'\nimport type { ApiQueryOptions } from '@01.software/sdk'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\nimport { parseJson } from '../lib/parse.js'\n\nfunction readFileAsBlob(filePath: string): { blob: Blob; filename: string } {\n const buffer = readFileSync(filePath)\n return { blob: new Blob([buffer]), filename: basename(filePath) }\n}\n\nfunction validateCollection(name: string): string {\n if (!(COLLECTIONS as readonly string[]).includes(name)) {\n const normalized = name.replace(/-/g, '').toLowerCase()\n const suggestions = COLLECTIONS.filter((c) => {\n const cn = c.replace(/-/g, '').toLowerCase()\n return (\n cn.startsWith(normalized) ||\n normalized.startsWith(cn) ||\n (normalized.length >= 3 && cn.includes(normalized))\n )\n }).slice(0, 5)\n const hint =\n suggestions.length > 0\n ? `Did you mean: ${suggestions.join(', ')}?`\n : 'Run \"01 --help\" for available collections.'\n throw new Error(`Unknown collection \"${name}\". ${hint}`)\n }\n return name\n}\n\nfunction parseSelect(input: string): Record<string, boolean> {\n return Object.fromEntries(input.split(',').map((f) => [f.trim(), true]))\n}\n\nexport function registerCrudCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n program\n .command('query <collection>')\n .description('Query documents from a collection')\n .option('--where <json>', 'Filter conditions (JSON)')\n .option('--limit <n>', 'Max results', (v: string) => parseInt(v, 10))\n .option('--page <n>', 'Page number', (v: string) => parseInt(v, 10))\n .option('--sort <field>', 'Sort field (prefix with - for descending)')\n .option(\n '--depth <n>',\n 'Relationship depth (0 = no population)',\n (v: string) => parseInt(v, 10),\n )\n .option('--select <fields>', 'Comma-separated fields to select')\n .action(async (collection: string, opts) => {\n try {\n const col = validateCollection(collection)\n const client = getClient()\n const options: Record<string, unknown> = {}\n if (opts.where) options.where = parseJson(opts.where, 'where')\n if (opts.limit) options.limit = opts.limit\n if (opts.page) options.page = opts.page\n if (opts.sort) options.sort = opts.sort\n if (opts.depth != null) options.depth = opts.depth\n if (opts.select) options.select = parseSelect(opts.select)\n const result = await client.collections\n .from(col as (typeof COLLECTIONS)[number])\n .find(options)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('get <collection> <id>')\n .description('Get a document by ID')\n .option(\n '--depth <n>',\n 'Relationship depth (0 = no population)',\n (v: string) => parseInt(v, 10),\n )\n .option('--select <fields>', 'Comma-separated fields to select')\n .action(async (collection: string, id: string, opts) => {\n try {\n const col = validateCollection(collection)\n const client = getClient()\n const options: Record<string, unknown> = {}\n if (opts.depth != null) options.depth = opts.depth\n if (opts.select) options.select = parseSelect(opts.select)\n const result = await client.collections\n .from(col as (typeof COLLECTIONS)[number])\n .findById(id, options)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('create <collection>')\n .description('Create a new document')\n .requiredOption('--data <json>', 'Document data (JSON)')\n .option('--file <path>', 'File to upload (for upload collections)')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (collection: string, opts) => {\n try {\n const col = validateCollection(collection)\n const data = parseJson(opts.data, 'data')\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'create',\n collection: col,\n data,\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n let fileOpts: { file: Blob; filename: string } | undefined\n if (opts.file) {\n const { blob, filename } = readFileAsBlob(opts.file)\n fileOpts = { file: blob, filename }\n }\n const result = await client.collections\n .from(col as (typeof COLLECTIONS)[number])\n .create(data, fileOpts)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('update <collection> <id>')\n .description('Update a document by ID')\n .requiredOption('--data <json>', 'Document data (JSON)')\n .option('--file <path>', 'File to upload (for upload collections)')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (collection: string, id: string, opts) => {\n try {\n const col = validateCollection(collection)\n const data = parseJson(opts.data, 'data')\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'update',\n collection: col,\n id,\n data,\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n let fileOpts: { file: Blob; filename: string } | undefined\n if (opts.file) {\n const { blob, filename } = readFileAsBlob(opts.file)\n fileOpts = { file: blob, filename }\n }\n const result = await client.collections\n .from(col as (typeof COLLECTIONS)[number])\n .update(id, data, fileOpts)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('delete <collection> <id>')\n .description('Delete a document by ID')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (collection: string, id: string, opts) => {\n try {\n const col = validateCollection(collection)\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'delete',\n collection: col,\n id,\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.collections\n .from(col as (typeof COLLECTIONS)[number])\n .remove(id)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('update-many <collection>')\n .description('Update multiple documents matching a filter')\n .requiredOption('--where <json>', 'Filter conditions (JSON)')\n .requiredOption('--data <json>', 'Update data (JSON)')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (collection: string, opts) => {\n try {\n const col = validateCollection(collection)\n const where = parseJson(opts.where, 'where') as ApiQueryOptions['where']\n const data = parseJson(opts.data, 'data')\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'update-many',\n collection: col,\n where,\n data,\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.collections\n .from(col as (typeof COLLECTIONS)[number])\n .updateMany(where, data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('delete-many <collection>')\n .description('Delete multiple documents matching a filter')\n .requiredOption('--where <json>', 'Filter conditions (JSON)')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (collection: string, opts) => {\n try {\n const col = validateCollection(collection)\n const where = parseJson(opts.where, 'where') as ApiQueryOptions['where']\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'delete-many',\n collection: col,\n where,\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.collections\n .from(col as (typeof COLLECTIONS)[number])\n .removeMany(where)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { exitWithError } from './output.js'\nimport { t } from './i18n.js'\n\n/**\n * Throw an AdminError-shaped object so `exitWithError` can render it correctly\n * under `--format json` and exit with code 3 (validation). The `code` literal\n * `invalid_argument` is already in the validation bucket per `api-error.ts`.\n */\nfunction failArg(label: string, value: string, expectedKind: 'object' | 'array' | 'value'): never {\n const message =\n expectedKind === 'object'\n ? t('InvalidJsonObject', { label })\n : expectedKind === 'array'\n ? t('InvalidJsonArray', { label })\n : t('InvalidJsonValue', { label, value })\n exitWithError({\n type: 'validation',\n code: 'invalid_argument',\n field: label,\n // `message` is read by `printError` for the stderr headline so the\n // user sees the label/value in the one-line summary; `detail` carries\n // the structured fields for `--format json` consumers.\n message,\n detail: { message, value, field: label },\n })\n}\n\nexport function parseJson(\n value: string,\n label: string,\n options: { format?: string } = {},\n): Record<string, unknown> {\n let parsed: unknown\n try {\n parsed = JSON.parse(value)\n } catch {\n return failArg(label, value, 'value')\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n return failArg(label, value, 'object')\n }\n void options\n return parsed as Record<string, unknown>\n}\n\nexport function parseJsonArray(\n value: string,\n label: string,\n options: { format?: string } = {},\n): unknown[] {\n let parsed: unknown\n try {\n parsed = JSON.parse(value)\n } catch {\n return failArg(label, value, 'value')\n }\n if (!Array.isArray(parsed)) {\n return failArg(label, value, 'array')\n }\n void options\n return parsed\n}\n","import { Command } from 'commander'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\nimport { parseJson, parseJsonArray } from '../lib/parse.js'\n\nexport function registerOrderCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const order = program.command('order').description('Order management')\n\n order\n .command('create')\n .description('Create a new order')\n .option('--payment-id <id>', 'Payment ID')\n .requiredOption('--order-number <num>', 'Order number')\n .requiredOption('--email <email>', 'Customer email')\n .option('--customer <id>', 'Customer ID')\n .option('--name <name>', 'Customer name')\n .option('--phone <phone>', 'Customer phone')\n .requiredOption('--shipping-address <json>', 'Shipping address (JSON)')\n .requiredOption('--products <json>', 'Order products array (JSON)')\n .requiredOption('--total-amount <n>', 'Total amount', parseFloat)\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (opts) => {\n try {\n const shippingAddress = parseJson(\n opts.shippingAddress,\n 'shipping-address',\n )\n const orderItems = parseJsonArray(opts.products, 'products')\n const data = {\n pgPaymentId: opts.paymentId,\n orderNumber: opts.orderNumber,\n customerSnapshot: {\n email: opts.email,\n name: opts.name,\n phone: opts.phone,\n },\n customer: opts.customer,\n shippingAddress,\n orderItems,\n totalAmount: opts.totalAmount,\n }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'order create', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.orders.create({\n ...data,\n orderItems: orderItems as Parameters<\n typeof client.commerce.orders.create\n >[0]['orderItems'],\n })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n order\n .command('get <orderNumber>')\n .description('Get an order by order number')\n .action(async (orderNumber: string) => {\n try {\n const client = getClient()\n const { docs: [order] } = await client.collections.from('orders').find({ where: { orderNumber: { equals: orderNumber } }, limit: 1, depth: 1 })\n if (!order) throw new Error('Order not found')\n printResult(order, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n order\n .command('update <orderNumber>')\n .description('Update order status')\n .requiredOption('--status <status>', 'New status')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (orderNumber: string, opts) => {\n try {\n const data = { orderNumber, status: opts.status }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'order update', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.orders.update(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n order\n .command('checkout')\n .description('Convert a cart to an order')\n .requiredOption('--cart-id <id>', 'Cart ID')\n .option('--payment-id <id>', 'Payment ID (optional for free orders)')\n .requiredOption('--order-number <num>', 'Order number')\n .requiredOption('--customer <json>', 'Customer snapshot (JSON)')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (opts) => {\n try {\n const customerSnapshot = parseJson(opts.customer, 'customer')\n const data = {\n cartId: opts.cartId,\n pgPaymentId: opts.paymentId,\n orderNumber: opts.orderNumber,\n customerSnapshot,\n }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'order checkout', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.orders.checkout({\n ...data,\n customerSnapshot: customerSnapshot as Parameters<\n typeof client.commerce.orders.checkout\n >[0]['customerSnapshot'],\n })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n order\n .command('fulfill <orderNumber>')\n .description('Create a fulfillment for an order')\n .requiredOption('--items <json>', 'Fulfillment items array (JSON)')\n .option('--carrier <name>', 'Shipping carrier')\n .option('--tracking-number <num>', 'Tracking number')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (orderNumber: string, opts) => {\n try {\n const items = parseJsonArray(opts.items, 'items')\n const data = {\n orderNumber,\n items,\n carrier: opts.carrier,\n trackingNumber: opts.trackingNumber,\n }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'order fulfill', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.orders.createFulfillment({\n ...data,\n items: items as Parameters<\n typeof client.commerce.orders.createFulfillment\n >[0]['items'],\n })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { Command } from 'commander'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\nimport { parseJsonArray } from '../lib/parse.js'\n\nexport function registerReturnCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const ret = program.command('return').description('Return management')\n\n ret\n .command('create <orderNumber>')\n .description('Create a return request')\n .requiredOption('--products <json>', 'Return products array (JSON)')\n .requiredOption('--refund-amount <n>', 'Refund amount', parseFloat)\n .option(\n '--reason <reason>',\n 'Return reason (change_of_mind, defective, wrong_delivery, damaged, other)',\n )\n .option('--reason-detail <text>', 'Detailed reason')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (orderNumber: string, opts) => {\n try {\n const returnItems = parseJsonArray(opts.products, 'products')\n const data = {\n orderNumber,\n returnItems,\n refundAmount: opts.refundAmount,\n reason: opts.reason,\n reasonDetail: opts.reasonDetail,\n }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'return create', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.orders.createReturn({\n ...data,\n returnItems: returnItems as Parameters<\n typeof client.commerce.orders.createReturn\n >[0]['returnItems'],\n })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n ret\n .command('update <returnId>')\n .description('Update return status')\n .requiredOption(\n '--status <status>',\n 'New status (processing, approved, rejected, completed)',\n )\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (returnId: string, opts) => {\n try {\n const data = { returnId, status: opts.status }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'return update', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.orders.updateReturn(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n ret\n .command('refund <orderNumber>')\n .description('Return with refund')\n .requiredOption('--products <json>', 'Return products array (JSON)')\n .requiredOption('--refund-amount <n>', 'Refund amount', parseFloat)\n .requiredOption('--payment-id <id>', 'Payment ID')\n .option('--reason <reason>', 'Return reason')\n .option('--reason-detail <text>', 'Detailed reason')\n .option('--refund-receipt-url <url>', 'Refund receipt URL')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (orderNumber: string, opts) => {\n try {\n const returnItems = parseJsonArray(opts.products, 'products')\n const data = {\n orderNumber,\n returnItems,\n refundAmount: opts.refundAmount,\n pgPaymentId: opts.paymentId,\n reason: opts.reason,\n reasonDetail: opts.reasonDetail,\n refundReceiptUrl: opts.refundReceiptUrl,\n }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'return refund', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.orders.returnWithRefund({\n ...data,\n returnItems: returnItems as Parameters<\n typeof client.commerce.orders.returnWithRefund\n >[0]['returnItems'],\n })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { Command } from 'commander'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\n\nexport function registerCartCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const cart = program.command('cart').description('Cart management')\n\n cart\n .command('add <cartId>')\n .description('Add an item to cart')\n .requiredOption('--product <id>', 'Product ID')\n .requiredOption('--variant <id>', 'Variant ID')\n .requiredOption('--option <id>', 'Option ID')\n .requiredOption('--quantity <n>', 'Quantity', (v: string) =>\n parseInt(v, 10),\n )\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (cartId: string, opts) => {\n try {\n const data = {\n cartId,\n product: opts.product,\n variant: opts.variant,\n option: opts.option,\n quantity: opts.quantity,\n }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'cart add', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.cart.addItem(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n cart\n .command('update <cartItemId>')\n .description('Update cart item quantity')\n .requiredOption('--quantity <n>', 'New quantity', (v: string) =>\n parseInt(v, 10),\n )\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (cartItemId: string, opts) => {\n try {\n const data = { cartItemId, quantity: opts.quantity }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'cart update', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.cart.updateItem(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n cart\n .command('remove <cartItemId>')\n .description('Remove an item from cart')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (cartItemId: string, opts) => {\n try {\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'cart remove',\n data: { cartItemId },\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.cart.removeItem({ cartItemId })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { Command } from 'commander'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\nimport { parseJsonArray } from '../lib/parse.js'\n\nexport function registerStockCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const stock = program.command('stock').description('Stock management')\n\n stock\n .command('check')\n .description('Check stock availability')\n .requiredOption(\n '--items <json>',\n 'Items to check (JSON array of { optionId, quantity })',\n )\n .action(async (opts) => {\n try {\n const client = getClient()\n const items = parseJsonArray(opts.items, 'items') as Parameters<\n typeof client.commerce.product.stockCheck\n >[0]['items']\n const result = await client.commerce.product.stockCheck({ items })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { Command } from 'commander'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\n\nexport function registerTransactionCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const tx = program\n .command('transaction')\n .description('Transaction management')\n\n tx.command('update')\n .description('Update transaction status')\n .requiredOption('--payment-id <id>', 'Payment ID')\n .requiredOption(\n '--status <status>',\n 'New status (pending, paid, failed, canceled)',\n )\n .requiredOption('--payment-method <method>', 'Payment method')\n .requiredOption('--receipt-url <url>', 'Receipt URL')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (opts) => {\n try {\n const data = {\n pgPaymentId: opts.paymentId,\n status: opts.status,\n paymentMethod: opts.paymentMethod,\n receiptUrl: opts.receiptUrl,\n }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'transaction update', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.orders.updateTransaction(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { randomBytes } from 'node:crypto'\nimport { createServer } from 'node:http'\nimport { execFile, exec } from 'node:child_process'\nimport { platform } from 'node:os'\nimport { URL } from 'node:url'\nimport type { Command } from 'commander'\nimport pc from 'picocolors'\nimport {\n loadCredentials,\n saveCredentials,\n deleteCredentials,\n getCredentialsPath,\n loadLocalCredentials,\n saveLocalCredentials,\n getLocalCredentialsPath,\n loadTenantList,\n saveTenantList,\n type TenantInfo,\n} from '../lib/credentials.js'\n\nconst WEB_URL = process.env.SOFTWARE_WEB_URL || 'https://01.software'\nconst TIMEOUT_MS = 3 * 60 * 1000 // 3 minutes\n\nfunction escapeHtml(s: string): string {\n return s\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n}\n\nfunction openBrowser(url: string): void {\n const os = platform()\n\n const onError = () => {\n console.log(\n pc.yellow(\n `Could not open browser automatically. Open this URL manually:\\n${url}`,\n ),\n )\n }\n\n if (os === 'win32') {\n exec(`start \"\" \"${url}\"`, (err) => {\n if (err) onError()\n })\n } else {\n const cmd = os === 'darwin' ? 'open' : 'xdg-open'\n execFile(cmd, [url], (err) => {\n if (err) onError()\n })\n }\n}\n\nconst PAGE_STYLE = `*{margin:0;box-sizing:border-box}\nbody{font-family:system-ui,-apple-system,sans-serif;display:flex;justify-content:center;align-items:center;min-height:100vh;background:#fff;color:#252525}\n@media(prefers-color-scheme:dark){body{background:#252525;color:#f5f5f5}}\n.card{text-align:center;padding:2rem 2.5rem;border-radius:10px;max-width:380px;width:100%}\n.icon{width:40px;height:40px;margin:0 auto 1rem;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:1.25rem}\n.icon.ok{background:rgba(0,0,0,.05);color:#252525}\n.icon.err{background:rgba(220,38,38,.08);color:#dc2626}\n@media(prefers-color-scheme:dark){.icon.ok{background:rgba(255,255,255,.08);color:#f5f5f5}}\nh1{font-size:.875rem;font-weight:600;margin-bottom:.375rem}\np{font-size:.75rem;color:#737373;line-height:1.5}`\n\nconst SUCCESS_HTML = `<!DOCTYPE html>\n<html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width\"><title>CLI Login</title>\n<style>${PAGE_STYLE}</style>\n</head><body><div class=\"card\"><div class=\"icon ok\">\\u2713</div><h1>Authenticated</h1><p>You can close this tab and return to the terminal.</p></div></body></html>`\n\nconst ERROR_HTML = (msg: string) => `<!DOCTYPE html>\n<html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width\"><title>CLI Login Error</title>\n<style>${PAGE_STYLE}</style>\n</head><body><div class=\"card\"><div class=\"icon err\">!</div><h1>Authentication failed</h1><p>${escapeHtml(msg)}</p></div></body></html>`\n\ninterface ExchangeResponse {\n publishableKey: string\n secretKey: string\n tenantName: string\n tenantId: string\n tenants?: TenantInfo[]\n}\n\nasync function exchangeCode(code: string): Promise<ExchangeResponse | null> {\n const url = `${WEB_URL}/api/cli/exchange`\n try {\n const res = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ code }),\n })\n if (!res.ok) {\n const body = await res.text().catch(() => '')\n console.error(\n pc.red(\n `Exchange failed: HTTP ${res.status} from ${url}${body ? ` — ${body.slice(0, 200)}` : ''}`,\n ),\n )\n return null\n }\n const data = (await res.json()) as Partial<ExchangeResponse>\n if (\n typeof data.publishableKey !== 'string' ||\n typeof data.secretKey !== 'string' ||\n typeof data.tenantName !== 'string' ||\n typeof data.tenantId !== 'string'\n ) {\n console.error(pc.red(`Exchange failed: malformed response from ${url}`))\n return null\n }\n return {\n publishableKey: data.publishableKey,\n secretKey: data.secretKey,\n tenantName: data.tenantName,\n tenantId: data.tenantId,\n tenants: Array.isArray(data.tenants)\n ? data.tenants.filter(\n (t): t is TenantInfo =>\n typeof (t as TenantInfo)?.id === 'string' &&\n typeof (t as TenantInfo)?.name === 'string',\n )\n : undefined,\n }\n } catch (err) {\n console.error(\n pc.red(\n `Exchange request to ${url} failed: ${err instanceof Error ? err.message : String(err)}`,\n ),\n )\n return null\n }\n}\n\n/**\n * Start a local HTTP server that receives the OAuth-style redirect callback\n * from the browser. The browser top-level-navigates to\n * http://127.0.0.1:{port}/callback?code={encryptedCode}&state={state}\n * and the CLI exchanges the opaque code with the web API to receive the\n * actual credentials server-to-server. This path has no CORS or PNA\n * preflight because the browser never issues a subresource fetch.\n */\nfunction startAuthServer(options: {\n state: string\n saveFn: (creds: {\n publishableKey: string\n secretKey: string\n tenantId?: string\n tenantName: string\n }) => void\n}): Promise<{ port: number; cleanup: (exitCode?: number) => void }> {\n return new Promise((resolve, reject) => {\n const server = createServer((req, res) => {\n if (!req.url) {\n res.writeHead(400).end()\n return\n }\n\n const url = new URL(req.url, `http://localhost`)\n\n if (url.pathname !== '/callback' || req.method !== 'GET') {\n res.writeHead(404).end()\n return\n }\n\n const error = url.searchParams.get('error')\n if (error) {\n res\n .writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', Connection: 'close' })\n .end(ERROR_HTML(error))\n console.error(pc.red(`Login failed: ${error}`))\n cleanup(2)\n return\n }\n\n const code = url.searchParams.get('code')\n const receivedState = url.searchParams.get('state')\n\n if (!code || !receivedState) {\n res\n .writeHead(400, { 'Content-Type': 'text/html; charset=utf-8', Connection: 'close' })\n .end(ERROR_HTML('Missing code or state. Start over with \"01 login\".'))\n cleanup(2)\n return\n }\n\n if (receivedState !== options.state) {\n res\n .writeHead(403, { 'Content-Type': 'text/html; charset=utf-8', Connection: 'close' })\n .end(ERROR_HTML('State mismatch. Start over with \"01 login\".'))\n console.error(pc.red('Login failed: state mismatch.'))\n cleanup(2)\n return\n }\n\n exchangeCode(code).then((creds) => {\n if (!creds) {\n res\n .writeHead(400, { 'Content-Type': 'text/html; charset=utf-8', Connection: 'close' })\n .end(ERROR_HTML('Invalid or expired code. Start over with \"01 login\".'))\n console.error(pc.red('Login failed: code exchange failed.'))\n cleanup(2)\n return\n }\n\n options.saveFn({\n publishableKey: creds.publishableKey,\n secretKey: creds.secretKey,\n tenantId: creds.tenantId,\n tenantName: creds.tenantName,\n })\n\n if (creds.tenants && creds.tenants.length > 0) {\n saveTenantList(creds.tenants)\n }\n\n console.log(pc.green(`\\nLogged in successfully!`))\n console.log(pc.dim(`Tenant: ${creds.tenantName}`))\n\n res\n .writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', Connection: 'close' })\n .end(SUCCESS_HTML)\n cleanup(0)\n })\n })\n\n let timeout: ReturnType<typeof setTimeout>\n let completed = false\n\n function cleanup(exitCode = 0) {\n if (completed) return\n completed = true\n clearTimeout(timeout)\n server.closeAllConnections?.()\n server.close(() => process.exit(exitCode))\n }\n\n server.listen(0, '127.0.0.1', () => {\n const addr = server.address()\n if (!addr || typeof addr === 'string') {\n reject(new Error('Failed to start local server.'))\n return\n }\n\n timeout = setTimeout(() => {\n console.error(\n pc.red('\\nLogin timed out (3 minutes). Please try again.'),\n )\n cleanup(4)\n }, TIMEOUT_MS)\n\n resolve({ port: addr.port, cleanup })\n })\n\n server.on('error', (err) => {\n reject(err)\n })\n })\n}\n\nexport function registerAuthCommands(program: Command): void {\n program\n .command('login')\n .description('Login via browser and store credentials')\n .action(async () => {\n const state = randomBytes(32).toString('hex')\n\n try {\n const { port } = await startAuthServer({\n state,\n saveFn: (creds) => {\n saveCredentials(creds)\n console.log(pc.dim(`Credentials saved to ${getCredentialsPath()}`))\n },\n })\n\n const params = new URLSearchParams({ port: String(port), state })\n const loginUrl = `${WEB_URL}/cli-auth?${params.toString()}`\n\n console.log(pc.dim('Opening browser for login...'))\n console.log(pc.dim(`If the browser does not open, visit:\\n${loginUrl}`))\n openBrowser(loginUrl)\n } catch (err) {\n console.error(\n pc.red(\n `Server error: ${err instanceof Error ? err.message : String(err)}`,\n ),\n )\n process.exit(4)\n }\n })\n\n program\n .command('logout')\n .description('Remove stored credentials')\n .action(() => {\n const deleted = deleteCredentials()\n if (deleted) {\n console.log(pc.green('Logged out. Credentials removed.'))\n } else {\n console.log(pc.dim('No stored credentials found.'))\n }\n })\n\n program\n .command('whoami')\n .description('Show current authentication status')\n .action(() => {\n // Check local credentials first\n const localCreds = loadLocalCredentials()\n const globalCreds = loadCredentials()\n const creds = localCreds || globalCreds\n const isLocal = !!localCreds\n\n if (!creds) {\n console.log(pc.dim('Not logged in. Run \"01 login\" to authenticate.'))\n return\n }\n\n const masked =\n creds.publishableKey.length > 8\n ? creds.publishableKey.slice(0, 4) + '...' + creds.publishableKey.slice(-4)\n : '****'\n\n const scope = isLocal ? pc.cyan(' (local)') : ''\n console.log(`Tenant: ${pc.bold(creds.tenantName)}${scope}`)\n console.log(`Publishable Key: ${pc.dim(masked)}`)\n console.log(`Stored at: ${pc.dim(creds.storedAt)}`)\n console.log(\n `File: ${pc.dim(isLocal ? getLocalCredentialsPath() : getCredentialsPath())}`,\n )\n })\n\n // -------------------------------------------------------------------------\n // tenant subcommands\n // -------------------------------------------------------------------------\n const tenant = program\n .command('tenant')\n .description('Manage tenant switching')\n\n tenant\n .command('list')\n .description('Show cached tenant list')\n .action(() => {\n const tenants = loadTenantList()\n if (!tenants || tenants.length === 0) {\n console.log(pc.dim('No cached tenants. Run \"01 login\" first.'))\n return\n }\n\n // Determine active tenant\n const localCreds = loadLocalCredentials()\n const globalCreds = loadCredentials()\n const activeCreds = localCreds || globalCreds\n const activeId = activeCreds?.tenantId\n const activeName = activeCreds?.tenantName\n\n console.log(pc.bold('Cached tenants:\\n'))\n for (const t of tenants) {\n const active = (activeId ? t.id === activeId : t.name === activeName)\n ? pc.green(' *')\n : ''\n console.log(` ${t.name}${active}`)\n }\n console.log()\n if (activeName) {\n const scope = localCreds ? '(local)' : '(global)'\n console.log(pc.dim(`* active ${scope}`))\n }\n })\n\n tenant\n .command('use <name>')\n .description('Switch to a different tenant via browser')\n .option('--local', 'Save credentials locally in the current project')\n .action(async (name: string, opts: { local?: boolean }) => {\n const tenants = loadTenantList()\n if (!tenants || tenants.length === 0) {\n console.error(pc.red('No cached tenants. Run \"01 login\" first.'))\n process.exit(2)\n }\n\n const match = tenants.find(\n (t) => t.name.toLowerCase() === name.toLowerCase(),\n )\n if (!match) {\n console.error(pc.red(`Tenant \"${name}\" not found in cache.`))\n console.error(\n pc.dim(`Available: ${tenants.map((t) => t.name).join(', ')}`),\n )\n process.exit(3)\n }\n\n const state = randomBytes(32).toString('hex')\n const isLocal = !!opts.local\n\n try {\n const { port } = await startAuthServer({\n state,\n saveFn: (creds) => {\n if (isLocal) {\n saveLocalCredentials(creds)\n console.log(\n pc.dim(`Credentials saved to ${getLocalCredentialsPath()}`),\n )\n } else {\n saveCredentials(creds)\n console.log(\n pc.dim(`Credentials saved to ${getCredentialsPath()}`),\n )\n }\n },\n })\n\n const params = new URLSearchParams({\n port: String(port),\n state,\n tenantId: match.id,\n })\n const loginUrl = `${WEB_URL}/cli-auth?${params.toString()}`\n\n console.log(pc.dim(`Switching to tenant \"${match.name}\"...`))\n console.log(pc.dim(`If the browser does not open, visit:\\n${loginUrl}`))\n openBrowser(loginUrl)\n } catch (err) {\n console.error(\n pc.red(\n `Server error: ${err instanceof Error ? err.message : String(err)}`,\n ),\n )\n process.exit(4)\n }\n })\n}\n","import { Command } from 'commander'\nimport { COLLECTIONS } from '@01.software/sdk'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\n\ndeclare const __DEFAULT_API_URL__: string\n\nfunction getApiUrl(): string {\n return (\n process.env.SOFTWARE_API_URL ||\n process.env.NEXT_PUBLIC_SOFTWARE_API_URL ||\n __DEFAULT_API_URL__\n ).replace(/\\/$/, '')\n}\n\nexport function registerSchemaCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const schema = program\n .command('schema')\n .description('Collection schema introspection')\n\n schema\n .command('list')\n .description('List available collections')\n .action(() => {\n printResult(COLLECTIONS, getFormat())\n })\n\n schema\n .command('show <collection>')\n .description('Show collection field schema')\n .action(async (collection: string) => {\n try {\n if (!(COLLECTIONS as readonly string[]).includes(collection)) {\n const normalized = collection.replace(/-/g, '').toLowerCase()\n const suggestions = (COLLECTIONS as readonly string[])\n .filter((c) => {\n const cn = c.replace(/-/g, '').toLowerCase()\n return (\n cn.startsWith(normalized) ||\n normalized.startsWith(cn) ||\n (normalized.length >= 3 && cn.includes(normalized))\n )\n })\n .slice(0, 5)\n const hint =\n suggestions.length > 0\n ? `Did you mean: ${suggestions.join(', ')}?`\n : 'Run \"01 schema list\" for available collections.'\n throw new Error(`Unknown collection \"${collection}\". ${hint}`)\n }\n const client = getClient()\n const baseUrl = getApiUrl()\n\n const url = `${baseUrl}/api/tenants/schema/${encodeURIComponent(collection)}`\n const response = await fetch(url, {\n headers: {\n 'X-Publishable-Key': client.publishableKey,\n Authorization: `Bearer ${client.secretKey}`,\n },\n })\n\n if (!response.ok) {\n const body = await response\n .json()\n .catch(() => ({ error: response.statusText }))\n const err = new Error(\n (body as { error?: string }).error || `HTTP ${response.status}`,\n )\n Object.assign(err, { status: response.status })\n throw err\n }\n\n const result = await response.json()\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { resolve, dirname } from 'node:path'\nimport { existsSync } from 'node:fs'\nimport { spawn } from 'node:child_process'\nimport { fileURLToPath } from 'node:url'\nimport type { Command } from 'commander'\nimport { resolveClient } from '../lib/client.js'\nimport { exitWithError } from '../lib/output.js'\n\nconst __dirname = dirname(fileURLToPath(import.meta.url))\n\n/**\n * Locate the MCP stdio entry point.\n * Resolve order:\n * 1. Packaged MCP server copied into packages/cli/dist/mcp/stdio.js\n * 2. Monorepo MCP build output: apps/mcp/dist/stdio.js\n * 3. xmcp output: apps/mcp/.xmcp/stdio.js\n */\nexport function findStdioEntry(baseDir = __dirname): string | null {\n const packaged = resolve(baseDir, 'mcp/stdio.js')\n if (existsSync(packaged)) return packaged\n\n const roots = ['../../../..', '../../..', '../..']\n const entries = ['apps/mcp/dist/stdio.js', 'apps/mcp/.xmcp/stdio.js']\n\n for (const entry of entries) {\n for (const root of roots) {\n const candidate = resolve(baseDir, root, entry)\n if (existsSync(candidate)) return candidate\n }\n }\n\n return null\n}\n\nexport function createMcpEnv(\n baseEnv: NodeJS.ProcessEnv,\n client: { publishableKey: string; secretKey: string },\n): NodeJS.ProcessEnv {\n const env: NodeJS.ProcessEnv = {\n ...baseEnv,\n SOFTWARE_PUBLISHABLE_KEY: client.publishableKey,\n SOFTWARE_SECRET_KEY: client.secretKey,\n }\n\n delete env.SOFTWARE_TENANT_ID\n\n return env\n}\n\nexport function registerMcpCommands(program: Command) {\n program\n .command('mcp')\n .description('Start MCP server over stdio')\n .action(() => {\n // 1. Validate credentials before spawning (exits with code 2 if missing)\n const client = resolveClient(program.opts().apiKey as string | undefined)\n\n // 2. Find stdio.js entry point\n const stdioEntry = findStdioEntry()\n if (!stdioEntry) {\n exitWithError(\n new Error(\n 'MCP server not found. Ensure apps/mcp is built (pnpm --filter mcp build).',\n ),\n )\n }\n\n // 3. Spawn stdio process (inherits env with SOFTWARE_PUBLISHABLE_KEY + SOFTWARE_SECRET_KEY)\n const child = spawn(process.execPath, [stdioEntry], {\n env: createMcpEnv(process.env, client),\n stdio: ['inherit', 'inherit', 'inherit'],\n })\n\n child.on('error', (err) => {\n exitWithError(new Error(`Failed to start MCP server: ${err.message}`))\n })\n\n child.on('exit', (code) => {\n process.exit(code ?? 0)\n })\n })\n}\n"],"mappings":";;;AAAA,SAAS,qBAAqB;AAC9B,SAAS,eAAe;;;ACDxB;AAAA,EACE;AAAA,EACA;AAAA,OACK;;;ACHP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,YAAY;AACrB,SAAS,eAAe;AAgBxB,IAAM,WAAW;AACjB,IAAM,YAAY;AAClB,IAAM,eAAe;AAMd,SAAS,qBAA6B;AAC3C,SAAO,KAAK,QAAQ,GAAG,UAAU,SAAS;AAC5C;AAEO,SAAS,kBAA4C;AAC1D,SAAO,oBAAoB,mBAAmB,CAAC;AACjD;AAEO,SAAS,gBACd,OACM;AACN,QAAM,MAAM,KAAK,QAAQ,GAAG,QAAQ;AACpC,MAAI,CAAC,WAAW,GAAG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AI,QAAQ;AAE5B,QACG,KAAK,IAAI,EACT,YAAY,kCAAkC,EAC9C,QAAQ,OAAO,EACf,OAAO,mBAAmB,uCAAuC,EACjE,OAAO,qBAAqB,uCAAuC,EACnE,OAAO,mBAAmB,yBAAyB;AAEtD,IAAM,YAAY,MACf,QAAQ,KAAK,EAAE,UAAU,QAAQ,IAAI,iBAAiB;AAOzD,QAAQ,KAAK,aAAa,MAAM;AAC9B,QAAM,OAAO,QAAQ,KAAK,EAAE;AAC5B,MAAI,SAAS,QAAQ,SAAS,KAAM,WAAU,IAAc;AAC5D,UAAQ,IAAI,gBAAgB,UAAU;AACxC,CAAC;AAED,QAAQ,GAAG,sBAAsB,CAAC,QAAQ;AACxC,gBAAc,KAAK,EAAE,QAAQ,UAAU,EAAE,CAAC;AAC5C,CAAC;AAED,IAAM,YAAY,MAChB,cAAc,QAAQ,KAAK,EAAE,MAA4B;AAE3D,qBAAqB,SAAS,WAAW,SAAS;AAClD,sBAAsB,SAAS,WAAW,SAAS;AACnD,uBAAuB,SAAS,WAAW,SAAS;AACpD,qBAAqB,SAAS,WAAW,SAAS;AAClD,sBAAsB,SAAS,WAAW,SAAS;AACnD,4BAA4B,SAAS,WAAW,SAAS;AACzD,uBAAuB,SAAS,WAAW,SAAS;AACpD,oBAAoB,OAAO;AAC3B,qBAAqB,OAAO;AAE5B,QAAQ,MAAM;","names":["t","readFileSync","readFileSync","program","getClient","getFormat","program","getClient","getFormat","order","program","getClient","getFormat","program","getClient","getFormat","program","getClient","getFormat","program","getClient","getFormat","pc","pc","t","resolve","program","COLLECTIONS","program","getClient","getFormat","COLLECTIONS","existsSync","existsSync","program","require"]}
|