@kelviq/cli 0.3.1 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -20,32 +20,45 @@ kelviq --help
20
20
 
21
21
  ## Commands
22
22
 
23
- Everything else (catalog browse commands, browser-handoff login) is not
24
- built yet — see "What's not here yet" below.
23
+ Browser-handoff login is not built yet — see "What's not here yet" below.
25
24
 
26
25
  | Command | What it does |
27
26
  |---|---|
28
27
  | `kelviq init` | Writes a starter `kelviq.config.ts` to the current directory. |
29
28
  | `kelviq login` | Pastes a Kelviq Server API key from the dashboard and stores it locally. |
30
29
  | `kelviq logout` | Removes a stored API key. |
31
- | `kelviq env` | Shows which environment and keys are configured — no live validation. `--json` for scripting. |
30
+ | `kelviq env` | Shows which environment and keys are configured, and which env files were read. `--check` makes one authenticated read per key. `--json` for scripting. |
32
31
  | `kelviq pull` | Fetches the remote catalog and writes it to `kelviq.config.ts`. |
33
32
  | `kelviq push` | Diffs `kelviq.config.ts` against an environment, confirms, and applies drafts-only writes. `--dry-run --json` for scripting. |
34
33
  | `kelviq promote` | Diffs the sandbox catalog against production and applies the same way — no local config file involved. |
34
+ | `kelviq status` | Shows the live catalog: products, features, and each plan's latest version with price and entitlement counts. `--json` for scripting. |
35
+ | `kelviq webhook add` / `list` | Registers the app's webhook endpoint and writes its signing secret into an env file without printing it. |
36
+ | `kelviq discount create` / `list` | Creates a discount code (product by identifier) after restating it for confirmation. |
35
37
 
36
38
  ```bash
37
39
  kelviq init # write kelviq.config.ts in the current directory
40
+ kelviq init --template usage # or a usage-based / license-key starter (saas is the default)
38
41
  kelviq login # paste a sandbox key (default env)
39
42
  kelviq login --prod # paste a production key
40
43
  kelviq logout --all # remove both stored keys
41
44
  kelviq env # show configured environment + key status
45
+ kelviq env --check # ...and make one authenticated read per key
42
46
  kelviq pull # pull the sandbox catalog into kelviq.config.ts
43
47
  kelviq pull --prod --force # pull production, overwriting an existing file
44
48
  kelviq push --dry-run # preview what push would change, no writes
45
49
  kelviq push --yes # push to sandbox non-interactively
46
50
  kelviq promote --dry-run # preview sandbox -> production
51
+ kelviq status # the live catalog, plan by plan
52
+ kelviq webhook add https://app.example.com/api/kelviq/webhooks \
53
+ --events checkout.completed,subscription.created --write-secret .env.local
54
+ kelviq discount create --name "Launch" --code LAUNCH20 --percent 20 \
55
+ --duration repeating --months 3 --product my-app --plans pro
47
56
  ```
48
57
 
58
+ Every command reads `KELVIQ_*` variables from `.env.local` then `.env` in the
59
+ working directory (the shell always wins), or from `--env-file <path>` when
60
+ given; `--no-env-file` turns that off.
61
+
49
62
  Run `kelviq push --help` / `kelviq promote --help` for the full flag set:
50
63
  `--publish`, `--migrate-features`, `--migrate-pricing`, `--prune`,
51
64
  `--allow-prod-prune`, `--verbose`, `--json`.
@@ -55,9 +68,9 @@ environment mode matching the target (sandbox by default, production with
55
68
  `--prod`), and tries to open it in your default browser, then prompts for
56
69
  the key on stdin (an interactive terminal masks each character as `*` while
57
70
  you type or paste, then reports how many characters it received). Kelviq has no
58
- key-introspection endpoint, so neither `login` nor `env` can confirm a key
59
- is actually valid or show which org it belongs to — `env` reports only what's
60
- configured locally.
71
+ key-introspection endpoint, so `login` cannot show which org a key belongs
72
+ to; `kelviq env --check` confirms a key is accepted by making one
73
+ authenticated read against its environment.
61
74
 
62
75
  ## `kelviq.config.ts`
63
76
 
@@ -282,8 +295,6 @@ and `--prune` only ever archives resources carrying the CLI's own
282
295
 
283
296
  ## What's not here yet
284
297
 
285
- - **Catalog browse commands** (list/show products, features, plans without a
286
- full `pull`) — not built yet.
287
298
  - **Browser-handoff login** (`whoami`, org display) — needs pairing-flow and
288
299
  key-introspection endpoints that don't exist on the platform yet; `login`
289
300
  is paste-key only for now.
package/dist/cli.js CHANGED
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { Command } from 'commander';
3
3
  import { initStyle } from './cli-ui/style.js';
4
+ import { registerDiscountCommand } from './commands/discount.js';
4
5
  import { registerEnvCommand } from './commands/env.js';
5
6
  import { registerInitCommand } from './commands/init.js';
6
7
  import { registerLoginCommand } from './commands/login.js';
@@ -8,7 +9,13 @@ import { registerLogoutCommand } from './commands/logout.js';
8
9
  import { registerPromoteCommand } from './commands/promote.js';
9
10
  import { registerPullCommand } from './commands/pull.js';
10
11
  import { registerPushCommand } from './commands/push.js';
12
+ import { registerStatusCommand } from './commands/status.js';
13
+ import { registerWebhookCommand } from './commands/webhook.js';
14
+ import { applyEnvFiles } from './core/env-file.js';
11
15
  import { getPackageVersion } from './core/version.js';
16
+ function collect(value, previous) {
17
+ return [...previous, value];
18
+ }
12
19
  const program = new Command();
13
20
  program
14
21
  .name('kelviq')
@@ -16,7 +23,11 @@ program
16
23
  .version(getPackageVersion())
17
24
  // CLI plan 014: must be typed before the subcommand name (e.g. `kelviq
18
25
  // --no-color push`) — a root-level option, same as `--version`/`--help`.
19
- .option('--no-color', 'Disable colored output');
26
+ .option('--no-color', 'Disable colored output')
27
+ // KELVIQ_* variables are read from `.env.local` then `.env` in the working
28
+ // directory (never overriding the shell), or from `--env-file` paths only.
29
+ .option('--env-file <path>', 'Load KELVIQ_* variables from this dotenv file instead of .env.local/.env (repeatable)', collect, [])
30
+ .option('--no-env-file', 'Do not read .env.local or .env from the working directory');
20
31
  // CLI plan 014: the ONE place style.ts's singleton is initialized — after
21
32
  // commander has parsed `--no-color` but before any command's action runs.
22
33
  // `optsWithGlobals()` reads the flag off the root program regardless of
@@ -29,6 +40,16 @@ program
29
40
  // `stream: { isTTY: false }` bypasses the TTY branch too.
30
41
  program.hook('preAction', (_thisCommand, actionCommand) => {
31
42
  const opts = actionCommand.optsWithGlobals();
43
+ if (opts.envFile !== false) {
44
+ const explicit = Array.isArray(opts.envFile) ? opts.envFile : [];
45
+ try {
46
+ applyEnvFiles(process.env, { cwd: process.cwd(), explicit });
47
+ }
48
+ catch (err) {
49
+ process.stderr.write(`${err instanceof Error ? err.message : String(err)}\n`);
50
+ process.exit(1);
51
+ }
52
+ }
32
53
  if (opts.json) {
33
54
  initStyle({ noColorFlag: true, stream: { isTTY: false }, env: {} });
34
55
  }
@@ -47,5 +68,8 @@ registerInitCommand(program);
47
68
  registerPullCommand(program);
48
69
  registerPushCommand(program);
49
70
  registerPromoteCommand(program);
71
+ registerStatusCommand(program);
72
+ registerWebhookCommand(program);
73
+ registerDiscountCommand(program);
50
74
  program.parseAsync(process.argv);
51
75
  //# sourceMappingURL=cli.js.map
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACvD,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AACzD,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAC3D,OAAO,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AAC7D,OAAO,EAAE,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AAC/D,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AACzD,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AACzD,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAEtD,MAAM,OAAO,GAAG,IAAI,OAAO,EAAE,CAAC;AAC9B,OAAO;KACJ,IAAI,CAAC,QAAQ,CAAC;KACd,WAAW,CAAC,wDAAwD,CAAC;KACrE,OAAO,CAAC,iBAAiB,EAAE,CAAC;IAC7B,uEAAuE;IACvE,yEAAyE;KACxE,MAAM,CAAC,YAAY,EAAE,wBAAwB,CAAC,CAAC;AAElD,0EAA0E;AAC1E,0EAA0E;AAC1E,wEAAwE;AACxE,6CAA6C;AAC7C,E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C,OAAO,CAAC,CAAC;AAC7B,mBAAmB,CAAC,OAAO,CAAC,CAAC;AAC7B,sBAAsB,CAAC,OAAO,CAAC,CAAC;AAChC,qBAAqB,CAAC,OAAO,CAAC,CAAC;AAC/B,sBAAsB,CAAC,OAAO,CAAC,CAAC;AAChC,uBAAuB,CAAC,OAAO,CAAC,CAAC;AAEjC,OAAO,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC"}
@@ -0,0 +1,56 @@
1
+ import { Command } from 'commander';
2
+ export interface DiscountIO {
3
+ stdin: NodeJS.ReadableStream;
4
+ stdout: NodeJS.WritableStream;
5
+ stderr: NodeJS.WritableStream;
6
+ isTTY: boolean;
7
+ env?: NodeJS.ProcessEnv;
8
+ configDir?: string;
9
+ }
10
+ export interface DiscountListOptions {
11
+ search?: string;
12
+ prod?: boolean;
13
+ json?: boolean;
14
+ }
15
+ export interface DiscountCreateOptions {
16
+ name?: string;
17
+ code?: string;
18
+ percent?: string;
19
+ amount?: string;
20
+ currency?: string;
21
+ duration?: string;
22
+ months?: string;
23
+ product?: string;
24
+ plans?: string;
25
+ maxRedemptions?: string;
26
+ redeemBy?: string;
27
+ prod?: boolean;
28
+ yes?: boolean;
29
+ json?: boolean;
30
+ }
31
+ export interface DiscountCreateBody {
32
+ discountType: 'PERCENTAGE' | 'FIXED_AMOUNT';
33
+ name: string;
34
+ code: string;
35
+ percentageOff?: number;
36
+ amountOff?: string;
37
+ currency?: string;
38
+ duration?: 'ONCE' | 'REPEATING' | 'FOREVER';
39
+ durationInMonths?: number;
40
+ maxRedemptions?: number;
41
+ redeemBy?: string;
42
+ appliesTo?: Array<{
43
+ product: string;
44
+ plans?: string[];
45
+ }>;
46
+ }
47
+ export declare function runDiscountList(options: DiscountListOptions, io: DiscountIO): Promise<number>;
48
+ /** Turns the flags into the API body, or returns the first validation error. Pure — the product identifier is resolved by the caller. */
49
+ export declare function buildDiscountBody(options: DiscountCreateOptions, productUuid?: string): {
50
+ body: DiscountCreateBody;
51
+ } | {
52
+ error: string;
53
+ };
54
+ export declare function describeDiscount(body: DiscountCreateBody, productIdentifier: string | undefined): string[];
55
+ export declare function runDiscountCreate(options: DiscountCreateOptions, io: DiscountIO): Promise<number>;
56
+ export declare function registerDiscountCommand(program: Command): void;
@@ -0,0 +1,251 @@
1
+ import { authHintLine, messageCarriesAuthStatus } from '../cli-ui/auth-hint.js';
2
+ import { loadCliConfig, resolveEnv } from '../core/config.js';
3
+ import { KelviqHttpClient } from '../core/http.js';
4
+ import { fetchAllPages } from '../sync/fetch-catalog.js';
5
+ import { closePrompt, confirm } from './push-shared.js';
6
+ const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
7
+ const CODE_PATTERN = /^[A-Z0-9]+$/;
8
+ function client(io, prod) {
9
+ const config = loadCliConfig(io.env ?? process.env, io.configDir);
10
+ const resolved = resolveEnv(config, prod);
11
+ const http = new KelviqHttpClient({
12
+ serverApiKey: resolved.key,
13
+ baseUrl: resolved.baseUrl,
14
+ edgeUrl: resolved.edgeUrl,
15
+ userAgent: config.userAgent,
16
+ });
17
+ return { http, envName: resolved.envName };
18
+ }
19
+ function failure(command, err, options, io) {
20
+ const message = err instanceof Error ? err.message : String(err);
21
+ if (options.json) {
22
+ io.stdout.write(`${JSON.stringify({ error: `${command} failed: ${message}` })}\n`);
23
+ }
24
+ else {
25
+ io.stderr.write(`${command} failed: ${message}\n`);
26
+ if (messageCarriesAuthStatus(message))
27
+ io.stderr.write(`${authHintLine()}\n`);
28
+ }
29
+ return 1;
30
+ }
31
+ export async function runDiscountList(options, io) {
32
+ try {
33
+ const { http, envName } = client(io, Boolean(options.prod));
34
+ const discounts = await fetchAllPages(http, {
35
+ path: '/discount/',
36
+ query: { page_size: 100, search: options.search },
37
+ label: 'discounts',
38
+ });
39
+ if (options.json) {
40
+ io.stdout.write(`${JSON.stringify({ environment: envName, discounts })}\n`);
41
+ return 0;
42
+ }
43
+ io.stdout.write(`Environment : ${envName}\n`);
44
+ if (discounts.length === 0) {
45
+ io.stdout.write('No discount codes.\n');
46
+ return 0;
47
+ }
48
+ for (const d of discounts) {
49
+ const amount = d.discountType === 'PERCENTAGE' ? `${String(d.percentageOff)}% off` : `${String(d.amountOff)} ${String(d.currency ?? '')} off`;
50
+ const duration = d.duration === 'REPEATING' ? `repeating for ${String(d.durationInMonths)} billing periods` : String(d.duration ?? '').toLowerCase();
51
+ const active = d.isActive === false ? 'disabled' : 'active';
52
+ io.stdout.write(`${String(d.code)} ${amount} ${duration} ${active} id ${String(d.id)}\n`);
53
+ }
54
+ return 0;
55
+ }
56
+ catch (err) {
57
+ return failure('discount list', err, options, io);
58
+ }
59
+ }
60
+ /** Turns the flags into the API body, or returns the first validation error. Pure — the product identifier is resolved by the caller. */
61
+ export function buildDiscountBody(options, productUuid) {
62
+ const name = options.name?.trim();
63
+ const code = options.code?.trim();
64
+ if (!name)
65
+ return { error: 'pass --name (shown on the customer\'s invoice).' };
66
+ if (!code)
67
+ return { error: 'pass --code (what customers enter at checkout).' };
68
+ if (!CODE_PATTERN.test(code))
69
+ return { error: `--code must be uppercase letters and digits only (got "${code}").` };
70
+ const hasPercent = options.percent !== undefined;
71
+ const hasAmount = options.amount !== undefined;
72
+ if (hasPercent === hasAmount)
73
+ return { error: 'pass exactly one of --percent <n> or --amount <x> --currency <code>.' };
74
+ const body = hasPercent ? { discountType: 'PERCENTAGE', name, code } : { discountType: 'FIXED_AMOUNT', name, code };
75
+ if (hasPercent) {
76
+ const percent = Number(options.percent);
77
+ if (!Number.isInteger(percent) || percent <= 0 || percent > 100)
78
+ return { error: `--percent must be a whole number from 1 to 100 (got "${options.percent}").` };
79
+ body.percentageOff = percent;
80
+ }
81
+ else {
82
+ const amount = Number(options.amount);
83
+ if (!Number.isFinite(amount) || amount <= 0)
84
+ return { error: `--amount must be a positive number (got "${options.amount}").` };
85
+ if (!options.currency)
86
+ return { error: '--amount needs --currency <ISO code>, e.g. --currency USD.' };
87
+ body.amountOff = amount.toFixed(2);
88
+ body.currency = options.currency.toUpperCase();
89
+ }
90
+ if (options.duration !== undefined) {
91
+ const duration = options.duration.toUpperCase();
92
+ if (duration !== 'ONCE' && duration !== 'REPEATING' && duration !== 'FOREVER') {
93
+ return { error: `--duration must be once, repeating or forever (got "${options.duration}").` };
94
+ }
95
+ body.duration = duration;
96
+ }
97
+ if (options.months !== undefined) {
98
+ const months = Number(options.months);
99
+ if (!Number.isInteger(months) || months <= 0)
100
+ return { error: `--months must be a positive whole number (got "${options.months}").` };
101
+ if (body.duration !== 'REPEATING')
102
+ return { error: '--months only applies with --duration repeating.' };
103
+ body.durationInMonths = months;
104
+ }
105
+ else if (body.duration === 'REPEATING') {
106
+ return { error: '--duration repeating needs --months <n> (billing periods, not calendar months).' };
107
+ }
108
+ if (options.maxRedemptions !== undefined) {
109
+ const max = Number(options.maxRedemptions);
110
+ if (!Number.isInteger(max) || max <= 0)
111
+ return { error: `--max-redemptions must be a positive whole number (got "${options.maxRedemptions}").` };
112
+ body.maxRedemptions = max;
113
+ }
114
+ if (options.redeemBy !== undefined) {
115
+ const when = new Date(options.redeemBy);
116
+ if (Number.isNaN(when.getTime()))
117
+ return { error: `--redeem-by must be an ISO 8601 date/time (got "${options.redeemBy}").` };
118
+ body.redeemBy = when.toISOString();
119
+ }
120
+ if (options.plans !== undefined && options.product === undefined)
121
+ return { error: '--plans needs --product <identifier>.' };
122
+ if (productUuid) {
123
+ const plans = (options.plans ?? '').split(',').map((p) => p.trim()).filter((p) => p.length > 0);
124
+ body.appliesTo = [{ product: productUuid, ...(plans.length > 0 ? { plans } : {}) }];
125
+ }
126
+ return { body };
127
+ }
128
+ export function describeDiscount(body, productIdentifier) {
129
+ const lines = [
130
+ ` code: ${body.code}`,
131
+ ` name: ${body.name}`,
132
+ ` discount: ${body.discountType === 'PERCENTAGE' ? `${body.percentageOff}% off` : `${body.amountOff} ${body.currency} off`}`,
133
+ ` duration: ${body.duration === 'REPEATING' ? `repeating for ${body.durationInMonths} billing periods (not calendar months)` : (body.duration ?? 'ONCE').toLowerCase()}`,
134
+ ];
135
+ if (body.appliesTo) {
136
+ const plans = body.appliesTo[0]?.plans;
137
+ lines.push(` applies to: product ${productIdentifier ?? body.appliesTo[0]?.product}${plans && plans.length > 0 ? `, plans ${plans.join(', ')}` : ' (all plans)'}`);
138
+ }
139
+ else {
140
+ lines.push(' applies to: every product');
141
+ }
142
+ if (body.maxRedemptions !== undefined)
143
+ lines.push(` max uses: ${body.maxRedemptions}`);
144
+ if (body.redeemBy !== undefined)
145
+ lines.push(` redeem by: ${body.redeemBy}`);
146
+ lines.push(' after creation only enabling/disabling can change; anything else means a new code');
147
+ return lines;
148
+ }
149
+ export async function runDiscountCreate(options, io) {
150
+ const write = (s) => io.stdout.write(s);
151
+ const writeErr = (s) => io.stderr.write(s);
152
+ try {
153
+ const { http, envName } = client(io, Boolean(options.prod));
154
+ let productUuid;
155
+ if (options.product !== undefined) {
156
+ if (UUID_PATTERN.test(options.product)) {
157
+ productUuid = options.product;
158
+ }
159
+ else {
160
+ // The product retrieve endpoint takes the UUID only (live-verified
161
+ // 2026-09-18: an identifier in the path is a 404), so look the
162
+ // identifier up through the list endpoint's search instead.
163
+ const found = await http.request({
164
+ method: 'GET',
165
+ path: '/catalog/products/',
166
+ query: { search: options.product, page_size: 100 },
167
+ auth: 'server',
168
+ });
169
+ if (!found.ok)
170
+ throw new Error(`could not resolve product "${options.product}" in ${envName}: ${found.error.message}`);
171
+ const match = (found.data.results ?? []).find((p) => p.identifier === options.product);
172
+ if (!match?.id)
173
+ throw new Error(`could not resolve product "${options.product}" in ${envName}: no product has that identifier`);
174
+ productUuid = match.id;
175
+ }
176
+ }
177
+ const built = buildDiscountBody(options, productUuid);
178
+ if ('error' in built) {
179
+ writeErr(`discount create failed: ${built.error}\n`);
180
+ return 1;
181
+ }
182
+ const { body } = built;
183
+ if (!options.yes) {
184
+ const summary = [`Create ${envName} discount code:`, ...describeDiscount(body, options.product)].join('\n');
185
+ if (!io.isTTY) {
186
+ writeErr(`${summary}\nRefusing to write without confirmation in a non-interactive session. Pass --yes to proceed.\n`);
187
+ return 1;
188
+ }
189
+ write(`${summary}\n`);
190
+ const ok = await confirm('Create it? [y/N] ', io);
191
+ if (!ok) {
192
+ write('Aborted; nothing was created.\n');
193
+ return 1;
194
+ }
195
+ }
196
+ const created = await http.request({ method: 'POST', path: '/discount/', body, auth: 'server' });
197
+ if (!created.ok)
198
+ throw new Error(`${created.error.message} (${created.error.status})`);
199
+ if (options.json) {
200
+ write(`${JSON.stringify({ environment: envName, discount: created.data })}\n`);
201
+ return 0;
202
+ }
203
+ write(`Created ${envName} discount ${body.code} (id ${String(created.data.id)})\n`);
204
+ return 0;
205
+ }
206
+ catch (err) {
207
+ return failure('discount create', err, options, io);
208
+ }
209
+ finally {
210
+ closePrompt(io);
211
+ }
212
+ }
213
+ export function registerDiscountCommand(program) {
214
+ const discount = program.command('discount').description('Manage discount codes: list them, or create one with the product given by identifier.');
215
+ const io = () => ({
216
+ stdin: process.stdin,
217
+ stdout: process.stdout,
218
+ stderr: process.stderr,
219
+ isTTY: Boolean(process.stdin.isTTY),
220
+ });
221
+ discount
222
+ .command('list')
223
+ .description('List discount codes.')
224
+ .option('--search <text>', 'Filter by name or code')
225
+ .option('--prod', 'Read the production environment instead of sandbox', false)
226
+ .option('--json', 'Machine-readable output', false)
227
+ .action(async (opts) => {
228
+ process.exitCode = await runDiscountList(opts, io());
229
+ });
230
+ discount
231
+ .command('create')
232
+ .description('Create a discount code after restating it for confirmation. Percentage: --percent 20. Fixed: --amount 10 --currency USD.')
233
+ .requiredOption('--name <text>', "Name shown on the customer's invoice")
234
+ .requiredOption('--code <CODE>', 'The code customers enter (uppercase letters and digits)')
235
+ .option('--percent <n>', 'Percentage off, 1-100')
236
+ .option('--amount <x>', 'Fixed amount off, in normal currency units (needs --currency)')
237
+ .option('--currency <code>', 'ISO currency code for --amount, e.g. USD')
238
+ .option('--duration <once|repeating|forever>', 'How long the discount applies (default: once)')
239
+ .option('--months <n>', 'With --duration repeating: number of billing periods (not calendar months)')
240
+ .option('--product <identifier>', 'Limit the code to one product (identifier or UUID)')
241
+ .option('--plans <list>', 'With --product: comma-separated plan identifiers to limit the code to')
242
+ .option('--max-redemptions <n>', 'Total number of times the code can be used')
243
+ .option('--redeem-by <datetime>', 'ISO 8601 date/time after which the code can no longer be redeemed')
244
+ .option('--prod', 'Target the production environment instead of sandbox', false)
245
+ .option('--yes', 'Skip the confirmation prompt (required in non-interactive sessions)', false)
246
+ .option('--json', 'Machine-readable output', false)
247
+ .action(async (opts) => {
248
+ process.exitCode = await runDiscountCreate(opts, io());
249
+ });
250
+ }
251
+ //# sourceMappingURL=discount.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"discount.js","sourceRoot":"","sources":["../../src/commands/discount.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,YAAY,EAAE,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAChF,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC9D,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAExD,MAAM,YAAY,GAAG,iEAAiE,CAAC;AACvF,MAAM,YAAY,GAAG,aAAa,CAAC;AAgDnC,SAAS,MAAM,CAAC,EAAc,EAAE,IAAa;IAC3C,MAAM,MAAM,GAAG,aAAa,CAAC,EAAE,CAAC,GAAG,IAAI,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,SAAS,CAAC,CAAC;IAClE,MAAM,QAAQ,GAAG,UAAU,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;IAC1C,MAAM,IAAI,GAAG,IAAI,gBAAgB,CAAC;QAChC,YAAY,EAAE,QAAQ,CAAC,GA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wBAAwB,EAAE,oDAAoD,CAAC;SACtF,MAAM,CAAC,gBAAgB,EAAE,uEAAuE,CAAC;SACjG,MAAM,CAAC,uBAAuB,EAAE,4CAA4C,CAAC;SAC7E,MAAM,CAAC,wBAAwB,EAAE,mEAAmE,CAAC;SACrG,MAAM,CAAC,QAAQ,EAAE,sDAAsD,EAAE,KAAK,CAAC;SAC/E,MAAM,CAAC,OAAO,EAAE,qEAAqE,EAAE,KAAK,CAAC;SAC7F,MAAM,CAAC,QAAQ,EAAE,yBAAyB,EAAE,KAAK,CAAC;SAClD,MAAM,CAAC,KAAK,EAAE,IAA2B,EAAE,EAAE;QAC5C,OAAO,CAAC,QAAQ,GAAG,MAAM,iBAAiB,CAAC,IAAI,EAAE,EAAE,EAAE,CAAC,CAAC;IACzD,CAAC,CAAC,CAAC;AACP,CAAC"}
@@ -1,4 +1,5 @@
1
1
  import { Command } from 'commander';
2
+ import { type CliConfig, type EnvName } from '../core/config.js';
2
3
  export interface EnvIO {
3
4
  stdout: NodeJS.WritableStream;
4
5
  /** Injectable for tests; defaults to the real user config directory. */
@@ -9,6 +10,16 @@ export interface EnvIO {
9
10
  export interface EnvOptions {
10
11
  /** CLI plan 015: machine-readable output — `{ environment, sandboxUrl, prodUrl, sandboxKey, prodKey }`, `sandboxKey`/`prodKey` always `"set"`/`"missing"`, never a key value. */
11
12
  json?: boolean;
13
+ /** Make one authenticated read per configured key and report whether the API accepted it (`runEnvCheck`). */
14
+ check?: boolean;
15
+ }
16
+ /** Outcome of one live key check. Never carries key material. */
17
+ export interface KeyCheck {
18
+ ok: boolean;
19
+ /** `ok`, `rejected` (401/403 — the key belongs to the other environment or was revoked), `error` (network or unexpected response), or `missing` (no key configured). */
20
+ status: 'ok' | 'rejected' | 'error' | 'missing';
21
+ httpStatus?: number;
22
+ message?: string;
12
23
  }
13
24
  /** CLI plan 015: the exact `kelviq env --json` document — field names verbatim (public, versioned contract; see README). `environment` is always the literal `"sandbox"`, matching the text report's own "sandbox (default...)" line — `env` has no `--prod` flag of its own, it always reports both keys' status together. */
14
25
  export interface EnvJsonDocument {
@@ -31,4 +42,12 @@ export interface EnvJsonDocument {
31
42
  * writes any part of a key's value, in either mode.
32
43
  */
33
44
  export declare function runEnvReport(io: EnvIO, options?: EnvOptions): string;
45
+ /** One lightweight authenticated read against `envName`'s host, reporting only whether the key was accepted. */
46
+ export declare function checkKey(config: CliConfig, envName: EnvName): Promise<KeyCheck>;
47
+ /**
48
+ * `kelviq env --check`: the plain report plus one live read per configured
49
+ * key. Exit code 1 when any configured key is rejected or errors, or when
50
+ * no key is configured at all — so a script or agent can gate on it.
51
+ */
52
+ export declare function runEnvCheck(io: EnvIO, options?: EnvOptions): Promise<number>;
34
53
  export declare function registerEnvCommand(program: Command): void;
@@ -1,5 +1,7 @@
1
1
  import { style } from '../cli-ui/style.js';
2
2
  import { loadCliConfig } from '../core/config.js';
3
+ import { lastEnvFileLoad } from '../core/env-file.js';
4
+ import { KelviqHttpClient } from '../core/http.js';
3
5
  /**
4
6
  * Builds and prints the environment report — plain text by default, or (CLI
5
7
  * plan 015) the `EnvJsonDocument` above with `options.json`. Returns the
@@ -43,17 +45,93 @@ export function runEnvReport(io, options = {}) {
43
45
  `Sandbox key : ${sandboxStatus}`,
44
46
  `Prod key : ${prodStatus}`,
45
47
  'Org : unknown — Kelviq has no key-introspection endpoint yet',
48
+ envFilesLine(),
46
49
  ];
47
50
  const report = lines.join('\n') + '\n';
48
51
  io.stdout.write(report);
49
52
  return report;
50
53
  }
54
+ /** Where the CLI read `KELVIQ_*` variables from — appended to the text report so an agent can see which env file was picked up. */
55
+ function envFilesLine() {
56
+ const load = lastEnvFileLoad();
57
+ if (load.loaded.length === 0)
58
+ return 'Env files : none read';
59
+ const applied = load.applied.length > 0 ? ` (${load.applied.join(', ')})` : ' (no KELVIQ_* variables taken)';
60
+ return `Env files : ${load.loaded.join(', ')}${applied}`;
61
+ }
62
+ /** One lightweight authenticated read against `envName`'s host, reporting only whether the key was accepted. */
63
+ export async function checkKey(config, envName) {
64
+ const key = envName === 'production' ? config.prodServerApiKey : config.sandboxServerApiKey;
65
+ if (!key)
66
+ return { ok: false, status: 'missing' };
67
+ const http = new KelviqHttpClient({
68
+ serverApiKey: key,
69
+ baseUrl: envName === 'production' ? config.baseUrl : config.sandboxBaseUrl,
70
+ edgeUrl: envName === 'production' ? config.edgeUrl : config.sandboxEdgeUrl,
71
+ userAgent: config.userAgent,
72
+ });
73
+ const result = await http.request({ method: 'GET', path: '/catalog/products/', query: { page_size: 1 }, auth: 'server' });
74
+ if (result.ok)
75
+ return { ok: true, status: 'ok' };
76
+ const httpStatus = result.error.httpStatus;
77
+ if (httpStatus === 401 || httpStatus === 403) {
78
+ return {
79
+ ok: false,
80
+ status: 'rejected',
81
+ httpStatus,
82
+ message: `HTTP ${httpStatus}: the key was rejected — it probably belongs to the other environment. Get a ${envName} key at https://app.kelviq.com/settings/api-keys?mode=${envName === 'production' ? 'live' : 'sandbox'}.`,
83
+ };
84
+ }
85
+ return { ok: false, status: 'error', httpStatus, message: result.error.message };
86
+ }
87
+ /**
88
+ * `kelviq env --check`: the plain report plus one live read per configured
89
+ * key. Exit code 1 when any configured key is rejected or errors, or when
90
+ * no key is configured at all — so a script or agent can gate on it.
91
+ */
92
+ export async function runEnvCheck(io, options = {}) {
93
+ const config = loadCliConfig(io.env ?? process.env, io.configDir);
94
+ const [sandbox, production] = await Promise.all([checkKey(config, 'sandbox'), checkKey(config, 'production')]);
95
+ const configured = [sandbox, production].filter((c) => c.status !== 'missing');
96
+ const exitCode = configured.length > 0 && configured.every((c) => c.ok) ? 0 : 1;
97
+ if (options.json) {
98
+ const doc = {
99
+ environment: 'sandbox',
100
+ sandboxUrl: config.sandboxBaseUrl,
101
+ prodUrl: config.baseUrl,
102
+ sandboxKey: config.sandboxServerApiKey ? 'set' : 'missing',
103
+ prodKey: config.prodServerApiKey ? 'set' : 'missing',
104
+ sandboxCheck: sandbox,
105
+ prodCheck: production,
106
+ };
107
+ io.stdout.write(`${JSON.stringify(doc)}\n`);
108
+ return exitCode;
109
+ }
110
+ runEnvReport(io, options);
111
+ const describe = (name, check) => {
112
+ if (check.status === 'missing')
113
+ return `${name} check : ${style.dim('skipped (no key configured)')}`;
114
+ if (check.ok)
115
+ return `${name} check : ${style.ok('ok')}`;
116
+ return `${name} check : ${style.fail(check.status)} — ${check.message ?? ''}`.trimEnd();
117
+ };
118
+ io.stdout.write(`${describe('Sandbox', sandbox)}\n${describe('Prod ', production)}\n`);
119
+ if (configured.length === 0) {
120
+ io.stdout.write(`${style.fail('No API key configured.')} Run \`kelviq login\` or set KELVIQ_SERVER_API_KEY.\n`);
121
+ }
122
+ return exitCode;
123
+ }
51
124
  export function registerEnvCommand(program) {
52
125
  program
53
126
  .command('env')
54
127
  .description('Show which Kelviq environment and API keys are configured.')
55
128
  .option('--json', 'Machine-readable output (never includes key material)', false)
56
- .action((opts) => {
129
+ .option('--check', 'Also make one authenticated read per configured key and report whether the API accepted it', false)
130
+ .action(async (opts) => {
131
+ if (opts.check) {
132
+ process.exitCode = await runEnvCheck({ stdout: process.stdout }, opts);
133
+ return;
134
+ }
57
135
  runEnvReport({ stdout: process.stdout }, opts);
58
136
  });
59
137
  }
@@ -1 +1 @@
1
- {"version":3,"file":"env.js","sourceRoot":"","sources":["../../src/commands/env.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAwBlD;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,YAAY,CAAC,EAAS,EAAE,UAAsB,EAAE;IAC9D,MAAM,MAAM,GAAG,aAAa,CAAC,EAAE,CAAC,GAAG,IAAI,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,SAAS,CAAC,CAAC;IAElE,IAAI,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,MAAM,GAAG,GAAoB;YAC3B,WAAW,EAAE,SAAS;YACtB,UAA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