@purpleturret/cli 0.1.0 → 0.2.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/README.md +1 -0
- package/dist/cli.js +12 -6
- package/dist/cli.js.map +1 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -94,6 +94,7 @@ The CLI finds `purpleturret.config.{ts,mts,js,mjs,json}` in the current director
|
|
|
94
94
|
| `theme` | `{ primaryColor?, buttonRadius?, accentMode? }` | Optional. Hex color; `sm \| md \| lg`; `light \| dark \| system`. |
|
|
95
95
|
| `stripe` | `{ priceId }` | Optional. Adopt an existing Stripe price on create. Immutable. |
|
|
96
96
|
| `active` | `boolean` | Optional. Inactive products stop accepting checkouts. |
|
|
97
|
+
| `buyerEmails` | `boolean` | Optional. `false` turns off Purpleturret's receipt, delivery and refund emails. |
|
|
97
98
|
|
|
98
99
|
**Rules to know before you edit:**
|
|
99
100
|
|
package/dist/cli.js
CHANGED
|
@@ -7,7 +7,7 @@ import { writeFile as writeFile2 } from "fs/promises";
|
|
|
7
7
|
import { relative, resolve } from "path";
|
|
8
8
|
|
|
9
9
|
// ../sdk/src/version.ts
|
|
10
|
-
var SDK_VERSION = "0.
|
|
10
|
+
var SDK_VERSION = "0.2.0";
|
|
11
11
|
|
|
12
12
|
// ../sdk/src/config/schema.ts
|
|
13
13
|
import { z } from "zod";
|
|
@@ -75,7 +75,8 @@ var productInputSchema = z.strictObject({
|
|
|
75
75
|
theme: themeSchema.optional(),
|
|
76
76
|
slug: z.string().regex(SLUG_PATTERN, "must be 3-64 characters of lowercase letters, digits, or '-'").optional(),
|
|
77
77
|
stripe: stripeSchema.optional(),
|
|
78
|
-
active: z.boolean().optional()
|
|
78
|
+
active: z.boolean().optional(),
|
|
79
|
+
buyerEmails: z.boolean().optional()
|
|
79
80
|
});
|
|
80
81
|
var configSchema = z.strictObject({
|
|
81
82
|
products: z.array(productInputSchema)
|
|
@@ -271,7 +272,8 @@ function toWireProduct(input) {
|
|
|
271
272
|
theme: input.theme ? toWireTheme(input.theme) : void 0,
|
|
272
273
|
slug: input.slug,
|
|
273
274
|
stripe: input.stripe ? { price_id: input.stripe.priceId } : void 0,
|
|
274
|
-
active: input.active
|
|
275
|
+
active: input.active,
|
|
276
|
+
buyer_emails: input.buyerEmails
|
|
275
277
|
};
|
|
276
278
|
return omitUndefined(wire);
|
|
277
279
|
}
|
|
@@ -319,6 +321,7 @@ function fromWireProduct(wire) {
|
|
|
319
321
|
theme: wire.theme ? fromWireTheme(wire.theme) : void 0,
|
|
320
322
|
stripe: wire.stripe ? fromWireStripe(wire.stripe) : void 0,
|
|
321
323
|
active: wire.active,
|
|
324
|
+
buyerEmails: wire.buyer_emails ?? void 0,
|
|
322
325
|
archivedAt: wire.archived_at ?? null,
|
|
323
326
|
createdAt: wire.created_at,
|
|
324
327
|
updatedAt: wire.updated_at
|
|
@@ -373,7 +376,9 @@ function productToInput(product) {
|
|
|
373
376
|
theme: product.theme,
|
|
374
377
|
slug: product.slug ?? void 0,
|
|
375
378
|
stripe: product.stripe,
|
|
376
|
-
active: product.active
|
|
379
|
+
active: product.active,
|
|
380
|
+
// The API always reports buyer_emails; only the opt-out is worth writing into a config.
|
|
381
|
+
buyerEmails: product.buyerEmails === false ? false : void 0
|
|
377
382
|
});
|
|
378
383
|
}
|
|
379
384
|
function fromWirePlanItem(item) {
|
|
@@ -664,7 +669,7 @@ import { join as join2 } from "path";
|
|
|
664
669
|
import dotenv from "dotenv";
|
|
665
670
|
|
|
666
671
|
// src/version.ts
|
|
667
|
-
var CLI_VERSION = "0.
|
|
672
|
+
var CLI_VERSION = "0.2.0";
|
|
668
673
|
|
|
669
674
|
// src/lib/credentials.ts
|
|
670
675
|
import { chmod, mkdir, readFile, rename, writeFile } from "fs/promises";
|
|
@@ -1124,7 +1129,8 @@ var PRODUCT_KEY_ORDER = [
|
|
|
1124
1129
|
"checkout",
|
|
1125
1130
|
"theme",
|
|
1126
1131
|
"stripe",
|
|
1127
|
-
"active"
|
|
1132
|
+
"active",
|
|
1133
|
+
"buyerEmails"
|
|
1128
1134
|
];
|
|
1129
1135
|
var IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
1130
1136
|
function renderConfigSource(products2, format = "ts") {
|
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/main.ts","../src/commands/init.ts","../../sdk/src/version.ts","../../sdk/src/config/schema.ts","../../sdk/src/client/errors.ts","../../sdk/src/client/wire.ts","../../sdk/src/client/client.ts","../src/lib/context.ts","../src/version.ts","../src/lib/credentials.ts","../src/lib/errors.ts","../src/lib/output.ts","../src/lib/pull-writer.ts","../src/lib/run.ts","../src/commands/login.ts","../src/commands/logout.ts","../src/commands/products.ts","../src/lib/render.ts","../src/lib/table.ts","../src/commands/pull.ts","../src/commands/push.ts","../src/lib/config-loader.ts","../src/commands/status.ts","../src/commands/whoami.ts","../src/cli.ts"],"sourcesContent":["import { defineCommand, runCommand, showUsage, type CommandDef } from \"citty\";\n\nimport { init } from \"./commands/init.js\";\nimport { login } from \"./commands/login.js\";\nimport { logout } from \"./commands/logout.js\";\nimport { products } from \"./commands/products.js\";\nimport { pull } from \"./commands/pull.js\";\nimport { push } from \"./commands/push.js\";\nimport { status } from \"./commands/status.js\";\nimport { whoami } from \"./commands/whoami.js\";\nimport { globalArgs, stashGlobalFlags, type GlobalFlags } from \"./lib/context.js\";\nimport { CliError, EXIT } from \"./lib/errors.js\";\nimport { Output, createPalette, shouldUseColor } from \"./lib/output.js\";\nimport { CLI_VERSION } from \"./version.js\";\n\nexport const main = defineCommand({\n meta: {\n name: \"purpleturret\",\n version: CLI_VERSION,\n description: \"Sync purpleturret.config.ts with your Purpleturret account. Also available as `pt`.\",\n },\n args: { ...globalArgs },\n setup({ args }) {\n stashGlobalFlags(args as GlobalFlags);\n },\n subCommands: { init, login, logout, whoami, status, push, pull, products },\n});\n\ntype AnyCommand = CommandDef<Record<string, never>>;\n\nasync function resolveSubCommand(cmd: AnyCommand, rawArgs: string[]): Promise<[AnyCommand, AnyCommand | undefined]> {\n let current: AnyCommand = cmd;\n let parent: AnyCommand | undefined;\n let args = rawArgs;\n for (;;) {\n const subCommands = (await current.subCommands) as Record<string, AnyCommand> | undefined;\n if (!subCommands) return [current, parent];\n const index = args.findIndex((arg) => !arg.startsWith(\"-\"));\n const name = index >= 0 ? args[index] : undefined;\n const next = name ? subCommands[name] : undefined;\n if (!next) return [current, parent];\n parent = current;\n current = next;\n args = args.slice(index + 1);\n }\n}\n\nfunction isCittyError(error: unknown): error is Error & { code?: string } {\n return error instanceof Error && error.name === \"CLIError\";\n}\n\nconst GLOBAL_STRING_FLAGS = new Set([\"--config\", \"--api-url\", \"--api-key\", \"--profile\"]);\n\n/**\n * citty picks the first token that does not start with \"-\" as the subcommand, so `pt --api-key x push`\n * would treat `x` as the command. Move flags that precede the subcommand behind it instead.\n */\nexport function hoistLeadingFlags(rawArgs: string[]): string[] {\n const leading: string[] = [];\n let index = 0;\n while (index < rawArgs.length) {\n const token = rawArgs[index]!;\n if (!token.startsWith(\"-\")) break;\n leading.push(token);\n index += 1;\n const next = rawArgs[index];\n if (GLOBAL_STRING_FLAGS.has(token) && next !== undefined && !next.startsWith(\"-\")) {\n leading.push(next);\n index += 1;\n }\n }\n if (index === 0 || index >= rawArgs.length) return rawArgs;\n return [...rawArgs.slice(index), ...leading];\n}\n\n/** Entry point shared by the bin shim and tests. Sets `process.exitCode`; never calls `process.exit`. */\nexport async function runCli(argv: string[] = process.argv.slice(2)): Promise<void> {\n const root = main as unknown as AnyCommand;\n const rawArgs = hoistLeadingFlags(argv);\n try {\n if (rawArgs.includes(\"--help\") || rawArgs.includes(\"-h\")) {\n const [cmd, parent] = await resolveSubCommand(root, rawArgs);\n await showUsage(cmd, parent);\n return;\n }\n if (rawArgs.length === 1 && rawArgs[0] === \"--version\") {\n process.stdout.write(`${CLI_VERSION}\\n`);\n return;\n }\n if (rawArgs.length === 0) {\n await showUsage(root);\n return;\n }\n await runCommand(root, { rawArgs });\n } catch (error) {\n const flags = parseLooseGlobals(rawArgs);\n const out = new Output({ json: flags.json, verbose: flags.verbose, palette: createPalette(shouldUseColor({ flag: flags.color })) });\n if (isCittyError(error)) {\n out.fail(new CliError(error.message, EXIT.USAGE, { code: \"usage\" }));\n if (!flags.json) {\n const [cmd, parent] = await resolveSubCommand(root, rawArgs);\n await showUsage(cmd, parent);\n }\n process.exitCode = EXIT.USAGE;\n return;\n }\n const cliError =\n error instanceof CliError ? error : new CliError(error instanceof Error ? error.message : String(error), EXIT.ERROR, { cause: error });\n out.fail(cliError);\n process.exitCode = cliError.exitCode;\n }\n}\n\nfunction parseLooseGlobals(rawArgs: string[]): { json: boolean; verbose: boolean; color: boolean | undefined } {\n return {\n json: rawArgs.includes(\"--json\"),\n verbose: rawArgs.includes(\"--verbose\"),\n color: rawArgs.includes(\"--no-color\") ? false : undefined,\n };\n}\n","import { existsSync } from \"node:fs\";\nimport { writeFile } from \"node:fs/promises\";\nimport { relative, resolve } from \"node:path\";\n\nimport { productToInput, type ProductInput } from \"@purpleturret/sdk\";\nimport { defineCommand } from \"citty\";\n\nimport { globalArgs } from \"../lib/context.js\";\nimport { CliError, EXIT } from \"../lib/errors.js\";\nimport { renderConfigSource, renderStarterConfig, type ConfigFormat } from \"../lib/pull-writer.js\";\nimport { defineRun } from \"../lib/run.js\";\n\nexport const init = defineCommand({\n meta: { name: \"init\", description: \"Create a purpleturret.config.ts in the current directory\" },\n args: {\n ...globalArgs,\n \"from-remote\": { type: \"boolean\", description: \"Seed the file with the products already managed on your account\" },\n force: { type: \"boolean\", description: \"Overwrite an existing config file\" },\n format: { type: \"string\", description: \"File format: ts (default) or json\" },\n },\n run: defineRun(async (ctx, args) => {\n const formatArg = (args.format ?? \"ts\").toLowerCase();\n if (formatArg !== \"ts\" && formatArg !== \"json\") {\n throw new CliError(`Unknown --format \"${args.format}\"; expected ts or json.`, EXIT.USAGE, { code: \"usage\" });\n }\n const format: ConfigFormat = formatArg;\n const target = resolve(ctx.cwd, ctx.configPath ?? `purpleturret.config.${format}`);\n if (existsSync(target) && !args.force) {\n throw new CliError(`${relative(ctx.cwd, target) || target} already exists.`, EXIT.USAGE, {\n code: \"file_exists\",\n hint: \"Pass --force to overwrite it, or --config <path> to write elsewhere.\",\n });\n }\n\n let source: string;\n let count: number;\n if (args[\"from-remote\"]) {\n const { products } = await ctx.client().config.get();\n const inputs = products.map(productToInput).filter((input): input is ProductInput => input !== null);\n source = renderConfigSource(inputs, format);\n count = inputs.length;\n } else {\n source = renderStarterConfig(format);\n count = 1;\n }\n await writeFile(target, source, \"utf8\");\n\n if (ctx.json) {\n ctx.out.printJson({ written: target, products: count, from_remote: Boolean(args[\"from-remote\"]) });\n return;\n }\n const { palette } = ctx.out;\n ctx.out.success(\n `Created ${relative(ctx.cwd, target) || target}${args[\"from-remote\"] ? ` with ${count} product${count === 1 ? \"\" : \"s\"} from your account` : \"\"}`,\n );\n ctx.out.info(\"\");\n ctx.out.info(\"Next steps:\");\n if (format === \"ts\") ctx.out.info(` ${palette.dim(\"1.\")} pnpm add -D @purpleturret/sdk ${palette.dim(\"(types + helpers used by the config)\")}`);\n ctx.out.info(` ${palette.dim(format === \"ts\" ? \"2.\" : \"1.\")} purpleturret login ${palette.dim(\"(or set PURPLETURRET_API_KEY)\")}`);\n ctx.out.info(` ${palette.dim(format === \"ts\" ? \"3.\" : \"2.\")} purpleturret push --dry-run`);\n }),\n});\n","/** Keep in sync with package.json. */\nexport const SDK_VERSION = \"0.1.0\";\n","import { z } from \"zod\";\n\nimport type { ProductInput, PurpleturretConfig } from \"../types.js\";\n\n/** Product keys and credit meters: 1-64 chars, lowercase letters, digits, `_` or `-`, starting with a letter or digit. */\nexport const KEY_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/;\n/** Public checkout slugs: 3-64 chars, lowercase letters, digits, or `-`. */\nexport const SLUG_PATTERN = /^[a-z0-9-]{3,64}$/;\nconst HEX_COLOR_PATTERN = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;\n\nconst KEY_MESSAGE = \"must be 1-64 characters of lowercase letters, digits, '_' or '-', starting with a letter or digit\";\n\nexport const keySchema = z.string().regex(KEY_PATTERN, KEY_MESSAGE);\nexport const meterSchema = z.string().regex(KEY_PATTERN, KEY_MESSAGE);\n\nexport const moneySchema = z.strictObject({\n amount: z\n .number(\"must be an integer amount in the smallest currency unit (e.g. cents)\")\n .int(\"must be an integer amount in the smallest currency unit (e.g. cents)\")\n .min(50, \"must be at least 50 (e.g. $0.50); use usd(dollars) to convert\"),\n currency: z\n .string()\n .trim()\n .toLowerCase()\n .regex(/^[a-z]{3}$/, \"must be a 3-letter ISO currency code\"),\n});\n\nexport const billingSchema = z.discriminatedUnion(\"type\", [\n z.strictObject({ type: z.literal(\"one_time\") }),\n z.strictObject({ type: z.literal(\"recurring\"), interval: z.enum([\"month\", \"year\"]) }),\n]);\n\nexport const tierSchema = z.strictObject({\n key: keySchema,\n name: z.string().trim().min(1, \"must not be empty\").max(80),\n rank: z.number().int(\"must be an integer\").min(0),\n});\n\nexport const groupSchema = z.strictObject({\n key: keySchema,\n tier: tierSchema.optional(),\n});\n\nexport const creditGrantSchema = z.strictObject({\n meter: meterSchema,\n amount: z.number().int(\"must be an integer\").positive(\"must be a positive integer\"),\n renewal: z.enum([\"reset\", \"accumulate\"]),\n expiresAfterDays: z.number().int(\"must be an integer\").positive(\"must be a positive integer\").optional(),\n});\n\nexport const deliverySchema = z.discriminatedUnion(\"method\", [\n z.strictObject({ method: z.literal(\"none\") }),\n z.strictObject({\n method: z.literal(\"redirect\"),\n url: z\n .string()\n .url(\"must be an absolute URL\")\n .refine((value) => value.startsWith(\"https://\"), \"must be an https:// URL\"),\n }),\n z.strictObject({ method: z.literal(\"instructions\"), instructions: z.string().trim().min(1, \"must not be empty\").max(10_000) }),\n]);\n\nexport const checkoutSchema = z.strictObject({\n layoutMode: z.enum([\"two_step\", \"one_step\"]).optional(),\n paymentStyle: z.enum([\"classic\", \"express\"]).optional(),\n providerMode: z.enum([\"inherit\", \"stripe\", \"paypal\", \"both\"]).optional(),\n contactFields: z.strictObject({ name: z.boolean().optional(), phone: z.boolean().optional() }).optional(),\n});\n\nexport const themeSchema = z.strictObject({\n primaryColor: z.string().regex(HEX_COLOR_PATTERN, \"must be a hex color such as #5F34CC\").optional(),\n buttonRadius: z.enum([\"sm\", \"md\", \"lg\"]).optional(),\n accentMode: z.enum([\"light\", \"dark\", \"system\"]).optional(),\n});\n\nexport const stripeSchema = z.strictObject({\n priceId: z.string().trim().min(1, \"must be a Stripe price id (price_…)\"),\n});\n\nexport const productInputSchema = z.strictObject({\n key: keySchema,\n name: z.string().trim().min(1, \"must not be empty\").max(120),\n description: z.string().max(5_000).optional(),\n price: moneySchema,\n billing: billingSchema,\n group: groupSchema.optional(),\n credits: z.array(creditGrantSchema).optional(),\n delivery: deliverySchema.optional(),\n checkout: checkoutSchema.optional(),\n theme: themeSchema.optional(),\n slug: z.string().regex(SLUG_PATTERN, \"must be 3-64 characters of lowercase letters, digits, or '-'\").optional(),\n stripe: stripeSchema.optional(),\n active: z.boolean().optional(),\n});\n\nexport const configSchema = z\n .strictObject({\n products: z.array(productInputSchema),\n })\n .superRefine((config, ctx) => {\n const seenKeys = new Map<string, number>();\n config.products.forEach((product, index) => {\n const firstIndex = seenKeys.get(product.key);\n if (firstIndex !== undefined) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"products\", index, \"key\"],\n message: `duplicate product key \"${product.key}\" (also used by products[${firstIndex}])`,\n });\n } else {\n seenKeys.set(product.key, index);\n }\n const seenMeters = new Map<string, number>();\n product.credits?.forEach((grant, grantIndex) => {\n const firstMeter = seenMeters.get(grant.meter);\n if (firstMeter !== undefined) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"products\", index, \"credits\", grantIndex, \"meter\"],\n message: `duplicate credit meter \"${grant.meter}\" (also used by credits[${firstMeter}])`,\n });\n } else {\n seenMeters.set(grant.meter, grantIndex);\n }\n });\n });\n });\n\nexport interface ConfigIssue {\n /** Dotted path such as `products[0].price.amount`. */\n path: string;\n message: string;\n}\n\nexport class ConfigValidationError extends Error {\n override readonly name = \"ConfigValidationError\";\n readonly issues: ConfigIssue[];\n\n constructor(issues: ConfigIssue[]) {\n super(formatIssues(issues));\n this.issues = issues;\n }\n}\n\nexport function formatIssuePath(path: ReadonlyArray<PropertyKey>): string {\n let out = \"\";\n for (const segment of path) {\n if (typeof segment === \"number\") out += `[${segment}]`;\n else out += out ? `.${String(segment)}` : String(segment);\n }\n return out || \"(root)\";\n}\n\nfunction formatIssues(issues: ConfigIssue[]): string {\n const lines = issues.map((issue) => ` - ${issue.path}: ${issue.message}`);\n return `Invalid Purpleturret config (${issues.length} issue${issues.length === 1 ? \"\" : \"s\"}):\\n${lines.join(\"\\n\")}`;\n}\n\n/**\n * Validate an arbitrary value as a Purpleturret config. Returns the normalized config (currencies\n * lowercased, strings trimmed) or throws `ConfigValidationError` listing every problem found.\n */\nexport function validateConfig(input: unknown): PurpleturretConfig {\n const result = configSchema.safeParse(input);\n if (result.success) return result.data as PurpleturretConfig;\n const issues: ConfigIssue[] = result.error.issues.map((issue) => ({\n path: formatIssuePath(issue.path),\n message: issue.message,\n }));\n throw new ConfigValidationError(issues);\n}\n\n/** Validate a single product declaration. */\nexport function validateProduct(input: unknown): ProductInput {\n const result = productInputSchema.safeParse(input);\n if (result.success) return result.data as ProductInput;\n throw new ConfigValidationError(result.error.issues.map((issue) => ({ path: formatIssuePath(issue.path), message: issue.message })));\n}\n","export interface PurpleturretApiErrorInit {\n status: number;\n code: string;\n message: string;\n requestId?: string | null;\n details?: unknown;\n retryAfter?: number | null;\n}\n\n/** A non-2xx response from the Purpleturret API. */\nexport class PurpleturretApiError extends Error {\n override readonly name = \"PurpleturretApiError\";\n readonly status: number;\n readonly code: string;\n readonly requestId: string | null;\n readonly details: unknown;\n /** Seconds to wait before retrying, from `Retry-After` (or `reset_at` on legacy envelopes). */\n readonly retryAfter: number | null;\n\n constructor(init: PurpleturretApiErrorInit) {\n super(init.message);\n this.status = init.status;\n this.code = init.code;\n this.requestId = init.requestId ?? null;\n this.details = init.details;\n this.retryAfter = init.retryAfter ?? null;\n }\n\n /**\n * Build an error from a response body. Accepts the structured envelope\n * `{ error: { code, message, request_id, details } }` as well as the legacy entitlements envelope\n * `{ error: \"code\", ...extra }`.\n */\n static fromResponse(status: number, body: unknown, retryAfterHeader?: string | null): PurpleturretApiError {\n const retryAfter = parseRetryAfter(retryAfterHeader);\n const record = body && typeof body === \"object\" && !Array.isArray(body) ? (body as Record<string, unknown>) : null;\n const envelope = record?.error;\n\n if (envelope && typeof envelope === \"object\") {\n const err = envelope as Record<string, unknown>;\n const code = typeof err.code === \"string\" && err.code ? err.code : `http_${status}`;\n const message = typeof err.message === \"string\" && err.message ? err.message : defaultMessage(status, code);\n const requestId = typeof err.request_id === \"string\" ? err.request_id : typeof err.requestId === \"string\" ? err.requestId : null;\n return new PurpleturretApiError({ status, code, message, requestId, details: err.details, retryAfter });\n }\n\n if (typeof envelope === \"string\" && record) {\n const { error: _code, message: rawMessage, request_id: requestId, ...rest } = record;\n const code = envelope || `http_${status}`;\n const message = typeof rawMessage === \"string\" && rawMessage ? rawMessage : defaultMessage(status, code);\n const resetAt = typeof rest.reset_at === \"number\" ? rest.reset_at : null;\n const legacyRetryAfter = retryAfter ?? (resetAt !== null ? Math.max(1, Math.ceil((resetAt - Date.now()) / 1000)) : null);\n return new PurpleturretApiError({\n status,\n code,\n message,\n requestId: typeof requestId === \"string\" ? requestId : null,\n details: Object.keys(rest).length > 0 ? rest : undefined,\n retryAfter: legacyRetryAfter,\n });\n }\n\n const text = typeof body === \"string\" ? body.trim().slice(0, 300) : \"\";\n return new PurpleturretApiError({\n status,\n code: `http_${status}`,\n message: text || defaultMessage(status, `http_${status}`),\n details: record ?? undefined,\n retryAfter,\n });\n }\n}\n\n/** The request never produced an HTTP response (DNS, connection refused, timeout, aborted). */\nexport class PurpleturretNetworkError extends Error {\n override readonly name = \"PurpleturretNetworkError\";\n readonly url: string;\n readonly timedOut: boolean;\n override readonly cause: unknown;\n\n constructor(url: string, cause: unknown, timedOut: boolean) {\n super(timedOut ? `Request to ${url} timed out` : `Request to ${url} failed: ${describeCause(cause)}`);\n this.url = url;\n this.cause = cause;\n this.timedOut = timedOut;\n }\n}\n\nexport function isTimeoutError(cause: unknown): boolean {\n return Boolean(cause && typeof cause === \"object\" && \"name\" in cause && (cause as { name?: unknown }).name === \"TimeoutError\");\n}\n\nfunction describeCause(cause: unknown): string {\n if (cause && typeof cause === \"object\") {\n const inner = (cause as { cause?: unknown }).cause;\n if (inner && typeof inner === \"object\" && \"message\" in inner && typeof (inner as { message?: unknown }).message === \"string\") {\n const code = (inner as { code?: unknown }).code;\n return typeof code === \"string\" ? `${code} (${(inner as { message: string }).message})` : (inner as { message: string }).message;\n }\n if (\"message\" in cause && typeof (cause as { message?: unknown }).message === \"string\") return (cause as { message: string }).message;\n }\n return String(cause);\n}\n\nfunction defaultMessage(status: number, code: string): string {\n switch (status) {\n case 401:\n return \"The API key was rejected\";\n case 403:\n return \"The API key is not allowed to perform this operation\";\n case 404:\n return \"The requested resource was not found\";\n case 409:\n return \"The request conflicts with the current state\";\n case 422:\n return \"The request was rejected as invalid\";\n case 429:\n return \"Too many requests; slow down and retry\";\n default:\n return status >= 500 ? `The Purpleturret API returned ${status}` : `Request failed with ${code}`;\n }\n}\n\nexport function parseRetryAfter(header: string | null | undefined): number | null {\n if (!header) return null;\n const trimmed = header.trim();\n if (/^\\d+$/.test(trimmed)) return Number(trimmed);\n const when = Date.parse(trimmed);\n if (Number.isNaN(when)) return null;\n return Math.max(0, Math.ceil((when - Date.now()) / 1000));\n}\n","import type {\n Account,\n Billing,\n CheckoutSettings,\n ConfigGetResult,\n ConfigPushResult,\n CreditAdjustResult,\n CreditBalancesResult,\n CreditConsumeResult,\n CreditGrant,\n CustomerRef,\n Delivery,\n Entitlement,\n LedgerEntry,\n Page,\n PlanAction,\n PlanItem,\n Product,\n ProductGroup,\n ProductInput,\n ProductTheme,\n StripeSettings,\n Tier,\n} from \"../types.js\";\n\n/*\n * Wire (snake_case) shapes as sent and received by the REST API.\n */\n\nexport interface WireMoney {\n amount: number;\n currency: string;\n}\n\nexport type WireBilling = { type: \"one_time\" } | { type: \"recurring\"; interval: \"month\" | \"year\" };\n\nexport interface WireTier {\n key: string;\n name: string;\n rank: number;\n}\n\nexport interface WireGroup {\n key: string;\n tier?: WireTier | null;\n}\n\nexport interface WireCreditGrant {\n meter: string;\n amount: number;\n renewal: \"reset\" | \"accumulate\";\n expires_after_days?: number | null;\n}\n\nexport type WireDelivery = { method: \"none\" } | { method: \"redirect\"; url: string } | { method: \"instructions\"; instructions: string };\n\nexport interface WireCheckout {\n layout_mode?: \"two_step\" | \"one_step\" | null;\n payment_style?: \"classic\" | \"express\" | null;\n provider_mode?: \"inherit\" | \"stripe\" | \"paypal\" | \"both\" | null;\n contact_fields?: { name?: boolean | null; phone?: boolean | null } | null;\n}\n\nexport interface WireTheme {\n primary_color?: string | null;\n button_radius?: \"sm\" | \"md\" | \"lg\" | null;\n accent_mode?: \"light\" | \"dark\" | \"system\" | null;\n}\n\nexport interface WireStripe {\n price_id: string;\n}\n\nexport interface WireProductInput {\n key: string;\n name: string;\n description?: string | null;\n price: WireMoney;\n billing: WireBilling;\n group?: WireGroup | null;\n credits?: WireCreditGrant[] | null;\n delivery?: WireDelivery | null;\n checkout?: WireCheckout | null;\n theme?: WireTheme | null;\n slug?: string | null;\n stripe?: WireStripe | null;\n active?: boolean;\n}\n\nexport interface WireProduct extends Omit<WireProductInput, \"key\" | \"slug\" | \"active\"> {\n key: string | null;\n id: string;\n slug: string | null;\n url: string | null;\n active: boolean;\n archived_at: number | null;\n created_at: number;\n updated_at: number;\n}\n\nexport interface WirePlanChange {\n path: string;\n from: unknown;\n to: unknown;\n note?: string | null;\n}\n\nexport interface WirePlanItem {\n key: string;\n action: PlanAction;\n changes?: WirePlanChange[] | null;\n product?: WireProduct | null;\n error?: { code?: string; message?: string } | string | null;\n}\n\nexport interface WireConfigPushResult {\n applied: boolean;\n summary: { create: number; update: number; unchanged: number; archive: number; conflict: number; error: number };\n results: WirePlanItem[];\n}\n\nexport interface WireConfigGetResult {\n products: WireProduct[];\n unmanaged_count: number;\n}\n\nexport interface WireAccount {\n id: string;\n email: string;\n name?: string | null;\n stripe: { connected: boolean; charges_enabled: boolean };\n paypal: { connected: boolean };\n key: { prefix: string; name?: string | null; scopes: string[] };\n}\n\nexport interface WirePage<T> {\n data: T[];\n next_cursor?: string | null;\n}\n\nexport interface WireCustomerRef {\n email?: string | null;\n external_id?: string | null;\n}\n\nexport interface WireCreditBalance {\n meter: string;\n balance: number;\n expires_at?: number | null;\n lifetime_granted: number;\n lifetime_consumed: number;\n}\n\nexport interface WireCreditBalancesResult {\n customer: WireCustomerRef;\n balances: WireCreditBalance[];\n}\n\nexport interface WireCreditConsumeResult {\n meter: string;\n balance: number;\n consumed: number;\n replayed: boolean;\n}\n\nexport interface WireCreditAdjustResult {\n meter: string;\n balance: number;\n}\n\nexport type WireLedgerEntry = Record<string, unknown>;\n\nexport type WireEntitlement = Record<string, unknown>;\n\n/*\n * Mappers.\n */\n\nfunction omitUndefined<T extends object>(value: T): T {\n const out: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {\n if (entry !== undefined) out[key] = entry;\n }\n return out as T;\n}\n\nexport function toWireProduct(input: ProductInput): WireProductInput {\n const wire: WireProductInput = {\n key: input.key,\n name: input.name,\n description: input.description,\n price: { amount: input.price.amount, currency: input.price.currency },\n billing: input.billing.type === \"recurring\" ? { type: \"recurring\", interval: input.billing.interval } : { type: \"one_time\" },\n group: input.group ? toWireGroup(input.group) : undefined,\n credits: input.credits?.map(toWireCreditGrant),\n delivery: input.delivery ? toWireDelivery(input.delivery) : undefined,\n checkout: input.checkout ? toWireCheckout(input.checkout) : undefined,\n theme: input.theme ? toWireTheme(input.theme) : undefined,\n slug: input.slug,\n stripe: input.stripe ? { price_id: input.stripe.priceId } : undefined,\n active: input.active,\n };\n return omitUndefined(wire);\n}\n\nfunction toWireGroup(group: ProductGroup): WireGroup {\n return omitUndefined({ key: group.key, tier: group.tier ? { key: group.tier.key, name: group.tier.name, rank: group.tier.rank } : undefined });\n}\n\nfunction toWireCreditGrant(grant: CreditGrant): WireCreditGrant {\n return omitUndefined({ meter: grant.meter, amount: grant.amount, renewal: grant.renewal, expires_after_days: grant.expiresAfterDays });\n}\n\nfunction toWireDelivery(delivery: Delivery): WireDelivery {\n switch (delivery.method) {\n case \"none\":\n return { method: \"none\" };\n case \"redirect\":\n return { method: \"redirect\", url: delivery.url };\n case \"instructions\":\n return { method: \"instructions\", instructions: delivery.instructions };\n }\n}\n\nfunction toWireCheckout(checkout: CheckoutSettings): WireCheckout {\n return omitUndefined({\n layout_mode: checkout.layoutMode,\n payment_style: checkout.paymentStyle,\n provider_mode: checkout.providerMode,\n contact_fields: checkout.contactFields ? omitUndefined({ name: checkout.contactFields.name, phone: checkout.contactFields.phone }) : undefined,\n });\n}\n\nfunction toWireTheme(theme: ProductTheme): WireTheme {\n return omitUndefined({ primary_color: theme.primaryColor, button_radius: theme.buttonRadius, accent_mode: theme.accentMode });\n}\n\nexport function fromWireProduct(wire: WireProduct): Product {\n const product: Product = {\n key: wire.key ?? null,\n id: wire.id,\n slug: wire.slug ?? null,\n url: wire.url ?? null,\n name: wire.name,\n description: wire.description ?? undefined,\n price: { amount: wire.price.amount, currency: wire.price.currency },\n billing: fromWireBilling(wire.billing),\n group: wire.group ? fromWireGroup(wire.group) : undefined,\n credits: wire.credits ? wire.credits.map(fromWireCreditGrant) : undefined,\n delivery: wire.delivery ?? undefined,\n checkout: wire.checkout ? fromWireCheckout(wire.checkout) : undefined,\n theme: wire.theme ? fromWireTheme(wire.theme) : undefined,\n stripe: wire.stripe ? fromWireStripe(wire.stripe) : undefined,\n active: wire.active,\n archivedAt: wire.archived_at ?? null,\n createdAt: wire.created_at,\n updatedAt: wire.updated_at,\n };\n return omitUndefined(product);\n}\n\nfunction fromWireBilling(billing: WireBilling): Billing {\n return billing.type === \"recurring\" ? { type: \"recurring\", interval: billing.interval } : { type: \"one_time\" };\n}\n\nfunction fromWireGroup(group: WireGroup): ProductGroup {\n const tier: Tier | undefined = group.tier ? { key: group.tier.key, name: group.tier.name, rank: group.tier.rank } : undefined;\n return omitUndefined({ key: group.key, tier });\n}\n\nfunction fromWireCreditGrant(grant: WireCreditGrant): CreditGrant {\n return omitUndefined({\n meter: grant.meter,\n amount: grant.amount,\n renewal: grant.renewal,\n expiresAfterDays: grant.expires_after_days ?? undefined,\n });\n}\n\nfunction fromWireCheckout(checkout: WireCheckout): CheckoutSettings {\n return omitUndefined({\n layoutMode: checkout.layout_mode ?? undefined,\n paymentStyle: checkout.payment_style ?? undefined,\n providerMode: checkout.provider_mode ?? undefined,\n contactFields: checkout.contact_fields\n ? omitUndefined({ name: checkout.contact_fields.name ?? undefined, phone: checkout.contact_fields.phone ?? undefined })\n : undefined,\n });\n}\n\nfunction fromWireTheme(theme: WireTheme): ProductTheme {\n return omitUndefined({\n primaryColor: theme.primary_color ?? undefined,\n buttonRadius: theme.button_radius ?? undefined,\n accentMode: theme.accent_mode ?? undefined,\n });\n}\n\nfunction fromWireStripe(stripe: WireStripe): StripeSettings {\n return { priceId: stripe.price_id };\n}\n\n/** Strip server-only fields from a fetched product so it can be re-declared in a config file. */\nexport function productToInput(product: Product): ProductInput | null {\n if (!product.key) return null;\n return omitUndefined({\n key: product.key,\n name: product.name,\n description: product.description,\n price: product.price,\n billing: product.billing,\n group: product.group,\n credits: product.credits,\n delivery: product.delivery,\n checkout: product.checkout,\n theme: product.theme,\n slug: product.slug ?? undefined,\n stripe: product.stripe,\n active: product.active,\n });\n}\n\nexport function fromWirePlanItem(item: WirePlanItem): PlanItem {\n let error: PlanItem[\"error\"];\n if (typeof item.error === \"string\") error = { code: item.error, message: item.error };\n else if (item.error && typeof item.error === \"object\") {\n error = { code: item.error.code ?? \"error\", message: item.error.message ?? item.error.code ?? \"Unknown error\" };\n }\n return omitUndefined({\n key: item.key,\n action: item.action,\n changes: (item.changes ?? []).map((change) =>\n omitUndefined({ path: change.path, from: change.from, to: change.to, note: change.note ?? undefined }),\n ),\n product: item.product ? fromWireProduct(item.product) : undefined,\n error,\n });\n}\n\nexport function fromWireConfigPushResult(wire: WireConfigPushResult): ConfigPushResult {\n return {\n applied: Boolean(wire.applied),\n summary: {\n create: wire.summary?.create ?? 0,\n update: wire.summary?.update ?? 0,\n unchanged: wire.summary?.unchanged ?? 0,\n archive: wire.summary?.archive ?? 0,\n conflict: wire.summary?.conflict ?? 0,\n error: wire.summary?.error ?? 0,\n },\n results: (wire.results ?? []).map(fromWirePlanItem),\n };\n}\n\nexport function fromWireConfigGetResult(wire: WireConfigGetResult): ConfigGetResult {\n return { products: (wire.products ?? []).map(fromWireProduct), unmanagedCount: wire.unmanaged_count ?? 0 };\n}\n\nexport function fromWireAccount(wire: WireAccount): Account {\n return {\n id: wire.id,\n email: wire.email,\n name: wire.name ?? null,\n stripe: { connected: Boolean(wire.stripe?.connected), chargesEnabled: Boolean(wire.stripe?.charges_enabled) },\n paypal: { connected: Boolean(wire.paypal?.connected) },\n key: { prefix: wire.key?.prefix ?? \"\", name: wire.key?.name ?? null, scopes: wire.key?.scopes ?? [] },\n };\n}\n\nexport function fromWirePage<W, T>(wire: WirePage<W>, map: (item: W) => T): Page<T> {\n return { data: (wire.data ?? []).map(map), nextCursor: wire.next_cursor ?? null };\n}\n\nfunction fromWireCustomerRef(ref: WireCustomerRef | null | undefined): CustomerRef {\n return { email: ref?.email ?? null, externalId: ref?.external_id ?? null };\n}\n\nexport function fromWireCreditBalances(wire: WireCreditBalancesResult): CreditBalancesResult {\n return {\n customer: fromWireCustomerRef(wire.customer),\n balances: (wire.balances ?? []).map((balance) => ({\n meter: balance.meter,\n balance: balance.balance,\n expiresAt: balance.expires_at ?? null,\n lifetimeGranted: balance.lifetime_granted ?? 0,\n lifetimeConsumed: balance.lifetime_consumed ?? 0,\n })),\n };\n}\n\nexport function fromWireCreditConsume(wire: WireCreditConsumeResult): CreditConsumeResult {\n return { meter: wire.meter, balance: wire.balance, consumed: wire.consumed, replayed: Boolean(wire.replayed) };\n}\n\nexport function fromWireCreditAdjust(wire: WireCreditAdjustResult): CreditAdjustResult {\n return { meter: wire.meter, balance: wire.balance };\n}\n\n/** snake_case → camelCase for a single key. */\nexport function camelCaseKey(key: string): string {\n return key.replace(/_([a-z0-9])/g, (_, char: string) => char.toUpperCase());\n}\n\n/** Deeply convert object keys to camelCase. Values are left untouched. */\nexport function camelizeKeys(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(camelizeKeys);\n if (value && typeof value === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value as Record<string, unknown>)) out[camelCaseKey(key)] = camelizeKeys(entry);\n return out;\n }\n return value;\n}\n\nexport function fromWireLedgerEntry(wire: WireLedgerEntry): LedgerEntry {\n const entry = camelizeKeys(wire) as Record<string, unknown>;\n return {\n ...entry,\n id: String(entry.id ?? \"\"),\n kind: entry.kind as LedgerEntry[\"kind\"],\n meter: String(entry.meter ?? \"\"),\n amount: Number(entry.amount ?? 0),\n balanceAfter: Number(entry.balanceAfter ?? 0),\n note: (entry.note as string | null | undefined) ?? null,\n createdAt: Number(entry.createdAt ?? 0),\n };\n}\n\nexport function fromWireEntitlement(wire: WireEntitlement): Entitlement {\n const { credits, ...rest } = wire;\n const base = camelizeKeys(rest) as Record<string, unknown>;\n const entitlement: Entitlement = {\n ...(base as Partial<Entitlement>),\n hasAccess: Boolean(base.hasAccess),\n status: String(base.status ?? \"none\"),\n };\n if (credits && typeof credits === \"object\") {\n // Meter names are user-defined keys; keep them verbatim and only camelize the values.\n entitlement.credits = Object.fromEntries(\n Object.entries(credits as Record<string, Record<string, unknown>>).map(([meter, value]) => [\n meter,\n { balance: Number(value?.balance ?? 0), expiresAt: (value?.expires_at as number | null | undefined) ?? null },\n ]),\n );\n }\n return entitlement;\n}\n","import type {\n Account,\n ConfigGetResult,\n ConfigPushResult,\n CreditAdjustResult,\n CreditBalancesResult,\n CreditConsumeResult,\n CustomerSelector,\n Entitlement,\n LedgerEntry,\n Page,\n Product,\n ProductInput,\n} from \"../types.js\";\nimport { SDK_VERSION } from \"../version.js\";\nimport { PurpleturretApiError, PurpleturretNetworkError, isTimeoutError } from \"./errors.js\";\nimport {\n fromWireAccount,\n fromWireConfigGetResult,\n fromWireConfigPushResult,\n fromWireCreditAdjust,\n fromWireCreditBalances,\n fromWireCreditConsume,\n fromWireEntitlement,\n fromWireLedgerEntry,\n fromWirePage,\n fromWireProduct,\n toWireProduct,\n type WireAccount,\n type WireConfigGetResult,\n type WireConfigPushResult,\n type WireCreditAdjustResult,\n type WireCreditBalancesResult,\n type WireCreditConsumeResult,\n type WireEntitlement,\n type WireLedgerEntry,\n type WirePage,\n type WireProduct,\n} from \"./wire.js\";\n\nexport const DEFAULT_BASE_URL = \"https://api.purpleturret.com\";\nexport const DEFAULT_TIMEOUT_MS = 30_000;\n\nexport interface PurpleturretClientOptions {\n /** Seller API key (`pt_sk_…`). */\n apiKey: string;\n /** API origin without `/v1`. Defaults to `https://api.purpleturret.com`; local dev uses `http://localhost:3001/api`. */\n baseUrl?: string;\n /** Custom fetch implementation (tests, polyfills). Defaults to `globalThis.fetch`. */\n fetch?: typeof fetch;\n /** Per-request timeout. Defaults to 30 s. */\n timeoutMs?: number;\n /** Extra `User-Agent` value; the SDK version is appended. */\n userAgent?: string;\n}\n\nexport interface ConfigPushOptions {\n products: ProductInput[];\n /** Archive keyed products that are missing from `products`. */\n prune?: boolean;\n /** Compute the plan without applying it. */\n dryRun?: boolean;\n /** Sent as `Idempotency-Key`; reuse it when retrying a failed apply. */\n idempotencyKey?: string;\n}\n\nexport interface ProductListOptions {\n cursor?: string;\n limit?: number;\n includeArchived?: boolean;\n}\n\nexport type CreditBalancesOptions = CustomerSelector & { meter?: string };\n\nexport type CreditConsumeOptions = CustomerSelector & {\n meter: string;\n amount: number;\n /** Required. Reusing a key replays the original result instead of consuming twice. */\n idempotencyKey: string;\n note?: string;\n};\n\nexport type CreditAdjustOptions = CustomerSelector & {\n meter: string;\n /** Signed amount: positive grants, negative removes. */\n amount: number;\n idempotencyKey?: string;\n note?: string;\n};\n\nexport type CreditLedgerOptions = CustomerSelector & { cursor?: string; limit?: number };\n\nexport type EntitlementOptions = CustomerSelector & { groupKey: string };\n\ninterface RequestOptions {\n query?: Record<string, string | number | boolean | undefined>;\n body?: unknown;\n idempotencyKey?: string;\n /** Statuses (besides 2xx) whose bodies are returned instead of thrown. */\n acceptStatuses?: number[];\n}\n\nexport class PurpleturretClient {\n readonly baseUrl: string;\n readonly timeoutMs: number;\n private readonly apiKey: string;\n private readonly fetchImpl: typeof fetch;\n private readonly userAgent: string;\n\n constructor(options: PurpleturretClientOptions) {\n if (!options || typeof options.apiKey !== \"string\" || !options.apiKey.trim()) {\n throw new TypeError(\"PurpleturretClient: apiKey is required\");\n }\n this.apiKey = options.apiKey.trim();\n this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).trim().replace(/\\/+$/, \"\");\n this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (typeof fetchImpl !== \"function\") throw new TypeError(\"PurpleturretClient: no fetch implementation available; pass options.fetch\");\n this.fetchImpl = fetchImpl;\n const sdkAgent = `purpleturret-sdk/${SDK_VERSION}`;\n this.userAgent = options.userAgent ? `${options.userAgent} ${sdkAgent}` : sdkAgent;\n }\n\n /** Absolute URL for an API path such as `/config`. */\n url(path: string, query?: RequestOptions[\"query\"]): string {\n const normalizedPath = path.startsWith(\"/\") ? path : `/${path}`;\n let url = `${this.baseUrl}/v1${normalizedPath}`;\n if (query) {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined) continue;\n params.set(key, String(value));\n }\n const qs = params.toString();\n if (qs) url += `?${qs}`;\n }\n return url;\n }\n\n readonly account = {\n get: async (): Promise<Account> => fromWireAccount(await this.request<WireAccount>(\"GET\", \"/account\")),\n };\n\n readonly config = {\n get: async (): Promise<ConfigGetResult> => fromWireConfigGetResult(await this.request<WireConfigGetResult>(\"GET\", \"/config\")),\n push: async (options: ConfigPushOptions): Promise<ConfigPushResult> => {\n const body: Record<string, unknown> = { products: options.products.map(toWireProduct) };\n if (options.prune !== undefined) body.prune = options.prune;\n if (options.dryRun !== undefined) body.dry_run = options.dryRun;\n const wire = await this.request<WireConfigPushResult>(\"PUT\", \"/config\", {\n body,\n idempotencyKey: options.idempotencyKey,\n // A conflict returns the full plan with a 409; surface it as a result so callers can render it.\n acceptStatuses: [409],\n });\n return fromWireConfigPushResult(wire);\n },\n };\n\n readonly products = {\n list: async (options: ProductListOptions = {}): Promise<Page<Product>> =>\n fromWirePage(\n await this.request<WirePage<WireProduct>>(\"GET\", \"/products\", {\n query: { cursor: options.cursor, limit: options.limit, include_archived: options.includeArchived },\n }),\n fromWireProduct,\n ),\n get: async (key: string): Promise<Product> => fromWireProduct(await this.request<WireProduct>(\"GET\", `/products/${encodeURIComponent(key)}`)),\n /** Archives the product (never hard-deletes). */\n archive: async (key: string): Promise<Product> =>\n fromWireProduct(await this.request<WireProduct>(\"DELETE\", `/products/${encodeURIComponent(key)}`)),\n };\n\n readonly credits = {\n balances: async (options: CreditBalancesOptions): Promise<CreditBalancesResult> =>\n fromWireCreditBalances(\n await this.request<WireCreditBalancesResult>(\"GET\", \"/credits/balances\", {\n query: { ...customerQuery(options), meter: options.meter },\n }),\n ),\n consume: async (options: CreditConsumeOptions): Promise<CreditConsumeResult> => {\n if (!options.idempotencyKey) throw new TypeError(\"credits.consume: idempotencyKey is required\");\n return fromWireCreditConsume(\n await this.request<WireCreditConsumeResult>(\"POST\", \"/credits/consume\", {\n body: { meter: options.meter, amount: options.amount, ...customerQuery(options), note: options.note },\n idempotencyKey: options.idempotencyKey,\n }),\n );\n },\n adjust: async (options: CreditAdjustOptions): Promise<CreditAdjustResult> =>\n fromWireCreditAdjust(\n await this.request<WireCreditAdjustResult>(\"POST\", \"/credits/adjust\", {\n body: { meter: options.meter, amount: options.amount, ...customerQuery(options), note: options.note },\n idempotencyKey: options.idempotencyKey,\n }),\n ),\n ledger: async (options: CreditLedgerOptions): Promise<Page<LedgerEntry>> =>\n fromWirePage(\n await this.request<WirePage<WireLedgerEntry>>(\"GET\", \"/credits/ledger\", {\n query: { ...customerQuery(options), cursor: options.cursor, limit: options.limit },\n }),\n fromWireLedgerEntry,\n ),\n };\n\n readonly entitlements = {\n /** Resolves with `hasAccess: false` (rather than throwing) when the customer has no subscription. */\n get: async (options: EntitlementOptions): Promise<Entitlement> =>\n fromWireEntitlement(\n await this.request<WireEntitlement>(\"GET\", \"/entitlements\", {\n query: { group_key: options.groupKey, ...customerQuery(options) },\n acceptStatuses: [404],\n }),\n ),\n };\n\n private async request<T>(method: string, path: string, options: RequestOptions = {}): Promise<T> {\n const url = this.url(path, options.query);\n const headers: Record<string, string> = {\n authorization: `Bearer ${this.apiKey}`,\n accept: \"application/json\",\n \"user-agent\": this.userAgent,\n };\n const hasBody = options.body !== undefined;\n if (hasBody) headers[\"content-type\"] = \"application/json\";\n if (options.idempotencyKey) headers[\"idempotency-key\"] = options.idempotencyKey;\n\n let response: Response;\n try {\n response = await this.fetchImpl(url, {\n method,\n headers,\n body: hasBody ? JSON.stringify(stripUndefined(options.body)) : undefined,\n signal: AbortSignal.timeout(this.timeoutMs),\n });\n } catch (cause) {\n throw new PurpleturretNetworkError(url, cause, isTimeoutError(cause));\n }\n\n const text = await response.text();\n let parsed: unknown = undefined;\n if (text) {\n try {\n parsed = JSON.parse(text);\n } catch {\n parsed = undefined;\n }\n }\n\n const accepted = response.ok || (options.acceptStatuses?.includes(response.status) ?? false);\n if (!accepted) {\n throw PurpleturretApiError.fromResponse(response.status, parsed ?? text, response.headers.get(\"retry-after\"));\n }\n if (!response.ok && parsed && typeof parsed === \"object\" && \"error\" in (parsed as Record<string, unknown>)) {\n const record = parsed as Record<string, unknown>;\n // A 404 entitlement lookup returns `{ has_access: false }` (no error); anything else with an\n // error envelope is still an error even if the status was in acceptStatuses.\n const looksLikePlan = \"results\" in record && \"summary\" in record;\n const looksLikeEntitlement = \"has_access\" in record;\n if (!looksLikePlan && !looksLikeEntitlement) {\n throw PurpleturretApiError.fromResponse(response.status, parsed, response.headers.get(\"retry-after\"));\n }\n }\n if (response.status === 204 || parsed === undefined) return undefined as T;\n return parsed as T;\n }\n}\n\nfunction customerQuery(selector: CustomerSelector): { external_id?: string; email?: string } {\n const out: { external_id?: string; email?: string } = {};\n if (selector.externalId) out.external_id = selector.externalId;\n if (selector.email) out.email = selector.email;\n if (!out.external_id && !out.email) throw new TypeError(\"Provide externalId or email to identify the customer\");\n return out;\n}\n\nfunction stripUndefined(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(stripUndefined);\n if (value && typeof value === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {\n if (entry !== undefined) out[key] = stripUndefined(entry);\n }\n return out;\n }\n return value;\n}\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { DEFAULT_BASE_URL, PurpleturretClient } from \"@purpleturret/sdk\";\nimport dotenv from \"dotenv\";\n\nimport { CLI_VERSION } from \"../version.js\";\nimport { CredentialsStore, DEFAULT_PROFILE, credentialsPath, type Profile } from \"./credentials.js\";\nimport { CliError, EXIT, type ErrorContext } from \"./errors.js\";\nimport { Output, createPalette, shouldUseColor } from \"./output.js\";\n\n/** Flags accepted by every command. */\nexport interface GlobalFlags {\n config?: string;\n \"api-url\"?: string;\n apiUrl?: string;\n \"api-key\"?: string;\n apiKey?: string;\n profile?: string;\n json?: boolean;\n color?: boolean;\n verbose?: boolean;\n}\n\nexport const globalArgs = {\n config: { type: \"string\", description: \"Path to purpleturret.config.{ts,mts,js,mjs,json} (default: search up to the git root)\" },\n \"api-url\": { type: \"string\", description: \"API origin (default: PURPLETURRET_API_URL, saved profile, or https://api.purpleturret.com)\" },\n \"api-key\": { type: \"string\", description: \"Seller API key (default: PURPLETURRET_API_KEY, .env.local/.env, or saved profile)\" },\n profile: { type: \"string\", description: 'Credentials profile name (default: \"default\")' },\n json: { type: \"boolean\", description: \"Print machine-readable JSON on stdout\" },\n color: { type: \"boolean\", description: \"Colorize output (disable with --no-color or NO_COLOR)\" },\n verbose: { type: \"boolean\", description: \"Log requests and stack traces to stderr\" },\n} as const;\n\nlet stashedGlobals: GlobalFlags = {};\n\n/** Remember flags parsed on the root command so `pt --json push` works as well as `pt push --json`. */\nexport function stashGlobalFlags(flags: GlobalFlags): void {\n stashedGlobals = { ...flags };\n}\n\nexport function mergeGlobalFlags(flags: GlobalFlags): GlobalFlags {\n const merged: GlobalFlags = { ...stashedGlobals };\n for (const [key, value] of Object.entries(flags)) {\n if (value !== undefined) (merged as Record<string, unknown>)[key] = value;\n }\n return merged;\n}\n\nexport type Source = \"flag\" | \"env\" | \"profile\" | \"default\" | \"none\";\n\nexport interface CliContext extends ErrorContext {\n cwd: string;\n env: NodeJS.ProcessEnv;\n flags: GlobalFlags;\n json: boolean;\n verbose: boolean;\n out: Output;\n profileName: string;\n profile: Profile | null;\n credentials: CredentialsStore;\n apiUrl: string;\n apiUrlSource: \"flag\" | \"env\" | \"profile\" | \"default\";\n apiKey: string | null;\n credentialSource: \"flag\" | \"env\" | \"profile\" | \"none\";\n configPath: string | undefined;\n /** Build an authenticated client, or fail with exit 3 when no key is available. */\n client(): PurpleturretClient;\n /** Build a client for an explicit key (used by `login`). */\n clientFor(apiKey: string): PurpleturretClient;\n}\n\nexport interface CreateContextOptions {\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n stdout?: NodeJS.WritableStream;\n stderr?: NodeJS.WritableStream;\n credentialsFile?: string;\n}\n\nexport function loadDotenv(cwd: string, env: NodeJS.ProcessEnv): string[] {\n const loaded: string[] = [];\n for (const name of [\".env.local\", \".env\"]) {\n const path = join(cwd, name);\n if (!existsSync(path)) continue;\n dotenv.config({ path, override: false, quiet: true, processEnv: env as Record<string, string> });\n loaded.push(path);\n }\n return loaded;\n}\n\nexport async function createContext(rawFlags: GlobalFlags, options: CreateContextOptions = {}): Promise<CliContext> {\n const cwd = options.cwd ?? process.cwd();\n const env = options.env ?? process.env;\n const flags = mergeGlobalFlags(rawFlags);\n const json = Boolean(flags.json);\n const verbose = Boolean(flags.verbose);\n const palette = createPalette(\n shouldUseColor({ flag: flags.color, env, stream: (options.stderr as { isTTY?: boolean } | undefined) ?? process.stderr }),\n );\n const out = new Output({ json, verbose, palette, stdout: options.stdout, stderr: options.stderr });\n\n const loadedEnvFiles = loadDotenv(cwd, env);\n if (loadedEnvFiles.length) out.debug(`loaded ${loadedEnvFiles.join(\", \")}`);\n\n const profileName = flags.profile?.trim() || DEFAULT_PROFILE;\n const credentials = new CredentialsStore(options.credentialsFile ?? credentialsPath(env));\n const profile = await credentials.getProfile(profileName);\n\n const flagKey = (flags[\"api-key\"] ?? flags.apiKey)?.trim();\n const envKey = env.PURPLETURRET_API_KEY?.trim();\n let apiKey: string | null = null;\n let credentialSource: CliContext[\"credentialSource\"] = \"none\";\n if (flagKey) [apiKey, credentialSource] = [flagKey, \"flag\"];\n else if (envKey) [apiKey, credentialSource] = [envKey, \"env\"];\n else if (profile?.apiKey) [apiKey, credentialSource] = [profile.apiKey, \"profile\"];\n\n const flagUrl = (flags[\"api-url\"] ?? flags.apiUrl)?.trim();\n const envUrl = env.PURPLETURRET_API_URL?.trim();\n let apiUrl = DEFAULT_BASE_URL;\n let apiUrlSource: CliContext[\"apiUrlSource\"] = \"default\";\n if (flagUrl) [apiUrl, apiUrlSource] = [flagUrl, \"flag\"];\n else if (envUrl) [apiUrl, apiUrlSource] = [envUrl, \"env\"];\n else if (profile?.apiUrl) [apiUrl, apiUrlSource] = [profile.apiUrl, \"profile\"];\n apiUrl = apiUrl.replace(/\\/+$/, \"\");\n if (!/^https?:\\/\\//.test(apiUrl)) {\n throw new CliError(`Invalid API URL \"${apiUrl}\"; it must start with http:// or https://`, EXIT.USAGE, { code: \"invalid_api_url\" });\n }\n\n let announcedUrl = false;\n const announceUrl = () => {\n if (announcedUrl || apiUrlSource === \"default\") return;\n announcedUrl = true;\n out.info(palette.yellow(`Using API ${apiUrl} (from ${describeSource(apiUrlSource)})`));\n };\n\n const fetchImpl: typeof fetch = async (input, init) => {\n const url = typeof input === \"string\" ? input : input instanceof URL ? input.toString() : input.url;\n out.debug(`${init?.method ?? \"GET\"} ${url}`);\n const started = Date.now();\n const response = await fetch(input, init);\n out.debug(`→ ${response.status} ${response.headers.get(\"x-request-id\") ?? \"\"} (${Date.now() - started}ms)`.trimEnd());\n return response;\n };\n\n const clientFor = (key: string) => {\n announceUrl();\n return new PurpleturretClient({ apiKey: key, baseUrl: apiUrl, fetch: fetchImpl, userAgent: `purpleturret-cli/${CLI_VERSION}` });\n };\n\n const context: CliContext = {\n cwd,\n env,\n flags,\n json,\n verbose,\n out,\n profileName,\n profile,\n credentials,\n apiUrl,\n apiUrlSource,\n apiKey,\n credentialSource,\n configPath: flags.config,\n clientFor,\n client() {\n if (!apiKey) {\n throw new CliError(`No API key found for profile \"${profileName}\".`, EXIT.AUTH, {\n code: \"no_credentials\",\n hint: \"Run `purpleturret login`, pass --api-key, or set PURPLETURRET_API_KEY (also read from .env.local / .env in the current directory).\",\n });\n }\n return clientFor(apiKey);\n },\n };\n return context;\n}\n\nexport function describeSource(source: Source): string {\n switch (source) {\n case \"flag\":\n return \"command-line flag\";\n case \"env\":\n return \"environment\";\n case \"profile\":\n return \"saved profile\";\n case \"default\":\n return \"default\";\n default:\n return \"none\";\n }\n}\n","/** Keep in sync with package.json. */\nexport const CLI_VERSION = \"0.1.0\";\n","import { chmod, mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nexport interface Profile {\n apiKey: string;\n /** Only stored when the key was validated against a non-default API URL. */\n apiUrl?: string;\n email?: string;\n keyPrefix?: string;\n scopes?: string[];\n savedAt: string;\n}\n\nexport interface CredentialsFile {\n version: 1;\n profiles: Record<string, Profile>;\n}\n\nexport const DEFAULT_PROFILE = \"default\";\n\n/** `$XDG_CONFIG_HOME/purpleturret/credentials.json`, defaulting to `~/.config`. */\nexport function credentialsPath(env: NodeJS.ProcessEnv = process.env): string {\n const xdg = env.XDG_CONFIG_HOME?.trim();\n const home = env.HOME?.trim() || homedir();\n const configHome = xdg && xdg.length > 0 ? xdg : join(home, \".config\");\n return join(configHome, \"purpleturret\", \"credentials.json\");\n}\n\nexport class CredentialsStore {\n readonly path: string;\n\n constructor(path: string = credentialsPath()) {\n this.path = path;\n }\n\n async read(): Promise<CredentialsFile> {\n let text: string;\n try {\n text = await readFile(this.path, \"utf8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return { version: 1, profiles: {} };\n throw error;\n }\n try {\n const parsed = JSON.parse(text) as Partial<CredentialsFile>;\n if (!parsed || typeof parsed !== \"object\" || typeof parsed.profiles !== \"object\" || parsed.profiles === null) {\n return { version: 1, profiles: {} };\n }\n return { version: 1, profiles: parsed.profiles as Record<string, Profile> };\n } catch {\n throw new Error(`Credentials file ${this.path} is not valid JSON. Fix or delete it and run \\`purpleturret login\\` again.`);\n }\n }\n\n async write(file: CredentialsFile): Promise<void> {\n await mkdir(dirname(this.path), { recursive: true, mode: 0o700 });\n const tmp = `${this.path}.${process.pid}.tmp`;\n await writeFile(tmp, `${JSON.stringify(file, null, 2)}\\n`, { encoding: \"utf8\", mode: 0o600 });\n await chmod(tmp, 0o600);\n await rename(tmp, this.path);\n }\n\n async getProfile(name: string = DEFAULT_PROFILE): Promise<Profile | null> {\n const file = await this.read();\n return file.profiles[name] ?? null;\n }\n\n async saveProfile(name: string, profile: Profile): Promise<void> {\n const file = await this.read();\n file.profiles[name] = profile;\n await this.write(file);\n }\n\n /** Returns true when a profile was removed. */\n async deleteProfile(name: string): Promise<boolean> {\n const file = await this.read();\n if (!(name in file.profiles)) return false;\n delete file.profiles[name];\n await this.write(file);\n return true;\n }\n}\n","import { ConfigValidationError, PurpleturretApiError, PurpleturretNetworkError } from \"@purpleturret/sdk\";\n\nexport const EXIT = {\n OK: 0,\n ERROR: 1,\n USAGE: 2,\n AUTH: 3,\n CONFLICT: 4,\n ABORTED: 130,\n} as const;\n\nexport type ExitCode = (typeof EXIT)[keyof typeof EXIT];\n\nexport const DASHBOARD_SETTINGS_URL = \"https://purpleturret.com/dashboard/settings\";\n\nexport class CliError extends Error {\n override readonly name = \"CliError\";\n readonly exitCode: ExitCode;\n readonly hint: string | undefined;\n readonly code: string | undefined;\n override readonly cause: unknown;\n\n constructor(message: string, exitCode: ExitCode = EXIT.ERROR, options: { hint?: string; code?: string; cause?: unknown } = {}) {\n super(message);\n this.exitCode = exitCode;\n this.hint = options.hint;\n this.code = options.code;\n this.cause = options.cause;\n }\n}\n\nexport interface ErrorContext {\n apiUrl: string;\n apiUrlSource: \"flag\" | \"env\" | \"profile\" | \"default\";\n credentialSource?: \"flag\" | \"env\" | \"profile\" | \"none\";\n}\n\n/** Map any thrown value to a `CliError` with the exit code and actionable message from the plan. */\nexport function toCliError(error: unknown, ctx: ErrorContext): CliError {\n if (error instanceof CliError) return error;\n\n if (error instanceof ConfigValidationError) {\n return new CliError(error.message, EXIT.USAGE, { code: \"config_invalid\", cause: error });\n }\n\n if (error instanceof PurpleturretNetworkError) {\n const where = ctx.apiUrlSource === \"default\" ? \"\" : ` (from ${describeUrlSource(ctx.apiUrlSource)})`;\n return new CliError(error.message, EXIT.ERROR, {\n code: error.timedOut ? \"timeout\" : \"network_error\",\n hint: `Check that the API URL ${ctx.apiUrl}${where} is reachable, or override it with --api-url / PURPLETURRET_API_URL.`,\n cause: error,\n });\n }\n\n if (error instanceof PurpleturretApiError) return fromApiError(error, ctx);\n\n if (error instanceof Error) return new CliError(error.message, EXIT.ERROR, { cause: error });\n return new CliError(String(error), EXIT.ERROR);\n}\n\nfunction fromApiError(error: PurpleturretApiError, ctx: ErrorContext): CliError {\n const requestId = error.requestId ? ` (request ${error.requestId})` : \"\";\n const detailText = formatDetails(error.details);\n\n if (error.code === \"stripe_not_connected\") {\n return new CliError(`${error.message}${requestId}`, EXIT.ERROR, {\n code: error.code,\n hint: `Connect Stripe first in Dashboard → Settings → Payments: ${DASHBOARD_SETTINGS_URL}`,\n cause: error,\n });\n }\n\n switch (error.status) {\n case 401: {\n const source = ctx.credentialSource;\n const hint =\n source === \"flag\"\n ? \"The key passed with --api-key was rejected. Mint a new seller key in Dashboard → Settings → Developers.\"\n : source === \"env\"\n ? \"PURPLETURRET_API_KEY was rejected. Mint a new seller key in Dashboard → Settings → Developers and update your .env.local.\"\n : \"Run `purpleturret login` to store a valid seller key, or pass --api-key / set PURPLETURRET_API_KEY.\";\n return new CliError(`The API key was rejected (401 ${error.code})${requestId}.`, EXIT.AUTH, { code: error.code, hint, cause: error });\n }\n case 403: {\n if (error.code === \"forbidden_key_type\") {\n return new CliError(`This is a hosting key (pt_host_…), which cannot manage products or credits${requestId}.`, EXIT.AUTH, {\n code: error.code,\n hint: `Use a seller key (pt_sk_…) minted in Dashboard → Settings → Developers: ${DASHBOARD_SETTINGS_URL}`,\n cause: error,\n });\n }\n const required = pickString(error.details, \"required_scope\") ?? pickString(error.details, \"scope\");\n return new CliError(`${error.message} (403 ${error.code})${requestId}.`, EXIT.AUTH, {\n code: error.code,\n hint: required\n ? `The key is missing the ${required} scope. Mint a key with that scope in Dashboard → Settings → Developers: ${DASHBOARD_SETTINGS_URL}`\n : `Mint a seller key with the config:read, config:write, credits:read, credits:write and entitlements:read scopes in Dashboard → Settings → Developers: ${DASHBOARD_SETTINGS_URL}`,\n cause: error,\n });\n }\n case 402:\n return new CliError(`${error.message} (402 ${error.code})${requestId}.${detailText}`, EXIT.ERROR, { code: error.code, cause: error });\n case 404:\n return new CliError(`${error.message} (404 ${error.code})${requestId}.`, EXIT.ERROR, { code: error.code, cause: error });\n case 409: {\n if (error.code === \"immutable_field_changed\") {\n return new CliError(`${error.message} (409 immutable_field_changed)${requestId}.${detailText}`, EXIT.CONFLICT, {\n code: error.code,\n hint: \"price.currency, billing, slug and stripe.priceId are immutable after create. Declare the change under a new product key and archive the old one (push --prune).\",\n cause: error,\n });\n }\n if (error.code === \"idempotency_conflict\") {\n return new CliError(`${error.message} (409 idempotency_conflict)${requestId}.`, EXIT.CONFLICT, {\n code: error.code,\n hint: \"The Idempotency-Key was already used with a different request body. Run push again to generate a fresh key.\",\n cause: error,\n });\n }\n return new CliError(`${error.message} (409 ${error.code})${requestId}.${detailText}`, EXIT.CONFLICT, { code: error.code, cause: error });\n }\n case 422:\n return new CliError(`The API rejected the request (422 ${error.code})${requestId}: ${error.message}${detailText}`, EXIT.USAGE, {\n code: error.code,\n cause: error,\n });\n case 429:\n return new CliError(`Rate limited (429 ${error.code})${requestId}.`, EXIT.ERROR, {\n code: error.code,\n hint: error.retryAfter !== null ? `Retry after ${error.retryAfter}s.` : \"Slow down and retry shortly.\",\n cause: error,\n });\n default:\n if (error.status >= 500) {\n return new CliError(`The Purpleturret API returned ${error.status} ${error.code}${requestId}: ${error.message}`, EXIT.ERROR, {\n code: error.code,\n hint: \"This is a server-side failure. Retry in a moment; if it persists, contact support with the request id.\",\n cause: error,\n });\n }\n return new CliError(`${error.message} (${error.status} ${error.code})${requestId}.${detailText}`, EXIT.ERROR, {\n code: error.code,\n cause: error,\n });\n }\n}\n\nfunction describeUrlSource(source: ErrorContext[\"apiUrlSource\"]): string {\n switch (source) {\n case \"flag\":\n return \"--api-url\";\n case \"env\":\n return \"PURPLETURRET_API_URL\";\n case \"profile\":\n return \"the saved profile\";\n default:\n return \"the default\";\n }\n}\n\nfunction pickString(details: unknown, key: string): string | undefined {\n if (details && typeof details === \"object\" && key in details) {\n const value = (details as Record<string, unknown>)[key];\n return typeof value === \"string\" ? value : undefined;\n }\n return undefined;\n}\n\nexport function formatDetails(details: unknown): string {\n if (details === undefined || details === null) return \"\";\n if (typeof details === \"string\") return `\\n ${details}`;\n if (Array.isArray(details)) {\n if (details.length === 0) return \"\";\n return `\\n${details.map((entry) => ` - ${formatDetailEntry(entry)}`).join(\"\\n\")}`;\n }\n if (typeof details === \"object\") {\n const entries = Object.entries(details as Record<string, unknown>);\n if (entries.length === 0) return \"\";\n if (\"issues\" in (details as Record<string, unknown>) && Array.isArray((details as Record<string, unknown>).issues)) {\n return formatDetails((details as Record<string, unknown>).issues);\n }\n return `\\n${entries.map(([key, value]) => ` ${key}: ${typeof value === \"string\" ? value : JSON.stringify(value)}`).join(\"\\n\")}`;\n }\n return `\\n ${String(details)}`;\n}\n\nfunction formatDetailEntry(entry: unknown): string {\n if (entry && typeof entry === \"object\") {\n const record = entry as Record<string, unknown>;\n const path = typeof record.path === \"string\" ? record.path : Array.isArray(record.path) ? record.path.join(\".\") : undefined;\n const message = typeof record.message === \"string\" ? record.message : JSON.stringify(record);\n return path ? `${path}: ${message}` : message;\n }\n return String(entry);\n}\n","import { createColors } from \"picocolors\";\n\nimport type { CliError } from \"./errors.js\";\n\nexport type Paint = (text: string | number) => string;\n\nexport interface Palette {\n enabled: boolean;\n green: Paint;\n yellow: Paint;\n red: Paint;\n cyan: Paint;\n magenta: Paint;\n dim: Paint;\n bold: Paint;\n}\n\nexport function createPalette(enabled: boolean): Palette {\n const colors = createColors(enabled);\n return {\n enabled,\n green: colors.green,\n yellow: colors.yellow,\n red: colors.red,\n cyan: colors.cyan,\n magenta: colors.magenta,\n dim: colors.dim,\n bold: colors.bold,\n };\n}\n\n/** Color is on only for a TTY, unless `--no-color` or `NO_COLOR` turns it off. */\nexport function shouldUseColor(options: { flag?: boolean; env?: NodeJS.ProcessEnv; stream?: { isTTY?: boolean } } = {}): boolean {\n const env = options.env ?? process.env;\n const stream = options.stream ?? process.stdout;\n if (options.flag === false) return false;\n if (env.NO_COLOR !== undefined && env.NO_COLOR !== \"\") return false;\n if (env.FORCE_COLOR !== undefined && env.FORCE_COLOR !== \"\" && env.FORCE_COLOR !== \"0\") return true;\n return Boolean(stream.isTTY);\n}\n\nexport function isInteractive(): boolean {\n return Boolean(process.stdin.isTTY && process.stdout.isTTY);\n}\n\nexport interface OutputOptions {\n json: boolean;\n verbose: boolean;\n palette: Palette;\n stdout?: NodeJS.WritableStream;\n stderr?: NodeJS.WritableStream;\n}\n\n/** Human messages go to stderr; results (plans, tables, JSON) go to stdout. */\nexport class Output {\n readonly json: boolean;\n readonly verbose: boolean;\n readonly palette: Palette;\n private readonly stdout: NodeJS.WritableStream;\n private readonly stderr: NodeJS.WritableStream;\n\n constructor(options: OutputOptions) {\n this.json = options.json;\n this.verbose = options.verbose;\n this.palette = options.palette;\n this.stdout = options.stdout ?? process.stdout;\n this.stderr = options.stderr ?? process.stderr;\n }\n\n /** Write result lines to stdout (suppressed in --json mode unless `force`). */\n print(text: string, force = false): void {\n if (this.json && !force) return;\n this.stdout.write(`${text}\\n`);\n }\n\n /** Write a JSON document to stdout. */\n printJson(value: unknown): void {\n this.stdout.write(`${JSON.stringify(value, null, 2)}\\n`);\n }\n\n info(text: string): void {\n if (this.json) return;\n this.stderr.write(`${text}\\n`);\n }\n\n success(text: string): void {\n if (this.json) return;\n this.stderr.write(`${this.palette.green(\"✔\")} ${text}\\n`);\n }\n\n warn(text: string): void {\n if (this.json) return;\n this.stderr.write(`${this.palette.yellow(\"!\")} ${text}\\n`);\n }\n\n debug(text: string): void {\n if (!this.verbose) return;\n this.stderr.write(`${this.palette.dim(`[debug] ${text}`)}\\n`);\n }\n\n /** Report a fatal error. In --json mode the error is emitted as JSON on stdout. */\n fail(error: CliError): void {\n if (this.json) {\n this.stdout.write(\n `${JSON.stringify({ error: { code: error.code ?? \"error\", message: error.message, hint: error.hint, exit_code: error.exitCode } })}\\n`,\n );\n return;\n }\n this.stderr.write(`${this.palette.red(\"error:\")} ${error.message}\\n`);\n if (error.hint) this.stderr.write(`${this.palette.dim(\"hint:\")} ${error.hint}\\n`);\n if (this.verbose && error.cause instanceof Error && error.cause.stack) {\n this.stderr.write(`${this.palette.dim(error.cause.stack)}\\n`);\n }\n }\n}\n","import type { ProductInput, PurpleturretConfig } from \"@purpleturret/sdk\";\n\nexport type ConfigFormat = \"ts\" | \"json\";\n\nconst PRODUCT_KEY_ORDER: (keyof ProductInput)[] = [\n \"key\",\n \"name\",\n \"description\",\n \"price\",\n \"billing\",\n \"slug\",\n \"group\",\n \"credits\",\n \"delivery\",\n \"checkout\",\n \"theme\",\n \"stripe\",\n \"active\",\n];\n\nconst IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\n/** Serialize products into a `purpleturret.config.ts` (or `.json`) source string. */\nexport function renderConfigSource(products: ProductInput[], format: ConfigFormat = \"ts\"): string {\n if (format === \"json\") {\n const config: PurpleturretConfig = { products: products.map(orderProductKeys) };\n return `${JSON.stringify(config, null, 2)}\\n`;\n }\n\n const helpers = new Set<string>([\"defineConfig\", \"product\"]);\n const body = products.map((product) => renderProduct(product, helpers, 4)).join(\"\\n\");\n const imports = [\"defineConfig\", \"money\", \"product\", \"usd\"].filter((name) => helpers.has(name));\n const productsBlock = products.length ? `[\\n${body}\\n ]` : \"[]\";\n return [\n `import { ${imports.join(\", \")} } from \"@purpleturret/sdk\";`,\n \"\",\n \"export default defineConfig({\",\n ` products: ${productsBlock},`,\n \"});\",\n \"\",\n ].join(\"\\n\");\n}\n\n/** Starter config written by `purpleturret init`. */\nexport function renderStarterConfig(format: ConfigFormat = \"ts\"): string {\n const example: ProductInput = {\n key: \"pro_monthly\",\n name: \"Pro\",\n description: \"Everything you need to get started.\",\n price: { amount: 2900, currency: \"usd\" },\n billing: { type: \"recurring\", interval: \"month\" },\n group: { key: \"my_app\", tier: { key: \"pro\", name: \"Pro\", rank: 1 } },\n delivery: { method: \"none\" },\n };\n if (format === \"json\") return renderConfigSource([example], \"json\");\n return [\n \"// Purpleturret product catalog. Push with `purpleturret push`; preview with `purpleturret push --dry-run`.\",\n \"// Docs: https://purpleturret.com/docs/cli\",\n renderConfigSource([example], \"ts\"),\n ].join(\"\\n\");\n}\n\nfunction orderProductKeys(product: ProductInput): ProductInput {\n const out: Record<string, unknown> = {};\n for (const key of PRODUCT_KEY_ORDER) {\n if (product[key] !== undefined) out[key] = product[key];\n }\n return out as unknown as ProductInput;\n}\n\nfunction renderProduct(product: ProductInput, helpers: Set<string>, indent: number): string {\n const pad = \" \".repeat(indent);\n const inner = \" \".repeat(indent + 2);\n const lines: string[] = [`${pad}product({`];\n for (const key of PRODUCT_KEY_ORDER) {\n const value = product[key];\n if (value === undefined) continue;\n let rendered: string;\n if (key === \"price\") {\n rendered = renderPrice(product.price, helpers);\n } else {\n rendered = renderValue(value, indent + 2);\n }\n lines.push(`${inner}${key}: ${rendered},`);\n }\n lines.push(`${pad}}),`);\n return lines.join(\"\\n\");\n}\n\nfunction renderPrice(price: ProductInput[\"price\"], helpers: Set<string>): string {\n if (price.currency === \"usd\") {\n helpers.add(\"usd\");\n return `usd(${formatDollars(price.amount)})`;\n }\n helpers.add(\"money\");\n return `money(${price.amount}, ${JSON.stringify(price.currency)})`;\n}\n\nfunction formatDollars(cents: number): string {\n if (cents % 100 === 0) return String(cents / 100);\n return (cents / 100).toFixed(2);\n}\n\nfunction renderKey(key: string): string {\n return IDENTIFIER.test(key) ? key : JSON.stringify(key);\n}\n\nfunction isFlat(value: unknown): boolean {\n if (Array.isArray(value)) return value.every((entry) => entry === null || typeof entry !== \"object\");\n if (value && typeof value === \"object\")\n return Object.values(value as Record<string, unknown>).every((entry) => entry === null || typeof entry !== \"object\");\n return true;\n}\n\nexport function renderValue(value: unknown, indent: number): string {\n if (value === null) return \"null\";\n if (typeof value === \"string\") return JSON.stringify(value);\n if (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n if (typeof value === \"undefined\") return \"undefined\";\n const pad = \" \".repeat(indent);\n const inner = \" \".repeat(indent + 2);\n if (Array.isArray(value)) {\n if (value.length === 0) return \"[]\";\n if (isFlat(value)) {\n const inline = `[${value.map((entry) => renderValue(entry, indent + 2)).join(\", \")}]`;\n if (inline.length + indent <= 100) return inline;\n }\n return `[\\n${value.map((entry) => `${inner}${renderValue(entry, indent + 2)},`).join(\"\\n\")}\\n${pad}]`;\n }\n if (typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>).filter(([, entry]) => entry !== undefined);\n if (entries.length === 0) return \"{}\";\n if (isFlat(value)) {\n const inline = `{ ${entries.map(([key, entry]) => `${renderKey(key)}: ${renderValue(entry, indent + 2)}`).join(\", \")} }`;\n if (inline.length + indent <= 100) return inline;\n }\n return `{\\n${entries.map(([key, entry]) => `${inner}${renderKey(key)}: ${renderValue(entry, indent + 2)},`).join(\"\\n\")}\\n${pad}}`;\n }\n return JSON.stringify(value);\n}\n","import { DEFAULT_BASE_URL } from \"@purpleturret/sdk\";\nimport { isCancel } from \"@clack/prompts\";\nimport type { ArgsDef, CommandContext } from \"citty\";\n\nimport { createContext, type CliContext, type GlobalFlags } from \"./context.js\";\nimport { CliError, EXIT, toCliError } from \"./errors.js\";\nimport { Output, createPalette, shouldUseColor } from \"./output.js\";\n\nexport type Handler<A extends ArgsDef> = (ctx: CliContext, args: CommandContext<A>[\"args\"]) => Promise<void>;\n\n/**\n * Wrap a command body: build the CLI context from the parsed flags, run, and translate any error into\n * a message plus exit code. Errors never escape to citty (which would print a stack and exit 1).\n */\nexport function defineRun<A extends ArgsDef>(handler: Handler<A>) {\n return async (command: CommandContext<A>): Promise<void> => {\n let ctx: CliContext | undefined;\n try {\n ctx = await createContext(command.args as GlobalFlags);\n await handler(ctx, command.args);\n } catch (error) {\n const cliError = toCliError(error, ctx ?? { apiUrl: DEFAULT_BASE_URL, apiUrlSource: \"default\" });\n const out =\n ctx?.out ??\n new Output({\n json: Boolean((command.args as GlobalFlags).json),\n verbose: Boolean((command.args as GlobalFlags).verbose),\n palette: createPalette(shouldUseColor({ flag: (command.args as GlobalFlags).color })),\n });\n out.fail(cliError);\n process.exitCode = cliError.exitCode;\n }\n };\n}\n\n/** Convert a cancelled @clack prompt into an exit-130 error. */\nexport function unwrapPrompt<T>(value: T | symbol): T {\n if (isCancel(value)) throw new CliError(\"Aborted.\", EXIT.ABORTED, { code: \"aborted\" });\n return value as T;\n}\n","import { password } from \"@clack/prompts\";\nimport { defineCommand } from \"citty\";\n\nimport { globalArgs } from \"../lib/context.js\";\nimport { CliError, EXIT } from \"../lib/errors.js\";\nimport { isInteractive } from \"../lib/output.js\";\nimport { defineRun, unwrapPrompt } from \"../lib/run.js\";\n\nexport const login = defineCommand({\n meta: { name: \"login\", description: \"Validate a seller API key and save it to ~/.config/purpleturret/credentials.json\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n let apiKey = ctx.credentialSource === \"flag\" || ctx.credentialSource === \"env\" ? ctx.apiKey : null;\n if (!apiKey) {\n if (!isInteractive()) {\n throw new CliError(\"No API key provided and stdin is not a terminal.\", EXIT.USAGE, {\n code: \"missing_api_key\",\n hint: \"Pass --api-key <pt_sk_…> or set PURPLETURRET_API_KEY when logging in non-interactively.\",\n });\n }\n const entered = unwrapPrompt(\n await password({\n message: \"Paste your seller API key (pt_sk_…). Mint one in Dashboard → Settings → Developers.\",\n validate: (value) => (value && value.trim().length > 0 ? undefined : \"An API key is required\"),\n }),\n );\n apiKey = entered.trim();\n }\n if (apiKey.startsWith(\"pt_host_\")) {\n throw new CliError(\"That is a hosting key (pt_host_…). The CLI needs a seller key (pt_sk_…).\", EXIT.AUTH, { code: \"forbidden_key_type\" });\n }\n\n const client = ctx.clientFor(apiKey);\n const account = await client.account.get();\n const apiUrl = ctx.apiUrlSource === \"default\" ? undefined : ctx.apiUrl;\n await ctx.credentials.saveProfile(ctx.profileName, {\n apiKey,\n apiUrl,\n email: account.email,\n keyPrefix: account.key.prefix,\n scopes: account.key.scopes,\n savedAt: new Date().toISOString(),\n });\n\n if (ctx.json) {\n ctx.out.printJson({ profile: ctx.profileName, credentials_file: ctx.credentials.path, api_url: ctx.apiUrl, account });\n return;\n }\n const { palette } = ctx.out;\n ctx.out.success(\n `Logged in as ${palette.bold(account.email)} with key ${account.key.prefix}… (scopes: ${account.key.scopes.join(\", \") || \"none\"})`,\n );\n ctx.out.info(palette.dim(`Saved profile \"${ctx.profileName}\" to ${ctx.credentials.path} (mode 0600)`));\n if (!account.stripe.connected) ctx.out.warn(\"Stripe is not connected on this account yet; `push` cannot create products until it is.\");\n }),\n});\n","import { defineCommand } from \"citty\";\n\nimport { globalArgs } from \"../lib/context.js\";\nimport { defineRun } from \"../lib/run.js\";\n\nexport const logout = defineCommand({\n meta: { name: \"logout\", description: \"Remove the saved credentials profile\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const removed = await ctx.credentials.deleteProfile(ctx.profileName);\n if (ctx.json) {\n ctx.out.printJson({ profile: ctx.profileName, removed });\n return;\n }\n if (removed) ctx.out.success(`Removed profile \"${ctx.profileName}\" from ${ctx.credentials.path}`);\n else ctx.out.warn(`No profile \"${ctx.profileName}\" in ${ctx.credentials.path}; nothing to do.`);\n }),\n});\n","import { type Product } from \"@purpleturret/sdk\";\nimport { defineCommand } from \"citty\";\n\nimport { globalArgs } from \"../lib/context.js\";\nimport { describeBilling, formatMoney } from \"../lib/render.js\";\nimport { defineRun } from \"../lib/run.js\";\nimport { renderTable } from \"../lib/table.js\";\n\nconst list = defineCommand({\n meta: { name: \"list\", description: \"List products on the account (config-managed and dashboard-only)\" },\n args: {\n ...globalArgs,\n all: { type: \"boolean\", description: \"Include archived products\" },\n },\n run: defineRun(async (ctx, args) => {\n const client = ctx.client();\n const products: Product[] = [];\n let cursor: string | undefined;\n do {\n const page = await client.products.list({ cursor, limit: 100, includeArchived: Boolean(args.all) });\n products.push(...page.data);\n cursor = page.nextCursor ?? undefined;\n } while (cursor);\n\n if (ctx.json) {\n ctx.out.printJson({ products });\n return;\n }\n const { palette } = ctx.out;\n if (products.length === 0) {\n ctx.out.print(palette.dim(\"No products yet. Run `purpleturret init` and `purpleturret push` to create some.\"));\n return;\n }\n const rows = products.map((product) => [\n product.key ?? palette.dim(\"(unmanaged)\"),\n product.name,\n `${formatMoney(product.price)}${describeBilling(product.billing)}`,\n product.archivedAt ? palette.red(\"archived\") : product.active ? \"active\" : palette.yellow(\"inactive\"),\n product.url ?? palette.dim(\"—\"),\n ]);\n for (const line of renderTable([\"KEY\", \"NAME\", \"PRICE\", \"STATUS\", \"URL\"], rows, palette.dim)) ctx.out.print(line);\n }),\n});\n\nexport const products = defineCommand({\n meta: { name: \"products\", description: \"Inspect products on the account\" },\n args: { ...globalArgs },\n subCommands: { list },\n});\n","import type { Billing, ConfigPushResult, Money, PlanAction, PlanItem, PlanSummary, Product } from \"@purpleturret/sdk\";\n\nimport type { Palette } from \"./output.js\";\n\nexport const PRICE_AMOUNT_NOTE = \"new Stripe price; existing subscriptions keep the old price\";\n\nconst ACTION_ORDER: PlanAction[] = [\"conflict\", \"error\", \"create\", \"update\", \"archive\", \"unchanged\"];\n\nconst ACTION_SYMBOL: Record<PlanAction, string> = {\n create: \"+\",\n update: \"~\",\n unchanged: \"=\",\n archive: \"-\",\n conflict: \"!\",\n error: \"x\",\n};\n\nexport function formatMoney(money: Money): string {\n const currency = money.currency.toUpperCase();\n const major = (money.amount / 100).toFixed(2);\n if (currency === \"USD\") return `$${major}`;\n return `${major} ${currency}`;\n}\n\nexport function describeBilling(billing: Billing): string {\n if (billing.type === \"recurring\") return billing.interval === \"year\" ? \"/year\" : \"/month\";\n return \" one-time\";\n}\n\nexport function describeProduct(product: Pick<Product, \"name\" | \"price\" | \"billing\">): string {\n return `${product.name} — ${formatMoney(product.price)}${describeBilling(product.billing)}`;\n}\n\nexport function formatValue(value: unknown): string {\n if (value === undefined || value === null) return \"(none)\";\n if (typeof value === \"string\") return JSON.stringify(value);\n if (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n return JSON.stringify(value);\n}\n\nfunction paintFor(action: PlanAction, palette: Palette) {\n switch (action) {\n case \"create\":\n return palette.green;\n case \"update\":\n return palette.yellow;\n case \"archive\":\n return palette.red;\n case \"conflict\":\n case \"error\":\n return (text: string | number) => palette.bold(palette.red(text));\n default:\n return palette.dim;\n }\n}\n\nexport interface RenderOptions {\n palette: Palette;\n /** `plan` renders a dry-run; `apply` renders the applied result. */\n mode: \"plan\" | \"apply\";\n}\n\n/** Render one plan item (header line plus nested change lines). */\nexport function renderPlanItem(item: PlanItem, options: RenderOptions & { keyWidth?: number }): string[] {\n const { palette } = options;\n const paint = paintFor(item.action, palette);\n const keyWidth = Math.max(options.keyWidth ?? 0, item.key.length);\n const symbol = ACTION_SYMBOL[item.action];\n const label = item.action.padEnd(9);\n const key = item.key.padEnd(keyWidth);\n\n let detail = \"\";\n if (item.action === \"create\" && item.product) detail = describeProduct(item.product);\n else if (item.action === \"unchanged\" && item.product) detail = palette.dim(describeProduct(item.product));\n else if (item.action === \"archive\" && item.product) detail = describeProduct(item.product);\n else if ((item.action === \"conflict\" || item.action === \"error\") && item.error) detail = `${item.error.code}: ${item.error.message}`;\n\n const lines = [`${paint(`${symbol} ${label}`)} ${paint(key)}${detail ? ` ${detail}` : \"\"}`.trimEnd()];\n\n if (item.changes.length === 0) return lines;\n const pathWidth = Math.max(...item.changes.map((change) => change.path.length));\n for (const change of item.changes) {\n const note = change.note ?? (change.path === \"price.amount\" && item.action !== \"create\" ? PRICE_AMOUNT_NOTE : undefined);\n const isNew = change.from === undefined || change.from === null;\n const transition =\n item.action === \"create\" || (isNew && item.action !== \"archive\")\n ? formatValue(change.to)\n : `${formatValue(change.from)} → ${formatValue(change.to)}`;\n const line = ` ${paint(symbol)} ${change.path.padEnd(pathWidth)} ${transition}${note ? ` ${palette.dim(`(${note})`)}` : \"\"}`;\n lines.push(line);\n }\n return lines;\n}\n\n/** Sort conflicts and errors first, then creates/updates/archives, unchanged last. */\nexport function sortPlanItems(items: PlanItem[]): PlanItem[] {\n return [...items].sort((a, b) => {\n const order = ACTION_ORDER.indexOf(a.action) - ACTION_ORDER.indexOf(b.action);\n return order !== 0 ? order : a.key.localeCompare(b.key);\n });\n}\n\nexport function hasChanges(summary: PlanSummary): boolean {\n return summary.create + summary.update + summary.archive + summary.conflict + summary.error > 0;\n}\n\nexport function renderSummary(summary: PlanSummary, options: RenderOptions): string {\n const { palette, mode } = options;\n const parts: string[] = [];\n if (mode === \"plan\") {\n if (summary.create) parts.push(palette.green(`${summary.create} to create`));\n if (summary.update) parts.push(palette.yellow(`${summary.update} to update`));\n if (summary.archive) parts.push(palette.red(`${summary.archive} to archive`));\n if (summary.unchanged) parts.push(palette.dim(`${summary.unchanged} unchanged`));\n if (summary.conflict) parts.push(palette.bold(palette.red(`${summary.conflict} conflict${summary.conflict === 1 ? \"\" : \"s\"}`)));\n if (summary.error) parts.push(palette.bold(palette.red(`${summary.error} error${summary.error === 1 ? \"\" : \"s\"}`)));\n if (!hasChanges(summary))\n return palette.dim(`No changes. ${summary.unchanged} product${summary.unchanged === 1 ? \"\" : \"s\"} already match the config.`);\n return `Plan: ${parts.join(\", \")}.`;\n }\n if (summary.create) parts.push(palette.green(`${summary.create} created`));\n if (summary.update) parts.push(palette.yellow(`${summary.update} updated`));\n if (summary.archive) parts.push(palette.red(`${summary.archive} archived`));\n if (summary.unchanged) parts.push(palette.dim(`${summary.unchanged} unchanged`));\n if (summary.conflict) parts.push(palette.bold(palette.red(`${summary.conflict} conflict${summary.conflict === 1 ? \"\" : \"s\"}`)));\n if (summary.error) parts.push(palette.bold(palette.red(`${summary.error} failed`)));\n const prefix = summary.error || summary.conflict ? \"Apply incomplete\" : \"Apply complete\";\n return `${prefix}: ${parts.length ? parts.join(\", \") : \"nothing to do\"}.`;\n}\n\n/** Full plan/apply rendering: one block per product followed by a summary line. */\nexport function renderPlan(result: ConfigPushResult, options: RenderOptions): string[] {\n const items = sortPlanItems(result.results);\n const keyWidth = items.reduce((width, item) => Math.max(width, item.key.length), 0);\n const lines: string[] = [];\n for (const item of items) {\n lines.push(...renderPlanItem(item, { ...options, keyWidth }));\n }\n if (lines.length) lines.push(\"\");\n lines.push(renderSummary(result.summary, options));\n return lines;\n}\n","/** Render a plain-text table with left-aligned, space-padded columns. */\nexport function renderTable(headers: string[], rows: string[][], dimHeader: (text: string) => string = (text) => text): string[] {\n const widths = headers.map((header, index) => Math.max(header.length, ...rows.map((row) => (row[index] ?? \"\").length)));\n const line = (cells: string[]) =>\n cells\n .map((cell, index) => cell.padEnd(widths[index] ?? 0))\n .join(\" \")\n .trimEnd();\n return [dimHeader(line(headers)), ...rows.map(line)];\n}\n","import { existsSync } from \"node:fs\";\nimport { writeFile } from \"node:fs/promises\";\nimport { relative, resolve } from \"node:path\";\n\nimport { productToInput, type ProductInput } from \"@purpleturret/sdk\";\nimport { defineCommand } from \"citty\";\n\nimport { globalArgs } from \"../lib/context.js\";\nimport { CliError, EXIT } from \"../lib/errors.js\";\nimport { renderConfigSource, type ConfigFormat } from \"../lib/pull-writer.js\";\nimport { defineRun } from \"../lib/run.js\";\n\nexport const pull = defineCommand({\n meta: { name: \"pull\", description: \"Write the account's config-managed products to a local config file\" },\n args: {\n ...globalArgs,\n out: { type: \"string\", description: \"Output file (default: purpleturret.config.ts; a .json extension writes JSON)\" },\n force: { type: \"boolean\", description: \"Overwrite an existing file\" },\n },\n run: defineRun(async (ctx, args) => {\n const { products, unmanagedCount } = await ctx.client().config.get();\n const inputs = products.map(productToInput).filter((input): input is ProductInput => input !== null);\n\n const out = args.out?.trim();\n if (ctx.json && !out) {\n ctx.out.printJson({ products: inputs, unmanaged_count: unmanagedCount, written: null });\n return;\n }\n\n const target = resolve(ctx.cwd, out || \"purpleturret.config.ts\");\n const format: ConfigFormat = target.endsWith(\".json\") ? \"json\" : \"ts\";\n if (existsSync(target) && !args.force) {\n throw new CliError(`${relative(ctx.cwd, target) || target} already exists.`, EXIT.USAGE, {\n code: \"file_exists\",\n hint: \"Pass --force to overwrite it, or --out <path> to write elsewhere.\",\n });\n }\n await writeFile(target, renderConfigSource(inputs, format), \"utf8\");\n\n if (ctx.json) {\n ctx.out.printJson({ products: inputs, unmanaged_count: unmanagedCount, written: target });\n return;\n }\n ctx.out.success(`Wrote ${inputs.length} product${inputs.length === 1 ? \"\" : \"s\"} to ${relative(ctx.cwd, target) || target}`);\n if (unmanagedCount > 0) {\n ctx.out.info(\n ctx.out.palette.dim(\n `${unmanagedCount} dashboard-only product${unmanagedCount === 1 ? \"\" : \"s\"} without a key were skipped (see \\`purpleturret products list\\`).`,\n ),\n );\n }\n }),\n});\n","import { randomUUID } from \"node:crypto\";\nimport { relative } from \"node:path\";\n\nimport { confirm } from \"@clack/prompts\";\nimport { PurpleturretNetworkError, type ConfigPushResult, type ProductInput, type PurpleturretClient } from \"@purpleturret/sdk\";\nimport { defineCommand } from \"citty\";\n\nimport { loadConfig } from \"../lib/config-loader.js\";\nimport { globalArgs, type CliContext } from \"../lib/context.js\";\nimport { CliError, EXIT } from \"../lib/errors.js\";\nimport { isInteractive } from \"../lib/output.js\";\nimport { hasChanges, renderPlan } from \"../lib/render.js\";\nimport { defineRun, unwrapPrompt } from \"../lib/run.js\";\n\nexport const push = defineCommand({\n meta: { name: \"push\", description: \"Plan and apply the local config to your Purpleturret account\" },\n args: {\n ...globalArgs,\n prune: { type: \"boolean\", description: \"Archive config-managed products that are missing from the config\" },\n \"dry-run\": { type: \"boolean\", description: \"Show the plan without applying it\" },\n yes: { type: \"boolean\", alias: \"y\", description: \"Apply without asking for confirmation (required in CI)\" },\n },\n run: defineRun(async (ctx, args) => {\n const prune = Boolean(args.prune);\n const dryRun = Boolean(args[\"dry-run\"]);\n const yes = Boolean(args.yes);\n\n const loaded = await loadConfig(ctx.cwd, ctx.configPath);\n const products = loaded.config.products;\n const { palette } = ctx.out;\n ctx.out.info(\n palette.dim(`Config: ${relative(ctx.cwd, loaded.path) || loaded.path} (${products.length} product${products.length === 1 ? \"\" : \"s\"})`),\n );\n\n const client = ctx.client();\n const plan = await client.config.push({ products, prune, dryRun: true });\n for (const line of renderPlan(plan, { palette, mode: \"plan\" })) ctx.out.print(line);\n\n if (plan.summary.conflict > 0) {\n if (ctx.json) {\n ctx.out.printJson({ plan, applied: false, error: { code: \"conflict\", message: `${plan.summary.conflict} conflict(s); nothing applied` } });\n process.exitCode = EXIT.CONFLICT;\n return;\n }\n throw new CliError(`${plan.summary.conflict} conflict${plan.summary.conflict === 1 ? \"\" : \"s\"}; nothing was applied.`, EXIT.CONFLICT, {\n code: \"conflict\",\n hint: \"price.currency, billing, slug and stripe.priceId are immutable after create. Declare the change under a new product key and archive the old one with --prune.\",\n });\n }\n if (plan.summary.error > 0) {\n if (ctx.json) {\n ctx.out.printJson({ plan, applied: false, error: { code: \"plan_error\", message: `${plan.summary.error} product(s) cannot be applied` } });\n process.exitCode = EXIT.ERROR;\n return;\n }\n throw new CliError(`${plan.summary.error} product${plan.summary.error === 1 ? \"\" : \"s\"} cannot be applied; see the errors above.`, EXIT.ERROR, {\n code: \"plan_error\",\n });\n }\n\n if (!hasChanges(plan.summary)) {\n if (ctx.json) ctx.out.printJson({ plan, applied: false });\n return;\n }\n if (dryRun) {\n if (ctx.json) ctx.out.printJson({ plan, applied: false });\n else ctx.out.info(palette.dim(\"Dry run; nothing was applied. Run `purpleturret push` to apply.\"));\n return;\n }\n\n if (!yes) {\n if (!isInteractive() || ctx.json) {\n throw new CliError(\"Refusing to apply without confirmation because this is not an interactive terminal.\", EXIT.USAGE, {\n code: \"confirmation_required\",\n hint: \"Re-run with --yes to apply non-interactively, or --dry-run to only preview.\",\n });\n }\n const approved = unwrapPrompt(await confirm({ message: \"Apply these changes?\", initialValue: false }));\n if (!approved) throw new CliError(\"Aborted.\", EXIT.ABORTED, { code: \"aborted\" });\n }\n\n const idempotencyKey = `pt-push-${randomUUID()}`;\n ctx.out.debug(`Idempotency-Key ${idempotencyKey}`);\n const result = await applyWithRetry(ctx, client, { products, prune, idempotencyKey });\n\n ctx.out.print(\"\");\n for (const line of renderPlan(result, { palette, mode: \"apply\" })) ctx.out.print(line);\n if (ctx.json) ctx.out.printJson({ plan, result, applied: result.applied });\n\n if (result.summary.conflict > 0) {\n process.exitCode = EXIT.CONFLICT;\n if (!ctx.json)\n ctx.out.fail(new CliError(\"The apply hit a conflict; some products may have been applied.\", EXIT.CONFLICT, { code: \"conflict\" }));\n return;\n }\n if (result.summary.error > 0) {\n process.exitCode = EXIT.ERROR;\n if (!ctx.json) {\n ctx.out.fail(\n new CliError(\n `${result.summary.error} product${result.summary.error === 1 ? \"\" : \"s\"} failed to apply; the rest were applied.`,\n EXIT.ERROR,\n {\n code: \"apply_error\",\n hint: \"Fix the reported errors and run push again; completed steps are skipped.\",\n },\n ),\n );\n }\n return;\n }\n const urls = result.results.filter((item) => item.action === \"create\" && item.product?.url).map((item) => ` ${item.key} ${item.product?.url}`);\n if (urls.length) {\n ctx.out.info(\"\");\n ctx.out.info(palette.dim(\"Checkout links:\"));\n for (const line of urls) ctx.out.info(line);\n }\n }),\n});\n\nasync function applyWithRetry(\n ctx: CliContext,\n client: PurpleturretClient,\n options: { products: ProductInput[]; prune: boolean; idempotencyKey: string },\n): Promise<ConfigPushResult> {\n try {\n return await client.config.push({ products: options.products, prune: options.prune, dryRun: false, idempotencyKey: options.idempotencyKey });\n } catch (error) {\n if (!(error instanceof PurpleturretNetworkError)) throw error;\n ctx.out.warn(`Network error while applying (${error.message}); retrying once with the same Idempotency-Key…`);\n return await client.config.push({ products: options.products, prune: options.prune, dryRun: false, idempotencyKey: options.idempotencyKey });\n }\n}\n","import { existsSync, statSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { dirname, extname, isAbsolute, join, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\nimport { validateConfig, type PurpleturretConfig } from \"@purpleturret/sdk\";\nimport { createJiti } from \"jiti\";\n\nimport { CliError, EXIT } from \"./errors.js\";\n\nexport const CONFIG_FILENAMES = [\n \"purpleturret.config.ts\",\n \"purpleturret.config.mts\",\n \"purpleturret.config.js\",\n \"purpleturret.config.mjs\",\n \"purpleturret.config.json\",\n] as const;\n\nexport interface LoadedConfig {\n path: string;\n config: PurpleturretConfig;\n}\n\n/**\n * Locate the config file. An explicit path is resolved against `cwd` and must exist. Otherwise the\n * standard names are searched in `cwd` and each parent, stopping at the git root (the first\n * directory containing `.git`) or the filesystem root.\n */\nexport function findConfigFile(cwd: string, explicit?: string): string {\n if (explicit) {\n const path = isAbsolute(explicit) ? explicit : resolve(cwd, explicit);\n if (!existsSync(path) || !statSync(path).isFile()) {\n throw new CliError(`Config file not found: ${path}`, EXIT.USAGE, { code: \"config_not_found\" });\n }\n return path;\n }\n\n let dir = resolve(cwd);\n const searched: string[] = [];\n for (;;) {\n searched.push(dir);\n for (const name of CONFIG_FILENAMES) {\n const candidate = join(dir, name);\n if (existsSync(candidate) && statSync(candidate).isFile()) return candidate;\n }\n const isGitRoot = existsSync(join(dir, \".git\"));\n const parent = dirname(dir);\n if (isGitRoot || parent === dir) break;\n dir = parent;\n }\n throw new CliError(`No purpleturret.config.{ts,mts,js,mjs,json} found in ${searched[0]} or its parents up to the git root.`, EXIT.USAGE, {\n code: \"config_not_found\",\n hint: \"Run `purpleturret init` to create one, or pass --config <path>.\",\n });\n}\n\n/** Load and validate a config file. TypeScript/ESM files are transpiled on the fly with jiti. */\nexport async function loadConfigFile(path: string): Promise<LoadedConfig> {\n const raw = await importConfigModule(path);\n const candidate = pickConfigExport(raw, path);\n const config = validateConfig(candidate);\n return { path, config };\n}\n\nexport async function loadConfig(cwd: string, explicit?: string): Promise<LoadedConfig> {\n return loadConfigFile(findConfigFile(cwd, explicit));\n}\n\nasync function importConfigModule(path: string): Promise<unknown> {\n const ext = extname(path).toLowerCase();\n if (ext === \".json\") {\n const text = await readFile(path, \"utf8\");\n try {\n return JSON.parse(text);\n } catch (error) {\n throw new CliError(`${path} is not valid JSON: ${(error as Error).message}`, EXIT.USAGE, { code: \"config_invalid\", cause: error });\n }\n }\n if (![\".ts\", \".mts\", \".js\", \".mjs\", \".cts\", \".cjs\"].includes(ext)) {\n throw new CliError(`Unsupported config file extension \"${ext}\" (${path}). Use .ts, .mts, .js, .mjs or .json.`, EXIT.USAGE, {\n code: \"config_invalid\",\n });\n }\n const jiti = createJiti(import.meta.url, { interopDefault: false, moduleCache: false, fsCache: false });\n try {\n return await jiti.import(pathToFileURL(path).href);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new CliError(`Failed to load ${path}: ${message}`, EXIT.USAGE, { code: \"config_load_failed\", cause: error });\n }\n}\n\nfunction pickConfigExport(raw: unknown, path: string): unknown {\n if (raw && typeof raw === \"object\") {\n const record = raw as Record<string, unknown>;\n if (\"default\" in record && record.default !== undefined) {\n const def = record.default;\n // `export default { default: ... }` interop layering\n if (def && typeof def === \"object\" && !(\"products\" in (def as object)) && \"default\" in (def as Record<string, unknown>)) {\n return (def as Record<string, unknown>).default;\n }\n return def;\n }\n if (\"config\" in record && record.config !== undefined) return record.config;\n if (\"products\" in record) return raw;\n }\n throw new CliError(`${path} must export a config as its default export or a named \\`config\\` export (see \\`purpleturret init\\`).`, EXIT.USAGE, {\n code: \"config_invalid\",\n });\n}\n","import { relative } from \"node:path\";\n\nimport { defineCommand } from \"citty\";\n\nimport { loadConfig } from \"../lib/config-loader.js\";\nimport { describeSource, globalArgs } from \"../lib/context.js\";\nimport { renderSummary, sortPlanItems } from \"../lib/render.js\";\nimport { defineRun } from \"../lib/run.js\";\n\nexport const status = defineCommand({\n meta: { name: \"status\", description: \"Compare the local config with the account (dry run) and print a summary\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const loaded = await loadConfig(ctx.cwd, ctx.configPath);\n const plan = await ctx.client().config.push({ products: loaded.config.products, dryRun: true });\n if (ctx.json) {\n ctx.out.printJson({ config: loaded.path, api_url: ctx.apiUrl, summary: plan.summary, results: plan.results });\n return;\n }\n const { palette } = ctx.out;\n ctx.out.print(`${palette.dim(\"Config\")} ${relative(ctx.cwd, loaded.path) || loaded.path} (${loaded.config.products.length} products)`);\n ctx.out.print(`${palette.dim(\"API URL\")} ${ctx.apiUrlSource === \"default\" ? ctx.apiUrl : palette.yellow(ctx.apiUrl)}`);\n ctx.out.print(\n `${palette.dim(\"Credentials\")} ${describeSource(ctx.credentialSource)}${ctx.credentialSource === \"profile\" ? ` \"${ctx.profileName}\"` : \"\"}`,\n );\n ctx.out.print(\"\");\n for (const item of sortPlanItems(plan.results)) {\n if (item.action === \"unchanged\") continue;\n const detail = item.error ? ` ${item.error.code}: ${item.error.message}` : \"\";\n ctx.out.print(` ${item.action.padEnd(9)} ${item.key}${detail}`);\n }\n ctx.out.print(renderSummary(plan.summary, { palette, mode: \"plan\" }));\n if (plan.summary.create + plan.summary.update + plan.summary.archive > 0) ctx.out.info(palette.dim(\"Run `purpleturret push` to apply.\"));\n }),\n});\n","import { defineCommand } from \"citty\";\n\nimport { describeSource, globalArgs } from \"../lib/context.js\";\nimport { defineRun } from \"../lib/run.js\";\n\nexport const whoami = defineCommand({\n meta: { name: \"whoami\", description: \"Show the account and key behind the current credentials\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const account = await ctx.client().account.get();\n if (ctx.json) {\n ctx.out.printJson({ account, api_url: ctx.apiUrl, credential_source: ctx.credentialSource, profile: ctx.profileName });\n return;\n }\n const { palette } = ctx.out;\n const rows: [string, string][] = [\n [\"Account\", `${account.email}${account.name ? ` (${account.name})` : \"\"}`],\n [\"Key\", `${account.key.prefix}…${account.key.name ? ` \"${account.key.name}\"` : \"\"}`],\n [\"Scopes\", account.key.scopes.join(\", \") || palette.dim(\"none\")],\n [\n \"Stripe\",\n account.stripe.connected\n ? account.stripe.chargesEnabled\n ? \"connected\"\n : \"connected (charges not enabled)\"\n : palette.yellow(\"not connected\"),\n ],\n [\"PayPal\", account.paypal.connected ? \"connected\" : palette.dim(\"not connected\")],\n [\"API URL\", ctx.apiUrlSource === \"default\" ? ctx.apiUrl : palette.yellow(ctx.apiUrl)],\n [\"Credentials\", `${describeSource(ctx.credentialSource)}${ctx.credentialSource === \"profile\" ? ` \"${ctx.profileName}\"` : \"\"}`],\n ];\n const width = Math.max(...rows.map(([label]) => label.length));\n for (const [label, value] of rows) ctx.out.print(`${palette.dim(label.padEnd(width))} ${value}`);\n }),\n});\n","import { runCli } from \"./main.js\";\n\nawait runCli();\n"],"mappings":";AAAA,SAAS,iBAAAA,gBAAe,YAAY,iBAAkC;;;ACAtE,SAAS,cAAAC,mBAAkB;AAC3B,SAAS,aAAAC,kBAAiB;AAC1B,SAAS,UAAU,eAAe;;;ACD3B,IAAM,cAAc;;;ACD3B,SAAS,SAAS;AAKX,IAAM,cAAc;AAEpB,IAAM,eAAe;AAC5B,IAAM,oBAAoB;AAE1B,IAAM,cAAc;AAEb,IAAM,YAAY,EAAE,OAAO,EAAE,MAAM,aAAa,WAAW;AAC3D,IAAM,cAAc,EAAE,OAAO,EAAE,MAAM,aAAa,WAAW;AAE7D,IAAM,cAAc,EAAE,aAAa;AAAA,EACxC,QAAQ,EACL,OAAO,sEAAsE,EAC7E,IAAI,sEAAsE,EAC1E,IAAI,IAAI,+DAA+D;AAAA,EAC1E,UAAU,EACP,OAAO,EACP,KAAK,EACL,YAAY,EACZ,MAAM,cAAc,sCAAsC;AAC/D,CAAC;AAEM,IAAM,gBAAgB,EAAE,mBAAmB,QAAQ;AAAA,EACxD,EAAE,aAAa,EAAE,MAAM,EAAE,QAAQ,UAAU,EAAE,CAAC;AAAA,EAC9C,EAAE,aAAa,EAAE,MAAM,EAAE,QAAQ,WAAW,GAAG,UAAU,EAAE,KAAK,CAAC,SAAS,MAAM,CAAC,EAAE,CAAC;AACtF,CAAC;AAEM,IAAM,aAAa,EAAE,aAAa;AAAA,EACvC,KAAK;AAAA,EACL,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,GAAG,mBAAmB,EAAE,IAAI,EAAE;AAAA,EAC1D,MAAM,EAAE,OAAO,EAAE,IAAI,oBAAoB,EAAE,IAAI,CAAC;AAClD,CAAC;AAEM,IAAM,cAAc,EAAE,aAAa;AAAA,EACxC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IACF;AACA,QAAI,QAAQ,WAAW,GAAG;AACxB,YAAM,UAAU,IAAI;AACpB;AAAA,IACF;AACA,UAAM,WAAW,MAAM,EAAE,QAAQ,CAAC;AAAA,EACpC,SAAS,OAAO;AACd,UAAM,QAAQ,kBAAkB,OAAO;AACvC,UAAM,MAAM,IAAI,OAAO,EAAE,MAAM,MAAM,MAAM,SAAS,MAAM,SAAS,SAAS,cAAc,eAAe,EAAE,MAAM,MAAM,MAAM,CAAC,CAAC,EAAE,CAAC;AAClI,QAAI,aAAa,KAAK,GAAG;AACvB,UAAI,KAAK,IAAI,SAAS,MAAM,SAAS,KAAK,OAAO,EAAE,MAAM,QAAQ,CAAC,CAAC;AACnE,UAAI,CAAC,MAAM,MAAM;AACf,cAAM,CAAC,KAAK,MAAM,IAAI,MAAM,kBAAkB,MAAM,OAAO;AAC3D,cAAM,UAAU,KAAK,MAAM;AAAA,MAC7B;AACA,cAAQ,WAAW,KAAK;AACxB;AAAA,IACF;AACA,UAAM,WACJ,iBAAiB,WAAW,QAAQ,IAAI,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG,KAAK,OAAO,EAAE,OAAO,MAAM,CAAC;AACvI,QAAI,KAAK,QAAQ;AACjB,YAAQ,WAAW,SAAS;AAAA,EAC9B;AACF;AAEA,SAAS,kBAAkB,SAAoF;AAC7G,SAAO;AAAA,IACL,MAAM,QAAQ,SAAS,QAAQ;AAAA,IAC/B,SAAS,QAAQ,SAAS,WAAW;AAAA,IACrC,OAAO,QAAQ,SAAS,YAAY,IAAI,QAAQ;AAAA,EAClD;AACF;;;AwBrHA,MAAM,OAAO;","names":["defineCommand","existsSync","writeFile","init","status","join","join","init","products","existsSync","products","writeFile","defineCommand","defineCommand","defineCommand","defineCommand","defineCommand","defineCommand","products","existsSync","writeFile","relative","resolve","defineCommand","defineCommand","products","resolve","existsSync","relative","writeFile","relative","defineCommand","existsSync","readFile","dirname","join","resolve","resolve","existsSync","join","dirname","readFile","defineCommand","products","relative","relative","defineCommand","defineCommand","relative","defineCommand","defineCommand","defineCommand"]}
|
|
1
|
+
{"version":3,"sources":["../src/main.ts","../src/commands/init.ts","../../sdk/src/version.ts","../../sdk/src/config/schema.ts","../../sdk/src/client/errors.ts","../../sdk/src/client/wire.ts","../../sdk/src/client/client.ts","../src/lib/context.ts","../src/version.ts","../src/lib/credentials.ts","../src/lib/errors.ts","../src/lib/output.ts","../src/lib/pull-writer.ts","../src/lib/run.ts","../src/commands/login.ts","../src/commands/logout.ts","../src/commands/products.ts","../src/lib/render.ts","../src/lib/table.ts","../src/commands/pull.ts","../src/commands/push.ts","../src/lib/config-loader.ts","../src/commands/status.ts","../src/commands/whoami.ts","../src/cli.ts"],"sourcesContent":["import { defineCommand, runCommand, showUsage, type CommandDef } from \"citty\";\n\nimport { init } from \"./commands/init.js\";\nimport { login } from \"./commands/login.js\";\nimport { logout } from \"./commands/logout.js\";\nimport { products } from \"./commands/products.js\";\nimport { pull } from \"./commands/pull.js\";\nimport { push } from \"./commands/push.js\";\nimport { status } from \"./commands/status.js\";\nimport { whoami } from \"./commands/whoami.js\";\nimport { globalArgs, stashGlobalFlags, type GlobalFlags } from \"./lib/context.js\";\nimport { CliError, EXIT } from \"./lib/errors.js\";\nimport { Output, createPalette, shouldUseColor } from \"./lib/output.js\";\nimport { CLI_VERSION } from \"./version.js\";\n\nexport const main = defineCommand({\n meta: {\n name: \"purpleturret\",\n version: CLI_VERSION,\n description: \"Sync purpleturret.config.ts with your Purpleturret account. Also available as `pt`.\",\n },\n args: { ...globalArgs },\n setup({ args }) {\n stashGlobalFlags(args as GlobalFlags);\n },\n subCommands: { init, login, logout, whoami, status, push, pull, products },\n});\n\ntype AnyCommand = CommandDef<Record<string, never>>;\n\nasync function resolveSubCommand(cmd: AnyCommand, rawArgs: string[]): Promise<[AnyCommand, AnyCommand | undefined]> {\n let current: AnyCommand = cmd;\n let parent: AnyCommand | undefined;\n let args = rawArgs;\n for (;;) {\n const subCommands = (await current.subCommands) as Record<string, AnyCommand> | undefined;\n if (!subCommands) return [current, parent];\n const index = args.findIndex((arg) => !arg.startsWith(\"-\"));\n const name = index >= 0 ? args[index] : undefined;\n const next = name ? subCommands[name] : undefined;\n if (!next) return [current, parent];\n parent = current;\n current = next;\n args = args.slice(index + 1);\n }\n}\n\nfunction isCittyError(error: unknown): error is Error & { code?: string } {\n return error instanceof Error && error.name === \"CLIError\";\n}\n\nconst GLOBAL_STRING_FLAGS = new Set([\"--config\", \"--api-url\", \"--api-key\", \"--profile\"]);\n\n/**\n * citty picks the first token that does not start with \"-\" as the subcommand, so `pt --api-key x push`\n * would treat `x` as the command. Move flags that precede the subcommand behind it instead.\n */\nexport function hoistLeadingFlags(rawArgs: string[]): string[] {\n const leading: string[] = [];\n let index = 0;\n while (index < rawArgs.length) {\n const token = rawArgs[index]!;\n if (!token.startsWith(\"-\")) break;\n leading.push(token);\n index += 1;\n const next = rawArgs[index];\n if (GLOBAL_STRING_FLAGS.has(token) && next !== undefined && !next.startsWith(\"-\")) {\n leading.push(next);\n index += 1;\n }\n }\n if (index === 0 || index >= rawArgs.length) return rawArgs;\n return [...rawArgs.slice(index), ...leading];\n}\n\n/** Entry point shared by the bin shim and tests. Sets `process.exitCode`; never calls `process.exit`. */\nexport async function runCli(argv: string[] = process.argv.slice(2)): Promise<void> {\n const root = main as unknown as AnyCommand;\n const rawArgs = hoistLeadingFlags(argv);\n try {\n if (rawArgs.includes(\"--help\") || rawArgs.includes(\"-h\")) {\n const [cmd, parent] = await resolveSubCommand(root, rawArgs);\n await showUsage(cmd, parent);\n return;\n }\n if (rawArgs.length === 1 && rawArgs[0] === \"--version\") {\n process.stdout.write(`${CLI_VERSION}\\n`);\n return;\n }\n if (rawArgs.length === 0) {\n await showUsage(root);\n return;\n }\n await runCommand(root, { rawArgs });\n } catch (error) {\n const flags = parseLooseGlobals(rawArgs);\n const out = new Output({ json: flags.json, verbose: flags.verbose, palette: createPalette(shouldUseColor({ flag: flags.color })) });\n if (isCittyError(error)) {\n out.fail(new CliError(error.message, EXIT.USAGE, { code: \"usage\" }));\n if (!flags.json) {\n const [cmd, parent] = await resolveSubCommand(root, rawArgs);\n await showUsage(cmd, parent);\n }\n process.exitCode = EXIT.USAGE;\n return;\n }\n const cliError =\n error instanceof CliError ? error : new CliError(error instanceof Error ? error.message : String(error), EXIT.ERROR, { cause: error });\n out.fail(cliError);\n process.exitCode = cliError.exitCode;\n }\n}\n\nfunction parseLooseGlobals(rawArgs: string[]): { json: boolean; verbose: boolean; color: boolean | undefined } {\n return {\n json: rawArgs.includes(\"--json\"),\n verbose: rawArgs.includes(\"--verbose\"),\n color: rawArgs.includes(\"--no-color\") ? false : undefined,\n };\n}\n","import { existsSync } from \"node:fs\";\nimport { writeFile } from \"node:fs/promises\";\nimport { relative, resolve } from \"node:path\";\n\nimport { productToInput, type ProductInput } from \"@purpleturret/sdk\";\nimport { defineCommand } from \"citty\";\n\nimport { globalArgs } from \"../lib/context.js\";\nimport { CliError, EXIT } from \"../lib/errors.js\";\nimport { renderConfigSource, renderStarterConfig, type ConfigFormat } from \"../lib/pull-writer.js\";\nimport { defineRun } from \"../lib/run.js\";\n\nexport const init = defineCommand({\n meta: { name: \"init\", description: \"Create a purpleturret.config.ts in the current directory\" },\n args: {\n ...globalArgs,\n \"from-remote\": { type: \"boolean\", description: \"Seed the file with the products already managed on your account\" },\n force: { type: \"boolean\", description: \"Overwrite an existing config file\" },\n format: { type: \"string\", description: \"File format: ts (default) or json\" },\n },\n run: defineRun(async (ctx, args) => {\n const formatArg = (args.format ?? \"ts\").toLowerCase();\n if (formatArg !== \"ts\" && formatArg !== \"json\") {\n throw new CliError(`Unknown --format \"${args.format}\"; expected ts or json.`, EXIT.USAGE, { code: \"usage\" });\n }\n const format: ConfigFormat = formatArg;\n const target = resolve(ctx.cwd, ctx.configPath ?? `purpleturret.config.${format}`);\n if (existsSync(target) && !args.force) {\n throw new CliError(`${relative(ctx.cwd, target) || target} already exists.`, EXIT.USAGE, {\n code: \"file_exists\",\n hint: \"Pass --force to overwrite it, or --config <path> to write elsewhere.\",\n });\n }\n\n let source: string;\n let count: number;\n if (args[\"from-remote\"]) {\n const { products } = await ctx.client().config.get();\n const inputs = products.map(productToInput).filter((input): input is ProductInput => input !== null);\n source = renderConfigSource(inputs, format);\n count = inputs.length;\n } else {\n source = renderStarterConfig(format);\n count = 1;\n }\n await writeFile(target, source, \"utf8\");\n\n if (ctx.json) {\n ctx.out.printJson({ written: target, products: count, from_remote: Boolean(args[\"from-remote\"]) });\n return;\n }\n const { palette } = ctx.out;\n ctx.out.success(\n `Created ${relative(ctx.cwd, target) || target}${args[\"from-remote\"] ? ` with ${count} product${count === 1 ? \"\" : \"s\"} from your account` : \"\"}`,\n );\n ctx.out.info(\"\");\n ctx.out.info(\"Next steps:\");\n if (format === \"ts\") ctx.out.info(` ${palette.dim(\"1.\")} pnpm add -D @purpleturret/sdk ${palette.dim(\"(types + helpers used by the config)\")}`);\n ctx.out.info(` ${palette.dim(format === \"ts\" ? \"2.\" : \"1.\")} purpleturret login ${palette.dim(\"(or set PURPLETURRET_API_KEY)\")}`);\n ctx.out.info(` ${palette.dim(format === \"ts\" ? \"3.\" : \"2.\")} purpleturret push --dry-run`);\n }),\n});\n","/** Keep in sync with package.json. */\nexport const SDK_VERSION = \"0.2.0\";\n","import { z } from \"zod\";\n\nimport type { ProductInput, PurpleturretConfig } from \"../types.js\";\n\n/** Product keys and credit meters: 1-64 chars, lowercase letters, digits, `_` or `-`, starting with a letter or digit. */\nexport const KEY_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/;\n/** Public checkout slugs: 3-64 chars, lowercase letters, digits, or `-`. */\nexport const SLUG_PATTERN = /^[a-z0-9-]{3,64}$/;\nconst HEX_COLOR_PATTERN = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;\n\nconst KEY_MESSAGE = \"must be 1-64 characters of lowercase letters, digits, '_' or '-', starting with a letter or digit\";\n\nexport const keySchema = z.string().regex(KEY_PATTERN, KEY_MESSAGE);\nexport const meterSchema = z.string().regex(KEY_PATTERN, KEY_MESSAGE);\n\nexport const moneySchema = z.strictObject({\n amount: z\n .number(\"must be an integer amount in the smallest currency unit (e.g. cents)\")\n .int(\"must be an integer amount in the smallest currency unit (e.g. cents)\")\n .min(50, \"must be at least 50 (e.g. $0.50); use usd(dollars) to convert\"),\n currency: z\n .string()\n .trim()\n .toLowerCase()\n .regex(/^[a-z]{3}$/, \"must be a 3-letter ISO currency code\"),\n});\n\nexport const billingSchema = z.discriminatedUnion(\"type\", [\n z.strictObject({ type: z.literal(\"one_time\") }),\n z.strictObject({ type: z.literal(\"recurring\"), interval: z.enum([\"month\", \"year\"]) }),\n]);\n\nexport const tierSchema = z.strictObject({\n key: keySchema,\n name: z.string().trim().min(1, \"must not be empty\").max(80),\n rank: z.number().int(\"must be an integer\").min(0),\n});\n\nexport const groupSchema = z.strictObject({\n key: keySchema,\n tier: tierSchema.optional(),\n});\n\nexport const creditGrantSchema = z.strictObject({\n meter: meterSchema,\n amount: z.number().int(\"must be an integer\").positive(\"must be a positive integer\"),\n renewal: z.enum([\"reset\", \"accumulate\"]),\n expiresAfterDays: z.number().int(\"must be an integer\").positive(\"must be a positive integer\").optional(),\n});\n\nexport const deliverySchema = z.discriminatedUnion(\"method\", [\n z.strictObject({ method: z.literal(\"none\") }),\n z.strictObject({\n method: z.literal(\"redirect\"),\n url: z\n .string()\n .url(\"must be an absolute URL\")\n .refine((value) => value.startsWith(\"https://\"), \"must be an https:// URL\"),\n }),\n z.strictObject({ method: z.literal(\"instructions\"), instructions: z.string().trim().min(1, \"must not be empty\").max(10_000) }),\n]);\n\nexport const checkoutSchema = z.strictObject({\n layoutMode: z.enum([\"two_step\", \"one_step\"]).optional(),\n paymentStyle: z.enum([\"classic\", \"express\"]).optional(),\n providerMode: z.enum([\"inherit\", \"stripe\", \"paypal\", \"both\"]).optional(),\n contactFields: z.strictObject({ name: z.boolean().optional(), phone: z.boolean().optional() }).optional(),\n});\n\nexport const themeSchema = z.strictObject({\n primaryColor: z.string().regex(HEX_COLOR_PATTERN, \"must be a hex color such as #5F34CC\").optional(),\n buttonRadius: z.enum([\"sm\", \"md\", \"lg\"]).optional(),\n accentMode: z.enum([\"light\", \"dark\", \"system\"]).optional(),\n});\n\nexport const stripeSchema = z.strictObject({\n priceId: z.string().trim().min(1, \"must be a Stripe price id (price_…)\"),\n});\n\nexport const productInputSchema = z.strictObject({\n key: keySchema,\n name: z.string().trim().min(1, \"must not be empty\").max(120),\n description: z.string().max(5_000).optional(),\n price: moneySchema,\n billing: billingSchema,\n group: groupSchema.optional(),\n credits: z.array(creditGrantSchema).optional(),\n delivery: deliverySchema.optional(),\n checkout: checkoutSchema.optional(),\n theme: themeSchema.optional(),\n slug: z.string().regex(SLUG_PATTERN, \"must be 3-64 characters of lowercase letters, digits, or '-'\").optional(),\n stripe: stripeSchema.optional(),\n active: z.boolean().optional(),\n buyerEmails: z.boolean().optional(),\n});\n\nexport const configSchema = z\n .strictObject({\n products: z.array(productInputSchema),\n })\n .superRefine((config, ctx) => {\n const seenKeys = new Map<string, number>();\n config.products.forEach((product, index) => {\n const firstIndex = seenKeys.get(product.key);\n if (firstIndex !== undefined) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"products\", index, \"key\"],\n message: `duplicate product key \"${product.key}\" (also used by products[${firstIndex}])`,\n });\n } else {\n seenKeys.set(product.key, index);\n }\n const seenMeters = new Map<string, number>();\n product.credits?.forEach((grant, grantIndex) => {\n const firstMeter = seenMeters.get(grant.meter);\n if (firstMeter !== undefined) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"products\", index, \"credits\", grantIndex, \"meter\"],\n message: `duplicate credit meter \"${grant.meter}\" (also used by credits[${firstMeter}])`,\n });\n } else {\n seenMeters.set(grant.meter, grantIndex);\n }\n });\n });\n });\n\nexport interface ConfigIssue {\n /** Dotted path such as `products[0].price.amount`. */\n path: string;\n message: string;\n}\n\nexport class ConfigValidationError extends Error {\n override readonly name = \"ConfigValidationError\";\n readonly issues: ConfigIssue[];\n\n constructor(issues: ConfigIssue[]) {\n super(formatIssues(issues));\n this.issues = issues;\n }\n}\n\nexport function formatIssuePath(path: ReadonlyArray<PropertyKey>): string {\n let out = \"\";\n for (const segment of path) {\n if (typeof segment === \"number\") out += `[${segment}]`;\n else out += out ? `.${String(segment)}` : String(segment);\n }\n return out || \"(root)\";\n}\n\nfunction formatIssues(issues: ConfigIssue[]): string {\n const lines = issues.map((issue) => ` - ${issue.path}: ${issue.message}`);\n return `Invalid Purpleturret config (${issues.length} issue${issues.length === 1 ? \"\" : \"s\"}):\\n${lines.join(\"\\n\")}`;\n}\n\n/**\n * Validate an arbitrary value as a Purpleturret config. Returns the normalized config (currencies\n * lowercased, strings trimmed) or throws `ConfigValidationError` listing every problem found.\n */\nexport function validateConfig(input: unknown): PurpleturretConfig {\n const result = configSchema.safeParse(input);\n if (result.success) return result.data as PurpleturretConfig;\n const issues: ConfigIssue[] = result.error.issues.map((issue) => ({\n path: formatIssuePath(issue.path),\n message: issue.message,\n }));\n throw new ConfigValidationError(issues);\n}\n\n/** Validate a single product declaration. */\nexport function validateProduct(input: unknown): ProductInput {\n const result = productInputSchema.safeParse(input);\n if (result.success) return result.data as ProductInput;\n throw new ConfigValidationError(result.error.issues.map((issue) => ({ path: formatIssuePath(issue.path), message: issue.message })));\n}\n","export interface PurpleturretApiErrorInit {\n status: number;\n code: string;\n message: string;\n requestId?: string | null;\n details?: unknown;\n retryAfter?: number | null;\n}\n\n/** A non-2xx response from the Purpleturret API. */\nexport class PurpleturretApiError extends Error {\n override readonly name = \"PurpleturretApiError\";\n readonly status: number;\n readonly code: string;\n readonly requestId: string | null;\n readonly details: unknown;\n /** Seconds to wait before retrying, from `Retry-After` (or `reset_at` on legacy envelopes). */\n readonly retryAfter: number | null;\n\n constructor(init: PurpleturretApiErrorInit) {\n super(init.message);\n this.status = init.status;\n this.code = init.code;\n this.requestId = init.requestId ?? null;\n this.details = init.details;\n this.retryAfter = init.retryAfter ?? null;\n }\n\n /**\n * Build an error from a response body. Accepts the structured envelope\n * `{ error: { code, message, request_id, details } }` as well as the legacy entitlements envelope\n * `{ error: \"code\", ...extra }`.\n */\n static fromResponse(status: number, body: unknown, retryAfterHeader?: string | null): PurpleturretApiError {\n const retryAfter = parseRetryAfter(retryAfterHeader);\n const record = body && typeof body === \"object\" && !Array.isArray(body) ? (body as Record<string, unknown>) : null;\n const envelope = record?.error;\n\n if (envelope && typeof envelope === \"object\") {\n const err = envelope as Record<string, unknown>;\n const code = typeof err.code === \"string\" && err.code ? err.code : `http_${status}`;\n const message = typeof err.message === \"string\" && err.message ? err.message : defaultMessage(status, code);\n const requestId = typeof err.request_id === \"string\" ? err.request_id : typeof err.requestId === \"string\" ? err.requestId : null;\n return new PurpleturretApiError({ status, code, message, requestId, details: err.details, retryAfter });\n }\n\n if (typeof envelope === \"string\" && record) {\n const { error: _code, message: rawMessage, request_id: requestId, ...rest } = record;\n const code = envelope || `http_${status}`;\n const message = typeof rawMessage === \"string\" && rawMessage ? rawMessage : defaultMessage(status, code);\n const resetAt = typeof rest.reset_at === \"number\" ? rest.reset_at : null;\n const legacyRetryAfter = retryAfter ?? (resetAt !== null ? Math.max(1, Math.ceil((resetAt - Date.now()) / 1000)) : null);\n return new PurpleturretApiError({\n status,\n code,\n message,\n requestId: typeof requestId === \"string\" ? requestId : null,\n details: Object.keys(rest).length > 0 ? rest : undefined,\n retryAfter: legacyRetryAfter,\n });\n }\n\n const text = typeof body === \"string\" ? body.trim().slice(0, 300) : \"\";\n return new PurpleturretApiError({\n status,\n code: `http_${status}`,\n message: text || defaultMessage(status, `http_${status}`),\n details: record ?? undefined,\n retryAfter,\n });\n }\n}\n\n/** The request never produced an HTTP response (DNS, connection refused, timeout, aborted). */\nexport class PurpleturretNetworkError extends Error {\n override readonly name = \"PurpleturretNetworkError\";\n readonly url: string;\n readonly timedOut: boolean;\n override readonly cause: unknown;\n\n constructor(url: string, cause: unknown, timedOut: boolean) {\n super(timedOut ? `Request to ${url} timed out` : `Request to ${url} failed: ${describeCause(cause)}`);\n this.url = url;\n this.cause = cause;\n this.timedOut = timedOut;\n }\n}\n\nexport function isTimeoutError(cause: unknown): boolean {\n return Boolean(cause && typeof cause === \"object\" && \"name\" in cause && (cause as { name?: unknown }).name === \"TimeoutError\");\n}\n\nfunction describeCause(cause: unknown): string {\n if (cause && typeof cause === \"object\") {\n const inner = (cause as { cause?: unknown }).cause;\n if (inner && typeof inner === \"object\" && \"message\" in inner && typeof (inner as { message?: unknown }).message === \"string\") {\n const code = (inner as { code?: unknown }).code;\n return typeof code === \"string\" ? `${code} (${(inner as { message: string }).message})` : (inner as { message: string }).message;\n }\n if (\"message\" in cause && typeof (cause as { message?: unknown }).message === \"string\") return (cause as { message: string }).message;\n }\n return String(cause);\n}\n\nfunction defaultMessage(status: number, code: string): string {\n switch (status) {\n case 401:\n return \"The API key was rejected\";\n case 403:\n return \"The API key is not allowed to perform this operation\";\n case 404:\n return \"The requested resource was not found\";\n case 409:\n return \"The request conflicts with the current state\";\n case 422:\n return \"The request was rejected as invalid\";\n case 429:\n return \"Too many requests; slow down and retry\";\n default:\n return status >= 500 ? `The Purpleturret API returned ${status}` : `Request failed with ${code}`;\n }\n}\n\nexport function parseRetryAfter(header: string | null | undefined): number | null {\n if (!header) return null;\n const trimmed = header.trim();\n if (/^\\d+$/.test(trimmed)) return Number(trimmed);\n const when = Date.parse(trimmed);\n if (Number.isNaN(when)) return null;\n return Math.max(0, Math.ceil((when - Date.now()) / 1000));\n}\n","import type {\n Account,\n Billing,\n CheckoutSettings,\n ConfigGetResult,\n ConfigPushResult,\n CreditAdjustResult,\n CreditBalancesResult,\n CreditConsumeResult,\n CreditGrant,\n CustomerRef,\n Delivery,\n Entitlement,\n LedgerEntry,\n Page,\n PlanAction,\n PlanItem,\n Product,\n ProductGroup,\n ProductInput,\n ProductTheme,\n StripeSettings,\n Tier,\n} from \"../types.js\";\n\n/*\n * Wire (snake_case) shapes as sent and received by the REST API.\n */\n\nexport interface WireMoney {\n amount: number;\n currency: string;\n}\n\nexport type WireBilling = { type: \"one_time\" } | { type: \"recurring\"; interval: \"month\" | \"year\" };\n\nexport interface WireTier {\n key: string;\n name: string;\n rank: number;\n}\n\nexport interface WireGroup {\n key: string;\n tier?: WireTier | null;\n}\n\nexport interface WireCreditGrant {\n meter: string;\n amount: number;\n renewal: \"reset\" | \"accumulate\";\n expires_after_days?: number | null;\n}\n\nexport type WireDelivery = { method: \"none\" } | { method: \"redirect\"; url: string } | { method: \"instructions\"; instructions: string };\n\nexport interface WireCheckout {\n layout_mode?: \"two_step\" | \"one_step\" | null;\n payment_style?: \"classic\" | \"express\" | null;\n provider_mode?: \"inherit\" | \"stripe\" | \"paypal\" | \"both\" | null;\n contact_fields?: { name?: boolean | null; phone?: boolean | null } | null;\n}\n\nexport interface WireTheme {\n primary_color?: string | null;\n button_radius?: \"sm\" | \"md\" | \"lg\" | null;\n accent_mode?: \"light\" | \"dark\" | \"system\" | null;\n}\n\nexport interface WireStripe {\n price_id: string;\n}\n\nexport interface WireProductInput {\n key: string;\n name: string;\n description?: string | null;\n price: WireMoney;\n billing: WireBilling;\n group?: WireGroup | null;\n credits?: WireCreditGrant[] | null;\n delivery?: WireDelivery | null;\n checkout?: WireCheckout | null;\n theme?: WireTheme | null;\n slug?: string | null;\n stripe?: WireStripe | null;\n active?: boolean;\n buyer_emails?: boolean;\n}\n\nexport interface WireProduct extends Omit<WireProductInput, \"key\" | \"slug\" | \"active\"> {\n key: string | null;\n id: string;\n slug: string | null;\n url: string | null;\n active: boolean;\n archived_at: number | null;\n created_at: number;\n updated_at: number;\n}\n\nexport interface WirePlanChange {\n path: string;\n from: unknown;\n to: unknown;\n note?: string | null;\n}\n\nexport interface WirePlanItem {\n key: string;\n action: PlanAction;\n changes?: WirePlanChange[] | null;\n product?: WireProduct | null;\n error?: { code?: string; message?: string } | string | null;\n}\n\nexport interface WireConfigPushResult {\n applied: boolean;\n summary: { create: number; update: number; unchanged: number; archive: number; conflict: number; error: number };\n results: WirePlanItem[];\n}\n\nexport interface WireConfigGetResult {\n products: WireProduct[];\n unmanaged_count: number;\n}\n\nexport interface WireAccount {\n id: string;\n email: string;\n name?: string | null;\n stripe: { connected: boolean; charges_enabled: boolean };\n paypal: { connected: boolean };\n key: { prefix: string; name?: string | null; scopes: string[] };\n}\n\nexport interface WirePage<T> {\n data: T[];\n next_cursor?: string | null;\n}\n\nexport interface WireCustomerRef {\n email?: string | null;\n external_id?: string | null;\n}\n\nexport interface WireCreditBalance {\n meter: string;\n balance: number;\n expires_at?: number | null;\n lifetime_granted: number;\n lifetime_consumed: number;\n}\n\nexport interface WireCreditBalancesResult {\n customer: WireCustomerRef;\n balances: WireCreditBalance[];\n}\n\nexport interface WireCreditConsumeResult {\n meter: string;\n balance: number;\n consumed: number;\n replayed: boolean;\n}\n\nexport interface WireCreditAdjustResult {\n meter: string;\n balance: number;\n}\n\nexport type WireLedgerEntry = Record<string, unknown>;\n\nexport type WireEntitlement = Record<string, unknown>;\n\n/*\n * Mappers.\n */\n\nfunction omitUndefined<T extends object>(value: T): T {\n const out: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {\n if (entry !== undefined) out[key] = entry;\n }\n return out as T;\n}\n\nexport function toWireProduct(input: ProductInput): WireProductInput {\n const wire: WireProductInput = {\n key: input.key,\n name: input.name,\n description: input.description,\n price: { amount: input.price.amount, currency: input.price.currency },\n billing: input.billing.type === \"recurring\" ? { type: \"recurring\", interval: input.billing.interval } : { type: \"one_time\" },\n group: input.group ? toWireGroup(input.group) : undefined,\n credits: input.credits?.map(toWireCreditGrant),\n delivery: input.delivery ? toWireDelivery(input.delivery) : undefined,\n checkout: input.checkout ? toWireCheckout(input.checkout) : undefined,\n theme: input.theme ? toWireTheme(input.theme) : undefined,\n slug: input.slug,\n stripe: input.stripe ? { price_id: input.stripe.priceId } : undefined,\n active: input.active,\n buyer_emails: input.buyerEmails,\n };\n return omitUndefined(wire);\n}\n\nfunction toWireGroup(group: ProductGroup): WireGroup {\n return omitUndefined({ key: group.key, tier: group.tier ? { key: group.tier.key, name: group.tier.name, rank: group.tier.rank } : undefined });\n}\n\nfunction toWireCreditGrant(grant: CreditGrant): WireCreditGrant {\n return omitUndefined({ meter: grant.meter, amount: grant.amount, renewal: grant.renewal, expires_after_days: grant.expiresAfterDays });\n}\n\nfunction toWireDelivery(delivery: Delivery): WireDelivery {\n switch (delivery.method) {\n case \"none\":\n return { method: \"none\" };\n case \"redirect\":\n return { method: \"redirect\", url: delivery.url };\n case \"instructions\":\n return { method: \"instructions\", instructions: delivery.instructions };\n }\n}\n\nfunction toWireCheckout(checkout: CheckoutSettings): WireCheckout {\n return omitUndefined({\n layout_mode: checkout.layoutMode,\n payment_style: checkout.paymentStyle,\n provider_mode: checkout.providerMode,\n contact_fields: checkout.contactFields ? omitUndefined({ name: checkout.contactFields.name, phone: checkout.contactFields.phone }) : undefined,\n });\n}\n\nfunction toWireTheme(theme: ProductTheme): WireTheme {\n return omitUndefined({ primary_color: theme.primaryColor, button_radius: theme.buttonRadius, accent_mode: theme.accentMode });\n}\n\nexport function fromWireProduct(wire: WireProduct): Product {\n const product: Product = {\n key: wire.key ?? null,\n id: wire.id,\n slug: wire.slug ?? null,\n url: wire.url ?? null,\n name: wire.name,\n description: wire.description ?? undefined,\n price: { amount: wire.price.amount, currency: wire.price.currency },\n billing: fromWireBilling(wire.billing),\n group: wire.group ? fromWireGroup(wire.group) : undefined,\n credits: wire.credits ? wire.credits.map(fromWireCreditGrant) : undefined,\n delivery: wire.delivery ?? undefined,\n checkout: wire.checkout ? fromWireCheckout(wire.checkout) : undefined,\n theme: wire.theme ? fromWireTheme(wire.theme) : undefined,\n stripe: wire.stripe ? fromWireStripe(wire.stripe) : undefined,\n active: wire.active,\n buyerEmails: wire.buyer_emails ?? undefined,\n archivedAt: wire.archived_at ?? null,\n createdAt: wire.created_at,\n updatedAt: wire.updated_at,\n };\n return omitUndefined(product);\n}\n\nfunction fromWireBilling(billing: WireBilling): Billing {\n return billing.type === \"recurring\" ? { type: \"recurring\", interval: billing.interval } : { type: \"one_time\" };\n}\n\nfunction fromWireGroup(group: WireGroup): ProductGroup {\n const tier: Tier | undefined = group.tier ? { key: group.tier.key, name: group.tier.name, rank: group.tier.rank } : undefined;\n return omitUndefined({ key: group.key, tier });\n}\n\nfunction fromWireCreditGrant(grant: WireCreditGrant): CreditGrant {\n return omitUndefined({\n meter: grant.meter,\n amount: grant.amount,\n renewal: grant.renewal,\n expiresAfterDays: grant.expires_after_days ?? undefined,\n });\n}\n\nfunction fromWireCheckout(checkout: WireCheckout): CheckoutSettings {\n return omitUndefined({\n layoutMode: checkout.layout_mode ?? undefined,\n paymentStyle: checkout.payment_style ?? undefined,\n providerMode: checkout.provider_mode ?? undefined,\n contactFields: checkout.contact_fields\n ? omitUndefined({ name: checkout.contact_fields.name ?? undefined, phone: checkout.contact_fields.phone ?? undefined })\n : undefined,\n });\n}\n\nfunction fromWireTheme(theme: WireTheme): ProductTheme {\n return omitUndefined({\n primaryColor: theme.primary_color ?? undefined,\n buttonRadius: theme.button_radius ?? undefined,\n accentMode: theme.accent_mode ?? undefined,\n });\n}\n\nfunction fromWireStripe(stripe: WireStripe): StripeSettings {\n return { priceId: stripe.price_id };\n}\n\n/** Strip server-only fields from a fetched product so it can be re-declared in a config file. */\nexport function productToInput(product: Product): ProductInput | null {\n if (!product.key) return null;\n return omitUndefined({\n key: product.key,\n name: product.name,\n description: product.description,\n price: product.price,\n billing: product.billing,\n group: product.group,\n credits: product.credits,\n delivery: product.delivery,\n checkout: product.checkout,\n theme: product.theme,\n slug: product.slug ?? undefined,\n stripe: product.stripe,\n active: product.active,\n // The API always reports buyer_emails; only the opt-out is worth writing into a config.\n buyerEmails: product.buyerEmails === false ? false : undefined,\n });\n}\n\nexport function fromWirePlanItem(item: WirePlanItem): PlanItem {\n let error: PlanItem[\"error\"];\n if (typeof item.error === \"string\") error = { code: item.error, message: item.error };\n else if (item.error && typeof item.error === \"object\") {\n error = { code: item.error.code ?? \"error\", message: item.error.message ?? item.error.code ?? \"Unknown error\" };\n }\n return omitUndefined({\n key: item.key,\n action: item.action,\n changes: (item.changes ?? []).map((change) =>\n omitUndefined({ path: change.path, from: change.from, to: change.to, note: change.note ?? undefined }),\n ),\n product: item.product ? fromWireProduct(item.product) : undefined,\n error,\n });\n}\n\nexport function fromWireConfigPushResult(wire: WireConfigPushResult): ConfigPushResult {\n return {\n applied: Boolean(wire.applied),\n summary: {\n create: wire.summary?.create ?? 0,\n update: wire.summary?.update ?? 0,\n unchanged: wire.summary?.unchanged ?? 0,\n archive: wire.summary?.archive ?? 0,\n conflict: wire.summary?.conflict ?? 0,\n error: wire.summary?.error ?? 0,\n },\n results: (wire.results ?? []).map(fromWirePlanItem),\n };\n}\n\nexport function fromWireConfigGetResult(wire: WireConfigGetResult): ConfigGetResult {\n return { products: (wire.products ?? []).map(fromWireProduct), unmanagedCount: wire.unmanaged_count ?? 0 };\n}\n\nexport function fromWireAccount(wire: WireAccount): Account {\n return {\n id: wire.id,\n email: wire.email,\n name: wire.name ?? null,\n stripe: { connected: Boolean(wire.stripe?.connected), chargesEnabled: Boolean(wire.stripe?.charges_enabled) },\n paypal: { connected: Boolean(wire.paypal?.connected) },\n key: { prefix: wire.key?.prefix ?? \"\", name: wire.key?.name ?? null, scopes: wire.key?.scopes ?? [] },\n };\n}\n\nexport function fromWirePage<W, T>(wire: WirePage<W>, map: (item: W) => T): Page<T> {\n return { data: (wire.data ?? []).map(map), nextCursor: wire.next_cursor ?? null };\n}\n\nfunction fromWireCustomerRef(ref: WireCustomerRef | null | undefined): CustomerRef {\n return { email: ref?.email ?? null, externalId: ref?.external_id ?? null };\n}\n\nexport function fromWireCreditBalances(wire: WireCreditBalancesResult): CreditBalancesResult {\n return {\n customer: fromWireCustomerRef(wire.customer),\n balances: (wire.balances ?? []).map((balance) => ({\n meter: balance.meter,\n balance: balance.balance,\n expiresAt: balance.expires_at ?? null,\n lifetimeGranted: balance.lifetime_granted ?? 0,\n lifetimeConsumed: balance.lifetime_consumed ?? 0,\n })),\n };\n}\n\nexport function fromWireCreditConsume(wire: WireCreditConsumeResult): CreditConsumeResult {\n return { meter: wire.meter, balance: wire.balance, consumed: wire.consumed, replayed: Boolean(wire.replayed) };\n}\n\nexport function fromWireCreditAdjust(wire: WireCreditAdjustResult): CreditAdjustResult {\n return { meter: wire.meter, balance: wire.balance };\n}\n\n/** snake_case → camelCase for a single key. */\nexport function camelCaseKey(key: string): string {\n return key.replace(/_([a-z0-9])/g, (_, char: string) => char.toUpperCase());\n}\n\n/** Deeply convert object keys to camelCase. Values are left untouched. */\nexport function camelizeKeys(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(camelizeKeys);\n if (value && typeof value === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value as Record<string, unknown>)) out[camelCaseKey(key)] = camelizeKeys(entry);\n return out;\n }\n return value;\n}\n\nexport function fromWireLedgerEntry(wire: WireLedgerEntry): LedgerEntry {\n const entry = camelizeKeys(wire) as Record<string, unknown>;\n return {\n ...entry,\n id: String(entry.id ?? \"\"),\n kind: entry.kind as LedgerEntry[\"kind\"],\n meter: String(entry.meter ?? \"\"),\n amount: Number(entry.amount ?? 0),\n balanceAfter: Number(entry.balanceAfter ?? 0),\n note: (entry.note as string | null | undefined) ?? null,\n createdAt: Number(entry.createdAt ?? 0),\n };\n}\n\nexport function fromWireEntitlement(wire: WireEntitlement): Entitlement {\n const { credits, ...rest } = wire;\n const base = camelizeKeys(rest) as Record<string, unknown>;\n const entitlement: Entitlement = {\n ...(base as Partial<Entitlement>),\n hasAccess: Boolean(base.hasAccess),\n status: String(base.status ?? \"none\"),\n };\n if (credits && typeof credits === \"object\") {\n // Meter names are user-defined keys; keep them verbatim and only camelize the values.\n entitlement.credits = Object.fromEntries(\n Object.entries(credits as Record<string, Record<string, unknown>>).map(([meter, value]) => [\n meter,\n { balance: Number(value?.balance ?? 0), expiresAt: (value?.expires_at as number | null | undefined) ?? null },\n ]),\n );\n }\n return entitlement;\n}\n","import type {\n Account,\n ConfigGetResult,\n ConfigPushResult,\n CreditAdjustResult,\n CreditBalancesResult,\n CreditConsumeResult,\n CustomerSelector,\n Entitlement,\n LedgerEntry,\n Page,\n Product,\n ProductInput,\n} from \"../types.js\";\nimport { SDK_VERSION } from \"../version.js\";\nimport { PurpleturretApiError, PurpleturretNetworkError, isTimeoutError } from \"./errors.js\";\nimport {\n fromWireAccount,\n fromWireConfigGetResult,\n fromWireConfigPushResult,\n fromWireCreditAdjust,\n fromWireCreditBalances,\n fromWireCreditConsume,\n fromWireEntitlement,\n fromWireLedgerEntry,\n fromWirePage,\n fromWireProduct,\n toWireProduct,\n type WireAccount,\n type WireConfigGetResult,\n type WireConfigPushResult,\n type WireCreditAdjustResult,\n type WireCreditBalancesResult,\n type WireCreditConsumeResult,\n type WireEntitlement,\n type WireLedgerEntry,\n type WirePage,\n type WireProduct,\n} from \"./wire.js\";\n\nexport const DEFAULT_BASE_URL = \"https://api.purpleturret.com\";\nexport const DEFAULT_TIMEOUT_MS = 30_000;\n\nexport interface PurpleturretClientOptions {\n /** Seller API key (`pt_sk_…`). */\n apiKey: string;\n /** API origin without `/v1`. Defaults to `https://api.purpleturret.com`; local dev uses `http://localhost:3001/api`. */\n baseUrl?: string;\n /** Custom fetch implementation (tests, polyfills). Defaults to `globalThis.fetch`. */\n fetch?: typeof fetch;\n /** Per-request timeout. Defaults to 30 s. */\n timeoutMs?: number;\n /** Extra `User-Agent` value; the SDK version is appended. */\n userAgent?: string;\n}\n\nexport interface ConfigPushOptions {\n products: ProductInput[];\n /** Archive keyed products that are missing from `products`. */\n prune?: boolean;\n /** Compute the plan without applying it. */\n dryRun?: boolean;\n /** Sent as `Idempotency-Key`; reuse it when retrying a failed apply. */\n idempotencyKey?: string;\n}\n\nexport interface ProductListOptions {\n cursor?: string;\n limit?: number;\n includeArchived?: boolean;\n}\n\nexport type CreditBalancesOptions = CustomerSelector & { meter?: string };\n\nexport type CreditConsumeOptions = CustomerSelector & {\n meter: string;\n amount: number;\n /** Required. Reusing a key replays the original result instead of consuming twice. */\n idempotencyKey: string;\n note?: string;\n};\n\nexport type CreditAdjustOptions = CustomerSelector & {\n meter: string;\n /** Signed amount: positive grants, negative removes. */\n amount: number;\n idempotencyKey?: string;\n note?: string;\n};\n\nexport type CreditLedgerOptions = CustomerSelector & { cursor?: string; limit?: number };\n\nexport type EntitlementOptions = CustomerSelector & { groupKey: string };\n\ninterface RequestOptions {\n query?: Record<string, string | number | boolean | undefined>;\n body?: unknown;\n idempotencyKey?: string;\n /** Statuses (besides 2xx) whose bodies are returned instead of thrown. */\n acceptStatuses?: number[];\n}\n\nexport class PurpleturretClient {\n readonly baseUrl: string;\n readonly timeoutMs: number;\n private readonly apiKey: string;\n private readonly fetchImpl: typeof fetch;\n private readonly userAgent: string;\n\n constructor(options: PurpleturretClientOptions) {\n if (!options || typeof options.apiKey !== \"string\" || !options.apiKey.trim()) {\n throw new TypeError(\"PurpleturretClient: apiKey is required\");\n }\n this.apiKey = options.apiKey.trim();\n this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).trim().replace(/\\/+$/, \"\");\n this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (typeof fetchImpl !== \"function\") throw new TypeError(\"PurpleturretClient: no fetch implementation available; pass options.fetch\");\n this.fetchImpl = fetchImpl;\n const sdkAgent = `purpleturret-sdk/${SDK_VERSION}`;\n this.userAgent = options.userAgent ? `${options.userAgent} ${sdkAgent}` : sdkAgent;\n }\n\n /** Absolute URL for an API path such as `/config`. */\n url(path: string, query?: RequestOptions[\"query\"]): string {\n const normalizedPath = path.startsWith(\"/\") ? path : `/${path}`;\n let url = `${this.baseUrl}/v1${normalizedPath}`;\n if (query) {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined) continue;\n params.set(key, String(value));\n }\n const qs = params.toString();\n if (qs) url += `?${qs}`;\n }\n return url;\n }\n\n readonly account = {\n get: async (): Promise<Account> => fromWireAccount(await this.request<WireAccount>(\"GET\", \"/account\")),\n };\n\n readonly config = {\n get: async (): Promise<ConfigGetResult> => fromWireConfigGetResult(await this.request<WireConfigGetResult>(\"GET\", \"/config\")),\n push: async (options: ConfigPushOptions): Promise<ConfigPushResult> => {\n const body: Record<string, unknown> = { products: options.products.map(toWireProduct) };\n if (options.prune !== undefined) body.prune = options.prune;\n if (options.dryRun !== undefined) body.dry_run = options.dryRun;\n const wire = await this.request<WireConfigPushResult>(\"PUT\", \"/config\", {\n body,\n idempotencyKey: options.idempotencyKey,\n // A conflict returns the full plan with a 409; surface it as a result so callers can render it.\n acceptStatuses: [409],\n });\n return fromWireConfigPushResult(wire);\n },\n };\n\n readonly products = {\n list: async (options: ProductListOptions = {}): Promise<Page<Product>> =>\n fromWirePage(\n await this.request<WirePage<WireProduct>>(\"GET\", \"/products\", {\n query: { cursor: options.cursor, limit: options.limit, include_archived: options.includeArchived },\n }),\n fromWireProduct,\n ),\n get: async (key: string): Promise<Product> => fromWireProduct(await this.request<WireProduct>(\"GET\", `/products/${encodeURIComponent(key)}`)),\n /** Archives the product (never hard-deletes). */\n archive: async (key: string): Promise<Product> =>\n fromWireProduct(await this.request<WireProduct>(\"DELETE\", `/products/${encodeURIComponent(key)}`)),\n };\n\n readonly credits = {\n balances: async (options: CreditBalancesOptions): Promise<CreditBalancesResult> =>\n fromWireCreditBalances(\n await this.request<WireCreditBalancesResult>(\"GET\", \"/credits/balances\", {\n query: { ...customerQuery(options), meter: options.meter },\n }),\n ),\n consume: async (options: CreditConsumeOptions): Promise<CreditConsumeResult> => {\n if (!options.idempotencyKey) throw new TypeError(\"credits.consume: idempotencyKey is required\");\n return fromWireCreditConsume(\n await this.request<WireCreditConsumeResult>(\"POST\", \"/credits/consume\", {\n body: { meter: options.meter, amount: options.amount, ...customerQuery(options), note: options.note },\n idempotencyKey: options.idempotencyKey,\n }),\n );\n },\n adjust: async (options: CreditAdjustOptions): Promise<CreditAdjustResult> =>\n fromWireCreditAdjust(\n await this.request<WireCreditAdjustResult>(\"POST\", \"/credits/adjust\", {\n body: { meter: options.meter, amount: options.amount, ...customerQuery(options), note: options.note },\n idempotencyKey: options.idempotencyKey,\n }),\n ),\n ledger: async (options: CreditLedgerOptions): Promise<Page<LedgerEntry>> =>\n fromWirePage(\n await this.request<WirePage<WireLedgerEntry>>(\"GET\", \"/credits/ledger\", {\n query: { ...customerQuery(options), cursor: options.cursor, limit: options.limit },\n }),\n fromWireLedgerEntry,\n ),\n };\n\n readonly entitlements = {\n /** Resolves with `hasAccess: false` (rather than throwing) when the customer has no subscription. */\n get: async (options: EntitlementOptions): Promise<Entitlement> =>\n fromWireEntitlement(\n await this.request<WireEntitlement>(\"GET\", \"/entitlements\", {\n query: { group_key: options.groupKey, ...customerQuery(options) },\n acceptStatuses: [404],\n }),\n ),\n };\n\n private async request<T>(method: string, path: string, options: RequestOptions = {}): Promise<T> {\n const url = this.url(path, options.query);\n const headers: Record<string, string> = {\n authorization: `Bearer ${this.apiKey}`,\n accept: \"application/json\",\n \"user-agent\": this.userAgent,\n };\n const hasBody = options.body !== undefined;\n if (hasBody) headers[\"content-type\"] = \"application/json\";\n if (options.idempotencyKey) headers[\"idempotency-key\"] = options.idempotencyKey;\n\n let response: Response;\n try {\n response = await this.fetchImpl(url, {\n method,\n headers,\n body: hasBody ? JSON.stringify(stripUndefined(options.body)) : undefined,\n signal: AbortSignal.timeout(this.timeoutMs),\n });\n } catch (cause) {\n throw new PurpleturretNetworkError(url, cause, isTimeoutError(cause));\n }\n\n const text = await response.text();\n let parsed: unknown = undefined;\n if (text) {\n try {\n parsed = JSON.parse(text);\n } catch {\n parsed = undefined;\n }\n }\n\n const accepted = response.ok || (options.acceptStatuses?.includes(response.status) ?? false);\n if (!accepted) {\n throw PurpleturretApiError.fromResponse(response.status, parsed ?? text, response.headers.get(\"retry-after\"));\n }\n if (!response.ok && parsed && typeof parsed === \"object\" && \"error\" in (parsed as Record<string, unknown>)) {\n const record = parsed as Record<string, unknown>;\n // A 404 entitlement lookup returns `{ has_access: false }` (no error); anything else with an\n // error envelope is still an error even if the status was in acceptStatuses.\n const looksLikePlan = \"results\" in record && \"summary\" in record;\n const looksLikeEntitlement = \"has_access\" in record;\n if (!looksLikePlan && !looksLikeEntitlement) {\n throw PurpleturretApiError.fromResponse(response.status, parsed, response.headers.get(\"retry-after\"));\n }\n }\n if (response.status === 204 || parsed === undefined) return undefined as T;\n return parsed as T;\n }\n}\n\nfunction customerQuery(selector: CustomerSelector): { external_id?: string; email?: string } {\n const out: { external_id?: string; email?: string } = {};\n if (selector.externalId) out.external_id = selector.externalId;\n if (selector.email) out.email = selector.email;\n if (!out.external_id && !out.email) throw new TypeError(\"Provide externalId or email to identify the customer\");\n return out;\n}\n\nfunction stripUndefined(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(stripUndefined);\n if (value && typeof value === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {\n if (entry !== undefined) out[key] = stripUndefined(entry);\n }\n return out;\n }\n return value;\n}\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { DEFAULT_BASE_URL, PurpleturretClient } from \"@purpleturret/sdk\";\nimport dotenv from \"dotenv\";\n\nimport { CLI_VERSION } from \"../version.js\";\nimport { CredentialsStore, DEFAULT_PROFILE, credentialsPath, type Profile } from \"./credentials.js\";\nimport { CliError, EXIT, type ErrorContext } from \"./errors.js\";\nimport { Output, createPalette, shouldUseColor } from \"./output.js\";\n\n/** Flags accepted by every command. */\nexport interface GlobalFlags {\n config?: string;\n \"api-url\"?: string;\n apiUrl?: string;\n \"api-key\"?: string;\n apiKey?: string;\n profile?: string;\n json?: boolean;\n color?: boolean;\n verbose?: boolean;\n}\n\nexport const globalArgs = {\n config: { type: \"string\", description: \"Path to purpleturret.config.{ts,mts,js,mjs,json} (default: search up to the git root)\" },\n \"api-url\": { type: \"string\", description: \"API origin (default: PURPLETURRET_API_URL, saved profile, or https://api.purpleturret.com)\" },\n \"api-key\": { type: \"string\", description: \"Seller API key (default: PURPLETURRET_API_KEY, .env.local/.env, or saved profile)\" },\n profile: { type: \"string\", description: 'Credentials profile name (default: \"default\")' },\n json: { type: \"boolean\", description: \"Print machine-readable JSON on stdout\" },\n color: { type: \"boolean\", description: \"Colorize output (disable with --no-color or NO_COLOR)\" },\n verbose: { type: \"boolean\", description: \"Log requests and stack traces to stderr\" },\n} as const;\n\nlet stashedGlobals: GlobalFlags = {};\n\n/** Remember flags parsed on the root command so `pt --json push` works as well as `pt push --json`. */\nexport function stashGlobalFlags(flags: GlobalFlags): void {\n stashedGlobals = { ...flags };\n}\n\nexport function mergeGlobalFlags(flags: GlobalFlags): GlobalFlags {\n const merged: GlobalFlags = { ...stashedGlobals };\n for (const [key, value] of Object.entries(flags)) {\n if (value !== undefined) (merged as Record<string, unknown>)[key] = value;\n }\n return merged;\n}\n\nexport type Source = \"flag\" | \"env\" | \"profile\" | \"default\" | \"none\";\n\nexport interface CliContext extends ErrorContext {\n cwd: string;\n env: NodeJS.ProcessEnv;\n flags: GlobalFlags;\n json: boolean;\n verbose: boolean;\n out: Output;\n profileName: string;\n profile: Profile | null;\n credentials: CredentialsStore;\n apiUrl: string;\n apiUrlSource: \"flag\" | \"env\" | \"profile\" | \"default\";\n apiKey: string | null;\n credentialSource: \"flag\" | \"env\" | \"profile\" | \"none\";\n configPath: string | undefined;\n /** Build an authenticated client, or fail with exit 3 when no key is available. */\n client(): PurpleturretClient;\n /** Build a client for an explicit key (used by `login`). */\n clientFor(apiKey: string): PurpleturretClient;\n}\n\nexport interface CreateContextOptions {\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n stdout?: NodeJS.WritableStream;\n stderr?: NodeJS.WritableStream;\n credentialsFile?: string;\n}\n\nexport function loadDotenv(cwd: string, env: NodeJS.ProcessEnv): string[] {\n const loaded: string[] = [];\n for (const name of [\".env.local\", \".env\"]) {\n const path = join(cwd, name);\n if (!existsSync(path)) continue;\n dotenv.config({ path, override: false, quiet: true, processEnv: env as Record<string, string> });\n loaded.push(path);\n }\n return loaded;\n}\n\nexport async function createContext(rawFlags: GlobalFlags, options: CreateContextOptions = {}): Promise<CliContext> {\n const cwd = options.cwd ?? process.cwd();\n const env = options.env ?? process.env;\n const flags = mergeGlobalFlags(rawFlags);\n const json = Boolean(flags.json);\n const verbose = Boolean(flags.verbose);\n const palette = createPalette(\n shouldUseColor({ flag: flags.color, env, stream: (options.stderr as { isTTY?: boolean } | undefined) ?? process.stderr }),\n );\n const out = new Output({ json, verbose, palette, stdout: options.stdout, stderr: options.stderr });\n\n const loadedEnvFiles = loadDotenv(cwd, env);\n if (loadedEnvFiles.length) out.debug(`loaded ${loadedEnvFiles.join(\", \")}`);\n\n const profileName = flags.profile?.trim() || DEFAULT_PROFILE;\n const credentials = new CredentialsStore(options.credentialsFile ?? credentialsPath(env));\n const profile = await credentials.getProfile(profileName);\n\n const flagKey = (flags[\"api-key\"] ?? flags.apiKey)?.trim();\n const envKey = env.PURPLETURRET_API_KEY?.trim();\n let apiKey: string | null = null;\n let credentialSource: CliContext[\"credentialSource\"] = \"none\";\n if (flagKey) [apiKey, credentialSource] = [flagKey, \"flag\"];\n else if (envKey) [apiKey, credentialSource] = [envKey, \"env\"];\n else if (profile?.apiKey) [apiKey, credentialSource] = [profile.apiKey, \"profile\"];\n\n const flagUrl = (flags[\"api-url\"] ?? flags.apiUrl)?.trim();\n const envUrl = env.PURPLETURRET_API_URL?.trim();\n let apiUrl = DEFAULT_BASE_URL;\n let apiUrlSource: CliContext[\"apiUrlSource\"] = \"default\";\n if (flagUrl) [apiUrl, apiUrlSource] = [flagUrl, \"flag\"];\n else if (envUrl) [apiUrl, apiUrlSource] = [envUrl, \"env\"];\n else if (profile?.apiUrl) [apiUrl, apiUrlSource] = [profile.apiUrl, \"profile\"];\n apiUrl = apiUrl.replace(/\\/+$/, \"\");\n if (!/^https?:\\/\\//.test(apiUrl)) {\n throw new CliError(`Invalid API URL \"${apiUrl}\"; it must start with http:// or https://`, EXIT.USAGE, { code: \"invalid_api_url\" });\n }\n\n let announcedUrl = false;\n const announceUrl = () => {\n if (announcedUrl || apiUrlSource === \"default\") return;\n announcedUrl = true;\n out.info(palette.yellow(`Using API ${apiUrl} (from ${describeSource(apiUrlSource)})`));\n };\n\n const fetchImpl: typeof fetch = async (input, init) => {\n const url = typeof input === \"string\" ? input : input instanceof URL ? input.toString() : input.url;\n out.debug(`${init?.method ?? \"GET\"} ${url}`);\n const started = Date.now();\n const response = await fetch(input, init);\n out.debug(`→ ${response.status} ${response.headers.get(\"x-request-id\") ?? \"\"} (${Date.now() - started}ms)`.trimEnd());\n return response;\n };\n\n const clientFor = (key: string) => {\n announceUrl();\n return new PurpleturretClient({ apiKey: key, baseUrl: apiUrl, fetch: fetchImpl, userAgent: `purpleturret-cli/${CLI_VERSION}` });\n };\n\n const context: CliContext = {\n cwd,\n env,\n flags,\n json,\n verbose,\n out,\n profileName,\n profile,\n credentials,\n apiUrl,\n apiUrlSource,\n apiKey,\n credentialSource,\n configPath: flags.config,\n clientFor,\n client() {\n if (!apiKey) {\n throw new CliError(`No API key found for profile \"${profileName}\".`, EXIT.AUTH, {\n code: \"no_credentials\",\n hint: \"Run `purpleturret login`, pass --api-key, or set PURPLETURRET_API_KEY (also read from .env.local / .env in the current directory).\",\n });\n }\n return clientFor(apiKey);\n },\n };\n return context;\n}\n\nexport function describeSource(source: Source): string {\n switch (source) {\n case \"flag\":\n return \"command-line flag\";\n case \"env\":\n return \"environment\";\n case \"profile\":\n return \"saved profile\";\n case \"default\":\n return \"default\";\n default:\n return \"none\";\n }\n}\n","/** Keep in sync with package.json. */\nexport const CLI_VERSION = \"0.2.0\";\n","import { chmod, mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nexport interface Profile {\n apiKey: string;\n /** Only stored when the key was validated against a non-default API URL. */\n apiUrl?: string;\n email?: string;\n keyPrefix?: string;\n scopes?: string[];\n savedAt: string;\n}\n\nexport interface CredentialsFile {\n version: 1;\n profiles: Record<string, Profile>;\n}\n\nexport const DEFAULT_PROFILE = \"default\";\n\n/** `$XDG_CONFIG_HOME/purpleturret/credentials.json`, defaulting to `~/.config`. */\nexport function credentialsPath(env: NodeJS.ProcessEnv = process.env): string {\n const xdg = env.XDG_CONFIG_HOME?.trim();\n const home = env.HOME?.trim() || homedir();\n const configHome = xdg && xdg.length > 0 ? xdg : join(home, \".config\");\n return join(configHome, \"purpleturret\", \"credentials.json\");\n}\n\nexport class CredentialsStore {\n readonly path: string;\n\n constructor(path: string = credentialsPath()) {\n this.path = path;\n }\n\n async read(): Promise<CredentialsFile> {\n let text: string;\n try {\n text = await readFile(this.path, \"utf8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return { version: 1, profiles: {} };\n throw error;\n }\n try {\n const parsed = JSON.parse(text) as Partial<CredentialsFile>;\n if (!parsed || typeof parsed !== \"object\" || typeof parsed.profiles !== \"object\" || parsed.profiles === null) {\n return { version: 1, profiles: {} };\n }\n return { version: 1, profiles: parsed.profiles as Record<string, Profile> };\n } catch {\n throw new Error(`Credentials file ${this.path} is not valid JSON. Fix or delete it and run \\`purpleturret login\\` again.`);\n }\n }\n\n async write(file: CredentialsFile): Promise<void> {\n await mkdir(dirname(this.path), { recursive: true, mode: 0o700 });\n const tmp = `${this.path}.${process.pid}.tmp`;\n await writeFile(tmp, `${JSON.stringify(file, null, 2)}\\n`, { encoding: \"utf8\", mode: 0o600 });\n await chmod(tmp, 0o600);\n await rename(tmp, this.path);\n }\n\n async getProfile(name: string = DEFAULT_PROFILE): Promise<Profile | null> {\n const file = await this.read();\n return file.profiles[name] ?? null;\n }\n\n async saveProfile(name: string, profile: Profile): Promise<void> {\n const file = await this.read();\n file.profiles[name] = profile;\n await this.write(file);\n }\n\n /** Returns true when a profile was removed. */\n async deleteProfile(name: string): Promise<boolean> {\n const file = await this.read();\n if (!(name in file.profiles)) return false;\n delete file.profiles[name];\n await this.write(file);\n return true;\n }\n}\n","import { ConfigValidationError, PurpleturretApiError, PurpleturretNetworkError } from \"@purpleturret/sdk\";\n\nexport const EXIT = {\n OK: 0,\n ERROR: 1,\n USAGE: 2,\n AUTH: 3,\n CONFLICT: 4,\n ABORTED: 130,\n} as const;\n\nexport type ExitCode = (typeof EXIT)[keyof typeof EXIT];\n\nexport const DASHBOARD_SETTINGS_URL = \"https://purpleturret.com/dashboard/settings\";\n\nexport class CliError extends Error {\n override readonly name = \"CliError\";\n readonly exitCode: ExitCode;\n readonly hint: string | undefined;\n readonly code: string | undefined;\n override readonly cause: unknown;\n\n constructor(message: string, exitCode: ExitCode = EXIT.ERROR, options: { hint?: string; code?: string; cause?: unknown } = {}) {\n super(message);\n this.exitCode = exitCode;\n this.hint = options.hint;\n this.code = options.code;\n this.cause = options.cause;\n }\n}\n\nexport interface ErrorContext {\n apiUrl: string;\n apiUrlSource: \"flag\" | \"env\" | \"profile\" | \"default\";\n credentialSource?: \"flag\" | \"env\" | \"profile\" | \"none\";\n}\n\n/** Map any thrown value to a `CliError` with the exit code and actionable message from the plan. */\nexport function toCliError(error: unknown, ctx: ErrorContext): CliError {\n if (error instanceof CliError) return error;\n\n if (error instanceof ConfigValidationError) {\n return new CliError(error.message, EXIT.USAGE, { code: \"config_invalid\", cause: error });\n }\n\n if (error instanceof PurpleturretNetworkError) {\n const where = ctx.apiUrlSource === \"default\" ? \"\" : ` (from ${describeUrlSource(ctx.apiUrlSource)})`;\n return new CliError(error.message, EXIT.ERROR, {\n code: error.timedOut ? \"timeout\" : \"network_error\",\n hint: `Check that the API URL ${ctx.apiUrl}${where} is reachable, or override it with --api-url / PURPLETURRET_API_URL.`,\n cause: error,\n });\n }\n\n if (error instanceof PurpleturretApiError) return fromApiError(error, ctx);\n\n if (error instanceof Error) return new CliError(error.message, EXIT.ERROR, { cause: error });\n return new CliError(String(error), EXIT.ERROR);\n}\n\nfunction fromApiError(error: PurpleturretApiError, ctx: ErrorContext): CliError {\n const requestId = error.requestId ? ` (request ${error.requestId})` : \"\";\n const detailText = formatDetails(error.details);\n\n if (error.code === \"stripe_not_connected\") {\n return new CliError(`${error.message}${requestId}`, EXIT.ERROR, {\n code: error.code,\n hint: `Connect Stripe first in Dashboard → Settings → Payments: ${DASHBOARD_SETTINGS_URL}`,\n cause: error,\n });\n }\n\n switch (error.status) {\n case 401: {\n const source = ctx.credentialSource;\n const hint =\n source === \"flag\"\n ? \"The key passed with --api-key was rejected. Mint a new seller key in Dashboard → Settings → Developers.\"\n : source === \"env\"\n ? \"PURPLETURRET_API_KEY was rejected. Mint a new seller key in Dashboard → Settings → Developers and update your .env.local.\"\n : \"Run `purpleturret login` to store a valid seller key, or pass --api-key / set PURPLETURRET_API_KEY.\";\n return new CliError(`The API key was rejected (401 ${error.code})${requestId}.`, EXIT.AUTH, { code: error.code, hint, cause: error });\n }\n case 403: {\n if (error.code === \"forbidden_key_type\") {\n return new CliError(`This is a hosting key (pt_host_…), which cannot manage products or credits${requestId}.`, EXIT.AUTH, {\n code: error.code,\n hint: `Use a seller key (pt_sk_…) minted in Dashboard → Settings → Developers: ${DASHBOARD_SETTINGS_URL}`,\n cause: error,\n });\n }\n const required = pickString(error.details, \"required_scope\") ?? pickString(error.details, \"scope\");\n return new CliError(`${error.message} (403 ${error.code})${requestId}.`, EXIT.AUTH, {\n code: error.code,\n hint: required\n ? `The key is missing the ${required} scope. Mint a key with that scope in Dashboard → Settings → Developers: ${DASHBOARD_SETTINGS_URL}`\n : `Mint a seller key with the config:read, config:write, credits:read, credits:write and entitlements:read scopes in Dashboard → Settings → Developers: ${DASHBOARD_SETTINGS_URL}`,\n cause: error,\n });\n }\n case 402:\n return new CliError(`${error.message} (402 ${error.code})${requestId}.${detailText}`, EXIT.ERROR, { code: error.code, cause: error });\n case 404:\n return new CliError(`${error.message} (404 ${error.code})${requestId}.`, EXIT.ERROR, { code: error.code, cause: error });\n case 409: {\n if (error.code === \"immutable_field_changed\") {\n return new CliError(`${error.message} (409 immutable_field_changed)${requestId}.${detailText}`, EXIT.CONFLICT, {\n code: error.code,\n hint: \"price.currency, billing, slug and stripe.priceId are immutable after create. Declare the change under a new product key and archive the old one (push --prune).\",\n cause: error,\n });\n }\n if (error.code === \"idempotency_conflict\") {\n return new CliError(`${error.message} (409 idempotency_conflict)${requestId}.`, EXIT.CONFLICT, {\n code: error.code,\n hint: \"The Idempotency-Key was already used with a different request body. Run push again to generate a fresh key.\",\n cause: error,\n });\n }\n return new CliError(`${error.message} (409 ${error.code})${requestId}.${detailText}`, EXIT.CONFLICT, { code: error.code, cause: error });\n }\n case 422:\n return new CliError(`The API rejected the request (422 ${error.code})${requestId}: ${error.message}${detailText}`, EXIT.USAGE, {\n code: error.code,\n cause: error,\n });\n case 429:\n return new CliError(`Rate limited (429 ${error.code})${requestId}.`, EXIT.ERROR, {\n code: error.code,\n hint: error.retryAfter !== null ? `Retry after ${error.retryAfter}s.` : \"Slow down and retry shortly.\",\n cause: error,\n });\n default:\n if (error.status >= 500) {\n return new CliError(`The Purpleturret API returned ${error.status} ${error.code}${requestId}: ${error.message}`, EXIT.ERROR, {\n code: error.code,\n hint: \"This is a server-side failure. Retry in a moment; if it persists, contact support with the request id.\",\n cause: error,\n });\n }\n return new CliError(`${error.message} (${error.status} ${error.code})${requestId}.${detailText}`, EXIT.ERROR, {\n code: error.code,\n cause: error,\n });\n }\n}\n\nfunction describeUrlSource(source: ErrorContext[\"apiUrlSource\"]): string {\n switch (source) {\n case \"flag\":\n return \"--api-url\";\n case \"env\":\n return \"PURPLETURRET_API_URL\";\n case \"profile\":\n return \"the saved profile\";\n default:\n return \"the default\";\n }\n}\n\nfunction pickString(details: unknown, key: string): string | undefined {\n if (details && typeof details === \"object\" && key in details) {\n const value = (details as Record<string, unknown>)[key];\n return typeof value === \"string\" ? value : undefined;\n }\n return undefined;\n}\n\nexport function formatDetails(details: unknown): string {\n if (details === undefined || details === null) return \"\";\n if (typeof details === \"string\") return `\\n ${details}`;\n if (Array.isArray(details)) {\n if (details.length === 0) return \"\";\n return `\\n${details.map((entry) => ` - ${formatDetailEntry(entry)}`).join(\"\\n\")}`;\n }\n if (typeof details === \"object\") {\n const entries = Object.entries(details as Record<string, unknown>);\n if (entries.length === 0) return \"\";\n if (\"issues\" in (details as Record<string, unknown>) && Array.isArray((details as Record<string, unknown>).issues)) {\n return formatDetails((details as Record<string, unknown>).issues);\n }\n return `\\n${entries.map(([key, value]) => ` ${key}: ${typeof value === \"string\" ? value : JSON.stringify(value)}`).join(\"\\n\")}`;\n }\n return `\\n ${String(details)}`;\n}\n\nfunction formatDetailEntry(entry: unknown): string {\n if (entry && typeof entry === \"object\") {\n const record = entry as Record<string, unknown>;\n const path = typeof record.path === \"string\" ? record.path : Array.isArray(record.path) ? record.path.join(\".\") : undefined;\n const message = typeof record.message === \"string\" ? record.message : JSON.stringify(record);\n return path ? `${path}: ${message}` : message;\n }\n return String(entry);\n}\n","import { createColors } from \"picocolors\";\n\nimport type { CliError } from \"./errors.js\";\n\nexport type Paint = (text: string | number) => string;\n\nexport interface Palette {\n enabled: boolean;\n green: Paint;\n yellow: Paint;\n red: Paint;\n cyan: Paint;\n magenta: Paint;\n dim: Paint;\n bold: Paint;\n}\n\nexport function createPalette(enabled: boolean): Palette {\n const colors = createColors(enabled);\n return {\n enabled,\n green: colors.green,\n yellow: colors.yellow,\n red: colors.red,\n cyan: colors.cyan,\n magenta: colors.magenta,\n dim: colors.dim,\n bold: colors.bold,\n };\n}\n\n/** Color is on only for a TTY, unless `--no-color` or `NO_COLOR` turns it off. */\nexport function shouldUseColor(options: { flag?: boolean; env?: NodeJS.ProcessEnv; stream?: { isTTY?: boolean } } = {}): boolean {\n const env = options.env ?? process.env;\n const stream = options.stream ?? process.stdout;\n if (options.flag === false) return false;\n if (env.NO_COLOR !== undefined && env.NO_COLOR !== \"\") return false;\n if (env.FORCE_COLOR !== undefined && env.FORCE_COLOR !== \"\" && env.FORCE_COLOR !== \"0\") return true;\n return Boolean(stream.isTTY);\n}\n\nexport function isInteractive(): boolean {\n return Boolean(process.stdin.isTTY && process.stdout.isTTY);\n}\n\nexport interface OutputOptions {\n json: boolean;\n verbose: boolean;\n palette: Palette;\n stdout?: NodeJS.WritableStream;\n stderr?: NodeJS.WritableStream;\n}\n\n/** Human messages go to stderr; results (plans, tables, JSON) go to stdout. */\nexport class Output {\n readonly json: boolean;\n readonly verbose: boolean;\n readonly palette: Palette;\n private readonly stdout: NodeJS.WritableStream;\n private readonly stderr: NodeJS.WritableStream;\n\n constructor(options: OutputOptions) {\n this.json = options.json;\n this.verbose = options.verbose;\n this.palette = options.palette;\n this.stdout = options.stdout ?? process.stdout;\n this.stderr = options.stderr ?? process.stderr;\n }\n\n /** Write result lines to stdout (suppressed in --json mode unless `force`). */\n print(text: string, force = false): void {\n if (this.json && !force) return;\n this.stdout.write(`${text}\\n`);\n }\n\n /** Write a JSON document to stdout. */\n printJson(value: unknown): void {\n this.stdout.write(`${JSON.stringify(value, null, 2)}\\n`);\n }\n\n info(text: string): void {\n if (this.json) return;\n this.stderr.write(`${text}\\n`);\n }\n\n success(text: string): void {\n if (this.json) return;\n this.stderr.write(`${this.palette.green(\"✔\")} ${text}\\n`);\n }\n\n warn(text: string): void {\n if (this.json) return;\n this.stderr.write(`${this.palette.yellow(\"!\")} ${text}\\n`);\n }\n\n debug(text: string): void {\n if (!this.verbose) return;\n this.stderr.write(`${this.palette.dim(`[debug] ${text}`)}\\n`);\n }\n\n /** Report a fatal error. In --json mode the error is emitted as JSON on stdout. */\n fail(error: CliError): void {\n if (this.json) {\n this.stdout.write(\n `${JSON.stringify({ error: { code: error.code ?? \"error\", message: error.message, hint: error.hint, exit_code: error.exitCode } })}\\n`,\n );\n return;\n }\n this.stderr.write(`${this.palette.red(\"error:\")} ${error.message}\\n`);\n if (error.hint) this.stderr.write(`${this.palette.dim(\"hint:\")} ${error.hint}\\n`);\n if (this.verbose && error.cause instanceof Error && error.cause.stack) {\n this.stderr.write(`${this.palette.dim(error.cause.stack)}\\n`);\n }\n }\n}\n","import type { ProductInput, PurpleturretConfig } from \"@purpleturret/sdk\";\n\nexport type ConfigFormat = \"ts\" | \"json\";\n\nconst PRODUCT_KEY_ORDER: (keyof ProductInput)[] = [\n \"key\",\n \"name\",\n \"description\",\n \"price\",\n \"billing\",\n \"slug\",\n \"group\",\n \"credits\",\n \"delivery\",\n \"checkout\",\n \"theme\",\n \"stripe\",\n \"active\",\n \"buyerEmails\",\n];\n\nconst IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\n/** Serialize products into a `purpleturret.config.ts` (or `.json`) source string. */\nexport function renderConfigSource(products: ProductInput[], format: ConfigFormat = \"ts\"): string {\n if (format === \"json\") {\n const config: PurpleturretConfig = { products: products.map(orderProductKeys) };\n return `${JSON.stringify(config, null, 2)}\\n`;\n }\n\n const helpers = new Set<string>([\"defineConfig\", \"product\"]);\n const body = products.map((product) => renderProduct(product, helpers, 4)).join(\"\\n\");\n const imports = [\"defineConfig\", \"money\", \"product\", \"usd\"].filter((name) => helpers.has(name));\n const productsBlock = products.length ? `[\\n${body}\\n ]` : \"[]\";\n return [\n `import { ${imports.join(\", \")} } from \"@purpleturret/sdk\";`,\n \"\",\n \"export default defineConfig({\",\n ` products: ${productsBlock},`,\n \"});\",\n \"\",\n ].join(\"\\n\");\n}\n\n/** Starter config written by `purpleturret init`. */\nexport function renderStarterConfig(format: ConfigFormat = \"ts\"): string {\n const example: ProductInput = {\n key: \"pro_monthly\",\n name: \"Pro\",\n description: \"Everything you need to get started.\",\n price: { amount: 2900, currency: \"usd\" },\n billing: { type: \"recurring\", interval: \"month\" },\n group: { key: \"my_app\", tier: { key: \"pro\", name: \"Pro\", rank: 1 } },\n delivery: { method: \"none\" },\n };\n if (format === \"json\") return renderConfigSource([example], \"json\");\n return [\n \"// Purpleturret product catalog. Push with `purpleturret push`; preview with `purpleturret push --dry-run`.\",\n \"// Docs: https://purpleturret.com/docs/cli\",\n renderConfigSource([example], \"ts\"),\n ].join(\"\\n\");\n}\n\nfunction orderProductKeys(product: ProductInput): ProductInput {\n const out: Record<string, unknown> = {};\n for (const key of PRODUCT_KEY_ORDER) {\n if (product[key] !== undefined) out[key] = product[key];\n }\n return out as unknown as ProductInput;\n}\n\nfunction renderProduct(product: ProductInput, helpers: Set<string>, indent: number): string {\n const pad = \" \".repeat(indent);\n const inner = \" \".repeat(indent + 2);\n const lines: string[] = [`${pad}product({`];\n for (const key of PRODUCT_KEY_ORDER) {\n const value = product[key];\n if (value === undefined) continue;\n let rendered: string;\n if (key === \"price\") {\n rendered = renderPrice(product.price, helpers);\n } else {\n rendered = renderValue(value, indent + 2);\n }\n lines.push(`${inner}${key}: ${rendered},`);\n }\n lines.push(`${pad}}),`);\n return lines.join(\"\\n\");\n}\n\nfunction renderPrice(price: ProductInput[\"price\"], helpers: Set<string>): string {\n if (price.currency === \"usd\") {\n helpers.add(\"usd\");\n return `usd(${formatDollars(price.amount)})`;\n }\n helpers.add(\"money\");\n return `money(${price.amount}, ${JSON.stringify(price.currency)})`;\n}\n\nfunction formatDollars(cents: number): string {\n if (cents % 100 === 0) return String(cents / 100);\n return (cents / 100).toFixed(2);\n}\n\nfunction renderKey(key: string): string {\n return IDENTIFIER.test(key) ? key : JSON.stringify(key);\n}\n\nfunction isFlat(value: unknown): boolean {\n if (Array.isArray(value)) return value.every((entry) => entry === null || typeof entry !== \"object\");\n if (value && typeof value === \"object\")\n return Object.values(value as Record<string, unknown>).every((entry) => entry === null || typeof entry !== \"object\");\n return true;\n}\n\nexport function renderValue(value: unknown, indent: number): string {\n if (value === null) return \"null\";\n if (typeof value === \"string\") return JSON.stringify(value);\n if (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n if (typeof value === \"undefined\") return \"undefined\";\n const pad = \" \".repeat(indent);\n const inner = \" \".repeat(indent + 2);\n if (Array.isArray(value)) {\n if (value.length === 0) return \"[]\";\n if (isFlat(value)) {\n const inline = `[${value.map((entry) => renderValue(entry, indent + 2)).join(\", \")}]`;\n if (inline.length + indent <= 100) return inline;\n }\n return `[\\n${value.map((entry) => `${inner}${renderValue(entry, indent + 2)},`).join(\"\\n\")}\\n${pad}]`;\n }\n if (typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>).filter(([, entry]) => entry !== undefined);\n if (entries.length === 0) return \"{}\";\n if (isFlat(value)) {\n const inline = `{ ${entries.map(([key, entry]) => `${renderKey(key)}: ${renderValue(entry, indent + 2)}`).join(\", \")} }`;\n if (inline.length + indent <= 100) return inline;\n }\n return `{\\n${entries.map(([key, entry]) => `${inner}${renderKey(key)}: ${renderValue(entry, indent + 2)},`).join(\"\\n\")}\\n${pad}}`;\n }\n return JSON.stringify(value);\n}\n","import { DEFAULT_BASE_URL } from \"@purpleturret/sdk\";\nimport { isCancel } from \"@clack/prompts\";\nimport type { ArgsDef, CommandContext } from \"citty\";\n\nimport { createContext, type CliContext, type GlobalFlags } from \"./context.js\";\nimport { CliError, EXIT, toCliError } from \"./errors.js\";\nimport { Output, createPalette, shouldUseColor } from \"./output.js\";\n\nexport type Handler<A extends ArgsDef> = (ctx: CliContext, args: CommandContext<A>[\"args\"]) => Promise<void>;\n\n/**\n * Wrap a command body: build the CLI context from the parsed flags, run, and translate any error into\n * a message plus exit code. Errors never escape to citty (which would print a stack and exit 1).\n */\nexport function defineRun<A extends ArgsDef>(handler: Handler<A>) {\n return async (command: CommandContext<A>): Promise<void> => {\n let ctx: CliContext | undefined;\n try {\n ctx = await createContext(command.args as GlobalFlags);\n await handler(ctx, command.args);\n } catch (error) {\n const cliError = toCliError(error, ctx ?? { apiUrl: DEFAULT_BASE_URL, apiUrlSource: \"default\" });\n const out =\n ctx?.out ??\n new Output({\n json: Boolean((command.args as GlobalFlags).json),\n verbose: Boolean((command.args as GlobalFlags).verbose),\n palette: createPalette(shouldUseColor({ flag: (command.args as GlobalFlags).color })),\n });\n out.fail(cliError);\n process.exitCode = cliError.exitCode;\n }\n };\n}\n\n/** Convert a cancelled @clack prompt into an exit-130 error. */\nexport function unwrapPrompt<T>(value: T | symbol): T {\n if (isCancel(value)) throw new CliError(\"Aborted.\", EXIT.ABORTED, { code: \"aborted\" });\n return value as T;\n}\n","import { password } from \"@clack/prompts\";\nimport { defineCommand } from \"citty\";\n\nimport { globalArgs } from \"../lib/context.js\";\nimport { CliError, EXIT } from \"../lib/errors.js\";\nimport { isInteractive } from \"../lib/output.js\";\nimport { defineRun, unwrapPrompt } from \"../lib/run.js\";\n\nexport const login = defineCommand({\n meta: { name: \"login\", description: \"Validate a seller API key and save it to ~/.config/purpleturret/credentials.json\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n let apiKey = ctx.credentialSource === \"flag\" || ctx.credentialSource === \"env\" ? ctx.apiKey : null;\n if (!apiKey) {\n if (!isInteractive()) {\n throw new CliError(\"No API key provided and stdin is not a terminal.\", EXIT.USAGE, {\n code: \"missing_api_key\",\n hint: \"Pass --api-key <pt_sk_…> or set PURPLETURRET_API_KEY when logging in non-interactively.\",\n });\n }\n const entered = unwrapPrompt(\n await password({\n message: \"Paste your seller API key (pt_sk_…). Mint one in Dashboard → Settings → Developers.\",\n validate: (value) => (value && value.trim().length > 0 ? undefined : \"An API key is required\"),\n }),\n );\n apiKey = entered.trim();\n }\n if (apiKey.startsWith(\"pt_host_\")) {\n throw new CliError(\"That is a hosting key (pt_host_…). The CLI needs a seller key (pt_sk_…).\", EXIT.AUTH, { code: \"forbidden_key_type\" });\n }\n\n const client = ctx.clientFor(apiKey);\n const account = await client.account.get();\n const apiUrl = ctx.apiUrlSource === \"default\" ? undefined : ctx.apiUrl;\n await ctx.credentials.saveProfile(ctx.profileName, {\n apiKey,\n apiUrl,\n email: account.email,\n keyPrefix: account.key.prefix,\n scopes: account.key.scopes,\n savedAt: new Date().toISOString(),\n });\n\n if (ctx.json) {\n ctx.out.printJson({ profile: ctx.profileName, credentials_file: ctx.credentials.path, api_url: ctx.apiUrl, account });\n return;\n }\n const { palette } = ctx.out;\n ctx.out.success(\n `Logged in as ${palette.bold(account.email)} with key ${account.key.prefix}… (scopes: ${account.key.scopes.join(\", \") || \"none\"})`,\n );\n ctx.out.info(palette.dim(`Saved profile \"${ctx.profileName}\" to ${ctx.credentials.path} (mode 0600)`));\n if (!account.stripe.connected) ctx.out.warn(\"Stripe is not connected on this account yet; `push` cannot create products until it is.\");\n }),\n});\n","import { defineCommand } from \"citty\";\n\nimport { globalArgs } from \"../lib/context.js\";\nimport { defineRun } from \"../lib/run.js\";\n\nexport const logout = defineCommand({\n meta: { name: \"logout\", description: \"Remove the saved credentials profile\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const removed = await ctx.credentials.deleteProfile(ctx.profileName);\n if (ctx.json) {\n ctx.out.printJson({ profile: ctx.profileName, removed });\n return;\n }\n if (removed) ctx.out.success(`Removed profile \"${ctx.profileName}\" from ${ctx.credentials.path}`);\n else ctx.out.warn(`No profile \"${ctx.profileName}\" in ${ctx.credentials.path}; nothing to do.`);\n }),\n});\n","import { type Product } from \"@purpleturret/sdk\";\nimport { defineCommand } from \"citty\";\n\nimport { globalArgs } from \"../lib/context.js\";\nimport { describeBilling, formatMoney } from \"../lib/render.js\";\nimport { defineRun } from \"../lib/run.js\";\nimport { renderTable } from \"../lib/table.js\";\n\nconst list = defineCommand({\n meta: { name: \"list\", description: \"List products on the account (config-managed and dashboard-only)\" },\n args: {\n ...globalArgs,\n all: { type: \"boolean\", description: \"Include archived products\" },\n },\n run: defineRun(async (ctx, args) => {\n const client = ctx.client();\n const products: Product[] = [];\n let cursor: string | undefined;\n do {\n const page = await client.products.list({ cursor, limit: 100, includeArchived: Boolean(args.all) });\n products.push(...page.data);\n cursor = page.nextCursor ?? undefined;\n } while (cursor);\n\n if (ctx.json) {\n ctx.out.printJson({ products });\n return;\n }\n const { palette } = ctx.out;\n if (products.length === 0) {\n ctx.out.print(palette.dim(\"No products yet. Run `purpleturret init` and `purpleturret push` to create some.\"));\n return;\n }\n const rows = products.map((product) => [\n product.key ?? palette.dim(\"(unmanaged)\"),\n product.name,\n `${formatMoney(product.price)}${describeBilling(product.billing)}`,\n product.archivedAt ? palette.red(\"archived\") : product.active ? \"active\" : palette.yellow(\"inactive\"),\n product.url ?? palette.dim(\"—\"),\n ]);\n for (const line of renderTable([\"KEY\", \"NAME\", \"PRICE\", \"STATUS\", \"URL\"], rows, palette.dim)) ctx.out.print(line);\n }),\n});\n\nexport const products = defineCommand({\n meta: { name: \"products\", description: \"Inspect products on the account\" },\n args: { ...globalArgs },\n subCommands: { list },\n});\n","import type { Billing, ConfigPushResult, Money, PlanAction, PlanItem, PlanSummary, Product } from \"@purpleturret/sdk\";\n\nimport type { Palette } from \"./output.js\";\n\nexport const PRICE_AMOUNT_NOTE = \"new Stripe price; existing subscriptions keep the old price\";\n\nconst ACTION_ORDER: PlanAction[] = [\"conflict\", \"error\", \"create\", \"update\", \"archive\", \"unchanged\"];\n\nconst ACTION_SYMBOL: Record<PlanAction, string> = {\n create: \"+\",\n update: \"~\",\n unchanged: \"=\",\n archive: \"-\",\n conflict: \"!\",\n error: \"x\",\n};\n\nexport function formatMoney(money: Money): string {\n const currency = money.currency.toUpperCase();\n const major = (money.amount / 100).toFixed(2);\n if (currency === \"USD\") return `$${major}`;\n return `${major} ${currency}`;\n}\n\nexport function describeBilling(billing: Billing): string {\n if (billing.type === \"recurring\") return billing.interval === \"year\" ? \"/year\" : \"/month\";\n return \" one-time\";\n}\n\nexport function describeProduct(product: Pick<Product, \"name\" | \"price\" | \"billing\">): string {\n return `${product.name} — ${formatMoney(product.price)}${describeBilling(product.billing)}`;\n}\n\nexport function formatValue(value: unknown): string {\n if (value === undefined || value === null) return \"(none)\";\n if (typeof value === \"string\") return JSON.stringify(value);\n if (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n return JSON.stringify(value);\n}\n\nfunction paintFor(action: PlanAction, palette: Palette) {\n switch (action) {\n case \"create\":\n return palette.green;\n case \"update\":\n return palette.yellow;\n case \"archive\":\n return palette.red;\n case \"conflict\":\n case \"error\":\n return (text: string | number) => palette.bold(palette.red(text));\n default:\n return palette.dim;\n }\n}\n\nexport interface RenderOptions {\n palette: Palette;\n /** `plan` renders a dry-run; `apply` renders the applied result. */\n mode: \"plan\" | \"apply\";\n}\n\n/** Render one plan item (header line plus nested change lines). */\nexport function renderPlanItem(item: PlanItem, options: RenderOptions & { keyWidth?: number }): string[] {\n const { palette } = options;\n const paint = paintFor(item.action, palette);\n const keyWidth = Math.max(options.keyWidth ?? 0, item.key.length);\n const symbol = ACTION_SYMBOL[item.action];\n const label = item.action.padEnd(9);\n const key = item.key.padEnd(keyWidth);\n\n let detail = \"\";\n if (item.action === \"create\" && item.product) detail = describeProduct(item.product);\n else if (item.action === \"unchanged\" && item.product) detail = palette.dim(describeProduct(item.product));\n else if (item.action === \"archive\" && item.product) detail = describeProduct(item.product);\n else if ((item.action === \"conflict\" || item.action === \"error\") && item.error) detail = `${item.error.code}: ${item.error.message}`;\n\n const lines = [`${paint(`${symbol} ${label}`)} ${paint(key)}${detail ? ` ${detail}` : \"\"}`.trimEnd()];\n\n if (item.changes.length === 0) return lines;\n const pathWidth = Math.max(...item.changes.map((change) => change.path.length));\n for (const change of item.changes) {\n const note = change.note ?? (change.path === \"price.amount\" && item.action !== \"create\" ? PRICE_AMOUNT_NOTE : undefined);\n const isNew = change.from === undefined || change.from === null;\n const transition =\n item.action === \"create\" || (isNew && item.action !== \"archive\")\n ? formatValue(change.to)\n : `${formatValue(change.from)} → ${formatValue(change.to)}`;\n const line = ` ${paint(symbol)} ${change.path.padEnd(pathWidth)} ${transition}${note ? ` ${palette.dim(`(${note})`)}` : \"\"}`;\n lines.push(line);\n }\n return lines;\n}\n\n/** Sort conflicts and errors first, then creates/updates/archives, unchanged last. */\nexport function sortPlanItems(items: PlanItem[]): PlanItem[] {\n return [...items].sort((a, b) => {\n const order = ACTION_ORDER.indexOf(a.action) - ACTION_ORDER.indexOf(b.action);\n return order !== 0 ? order : a.key.localeCompare(b.key);\n });\n}\n\nexport function hasChanges(summary: PlanSummary): boolean {\n return summary.create + summary.update + summary.archive + summary.conflict + summary.error > 0;\n}\n\nexport function renderSummary(summary: PlanSummary, options: RenderOptions): string {\n const { palette, mode } = options;\n const parts: string[] = [];\n if (mode === \"plan\") {\n if (summary.create) parts.push(palette.green(`${summary.create} to create`));\n if (summary.update) parts.push(palette.yellow(`${summary.update} to update`));\n if (summary.archive) parts.push(palette.red(`${summary.archive} to archive`));\n if (summary.unchanged) parts.push(palette.dim(`${summary.unchanged} unchanged`));\n if (summary.conflict) parts.push(palette.bold(palette.red(`${summary.conflict} conflict${summary.conflict === 1 ? \"\" : \"s\"}`)));\n if (summary.error) parts.push(palette.bold(palette.red(`${summary.error} error${summary.error === 1 ? \"\" : \"s\"}`)));\n if (!hasChanges(summary))\n return palette.dim(`No changes. ${summary.unchanged} product${summary.unchanged === 1 ? \"\" : \"s\"} already match the config.`);\n return `Plan: ${parts.join(\", \")}.`;\n }\n if (summary.create) parts.push(palette.green(`${summary.create} created`));\n if (summary.update) parts.push(palette.yellow(`${summary.update} updated`));\n if (summary.archive) parts.push(palette.red(`${summary.archive} archived`));\n if (summary.unchanged) parts.push(palette.dim(`${summary.unchanged} unchanged`));\n if (summary.conflict) parts.push(palette.bold(palette.red(`${summary.conflict} conflict${summary.conflict === 1 ? \"\" : \"s\"}`)));\n if (summary.error) parts.push(palette.bold(palette.red(`${summary.error} failed`)));\n const prefix = summary.error || summary.conflict ? \"Apply incomplete\" : \"Apply complete\";\n return `${prefix}: ${parts.length ? parts.join(\", \") : \"nothing to do\"}.`;\n}\n\n/** Full plan/apply rendering: one block per product followed by a summary line. */\nexport function renderPlan(result: ConfigPushResult, options: RenderOptions): string[] {\n const items = sortPlanItems(result.results);\n const keyWidth = items.reduce((width, item) => Math.max(width, item.key.length), 0);\n const lines: string[] = [];\n for (const item of items) {\n lines.push(...renderPlanItem(item, { ...options, keyWidth }));\n }\n if (lines.length) lines.push(\"\");\n lines.push(renderSummary(result.summary, options));\n return lines;\n}\n","/** Render a plain-text table with left-aligned, space-padded columns. */\nexport function renderTable(headers: string[], rows: string[][], dimHeader: (text: string) => string = (text) => text): string[] {\n const widths = headers.map((header, index) => Math.max(header.length, ...rows.map((row) => (row[index] ?? \"\").length)));\n const line = (cells: string[]) =>\n cells\n .map((cell, index) => cell.padEnd(widths[index] ?? 0))\n .join(\" \")\n .trimEnd();\n return [dimHeader(line(headers)), ...rows.map(line)];\n}\n","import { existsSync } from \"node:fs\";\nimport { writeFile } from \"node:fs/promises\";\nimport { relative, resolve } from \"node:path\";\n\nimport { productToInput, type ProductInput } from \"@purpleturret/sdk\";\nimport { defineCommand } from \"citty\";\n\nimport { globalArgs } from \"../lib/context.js\";\nimport { CliError, EXIT } from \"../lib/errors.js\";\nimport { renderConfigSource, type ConfigFormat } from \"../lib/pull-writer.js\";\nimport { defineRun } from \"../lib/run.js\";\n\nexport const pull = defineCommand({\n meta: { name: \"pull\", description: \"Write the account's config-managed products to a local config file\" },\n args: {\n ...globalArgs,\n out: { type: \"string\", description: \"Output file (default: purpleturret.config.ts; a .json extension writes JSON)\" },\n force: { type: \"boolean\", description: \"Overwrite an existing file\" },\n },\n run: defineRun(async (ctx, args) => {\n const { products, unmanagedCount } = await ctx.client().config.get();\n const inputs = products.map(productToInput).filter((input): input is ProductInput => input !== null);\n\n const out = args.out?.trim();\n if (ctx.json && !out) {\n ctx.out.printJson({ products: inputs, unmanaged_count: unmanagedCount, written: null });\n return;\n }\n\n const target = resolve(ctx.cwd, out || \"purpleturret.config.ts\");\n const format: ConfigFormat = target.endsWith(\".json\") ? \"json\" : \"ts\";\n if (existsSync(target) && !args.force) {\n throw new CliError(`${relative(ctx.cwd, target) || target} already exists.`, EXIT.USAGE, {\n code: \"file_exists\",\n hint: \"Pass --force to overwrite it, or --out <path> to write elsewhere.\",\n });\n }\n await writeFile(target, renderConfigSource(inputs, format), \"utf8\");\n\n if (ctx.json) {\n ctx.out.printJson({ products: inputs, unmanaged_count: unmanagedCount, written: target });\n return;\n }\n ctx.out.success(`Wrote ${inputs.length} product${inputs.length === 1 ? \"\" : \"s\"} to ${relative(ctx.cwd, target) || target}`);\n if (unmanagedCount > 0) {\n ctx.out.info(\n ctx.out.palette.dim(\n `${unmanagedCount} dashboard-only product${unmanagedCount === 1 ? \"\" : \"s\"} without a key were skipped (see \\`purpleturret products list\\`).`,\n ),\n );\n }\n }),\n});\n","import { randomUUID } from \"node:crypto\";\nimport { relative } from \"node:path\";\n\nimport { confirm } from \"@clack/prompts\";\nimport { PurpleturretNetworkError, type ConfigPushResult, type ProductInput, type PurpleturretClient } from \"@purpleturret/sdk\";\nimport { defineCommand } from \"citty\";\n\nimport { loadConfig } from \"../lib/config-loader.js\";\nimport { globalArgs, type CliContext } from \"../lib/context.js\";\nimport { CliError, EXIT } from \"../lib/errors.js\";\nimport { isInteractive } from \"../lib/output.js\";\nimport { hasChanges, renderPlan } from \"../lib/render.js\";\nimport { defineRun, unwrapPrompt } from \"../lib/run.js\";\n\nexport const push = defineCommand({\n meta: { name: \"push\", description: \"Plan and apply the local config to your Purpleturret account\" },\n args: {\n ...globalArgs,\n prune: { type: \"boolean\", description: \"Archive config-managed products that are missing from the config\" },\n \"dry-run\": { type: \"boolean\", description: \"Show the plan without applying it\" },\n yes: { type: \"boolean\", alias: \"y\", description: \"Apply without asking for confirmation (required in CI)\" },\n },\n run: defineRun(async (ctx, args) => {\n const prune = Boolean(args.prune);\n const dryRun = Boolean(args[\"dry-run\"]);\n const yes = Boolean(args.yes);\n\n const loaded = await loadConfig(ctx.cwd, ctx.configPath);\n const products = loaded.config.products;\n const { palette } = ctx.out;\n ctx.out.info(\n palette.dim(`Config: ${relative(ctx.cwd, loaded.path) || loaded.path} (${products.length} product${products.length === 1 ? \"\" : \"s\"})`),\n );\n\n const client = ctx.client();\n const plan = await client.config.push({ products, prune, dryRun: true });\n for (const line of renderPlan(plan, { palette, mode: \"plan\" })) ctx.out.print(line);\n\n if (plan.summary.conflict > 0) {\n if (ctx.json) {\n ctx.out.printJson({ plan, applied: false, error: { code: \"conflict\", message: `${plan.summary.conflict} conflict(s); nothing applied` } });\n process.exitCode = EXIT.CONFLICT;\n return;\n }\n throw new CliError(`${plan.summary.conflict} conflict${plan.summary.conflict === 1 ? \"\" : \"s\"}; nothing was applied.`, EXIT.CONFLICT, {\n code: \"conflict\",\n hint: \"price.currency, billing, slug and stripe.priceId are immutable after create. Declare the change under a new product key and archive the old one with --prune.\",\n });\n }\n if (plan.summary.error > 0) {\n if (ctx.json) {\n ctx.out.printJson({ plan, applied: false, error: { code: \"plan_error\", message: `${plan.summary.error} product(s) cannot be applied` } });\n process.exitCode = EXIT.ERROR;\n return;\n }\n throw new CliError(`${plan.summary.error} product${plan.summary.error === 1 ? \"\" : \"s\"} cannot be applied; see the errors above.`, EXIT.ERROR, {\n code: \"plan_error\",\n });\n }\n\n if (!hasChanges(plan.summary)) {\n if (ctx.json) ctx.out.printJson({ plan, applied: false });\n return;\n }\n if (dryRun) {\n if (ctx.json) ctx.out.printJson({ plan, applied: false });\n else ctx.out.info(palette.dim(\"Dry run; nothing was applied. Run `purpleturret push` to apply.\"));\n return;\n }\n\n if (!yes) {\n if (!isInteractive() || ctx.json) {\n throw new CliError(\"Refusing to apply without confirmation because this is not an interactive terminal.\", EXIT.USAGE, {\n code: \"confirmation_required\",\n hint: \"Re-run with --yes to apply non-interactively, or --dry-run to only preview.\",\n });\n }\n const approved = unwrapPrompt(await confirm({ message: \"Apply these changes?\", initialValue: false }));\n if (!approved) throw new CliError(\"Aborted.\", EXIT.ABORTED, { code: \"aborted\" });\n }\n\n const idempotencyKey = `pt-push-${randomUUID()}`;\n ctx.out.debug(`Idempotency-Key ${idempotencyKey}`);\n const result = await applyWithRetry(ctx, client, { products, prune, idempotencyKey });\n\n ctx.out.print(\"\");\n for (const line of renderPlan(result, { palette, mode: \"apply\" })) ctx.out.print(line);\n if (ctx.json) ctx.out.printJson({ plan, result, applied: result.applied });\n\n if (result.summary.conflict > 0) {\n process.exitCode = EXIT.CONFLICT;\n if (!ctx.json)\n ctx.out.fail(new CliError(\"The apply hit a conflict; some products may have been applied.\", EXIT.CONFLICT, { code: \"conflict\" }));\n return;\n }\n if (result.summary.error > 0) {\n process.exitCode = EXIT.ERROR;\n if (!ctx.json) {\n ctx.out.fail(\n new CliError(\n `${result.summary.error} product${result.summary.error === 1 ? \"\" : \"s\"} failed to apply; the rest were applied.`,\n EXIT.ERROR,\n {\n code: \"apply_error\",\n hint: \"Fix the reported errors and run push again; completed steps are skipped.\",\n },\n ),\n );\n }\n return;\n }\n const urls = result.results.filter((item) => item.action === \"create\" && item.product?.url).map((item) => ` ${item.key} ${item.product?.url}`);\n if (urls.length) {\n ctx.out.info(\"\");\n ctx.out.info(palette.dim(\"Checkout links:\"));\n for (const line of urls) ctx.out.info(line);\n }\n }),\n});\n\nasync function applyWithRetry(\n ctx: CliContext,\n client: PurpleturretClient,\n options: { products: ProductInput[]; prune: boolean; idempotencyKey: string },\n): Promise<ConfigPushResult> {\n try {\n return await client.config.push({ products: options.products, prune: options.prune, dryRun: false, idempotencyKey: options.idempotencyKey });\n } catch (error) {\n if (!(error instanceof PurpleturretNetworkError)) throw error;\n ctx.out.warn(`Network error while applying (${error.message}); retrying once with the same Idempotency-Key…`);\n return await client.config.push({ products: options.products, prune: options.prune, dryRun: false, idempotencyKey: options.idempotencyKey });\n }\n}\n","import { existsSync, statSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { dirname, extname, isAbsolute, join, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\nimport { validateConfig, type PurpleturretConfig } from \"@purpleturret/sdk\";\nimport { createJiti } from \"jiti\";\n\nimport { CliError, EXIT } from \"./errors.js\";\n\nexport const CONFIG_FILENAMES = [\n \"purpleturret.config.ts\",\n \"purpleturret.config.mts\",\n \"purpleturret.config.js\",\n \"purpleturret.config.mjs\",\n \"purpleturret.config.json\",\n] as const;\n\nexport interface LoadedConfig {\n path: string;\n config: PurpleturretConfig;\n}\n\n/**\n * Locate the config file. An explicit path is resolved against `cwd` and must exist. Otherwise the\n * standard names are searched in `cwd` and each parent, stopping at the git root (the first\n * directory containing `.git`) or the filesystem root.\n */\nexport function findConfigFile(cwd: string, explicit?: string): string {\n if (explicit) {\n const path = isAbsolute(explicit) ? explicit : resolve(cwd, explicit);\n if (!existsSync(path) || !statSync(path).isFile()) {\n throw new CliError(`Config file not found: ${path}`, EXIT.USAGE, { code: \"config_not_found\" });\n }\n return path;\n }\n\n let dir = resolve(cwd);\n const searched: string[] = [];\n for (;;) {\n searched.push(dir);\n for (const name of CONFIG_FILENAMES) {\n const candidate = join(dir, name);\n if (existsSync(candidate) && statSync(candidate).isFile()) return candidate;\n }\n const isGitRoot = existsSync(join(dir, \".git\"));\n const parent = dirname(dir);\n if (isGitRoot || parent === dir) break;\n dir = parent;\n }\n throw new CliError(`No purpleturret.config.{ts,mts,js,mjs,json} found in ${searched[0]} or its parents up to the git root.`, EXIT.USAGE, {\n code: \"config_not_found\",\n hint: \"Run `purpleturret init` to create one, or pass --config <path>.\",\n });\n}\n\n/** Load and validate a config file. TypeScript/ESM files are transpiled on the fly with jiti. */\nexport async function loadConfigFile(path: string): Promise<LoadedConfig> {\n const raw = await importConfigModule(path);\n const candidate = pickConfigExport(raw, path);\n const config = validateConfig(candidate);\n return { path, config };\n}\n\nexport async function loadConfig(cwd: string, explicit?: string): Promise<LoadedConfig> {\n return loadConfigFile(findConfigFile(cwd, explicit));\n}\n\nasync function importConfigModule(path: string): Promise<unknown> {\n const ext = extname(path).toLowerCase();\n if (ext === \".json\") {\n const text = await readFile(path, \"utf8\");\n try {\n return JSON.parse(text);\n } catch (error) {\n throw new CliError(`${path} is not valid JSON: ${(error as Error).message}`, EXIT.USAGE, { code: \"config_invalid\", cause: error });\n }\n }\n if (![\".ts\", \".mts\", \".js\", \".mjs\", \".cts\", \".cjs\"].includes(ext)) {\n throw new CliError(`Unsupported config file extension \"${ext}\" (${path}). Use .ts, .mts, .js, .mjs or .json.`, EXIT.USAGE, {\n code: \"config_invalid\",\n });\n }\n const jiti = createJiti(import.meta.url, { interopDefault: false, moduleCache: false, fsCache: false });\n try {\n return await jiti.import(pathToFileURL(path).href);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new CliError(`Failed to load ${path}: ${message}`, EXIT.USAGE, { code: \"config_load_failed\", cause: error });\n }\n}\n\nfunction pickConfigExport(raw: unknown, path: string): unknown {\n if (raw && typeof raw === \"object\") {\n const record = raw as Record<string, unknown>;\n if (\"default\" in record && record.default !== undefined) {\n const def = record.default;\n // `export default { default: ... }` interop layering\n if (def && typeof def === \"object\" && !(\"products\" in (def as object)) && \"default\" in (def as Record<string, unknown>)) {\n return (def as Record<string, unknown>).default;\n }\n return def;\n }\n if (\"config\" in record && record.config !== undefined) return record.config;\n if (\"products\" in record) return raw;\n }\n throw new CliError(`${path} must export a config as its default export or a named \\`config\\` export (see \\`purpleturret init\\`).`, EXIT.USAGE, {\n code: \"config_invalid\",\n });\n}\n","import { relative } from \"node:path\";\n\nimport { defineCommand } from \"citty\";\n\nimport { loadConfig } from \"../lib/config-loader.js\";\nimport { describeSource, globalArgs } from \"../lib/context.js\";\nimport { renderSummary, sortPlanItems } from \"../lib/render.js\";\nimport { defineRun } from \"../lib/run.js\";\n\nexport const status = defineCommand({\n meta: { name: \"status\", description: \"Compare the local config with the account (dry run) and print a summary\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const loaded = await loadConfig(ctx.cwd, ctx.configPath);\n const plan = await ctx.client().config.push({ products: loaded.config.products, dryRun: true });\n if (ctx.json) {\n ctx.out.printJson({ config: loaded.path, api_url: ctx.apiUrl, summary: plan.summary, results: plan.results });\n return;\n }\n const { palette } = ctx.out;\n ctx.out.print(`${palette.dim(\"Config\")} ${relative(ctx.cwd, loaded.path) || loaded.path} (${loaded.config.products.length} products)`);\n ctx.out.print(`${palette.dim(\"API URL\")} ${ctx.apiUrlSource === \"default\" ? ctx.apiUrl : palette.yellow(ctx.apiUrl)}`);\n ctx.out.print(\n `${palette.dim(\"Credentials\")} ${describeSource(ctx.credentialSource)}${ctx.credentialSource === \"profile\" ? ` \"${ctx.profileName}\"` : \"\"}`,\n );\n ctx.out.print(\"\");\n for (const item of sortPlanItems(plan.results)) {\n if (item.action === \"unchanged\") continue;\n const detail = item.error ? ` ${item.error.code}: ${item.error.message}` : \"\";\n ctx.out.print(` ${item.action.padEnd(9)} ${item.key}${detail}`);\n }\n ctx.out.print(renderSummary(plan.summary, { palette, mode: \"plan\" }));\n if (plan.summary.create + plan.summary.update + plan.summary.archive > 0) ctx.out.info(palette.dim(\"Run `purpleturret push` to apply.\"));\n }),\n});\n","import { defineCommand } from \"citty\";\n\nimport { describeSource, globalArgs } from \"../lib/context.js\";\nimport { defineRun } from \"../lib/run.js\";\n\nexport const whoami = defineCommand({\n meta: { name: \"whoami\", description: \"Show the account and key behind the current credentials\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const account = await ctx.client().account.get();\n if (ctx.json) {\n ctx.out.printJson({ account, api_url: ctx.apiUrl, credential_source: ctx.credentialSource, profile: ctx.profileName });\n return;\n }\n const { palette } = ctx.out;\n const rows: [string, string][] = [\n [\"Account\", `${account.email}${account.name ? ` (${account.name})` : \"\"}`],\n [\"Key\", `${account.key.prefix}…${account.key.name ? ` \"${account.key.name}\"` : \"\"}`],\n [\"Scopes\", account.key.scopes.join(\", \") || palette.dim(\"none\")],\n [\n \"Stripe\",\n account.stripe.connected\n ? account.stripe.chargesEnabled\n ? \"connected\"\n : \"connected (charges not enabled)\"\n : palette.yellow(\"not connected\"),\n ],\n [\"PayPal\", account.paypal.connected ? \"connected\" : palette.dim(\"not connected\")],\n [\"API URL\", ctx.apiUrlSource === \"default\" ? ctx.apiUrl : palette.yellow(ctx.apiUrl)],\n [\"Credentials\", `${describeSource(ctx.credentialSource)}${ctx.credentialSource === \"profile\" ? ` \"${ctx.profileName}\"` : \"\"}`],\n ];\n const width = Math.max(...rows.map(([label]) => label.length));\n for (const [label, value] of rows) ctx.out.print(`${palette.dim(label.padEnd(width))} ${value}`);\n }),\n});\n","import { runCli } from \"./main.js\";\n\nawait runCli();\n"],"mappings":";AAAA,SAAS,iBAAAA,gBAAe,YAAY,iBAAkC;;;ACAtE,SAAS,cAAAC,mBAAkB;AAC3B,SAAS,aAAAC,kBAAiB;AAC1B,SAAS,UAAU,eAAe;;;ACD3B,IAAM,cAAc;;;ACD3B,SAAS,SAAS;AAKX,IAAM,cAAc;AAEpB,IAAM,eAAe;AAC5B,IAAM,oBAAoB;AAE1B,IAAM,cAAc;AAEb,IAAM,YAAY,EAAE,OAAO,EAAE,MAAM,aAAa,WAAW;AAC3D,IAAM,cAAc,EAAE,OAAO,EAAE,MAAM,aAAa,WAAW;AAE7D,IAAM,cAAc,EAAE,aAAa;AAAA,EACxC,QAAQ,EACL,OAAO,sEAAsE,EAC7E,IAAI,sEAAsE,EAC1E,IAAI,IAAI,+DAA+D;AAAA,EAC1E,UAAU,EACP,OAAO,EACP,KAAK,EACL,YAAY,EACZ,MAAM,cAAc,sCAAsC;AAC/D,CAAC;AAEM,IAAM,gBAAgB,EAAE,mBAAmB,QAAQ;AAAA,EACxD,EAAE,aAAa,EAAE,MAAM,EAAE,QAAQ,UAAU,EAAE,CAAC;AAAA,EAC9C,EAAE,aAAa,EAAE,MAAM,EAAE,QAAQ,WAAW,GAAG,UAAU,EAAE,KAAK,CAAC,SAAS,MAAM,CAAC,EAAE,CAAC;AACtF,CAAC;AAEM,IAAM,aAAa,EAAE,aAAa;AAAA,EACvC,KAAK;AAAA,EACL,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,GAAG,mBAAmB,EAAE,IAAI,EAAE;AAAA,EAC1D,MAAM,EAAE,OAAO,EAAE,IAAI,oBAAoB,EAAE,IAAI,CAAC;AAClD,CAAC;AAEM,IAAM,cAAc,EAAE,aAAa;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Sync","products","writeFile","defineCommand","defineCommand","defineCommand","defineCommand","defineCommand","defineCommand","products","existsSync","writeFile","relative","resolve","defineCommand","defineCommand","products","resolve","existsSync","relative","writeFile","relative","defineCommand","existsSync","readFile","dirname","join","resolve","resolve","existsSync","join","dirname","readFile","defineCommand","products","relative","relative","defineCommand","defineCommand","relative","defineCommand","defineCommand","defineCommand"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@purpleturret/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Sync purpleturret.config.ts with your Purpleturret account",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -32,8 +32,8 @@
|
|
|
32
32
|
"tsup": "^8.5.0",
|
|
33
33
|
"typescript": "^6",
|
|
34
34
|
"vitest": "^4.1.10",
|
|
35
|
-
"@purpleturret/
|
|
36
|
-
"@purpleturret/
|
|
35
|
+
"@purpleturret/sdk": "0.2.0",
|
|
36
|
+
"@purpleturret/config": "0.0.0"
|
|
37
37
|
},
|
|
38
38
|
"scripts": {
|
|
39
39
|
"build": "tsup",
|