@stewardhq/cli 0.7.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +47 -12
- package/dist/bin.js +499 -188
- package/package.json +4 -4
package/dist/bin.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { userInfo } from "node:os";
|
|
3
3
|
import { createInterface } from "node:readline/promises";
|
|
4
4
|
import { setTimeout } from "node:timers/promises";
|
|
5
|
-
import { ApiKeyCreateInputSchema, BankTransferRecordInputSchema, CatalogSyncInputSchema, CreditAdjustmentInputSchema, DunningPolicySchema, EventsIngestInputSchema, METER_CHARGE_MODES, MeterCreditPropertiesSchema, ProductSettingsPatchSchema, RepriceInputSchema, StewardApiError, StewardConfigError, StewardError, StewardNetworkError, WebhookEndpointCreateInputSchema, WebhookEndpointRotateInputSchema, createSteward, generateApiKeyToken, generateWebhookSecret, plainDecimalOf } from "@stewardhq/sdk";
|
|
5
|
+
import { ACCOUNT_INCLUDES, AccountMetadataPatchInputSchema, ApiKeyCreateInputSchema, BankTransferRecordInputSchema, CatalogSyncInputSchema, CreditAdjustmentInputSchema, DunningPolicySchema, EventsIngestInputSchema, FxRateSchema, METER_CHARGE_MODES, MeterCreditPropertiesSchema, ProductSettingsPatchSchema, RepriceInputSchema, StewardApiError, StewardConfigError, StewardError, StewardNetworkError, WebhookEndpointCreateInputSchema, WebhookEndpointRotateInputSchema, createSteward, generateApiKeyToken, generateWebhookSecret, plainDecimalOf } from "@stewardhq/sdk";
|
|
6
6
|
import { parseArgs } from "node:util";
|
|
7
7
|
import { basename, dirname, extname, join, relative, resolve } from "node:path";
|
|
8
8
|
import { link, lstat, readFile, rename, unlink, writeFile } from "node:fs/promises";
|
|
@@ -10,7 +10,7 @@ import { randomUUID } from "node:crypto";
|
|
|
10
10
|
import { pathToFileURL } from "node:url";
|
|
11
11
|
//#region src/io.ts
|
|
12
12
|
const SECRET_PATTERN = /\b(whsec_|stw_)[A-Za-z0-9_\-+/=]+/g;
|
|
13
|
-
/**
|
|
13
|
+
/** Masks secret-shaped values (`whsec_***`). */
|
|
14
14
|
function redactSecrets(text) {
|
|
15
15
|
return text.replace(SECRET_PATTERN, "$1***");
|
|
16
16
|
}
|
|
@@ -20,7 +20,7 @@ function createOutput(stdout, stderr) {
|
|
|
20
20
|
err: (line = "") => stderr.write(`${redactSecrets(line)}\n`)
|
|
21
21
|
};
|
|
22
22
|
}
|
|
23
|
-
/**
|
|
23
|
+
/** An error shown to the user, without a stack trace. */
|
|
24
24
|
var CliError = class extends Error {
|
|
25
25
|
exitCode;
|
|
26
26
|
constructor(message, exitCode = 1) {
|
|
@@ -29,14 +29,14 @@ var CliError = class extends Error {
|
|
|
29
29
|
this.exitCode = exitCode;
|
|
30
30
|
}
|
|
31
31
|
};
|
|
32
|
-
/**
|
|
32
|
+
/** Wrong usage (unknown flag, missing argument): exit code 2. */
|
|
33
33
|
var UsageError = class extends CliError {
|
|
34
34
|
constructor(message) {
|
|
35
35
|
super(message, 2);
|
|
36
36
|
this.name = "UsageError";
|
|
37
37
|
}
|
|
38
38
|
};
|
|
39
|
-
/** `node:fs`
|
|
39
|
+
/** The code of a `node:fs` error (`ENOENT`…). */
|
|
40
40
|
function errnoCode(error) {
|
|
41
41
|
const code = typeof error === "object" && error !== null ? error.code : void 0;
|
|
42
42
|
return typeof code === "string" ? code : void 0;
|
|
@@ -47,8 +47,8 @@ const HELP_OPTION = { help: {
|
|
|
47
47
|
type: "boolean",
|
|
48
48
|
short: "h"
|
|
49
49
|
} };
|
|
50
|
-
const hint = (command) => ` (
|
|
51
|
-
/** `command`:
|
|
50
|
+
const hint = (command) => ` (details: steward ${command} --help)`;
|
|
51
|
+
/** `command`: the command name for the help hint in the error message (`endpoints`). */
|
|
52
52
|
function parse(args, options, command) {
|
|
53
53
|
try {
|
|
54
54
|
return parseArgs({
|
|
@@ -61,24 +61,24 @@ function parse(args, options, command) {
|
|
|
61
61
|
throw new UsageError(`${error instanceof Error ? error.message : String(error)}${hint(command)}`);
|
|
62
62
|
}
|
|
63
63
|
}
|
|
64
|
-
/**
|
|
64
|
+
/** The number of positional arguments must be within `[min, max]`. */
|
|
65
65
|
function expectPositionals(positionals, min, max, command) {
|
|
66
|
-
if (positionals.length < min) throw new UsageError(`
|
|
67
|
-
if (positionals.length > max) throw new UsageError(`
|
|
66
|
+
if (positionals.length < min) throw new UsageError(`missing argument${hint(command)}`);
|
|
67
|
+
if (positionals.length > max) throw new UsageError(`unexpected argument: ${positionals.slice(max).join(" ")}${hint(command)}`);
|
|
68
68
|
}
|
|
69
69
|
function requireOption(value, flag, command) {
|
|
70
|
-
if (value === void 0 || value.trim() === "") throw new UsageError(`${flag}
|
|
70
|
+
if (value === void 0 || value.trim() === "") throw new UsageError(`${flag} is required${hint(command)}`);
|
|
71
71
|
return value;
|
|
72
72
|
}
|
|
73
73
|
/** `a, b,,c` → `["a", "b", "c"]`. */
|
|
74
74
|
function parseList(value) {
|
|
75
75
|
return value.split(",").map((item) => item.trim()).filter((item) => item !== "");
|
|
76
76
|
}
|
|
77
|
-
/**
|
|
77
|
+
/** Positive integer (digits only). */
|
|
78
78
|
function parsePositiveInt(value, flag, { max = Number.MAX_SAFE_INTEGER } = {}) {
|
|
79
79
|
const trimmed = value.trim();
|
|
80
80
|
const n = /^\d+$/.test(trimmed) ? Number(trimmed) : NaN;
|
|
81
|
-
if (!Number.isSafeInteger(n) || n < 1 || n > max) throw new UsageError(`${flag}: 1
|
|
81
|
+
if (!Number.isSafeInteger(n) || n < 1 || n > max) throw new UsageError(`${flag}: must be an integer between 1 and ${max}`);
|
|
82
82
|
return n;
|
|
83
83
|
}
|
|
84
84
|
/** Non-negative integer (digits only), e.g. an amount in minor units. */
|
|
@@ -115,6 +115,10 @@ function definesBenefits(input) {
|
|
|
115
115
|
function definesMeters(input) {
|
|
116
116
|
return Object.keys(input.meters ?? {}).length > 0 || (input.meteredPrices ?? []).length > 0;
|
|
117
117
|
}
|
|
118
|
+
/** A catalog with an unlisted plan needs a steward with the `unlisted_plans` capability: an older one would offer the plan. */
|
|
119
|
+
function definesUnlistedPlans(input) {
|
|
120
|
+
return input.plans.some((plan) => plan.listed === false);
|
|
121
|
+
}
|
|
118
122
|
const isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
119
123
|
/** JSON with sorted object keys: key order does not count as a change. */
|
|
120
124
|
const canonical = (value) => JSON.stringify(value ?? null, (_key, v) => isPlainObject(v) ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) : v);
|
|
@@ -226,6 +230,11 @@ function diffCatalog(current, file) {
|
|
|
226
230
|
removed
|
|
227
231
|
});
|
|
228
232
|
}
|
|
233
|
+
const currentListing = new Map((current?.plans ?? []).map((plan) => [plan.code, plan.listed ?? true]));
|
|
234
|
+
const planListing = input.plans.filter((plan) => (currentListing.get(plan.code) ?? true) !== plan.listed).map((plan) => ({
|
|
235
|
+
plan: plan.code,
|
|
236
|
+
listed: plan.listed
|
|
237
|
+
}));
|
|
229
238
|
const currentPrices = new Map((current?.prices ?? []).map((price) => [priceKey(price), price]));
|
|
230
239
|
const inputKeys = new Set(input.prices.map(priceKey));
|
|
231
240
|
const prices = {
|
|
@@ -267,6 +276,7 @@ function diffCatalog(current, file) {
|
|
|
267
276
|
return {
|
|
268
277
|
benefits,
|
|
269
278
|
planBenefits,
|
|
279
|
+
planListing,
|
|
270
280
|
prices,
|
|
271
281
|
meters: diffMeters(current, input),
|
|
272
282
|
credits,
|
|
@@ -318,6 +328,7 @@ function describeDiff(diff) {
|
|
|
318
328
|
if (diff.benefits.changed.length > 0) row("changed benefits", list$1(diff.benefits.changed));
|
|
319
329
|
if (diff.benefits.archived.length > 0) row("archived benefits", `${list$1(diff.benefits.archived)} (accounts that have them lose them)`);
|
|
320
330
|
for (const { plan, added, removed } of diff.planBenefits) row("plan benefits", `${plan}: ${[...added.map((code) => `+${code}`), ...removed.map((code) => `-${code}`)].join(" ")}`);
|
|
331
|
+
for (const { plan, listed } of diff.planListing) row("plan listing", `${plan}: ${listed ? "listed (offered" : "unlisted (not offered"} in the portal's "Change plan")`);
|
|
321
332
|
for (const price of diff.prices.added) row("new price", price);
|
|
322
333
|
for (const price of diff.prices.deactivated) row("deactivated price", price);
|
|
323
334
|
for (const change of diff.prices.changed) row("price change", describePriceChange(change));
|
|
@@ -349,18 +360,6 @@ function priceChangeCount(diff) {
|
|
|
349
360
|
return diff.prices.changed.length + diff.meteredPrices.changed.length;
|
|
350
361
|
}
|
|
351
362
|
//#endregion
|
|
352
|
-
//#region src/confirm.ts
|
|
353
|
-
/**
|
|
354
|
-
* Asks before a change that cannot be taken back; `yes` (`--yes`) skips the question. Without a
|
|
355
|
-
* terminal (CI, pipes) the command needs `--yes`: `notConfirmed` says what was not done.
|
|
356
|
-
*/
|
|
357
|
-
async function confirm(ctx, question, options) {
|
|
358
|
-
if (options.yes) return true;
|
|
359
|
-
const answer = await ctx.prompt(`${question} [y/N] `);
|
|
360
|
-
if (answer === null) throw new CliError(`confirmation needed: run again with --yes (${options.notConfirmed})`);
|
|
361
|
-
return /^y(es)?$/i.test(answer.trim());
|
|
362
|
-
}
|
|
363
|
-
//#endregion
|
|
364
363
|
//#region src/dotenv.ts
|
|
365
364
|
const LINE = /^(\s*)(export\s+)?([A-Za-z_][A-Za-z0-9_.-]*)\s*=(.*)$/;
|
|
366
365
|
function unquote(rest) {
|
|
@@ -395,7 +394,7 @@ async function readDotenvFile(path) {
|
|
|
395
394
|
//#endregion
|
|
396
395
|
//#region src/env.ts
|
|
397
396
|
const ENV_LOCAL = ".env.local";
|
|
398
|
-
/**
|
|
397
|
+
/** If even one of these is in the process environment, `.env.local` is not read. */
|
|
399
398
|
const CONNECTION_VARIABLES = [
|
|
400
399
|
"STEWARD_URL",
|
|
401
400
|
"STEWARD_API_KEY",
|
|
@@ -417,7 +416,7 @@ const clean = (value) => {
|
|
|
417
416
|
async function resolveEnv(ctx) {
|
|
418
417
|
const fromEnv = CONNECTION_VARIABLES.some((name) => clean(ctx.env[name]) !== void 0);
|
|
419
418
|
const local = fromEnv ? null : await readDotenvFile(join(ctx.cwd, ENV_LOCAL));
|
|
420
|
-
const source = local === null ? "
|
|
419
|
+
const source = local === null ? "environment" : ".env.local";
|
|
421
420
|
const get = (name) => local === null ? clean(ctx.env[name]) : clean(local.get(name));
|
|
422
421
|
return {
|
|
423
422
|
source,
|
|
@@ -442,21 +441,21 @@ async function resolveEnv(ctx) {
|
|
|
442
441
|
}
|
|
443
442
|
function whereMissing(env) {
|
|
444
443
|
switch (env.envLocal) {
|
|
445
|
-
case "skipped": return `
|
|
446
|
-
case "read": return
|
|
447
|
-
case "missing": return `
|
|
444
|
+
case "skipped": return `not set in the environment (./${ENV_LOCAL} was not read because a steward connection variable is in the environment; sources are not mixed)`;
|
|
445
|
+
case "read": return `not set in ./${ENV_LOCAL} (no steward connection variable in the environment)`;
|
|
446
|
+
case "missing": return `not set (environment variable or ./${ENV_LOCAL}; no such file)`;
|
|
448
447
|
}
|
|
449
448
|
}
|
|
450
|
-
const ADMIN_HINT = "Set them as environment variables or in ./.env.local.
|
|
449
|
+
const ADMIN_HINT = "Set them as environment variables or in ./.env.local. STEWARD_ADMIN_URL is the address where your steward serves /v1 (for example https://billing.example.com); the admin key comes from its operator.";
|
|
451
450
|
function pairError(names, missing, env) {
|
|
452
|
-
return new CliError(`${names.url} + ${names.key}
|
|
451
|
+
return new CliError(`${names.url} + ${names.key} required: ${missing.join(" and ")} ${whereMissing(env)}.\n${ADMIN_HINT}`);
|
|
453
452
|
}
|
|
454
453
|
function requireAdminTarget(env) {
|
|
455
454
|
const pair = env.pair(ADMIN_PAIR);
|
|
456
455
|
if ("missing" in pair) throw pairError(ADMIN_PAIR, pair.missing, env);
|
|
457
456
|
return pair;
|
|
458
457
|
}
|
|
459
|
-
/**
|
|
458
|
+
/** The product pair; if both are unset, the admin pair (`GET /v1/doctor` is open to both). A half pair is an error. */
|
|
460
459
|
function requireReadTarget(env) {
|
|
461
460
|
const product = env.pair(PRODUCT_PAIR);
|
|
462
461
|
if (!("missing" in product)) return product;
|
|
@@ -464,28 +463,28 @@ function requireReadTarget(env) {
|
|
|
464
463
|
const admin = env.pair(ADMIN_PAIR);
|
|
465
464
|
if (!("missing" in admin)) return admin;
|
|
466
465
|
if (admin.present.length > 0) throw pairError(ADMIN_PAIR, admin.missing, env);
|
|
467
|
-
throw new CliError(`${PRODUCT_PAIR.url} + ${PRODUCT_PAIR.key} (
|
|
466
|
+
throw new CliError(`${PRODUCT_PAIR.url} + ${PRODUCT_PAIR.key} (or ${ADMIN_PAIR.url} + ${ADMIN_PAIR.key}) required: ${whereMissing(env)}.\n${ADMIN_HINT}`);
|
|
468
467
|
}
|
|
469
|
-
/**
|
|
468
|
+
/** The source and pair in use and the target's origin (a stderr line; no key value). */
|
|
470
469
|
function connectionLine(target) {
|
|
471
|
-
return `
|
|
470
|
+
return `connection: ${target.source} · ${target.pair.url} + ${target.pair.key} → ${originOf(target.url)}`;
|
|
472
471
|
}
|
|
473
|
-
/**
|
|
472
|
+
/** `operator:<name>` from the operating system user name (the contract's `type[:id]` form). */
|
|
474
473
|
function actorRefOf(username) {
|
|
475
474
|
const id = username.replace(/[^A-Za-z0-9_.@-]/g, "_").slice(0, 190);
|
|
476
475
|
return id === "" ? "operator" : `operator:${id}`;
|
|
477
476
|
}
|
|
478
|
-
/**
|
|
477
|
+
/** The target's origin (credentials and path are not printed). */
|
|
479
478
|
function originOf(url) {
|
|
480
479
|
try {
|
|
481
480
|
return new URL(url).origin;
|
|
482
481
|
} catch {
|
|
483
|
-
return "(
|
|
482
|
+
return "(invalid address)";
|
|
484
483
|
}
|
|
485
484
|
}
|
|
486
485
|
/**
|
|
487
|
-
*
|
|
488
|
-
*
|
|
486
|
+
* A client bound to the target. The same URL/key is given as both the product and the admin base:
|
|
487
|
+
* the command only calls the methods that fit the target's scope.
|
|
489
488
|
*/
|
|
490
489
|
function clientFor(ctx, target, options = {}) {
|
|
491
490
|
return createSteward({
|
|
@@ -500,7 +499,7 @@ function clientFor(ctx, target, options = {}) {
|
|
|
500
499
|
retries: options.retries === false ? { attempts: 0 } : { sleep: ctx.sleep }
|
|
501
500
|
});
|
|
502
501
|
}
|
|
503
|
-
/**
|
|
502
|
+
/** A steward call: an SDK error becomes a `CliError` carrying the target's origin. */
|
|
504
503
|
async function callSteward(target, fn) {
|
|
505
504
|
try {
|
|
506
505
|
return await fn();
|
|
@@ -514,26 +513,215 @@ const CODE_HINTS = {
|
|
|
514
513
|
meter_locked: " — a meter's filter and aggregation are fixed once it has counted a period: give the new rule a new meter code",
|
|
515
514
|
metered_price_tax_mismatch: " — a metered price needs the tax terms (taxInclusive, taxRateBps) of its plan's base price in that currency"
|
|
516
515
|
};
|
|
517
|
-
/** SDK
|
|
516
|
+
/** Turns an SDK error into a one-line user message (no values or keys). */
|
|
518
517
|
function describeStewardError(error, target) {
|
|
519
518
|
const where = target ? ` (${originOf(target.url)})` : "";
|
|
520
|
-
const request = error.requestId !== void 0 ? ` [
|
|
521
|
-
if (error instanceof StewardNetworkError) return `steward
|
|
522
|
-
if (error instanceof StewardConfigError) return `
|
|
519
|
+
const request = error.requestId !== void 0 ? ` [request ${error.requestId}]` : "";
|
|
520
|
+
if (error instanceof StewardNetworkError) return `could not reach steward${where}: ${error.code === "timeout" ? "timed out" : "could not connect"}. Is the address right and reachable from this machine?`;
|
|
521
|
+
if (error instanceof StewardConfigError) return `configuration error: ${error.message}`;
|
|
523
522
|
if (error instanceof StewardApiError) {
|
|
524
|
-
const hint = error.httpStatus === 401 ? " —
|
|
523
|
+
const hint = error.httpStatus === 401 ? " — the key is invalid or revoked" : error.httpStatus === 403 ? " — this operation needs an admin-scoped key" : Object.hasOwn(CODE_HINTS, error.code) ? CODE_HINTS[error.code] : "";
|
|
525
524
|
const message = error.message !== error.code ? `: ${error.message}` : "";
|
|
526
|
-
return `steward
|
|
525
|
+
return `steward error${where}: ${error.code} (HTTP ${error.httpStatus})${message}${hint}${request}`;
|
|
527
526
|
}
|
|
528
|
-
return `steward
|
|
527
|
+
return `steward response does not match the contract${where}: ${error.code} (HTTP ${error.httpStatus}) — the CLI and steward versions may be incompatible${request}`;
|
|
528
|
+
}
|
|
529
|
+
//#endregion
|
|
530
|
+
//#region src/commands/accounts.ts
|
|
531
|
+
const ACCOUNTS_USAGE = `Usage:
|
|
532
|
+
steward accounts get <ref> [--include <a,b>] [--json]
|
|
533
|
+
steward accounts metadata set <ref> <key>=<value>… [--reason <text>] [--json]
|
|
534
|
+
steward accounts metadata unset <ref> <key>… [--reason <text>] [--json]
|
|
535
|
+
|
|
536
|
+
get reads an account (GET /v1/accounts/:ref): name, plan, the primary subscription and the
|
|
537
|
+
metadata. Nothing is written.
|
|
538
|
+
|
|
539
|
+
--include <a,b> also read profile, subscriptions, checkouts, payments, invoices, grants
|
|
540
|
+
(comma separated). Subscriptions are listed, the others are counted; --json
|
|
541
|
+
prints the whole response.
|
|
542
|
+
--json print the response as JSON
|
|
543
|
+
|
|
544
|
+
metadata set / unset change single metadata keys (PATCH /v1/accounts/:ref/metadata) and leave
|
|
545
|
+
every other key as it is. Steward merges them in one atomic write, so the change cannot
|
|
546
|
+
overwrite a key another writer (the product, another operator) changes at the same time. The
|
|
547
|
+
command reads the account first, prints each key's value before and after, then sends the
|
|
548
|
+
change. Steward records it in the audit trail with the key names, --reason and the operator;
|
|
549
|
+
the account state does not change and no event is emitted. Running it again is harmless.
|
|
550
|
+
|
|
551
|
+
<key>=<value> split at the first "="; key at most 64 characters, value at most 500. An
|
|
552
|
+
empty value (key=) is stored as empty text; unset removes the key.
|
|
553
|
+
--reason <text> why (3–500 characters); kept in the audit trail only
|
|
554
|
+
--json print the updated account as JSON (the before → after lines go to stderr)
|
|
555
|
+
|
|
556
|
+
The account must exist: these commands never create one (404 account_not_found). Metadata
|
|
557
|
+
must not carry personal data (names, e-mail addresses, phone numbers): use opaque ids and
|
|
558
|
+
flags. set and unset need a steward whose GET /v1/me lists the "account_metadata" capability.
|
|
559
|
+
|
|
560
|
+
Connection: STEWARD_URL + STEWARD_API_KEY (or, when neither is set, STEWARD_ADMIN_URL +
|
|
561
|
+
STEWARD_ADMIN_API_KEY). Environment, otherwise ./.env.local. Changes are sent with
|
|
562
|
+
X-Actor-Ref operator:<user>.
|
|
563
|
+
Exit code 1: steward refused (unknown or deleted account, no capability); 2: wrong usage,
|
|
564
|
+
nothing was sent.`;
|
|
565
|
+
const GET_OPTIONS$1 = {
|
|
566
|
+
...HELP_OPTION,
|
|
567
|
+
include: { type: "string" },
|
|
568
|
+
json: { type: "boolean" }
|
|
569
|
+
};
|
|
570
|
+
const METADATA_OPTIONS = {
|
|
571
|
+
...HELP_OPTION,
|
|
572
|
+
reason: { type: "string" },
|
|
573
|
+
json: { type: "boolean" }
|
|
574
|
+
};
|
|
575
|
+
/** A metadata value on one terminal line: as is, or JSON-quoted when empty, padded or with control characters. */
|
|
576
|
+
function show(value) {
|
|
577
|
+
return value === "" || value !== value.trim() || /\p{Cc}/u.test(value) ? JSON.stringify(value) : value;
|
|
578
|
+
}
|
|
579
|
+
/** Human-readable account read: name, plan, primary subscription, metadata, and the included parts. */
|
|
580
|
+
function formatAccount(account) {
|
|
581
|
+
const { snapshot } = account;
|
|
582
|
+
const lines = [
|
|
583
|
+
`account ${account.ref} · ${account.displayName}`,
|
|
584
|
+
` created ${account.createdAt}`,
|
|
585
|
+
` plan ${snapshot.planCode} · access ${snapshot.accessState}`
|
|
586
|
+
];
|
|
587
|
+
const sub = snapshot.subscription;
|
|
588
|
+
if (sub === null) lines.push(" subscription none");
|
|
589
|
+
else {
|
|
590
|
+
const ends = sub.cancelAt !== null ? `cancels at ${sub.cancelAt}` : `period ends ${sub.currentPeriodEnd ?? "-"}`;
|
|
591
|
+
lines.push(` subscription ${sub.status} · ${sub.planCode} ${sub.interval} · ${formatMinor(sub.amountMinor, sub.currency)} · ${ends}`);
|
|
592
|
+
}
|
|
593
|
+
const keys = Object.keys(account.metadata);
|
|
594
|
+
if (keys.length === 0) lines.push(" metadata none");
|
|
595
|
+
else {
|
|
596
|
+
lines.push(" metadata");
|
|
597
|
+
const width = Math.max(...keys.map((key) => key.length));
|
|
598
|
+
for (const key of keys) lines.push(` ${key.padEnd(width)} ${show(account.metadata[key])}`);
|
|
599
|
+
}
|
|
600
|
+
if (account.profile !== void 0) lines.push(` profile ${account.profile === null ? "none" : account.profile.kind}`);
|
|
601
|
+
if (account.subscriptions !== void 0) {
|
|
602
|
+
lines.push(` subscriptions ${account.subscriptions.length}`);
|
|
603
|
+
for (const s of account.subscriptions) lines.push(` ${s.id} ${s.status} · ${s.planCode} ${s.interval} · ${formatMinor(s.amountMinor, s.currency)} · period ends ${s.currentPeriodEnd ?? "-"}`);
|
|
604
|
+
}
|
|
605
|
+
for (const part of [
|
|
606
|
+
"checkouts",
|
|
607
|
+
"payments",
|
|
608
|
+
"invoices",
|
|
609
|
+
"grants"
|
|
610
|
+
]) {
|
|
611
|
+
const items = account[part];
|
|
612
|
+
if (items !== void 0) lines.push(` ${part.padEnd(13)} ${items.length}${items.length > 0 ? " (--json for the details)" : ""}`);
|
|
613
|
+
}
|
|
614
|
+
return lines;
|
|
615
|
+
}
|
|
616
|
+
async function getCommand(ctx, out, args) {
|
|
617
|
+
const { values, positionals } = parse(args, GET_OPTIONS$1, "accounts");
|
|
618
|
+
if (values.help) {
|
|
619
|
+
out.out(ACCOUNTS_USAGE);
|
|
620
|
+
return 0;
|
|
621
|
+
}
|
|
622
|
+
expectPositionals(positionals, 1, 1, "accounts");
|
|
623
|
+
const ref = positionals[0];
|
|
624
|
+
const include = values.include === void 0 ? [] : parseList(values.include);
|
|
625
|
+
const unknown = include.filter((item) => !ACCOUNT_INCLUDES.includes(item));
|
|
626
|
+
if (unknown.length > 0) throw new UsageError(`--include: unknown ${unknown.join(", ")} (one of: ${ACCOUNT_INCLUDES.join(", ")})`);
|
|
627
|
+
const target = requireReadTarget(await resolveEnv(ctx));
|
|
628
|
+
out.err(connectionLine(target));
|
|
629
|
+
const account = await callSteward(target, () => clientFor(ctx, target).accounts.get(ref, { include }));
|
|
630
|
+
if (values.json) out.out(JSON.stringify(account, null, 2));
|
|
631
|
+
else for (const line of formatAccount(account)) out.out(line);
|
|
632
|
+
return 0;
|
|
633
|
+
}
|
|
634
|
+
/** `key=value` arguments (split at the first `=`) or bare keys → the patch: a value sets, `null` removes. */
|
|
635
|
+
function parseMetadataChange(action, items) {
|
|
636
|
+
const change = /* @__PURE__ */ new Map();
|
|
637
|
+
for (const item of items) {
|
|
638
|
+
const at = action === "set" ? item.indexOf("=") : item.length;
|
|
639
|
+
if (at <= 0) throw new UsageError(action === "set" ? `expected key=value, got "${item}"` : "a key cannot be empty");
|
|
640
|
+
const key = item.slice(0, at);
|
|
641
|
+
if (key === "__proto__") throw new UsageError("key \"__proto__\" is not accepted");
|
|
642
|
+
if (change.has(key)) throw new UsageError(`key "${key}" given twice`);
|
|
643
|
+
change.set(key, action === "set" ? item.slice(at + 1) : null);
|
|
644
|
+
}
|
|
645
|
+
return Object.fromEntries(change);
|
|
646
|
+
}
|
|
647
|
+
/** One line per key of the patch: its value now and after the patch. */
|
|
648
|
+
function changeLines(current, change) {
|
|
649
|
+
return Object.entries(change).map(([key, value]) => {
|
|
650
|
+
const before = Object.hasOwn(current, key) ? current[key] : null;
|
|
651
|
+
const from = before === null ? "(none)" : show(before);
|
|
652
|
+
if (value === null) return ` ${key}: ${from} → ${before === null ? "(none) (unchanged)" : "(removed)"}`;
|
|
653
|
+
return ` ${key}: ${from} → ${show(value)}${before === value ? " (unchanged)" : ""}`;
|
|
654
|
+
});
|
|
655
|
+
}
|
|
656
|
+
/** An older steward has no metadata patch endpoint: its 404 would read like a missing account. */
|
|
657
|
+
async function requireMetadataCapability(steward, target) {
|
|
658
|
+
if (((await callSteward(target, () => steward.me())).capabilities ?? []).includes("account_metadata")) return;
|
|
659
|
+
throw new CliError(`steward at ${originOf(target.url)} does not support changing single metadata keys (GET /v1/me capabilities has no "account_metadata"). Update steward first; nothing was sent.`);
|
|
660
|
+
}
|
|
661
|
+
async function metadataCommand(ctx, out, args) {
|
|
662
|
+
const [action, ...rest] = args;
|
|
663
|
+
if (action === void 0 || action === "--help" || action === "-h" || action === "help") {
|
|
664
|
+
out.out(ACCOUNTS_USAGE);
|
|
665
|
+
return action === void 0 ? 2 : 0;
|
|
666
|
+
}
|
|
667
|
+
if (action !== "set" && action !== "unset") throw new UsageError(`unknown subcommand: accounts metadata ${action} (see: steward accounts --help)`);
|
|
668
|
+
const { values, positionals } = parse(rest, METADATA_OPTIONS, "accounts");
|
|
669
|
+
if (values.help) {
|
|
670
|
+
out.out(ACCOUNTS_USAGE);
|
|
671
|
+
return 0;
|
|
672
|
+
}
|
|
673
|
+
expectPositionals(positionals, 2, 101, "accounts");
|
|
674
|
+
const [ref, ...items] = positionals;
|
|
675
|
+
const input = AccountMetadataPatchInputSchema.safeParse({
|
|
676
|
+
metadata: parseMetadataChange(action, items),
|
|
677
|
+
...values.reason !== void 0 ? { reason: values.reason } : {}
|
|
678
|
+
});
|
|
679
|
+
if (!input.success) throw new UsageError(`invalid metadata change (nothing was sent)\n${input.error.issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(root)"}: ${issue.message}`).join("\n")}`);
|
|
680
|
+
const target = requireReadTarget(await resolveEnv(ctx));
|
|
681
|
+
out.err(connectionLine(target));
|
|
682
|
+
const steward = clientFor(ctx, target);
|
|
683
|
+
await requireMetadataCapability(steward, target);
|
|
684
|
+
const current = await callSteward(target, () => steward.accounts.get(ref));
|
|
685
|
+
const say = values.json ? out.err : out.out;
|
|
686
|
+
say(`metadata of ${ref}:`);
|
|
687
|
+
for (const line of changeLines(current.metadata, input.data.metadata)) say(line);
|
|
688
|
+
const updated = await callSteward(target, () => steward.accounts.updateMetadata(ref, input.data));
|
|
689
|
+
if (values.json) out.out(JSON.stringify(updated, null, 2));
|
|
690
|
+
else {
|
|
691
|
+
const count = Object.keys(updated.metadata).length;
|
|
692
|
+
out.out(`written → ${originOf(target.url)}: ${ref} now has ${count} metadata key${count === 1 ? "" : "s"}`);
|
|
693
|
+
}
|
|
694
|
+
return 0;
|
|
695
|
+
}
|
|
696
|
+
async function accountsCommand(ctx, out, args) {
|
|
697
|
+
const [sub, ...rest] = args;
|
|
698
|
+
if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
|
|
699
|
+
out.out(ACCOUNTS_USAGE);
|
|
700
|
+
return sub === void 0 ? 2 : 0;
|
|
701
|
+
}
|
|
702
|
+
if (sub === "get") return getCommand(ctx, out, rest);
|
|
703
|
+
if (sub === "metadata") return metadataCommand(ctx, out, rest);
|
|
704
|
+
throw new UsageError(`unknown subcommand: accounts ${sub} (see: steward accounts --help)`);
|
|
705
|
+
}
|
|
706
|
+
//#endregion
|
|
707
|
+
//#region src/confirm.ts
|
|
708
|
+
/**
|
|
709
|
+
* Asks before a change that cannot be taken back; `yes` (`--yes`) skips the question. Without a
|
|
710
|
+
* terminal (CI, pipes) the command needs `--yes`: `notConfirmed` says what was not done.
|
|
711
|
+
*/
|
|
712
|
+
async function confirm(ctx, question, options) {
|
|
713
|
+
if (options.yes) return true;
|
|
714
|
+
const answer = await ctx.prompt(`${question} [y/N] `);
|
|
715
|
+
if (answer === null) throw new CliError(`confirmation needed: run again with --yes (${options.notConfirmed})`);
|
|
716
|
+
return /^y(es)?$/i.test(answer.trim());
|
|
529
717
|
}
|
|
530
718
|
//#endregion
|
|
531
719
|
//#region src/secret-file.ts
|
|
532
720
|
async function withSecretFile(cwd, out, secret, options, action) {
|
|
533
721
|
const target = resolve(cwd, out);
|
|
534
722
|
try {
|
|
535
|
-
if ((await lstat(target)).isDirectory()) throw new CliError(`--out
|
|
536
|
-
if (!options.force) throw new CliError(`${out}
|
|
723
|
+
if ((await lstat(target)).isDirectory()) throw new CliError(`--out is a folder: ${out}`);
|
|
724
|
+
if (!options.force) throw new CliError(`${out} already exists; use --force to overwrite it (no request was sent)`);
|
|
537
725
|
} catch (error) {
|
|
538
726
|
if (error instanceof CliError) throw error;
|
|
539
727
|
if (errnoCode(error) !== "ENOENT") throw error;
|
|
@@ -546,8 +734,8 @@ async function withSecretFile(cwd, out, secret, options, action) {
|
|
|
546
734
|
});
|
|
547
735
|
} catch (error) {
|
|
548
736
|
const code = errnoCode(error);
|
|
549
|
-
if (code === "ENOENT") throw new CliError(`--out
|
|
550
|
-
throw new CliError(`
|
|
737
|
+
if (code === "ENOENT") throw new CliError(`--out folder does not exist: ${relative(cwd, dirname(target)) || "."}`);
|
|
738
|
+
throw new CliError(`could not write the secret file (${code ?? "error"}): ${out} (no request was sent)`);
|
|
551
739
|
}
|
|
552
740
|
let value;
|
|
553
741
|
try {
|
|
@@ -577,23 +765,24 @@ async function withSecretFile(cwd, out, secret, options, action) {
|
|
|
577
765
|
}
|
|
578
766
|
//#endregion
|
|
579
767
|
//#region src/commands/endpoints.ts
|
|
580
|
-
const ENDPOINTS_USAGE = `
|
|
768
|
+
const ENDPOINTS_USAGE = `Usage:
|
|
581
769
|
steward endpoints list [--json]
|
|
582
|
-
steward endpoints add --url <url> --out <
|
|
583
|
-
steward endpoints rotate <id> --out <
|
|
770
|
+
steward endpoints add --url <url> --out <file> [--event-types <a,b>] [--description <text>] [--force]
|
|
771
|
+
steward endpoints rotate <id> --out <file> [--force]
|
|
584
772
|
steward endpoints deactivate <id>
|
|
585
773
|
|
|
586
|
-
Webhook
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
774
|
+
Webhook endpoints (/v1/admin/webhook-endpoints). The signing secret (whsec_…) is
|
|
775
|
+
generated on this machine and written ONLY to the --out file (0600, no trailing
|
|
776
|
+
newline); it is not written to the terminal and steward never returns it in any
|
|
777
|
+
response. If the file exists, no request is sent without --force. The operator moves
|
|
778
|
+
the secret into the product's Secret (the CLI does not call kubectl); on rotation the
|
|
779
|
+
product moves over with a "new,old" list. Delete the file after moving it. Without
|
|
780
|
+
--event-types only account.state_changed. deactivate cannot be undone (open a new
|
|
781
|
+
endpoint).
|
|
593
782
|
|
|
594
|
-
|
|
783
|
+
Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
|
|
595
784
|
function schemaProblems(issues) {
|
|
596
|
-
return issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(
|
|
785
|
+
return issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(root)"}: ${issue.message}`).join("\n");
|
|
597
786
|
}
|
|
598
787
|
const lastDeliveryText = (endpoint) => {
|
|
599
788
|
const last = endpoint.lastDelivery;
|
|
@@ -605,7 +794,7 @@ function table(rows) {
|
|
|
605
794
|
const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
|
|
606
795
|
return rows.map((row) => row.map((cell, column) => column === row.length - 1 ? cell : cell.padEnd(widths[column])).join(" "));
|
|
607
796
|
}
|
|
608
|
-
const typesText = (endpoint) => endpoint.eventTypes === null ? "(
|
|
797
|
+
const typesText = (endpoint) => endpoint.eventTypes === null ? "(no filter: 0.1 types)" : endpoint.eventTypes.join(",");
|
|
609
798
|
async function endpointsCommand(ctx, out, args) {
|
|
610
799
|
const [sub, ...rest] = args;
|
|
611
800
|
if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
|
|
@@ -623,13 +812,13 @@ async function endpointsCommand(ctx, out, args) {
|
|
|
623
812
|
out.err(connectionLine(target));
|
|
624
813
|
const { items } = await callSteward(target, () => clientFor(ctx, target).admin.endpoints.list());
|
|
625
814
|
if (values.json) out.out(JSON.stringify(items, null, 2));
|
|
626
|
-
else if (items.length === 0) out.out("
|
|
815
|
+
else if (items.length === 0) out.out("no endpoints — steward endpoints add --url <url> --out <file>");
|
|
627
816
|
else {
|
|
628
817
|
const rows = [[
|
|
629
818
|
"ID",
|
|
630
|
-
"
|
|
631
|
-
"
|
|
632
|
-
"
|
|
819
|
+
"STATUS",
|
|
820
|
+
"EVENTS",
|
|
821
|
+
"LAST DELIVERY",
|
|
633
822
|
"URL"
|
|
634
823
|
]];
|
|
635
824
|
for (const e of items) rows.push([
|
|
@@ -664,17 +853,17 @@ async function endpointsCommand(ctx, out, args) {
|
|
|
664
853
|
...values.description !== void 0 ? { description: values.description } : {}
|
|
665
854
|
};
|
|
666
855
|
const parsed = WebhookEndpointCreateInputSchema.safeParse(input);
|
|
667
|
-
if (!parsed.success) throw new UsageError(`endpoint
|
|
856
|
+
if (!parsed.success) throw new UsageError(`invalid endpoint (no request was sent)\n${schemaProblems(parsed.error.issues)}`);
|
|
668
857
|
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
669
858
|
out.err(connectionLine(target));
|
|
670
859
|
const steward = clientFor(ctx, target);
|
|
671
860
|
const result = await withSecretFile(ctx.cwd, file, secret, { force: values.force === true }, () => callSteward(target, () => steward.admin.endpoints.create(input)));
|
|
672
861
|
const endpoint = result.value;
|
|
673
|
-
out.out(`endpoint
|
|
862
|
+
out.out(`endpoint created → ${originOf(target.url)}`);
|
|
674
863
|
out.out(` id ${endpoint.id}`);
|
|
675
864
|
out.out(` url ${endpoint.url}`);
|
|
676
|
-
out.out(`
|
|
677
|
-
secretNotice(out, result.path, result.fallback, "
|
|
865
|
+
out.out(` events ${typesText(endpoint)}`);
|
|
866
|
+
secretNotice(out, result.path, result.fallback, "Move the secret into the product's Secret (STEWARD_WEBHOOK_SECRET), then delete the file.");
|
|
678
867
|
return 0;
|
|
679
868
|
}
|
|
680
869
|
if (sub === "rotate") {
|
|
@@ -689,15 +878,15 @@ async function endpointsCommand(ctx, out, args) {
|
|
|
689
878
|
const file = requireOption(values.out, "--out", "endpoints");
|
|
690
879
|
const secret = generateWebhookSecret();
|
|
691
880
|
const parsed = WebhookEndpointRotateInputSchema.safeParse({ secret });
|
|
692
|
-
if (!parsed.success) throw new UsageError(`
|
|
881
|
+
if (!parsed.success) throw new UsageError(`invalid secret\n${schemaProblems(parsed.error.issues)}`);
|
|
693
882
|
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
694
883
|
out.err(connectionLine(target));
|
|
695
884
|
const steward = clientFor(ctx, target);
|
|
696
885
|
const result = await withSecretFile(ctx.cwd, file, secret, { force: values.force === true }, () => callSteward(target, () => steward.admin.endpoints.rotate(id, { secret })));
|
|
697
|
-
out.out(`
|
|
886
|
+
out.out(`secret rotated → ${originOf(target.url)}`);
|
|
698
887
|
out.out(` id ${result.value.id}`);
|
|
699
888
|
out.out(` url ${result.value.url}`);
|
|
700
|
-
secretNotice(out, result.path, result.fallback, "
|
|
889
|
+
secretNotice(out, result.path, result.fallback, "Set STEWARD_WEBHOOK_SECRET in the product's Secret to \"new,old\" and roll out; the old secret stays in steward as a second signature for the transition. Then delete the file.");
|
|
701
890
|
return 0;
|
|
702
891
|
}
|
|
703
892
|
if (sub === "deactivate") {
|
|
@@ -707,10 +896,10 @@ async function endpointsCommand(ctx, out, args) {
|
|
|
707
896
|
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
708
897
|
out.err(connectionLine(target));
|
|
709
898
|
const endpoint = await callSteward(target, () => clientFor(ctx, target).admin.endpoints.deactivate(positionals[0]));
|
|
710
|
-
out.out(`endpoint
|
|
899
|
+
out.out(`endpoint deactivated → ${originOf(target.url)}: ${endpoint.id} (${endpoint.url}, status ${endpoint.status})`);
|
|
711
900
|
return 0;
|
|
712
901
|
}
|
|
713
|
-
throw new UsageError(`
|
|
902
|
+
throw new UsageError(`unknown subcommand: endpoints ${sub} (details: steward endpoints --help)`);
|
|
714
903
|
}
|
|
715
904
|
function help$3(out) {
|
|
716
905
|
out.out(ENDPOINTS_USAGE);
|
|
@@ -725,16 +914,22 @@ function secretNotice(out, path, fallback, next) {
|
|
|
725
914
|
//#endregion
|
|
726
915
|
//#region src/commands/bank-transfers.ts
|
|
727
916
|
const BANK_TRANSFERS_USAGE = `Usage:
|
|
728
|
-
steward bank-transfers list [--status pending|expired] [--
|
|
917
|
+
steward bank-transfers list [--status pending|expired] [--rate <rate> [--currency <CUR>]]
|
|
918
|
+
[--json]
|
|
729
919
|
steward bank-transfers record <code> --amount <minor> --currency <CUR> --received-at <iso>
|
|
730
|
-
--bank-ref <ref> [--
|
|
920
|
+
--bank-ref <ref> [--rate <rate>]
|
|
921
|
+
[--checkout <id> [--accept-expired] | --invoice <id>]
|
|
731
922
|
[--yes] [--json]
|
|
923
|
+
steward bank-transfers fx-report [--from <iso>] [--to <iso>] [--json | --csv]
|
|
732
924
|
|
|
733
925
|
Bank transfer (havale/EFT) reconciliation (/v1/admin/bank-transfers).
|
|
734
926
|
|
|
735
927
|
list: what the bank statement is matched against. pending (default): checkouts waiting for a
|
|
736
928
|
transfer and unpaid invoices of accounts with an order code, by deadline; expired: checkouts
|
|
737
|
-
that expired in the last 30 days.
|
|
929
|
+
that expired in the last 30 days. --rate previews a transfer in another currency: next to each
|
|
930
|
+
item the product lets be paid in another currency (settings.billing.bankTransfer.settleIn) it
|
|
931
|
+
shows the amount expected at that rate (--currency names it when an item accepts several). It
|
|
932
|
+
writes nothing.
|
|
738
933
|
|
|
739
934
|
record: a transfer seen on the bank account. <code> is the order code from the transfer
|
|
740
935
|
description (case and dashes are forgiven). Only a checkout or unpaid invoice waiting for
|
|
@@ -745,6 +940,18 @@ number; one payment per reference. When several items match, name one with --che
|
|
|
745
940
|
A refused transfer is refunded through the bank. Recording needs confirmation (a prompt on a
|
|
746
941
|
terminal, otherwise --yes): it starts a subscription or pays an invoice.
|
|
747
942
|
|
|
943
|
+
record --rate: a transfer in another currency than the item's (a USD invoice paid with TRY,
|
|
944
|
+
when the product allows it). --rate is the exchange rate you enter: --currency per 1 unit of
|
|
945
|
+
the item's currency, up to 6 decimal places (34.5218). The item matches when --amount is
|
|
946
|
+
within the product's tolerance (fxToleranceBps, default 0.5%) of its amount at that rate, and
|
|
947
|
+
is settled in its own currency. --rate is required for such a transfer and refused for one in
|
|
948
|
+
the item's currency. Steward never looks a rate up.
|
|
949
|
+
|
|
950
|
+
fx-report: the payments received in another currency (invoice number and date, amount settled,
|
|
951
|
+
amount received, the rate entered, received date), latest first; --from (inclusive) and --to
|
|
952
|
+
(exclusive) are ISO-8601 with an offset, by received date. The accountant's input for
|
|
953
|
+
exchange-difference invoices, which steward does not issue.
|
|
954
|
+
|
|
748
955
|
Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
|
|
749
956
|
const WITH_OFFSET = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/;
|
|
750
957
|
async function bankTransfersCommand(ctx, out, args) {
|
|
@@ -757,21 +964,32 @@ async function bankTransfersCommand(ctx, out, args) {
|
|
|
757
964
|
const { values, positionals } = parse(rest, {
|
|
758
965
|
...HELP_OPTION,
|
|
759
966
|
status: { type: "string" },
|
|
967
|
+
rate: { type: "string" },
|
|
968
|
+
currency: { type: "string" },
|
|
760
969
|
json: { type: "boolean" }
|
|
761
970
|
}, "bank-transfers");
|
|
762
971
|
if (values.help) return help$2(out);
|
|
763
972
|
expectPositionals(positionals, 0, 0, "bank-transfers");
|
|
764
973
|
const status = values.status ?? "pending";
|
|
765
974
|
if (status !== "pending" && status !== "expired") throw new UsageError("--status: pending or expired");
|
|
975
|
+
const rate = values.rate !== void 0 ? parseRate(values.rate) : void 0;
|
|
976
|
+
if (values.currency !== void 0 && rate === void 0) throw new UsageError("--currency needs --rate");
|
|
977
|
+
const currency = values.currency?.toUpperCase();
|
|
978
|
+
if (currency !== void 0 && !/^[A-Z]{3}$/.test(currency)) throw new UsageError("--currency: an ISO-4217 code (TRY)");
|
|
979
|
+
const preview = {
|
|
980
|
+
...rate !== void 0 ? { rate } : {},
|
|
981
|
+
...currency !== void 0 ? { currency } : {}
|
|
982
|
+
};
|
|
766
983
|
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
767
984
|
out.err(connectionLine(target));
|
|
768
|
-
const { items } = await callSteward(target, () => clientFor(ctx, target).admin.bankTransfers.list(status));
|
|
985
|
+
const { items } = await callSteward(target, () => clientFor(ctx, target).admin.bankTransfers.list(status, preview));
|
|
769
986
|
if (values.json) out.out(JSON.stringify(items, null, 2));
|
|
770
987
|
else if (items.length === 0) out.out(`no ${status} bank transfers`);
|
|
771
988
|
else {
|
|
772
989
|
const rows = [[
|
|
773
990
|
"CODE",
|
|
774
991
|
"AMOUNT",
|
|
992
|
+
...rate !== void 0 ? [`EXPECTED @ ${rate}`] : [],
|
|
775
993
|
"DEADLINE",
|
|
776
994
|
"KIND",
|
|
777
995
|
"PLAN",
|
|
@@ -781,6 +999,7 @@ async function bankTransfersCommand(ctx, out, args) {
|
|
|
781
999
|
for (const i of items) rows.push([
|
|
782
1000
|
i.code ?? "-",
|
|
783
1001
|
formatMinor(i.totalMinor, i.currency),
|
|
1002
|
+
...rate !== void 0 ? [i.expectedMinor !== void 0 && i.expectedCurrency !== void 0 ? formatMinor(i.expectedMinor, i.expectedCurrency) : "-"] : [],
|
|
784
1003
|
i.deadline ?? "-",
|
|
785
1004
|
i.kind,
|
|
786
1005
|
i.planCode ?? "-",
|
|
@@ -798,6 +1017,7 @@ async function bankTransfersCommand(ctx, out, args) {
|
|
|
798
1017
|
currency: { type: "string" },
|
|
799
1018
|
"received-at": { type: "string" },
|
|
800
1019
|
"bank-ref": { type: "string" },
|
|
1020
|
+
rate: { type: "string" },
|
|
801
1021
|
checkout: { type: "string" },
|
|
802
1022
|
invoice: { type: "string" },
|
|
803
1023
|
"accept-expired": { type: "boolean" },
|
|
@@ -817,6 +1037,7 @@ async function bankTransfersCommand(ctx, out, args) {
|
|
|
817
1037
|
currency: requireOption(values.currency, "--currency", "bank-transfers").toUpperCase(),
|
|
818
1038
|
receivedAt,
|
|
819
1039
|
bankRef: requireOption(values["bank-ref"], "--bank-ref", "bank-transfers"),
|
|
1040
|
+
...values.rate !== void 0 ? { rate: parseRate(values.rate) } : {},
|
|
820
1041
|
...values.checkout !== void 0 ? { checkoutSessionId: values.checkout } : {},
|
|
821
1042
|
...values.invoice !== void 0 ? { invoiceId: values.invoice } : {},
|
|
822
1043
|
...values["accept-expired"] ? { acceptExpired: true } : {}
|
|
@@ -825,7 +1046,7 @@ async function bankTransfersCommand(ctx, out, args) {
|
|
|
825
1046
|
if (!parsed.success) throw new UsageError(`invalid transfer (nothing was sent)\n${parsed.error.issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(root)"}: ${issue.message}`).join("\n")}`);
|
|
826
1047
|
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
827
1048
|
out.err(connectionLine(target));
|
|
828
|
-
if (!await confirm(ctx, `Record ${formatMinor(input.amountMinor, input.currency)} for order code ${input.code} (bank ref ${input.bankRef})?`, {
|
|
1049
|
+
if (!await confirm(ctx, `Record ${formatMinor(input.amountMinor, input.currency)}${input.rate !== void 0 ? ` at the rate ${input.rate}` : ""} for order code ${input.code} (bank ref ${input.bankRef})?`, {
|
|
829
1050
|
yes: values.yes === true,
|
|
830
1051
|
notConfirmed: "nothing was recorded"
|
|
831
1052
|
})) {
|
|
@@ -837,11 +1058,83 @@ async function bankTransfersCommand(ctx, out, args) {
|
|
|
837
1058
|
out.out(JSON.stringify(recorded, null, 2));
|
|
838
1059
|
return 0;
|
|
839
1060
|
}
|
|
840
|
-
|
|
1061
|
+
const settled = recorded.fxRate !== void 0 && recorded.settledAmountMinor !== void 0 && recorded.settledCurrency !== void 0 ? ` (settled ${formatMinor(recorded.settledAmountMinor, recorded.settledCurrency)} at ${recorded.fxRate})` : "";
|
|
1062
|
+
out.out((recorded.invoiceId !== null ? `recorded → ${originOf(target.url)}: account ${recorded.accountRef}, invoice ${recorded.invoiceId} paid${recorded.paidAfterWriteoff ? " (after write-off)" : ""}` : `recorded → ${originOf(target.url)}: account ${recorded.accountRef}, checkout ${recorded.checkoutSessionId} completed, subscription ${recorded.subscriptionId} started${recorded.replacedSubscriptionId !== null ? `, subscription ${recorded.replacedSubscriptionId} replaced` : ""}${recorded.acceptedAfterExpiry ? " (accepted after expiry)" : ""}`) + settled);
|
|
1063
|
+
return 0;
|
|
1064
|
+
}
|
|
1065
|
+
if (sub === "fx-report") {
|
|
1066
|
+
const { values, positionals } = parse(rest, {
|
|
1067
|
+
...HELP_OPTION,
|
|
1068
|
+
from: { type: "string" },
|
|
1069
|
+
to: { type: "string" },
|
|
1070
|
+
json: { type: "boolean" },
|
|
1071
|
+
csv: { type: "boolean" }
|
|
1072
|
+
}, "bank-transfers");
|
|
1073
|
+
if (values.help) return help$2(out);
|
|
1074
|
+
expectPositionals(positionals, 0, 0, "bank-transfers");
|
|
1075
|
+
if (values.json && values.csv) throw new UsageError("--json or --csv, not both");
|
|
1076
|
+
if (values.from !== void 0 && !WITH_OFFSET.test(values.from)) throw new UsageError("--from: ISO-8601 with an offset (2026-09-01T00:00:00+03:00)");
|
|
1077
|
+
if (values.to !== void 0 && !WITH_OFFSET.test(values.to)) throw new UsageError("--to: ISO-8601 with an offset (2026-10-01T00:00:00+03:00)");
|
|
1078
|
+
const range = {
|
|
1079
|
+
...values.from !== void 0 ? { from: values.from } : {},
|
|
1080
|
+
...values.to !== void 0 ? { to: values.to } : {}
|
|
1081
|
+
};
|
|
1082
|
+
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
1083
|
+
out.err(connectionLine(target));
|
|
1084
|
+
const { items } = await callSteward(target, () => clientFor(ctx, target).admin.bankTransfers.fxReport(range));
|
|
1085
|
+
if (values.json) out.out(JSON.stringify(items, null, 2));
|
|
1086
|
+
else if (values.csv) {
|
|
1087
|
+
out.out("invoice_number,invoice_date,amount_minor,currency,received_minor,received_currency,fx_rate,received_at,bank_ref,account,payment_id");
|
|
1088
|
+
for (const i of items) out.out([
|
|
1089
|
+
i.invoiceNumber ?? "",
|
|
1090
|
+
i.invoiceIssuedAt ?? "",
|
|
1091
|
+
i.amountMinor,
|
|
1092
|
+
i.currency,
|
|
1093
|
+
i.receivedAmountMinor,
|
|
1094
|
+
i.receivedCurrency,
|
|
1095
|
+
i.fxRate,
|
|
1096
|
+
i.receivedAt,
|
|
1097
|
+
i.bankRef,
|
|
1098
|
+
i.accountRef,
|
|
1099
|
+
i.paymentId
|
|
1100
|
+
].map(csvField).join(","));
|
|
1101
|
+
} else if (items.length === 0) out.out("no bank transfers in another currency");
|
|
1102
|
+
else {
|
|
1103
|
+
const rows = [[
|
|
1104
|
+
"INVOICE",
|
|
1105
|
+
"INVOICE DATE",
|
|
1106
|
+
"AMOUNT",
|
|
1107
|
+
"RECEIVED",
|
|
1108
|
+
"RATE",
|
|
1109
|
+
"RECEIVED AT",
|
|
1110
|
+
"BANK REF",
|
|
1111
|
+
"ACCOUNT"
|
|
1112
|
+
]];
|
|
1113
|
+
for (const i of items) rows.push([
|
|
1114
|
+
i.invoiceNumber ?? "-",
|
|
1115
|
+
i.invoiceIssuedAt ?? "-",
|
|
1116
|
+
formatMinor(i.amountMinor, i.currency),
|
|
1117
|
+
formatMinor(i.receivedAmountMinor, i.receivedCurrency),
|
|
1118
|
+
i.fxRate,
|
|
1119
|
+
i.receivedAt,
|
|
1120
|
+
i.bankRef,
|
|
1121
|
+
i.accountRef
|
|
1122
|
+
]);
|
|
1123
|
+
for (const line of table(rows)) out.out(line);
|
|
1124
|
+
}
|
|
841
1125
|
return 0;
|
|
842
1126
|
}
|
|
843
1127
|
throw new UsageError(`unknown subcommand: bank-transfers ${sub} (see: steward bank-transfers --help)`);
|
|
844
1128
|
}
|
|
1129
|
+
function parseRate(value) {
|
|
1130
|
+
if (!FxRateSchema.safeParse(value).success) throw new UsageError("--rate: a positive decimal with at most 6 decimal places (34.5218)");
|
|
1131
|
+
return value;
|
|
1132
|
+
}
|
|
1133
|
+
/** RFC 4180 quoting; a leading = + - @ is prefixed so a spreadsheet does not read the field as a formula. */
|
|
1134
|
+
function csvField(value) {
|
|
1135
|
+
const text = typeof value === "string" && /^[=+\-@]/.test(value) ? `'${value}` : String(value);
|
|
1136
|
+
return /[",\n\r]/.test(text) ? `"${text.replace(/"/g, "\"\"")}"` : text;
|
|
1137
|
+
}
|
|
845
1138
|
function help$2(out) {
|
|
846
1139
|
out.out(BANK_TRANSFERS_USAGE);
|
|
847
1140
|
return 0;
|
|
@@ -864,7 +1157,7 @@ function pickExport(mod, file) {
|
|
|
864
1157
|
if (mod.default !== void 0) return mod.default;
|
|
865
1158
|
const candidates = Object.values(mod).filter(hasSyncInput);
|
|
866
1159
|
if (candidates.length === 1) return candidates[0];
|
|
867
|
-
throw new CliError(`${file}:
|
|
1160
|
+
throw new CliError(`${file}: no catalog found — expected \`export const catalog = defineCatalog(…)\` or a default export`);
|
|
868
1161
|
}
|
|
869
1162
|
async function loadCatalogFile(ctx, file) {
|
|
870
1163
|
const path = resolve(ctx.cwd, file);
|
|
@@ -875,46 +1168,46 @@ async function loadCatalogFile(ctx, file) {
|
|
|
875
1168
|
try {
|
|
876
1169
|
text = await readFile(path, "utf8");
|
|
877
1170
|
} catch (error) {
|
|
878
|
-
throw new CliError(errnoCode(error) === "ENOENT" ? `
|
|
1171
|
+
throw new CliError(errnoCode(error) === "ENOENT" ? `catalog file does not exist: ${file}` : `could not read the catalog file: ${file}`);
|
|
879
1172
|
}
|
|
880
1173
|
try {
|
|
881
1174
|
exported = JSON.parse(text);
|
|
882
1175
|
} catch {
|
|
883
|
-
throw new CliError(`${file}:
|
|
1176
|
+
throw new CliError(`${file}: not valid JSON`);
|
|
884
1177
|
}
|
|
885
1178
|
} else if (MODULE_EXTENSIONS.has(ext) || TS_EXTENSIONS.has(ext)) {
|
|
886
|
-
if (TS_EXTENSIONS.has(ext) && !ctx.typescript) throw new CliError(`${file}:
|
|
1179
|
+
if (TS_EXTENSIONS.has(ext) && !ctx.typescript) throw new CliError(`${file}: this Node version cannot load a TypeScript file directly (${process.version}). Use Node ≥ 22.18, set \`NODE_OPTIONS=--experimental-strip-types\` or export the catalog as .mjs/.json.`);
|
|
887
1180
|
let mod;
|
|
888
1181
|
try {
|
|
889
1182
|
await readFile(path);
|
|
890
1183
|
} catch (error) {
|
|
891
|
-
throw new CliError(errnoCode(error) === "ENOENT" ? `
|
|
1184
|
+
throw new CliError(errnoCode(error) === "ENOENT" ? `catalog file does not exist: ${file}` : `could not read the catalog file: ${file}`);
|
|
892
1185
|
}
|
|
893
1186
|
try {
|
|
894
1187
|
mod = await ctx.importModule(pathToFileURL(path).href);
|
|
895
1188
|
} catch (error) {
|
|
896
|
-
throw new CliError(
|
|
1189
|
+
throw new CliError(`could not load ${file}: ${error instanceof Error ? error.message : String(error)}`);
|
|
897
1190
|
}
|
|
898
1191
|
exported = pickExport(mod, file);
|
|
899
|
-
} else throw new UsageError(`
|
|
1192
|
+
} else throw new UsageError(`the catalog file must be .ts, .mts, .js, .mjs, .cjs or .json: ${file}`);
|
|
900
1193
|
let input;
|
|
901
1194
|
try {
|
|
902
1195
|
input = hasSyncInput(exported) ? exported.toSyncInput() : exported;
|
|
903
1196
|
} catch (error) {
|
|
904
|
-
throw new CliError(`${file}: toSyncInput()
|
|
1197
|
+
throw new CliError(`${file}: toSyncInput() failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
905
1198
|
}
|
|
906
1199
|
const parsed = CatalogSyncInputSchema.safeParse(input);
|
|
907
|
-
if (!parsed.success) throw new CliError(`${file}:
|
|
1200
|
+
if (!parsed.success) throw new CliError(`${file}: invalid catalog (no request was sent)\n${parsed.error.issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(root)"}: ${issue.message}`).join("\n")}`);
|
|
908
1201
|
return input;
|
|
909
1202
|
}
|
|
910
1203
|
//#endregion
|
|
911
1204
|
//#region src/commands/catalog.ts
|
|
912
|
-
const CATALOG_USAGE = `
|
|
1205
|
+
const CATALOG_USAGE = `Usage: steward catalog push <file> [--yes]
|
|
913
1206
|
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
(\`export const catalog = defineCatalog(…)\`
|
|
917
|
-
(
|
|
1207
|
+
Syncs the catalog definition to steward (PUT /v1/admin/catalog), then prints the version
|
|
1208
|
+
and the counts. File: .ts/.mts (Node type stripping, Node ≥ 22.18), .js/.mjs/.cjs
|
|
1209
|
+
(\`export const catalog = defineCatalog(…)\` or a default export) or .json
|
|
1210
|
+
(the sync body). No request is sent for an invalid catalog.
|
|
918
1211
|
|
|
919
1212
|
Before pushing, prints what changes against steward's current catalog: benefits
|
|
920
1213
|
(new, changed, archived, plan benefit lists) and prices (new, deactivated, amount or
|
|
@@ -931,8 +1224,13 @@ are fixed once it has counted a period (422 meter_locked: use a new meter code).
|
|
|
931
1224
|
catalog with meters or metered prices is pushed only to a steward whose GET /v1/me
|
|
932
1225
|
lists the "meters" capability.
|
|
933
1226
|
|
|
934
|
-
|
|
935
|
-
|
|
1227
|
+
Unlisted plans: a plan with "listed: false" is sellable but not offered in the hosted
|
|
1228
|
+
portal's "Change plan"; the diff shows a plan that becomes unlisted or listed. Such a
|
|
1229
|
+
catalog is pushed only to a steward whose GET /v1/me lists the "unlisted_plans"
|
|
1230
|
+
capability (an older steward would offer the plan).
|
|
1231
|
+
|
|
1232
|
+
Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).
|
|
1233
|
+
Exit code 1: a price could not be created at the provider (run the sync again);
|
|
936
1234
|
the push was refused or not confirmed.`;
|
|
937
1235
|
const PUSH_OPTIONS = {
|
|
938
1236
|
...HELP_OPTION,
|
|
@@ -942,20 +1240,20 @@ const PUSH_OPTIONS = {
|
|
|
942
1240
|
}
|
|
943
1241
|
};
|
|
944
1242
|
const list = (items) => items.length > 0 ? items.join(", ") : "-";
|
|
945
|
-
/**
|
|
1243
|
+
/** Sync + version read; the summary lines and whether there were provider errors. */
|
|
946
1244
|
async function pushCatalog(steward, target, input) {
|
|
947
1245
|
const result = await callSteward(target, () => steward.admin.catalog.sync(input));
|
|
948
|
-
const version = (await callSteward(target, () => steward.catalog.read())).etag?.replace(/^W\//, "").replace(/"/g, "") ?? "
|
|
1246
|
+
const version = (await callSteward(target, () => steward.catalog.read())).etag?.replace(/^W\//, "").replace(/"/g, "") ?? "unknown";
|
|
949
1247
|
const benefitCount = Object.keys(input.benefits ?? {}).length;
|
|
950
1248
|
const meterCount = Object.keys(input.meters ?? {}).length;
|
|
951
1249
|
const meteredCount = (input.meteredPrices ?? []).length;
|
|
952
1250
|
const metering = `${meterCount > 0 ? ` · ${meterCount} meter${meterCount === 1 ? "" : "s"}` : ""}${meteredCount > 0 ? ` · ${meteredCount} metered price${meteredCount === 1 ? "" : "s"}` : ""}`;
|
|
953
|
-
const lines = [`
|
|
954
|
-
lines.push(`
|
|
955
|
-
lines.push(`
|
|
956
|
-
if (result.unchanged) lines.push("
|
|
1251
|
+
const lines = [`catalog synced → ${originOf(target.url)}`];
|
|
1252
|
+
lines.push(` version ${version}`);
|
|
1253
|
+
lines.push(` defines ${input.plans.length} plan${input.plans.length === 1 ? "" : "s"} · ${input.features.length} feature${input.features.length === 1 ? "" : "s"} · ${input.prices.length} price${input.prices.length === 1 ? "" : "s"}${benefitCount > 0 ? ` · ${benefitCount} benefit${benefitCount === 1 ? "" : "s"}` : ""}${metering} · default plan ${input.defaultPlanCode}`);
|
|
1254
|
+
if (result.unchanged) lines.push(" changes none");
|
|
957
1255
|
else {
|
|
958
|
-
lines.push(`
|
|
1256
|
+
lines.push(` changes new prices ${result.createdPrices.length} · deactivated prices ${result.deactivatedPrices.length} · changed plans: ${list(result.changedPlans)} · retired plans: ${list(result.retiredPlans)} · removed features: ${list(result.removedFeatures)}${result.defaultPlanChanged ? " · default plan changed" : ""}`);
|
|
959
1257
|
const changedBenefits = result.changedBenefits ?? [];
|
|
960
1258
|
const archivedBenefits = result.archivedBenefits ?? [];
|
|
961
1259
|
if (changedBenefits.length > 0 || archivedBenefits.length > 0) lines.push(` benefits changed: ${list(changedBenefits)} · archived: ${list(archivedBenefits)}`);
|
|
@@ -970,7 +1268,7 @@ async function pushCatalog(steward, target, input) {
|
|
|
970
1268
|
];
|
|
971
1269
|
if (created.length + updated.length + deactivated.length > 0) lines.push(` metered new ${created.length} · updated in place ${updated.length} · deactivated ${deactivated.length}`);
|
|
972
1270
|
}
|
|
973
|
-
for (const error of result.providerErrors) lines.push(` ✗
|
|
1271
|
+
for (const error of result.providerErrors) lines.push(` ✗ provider error: price ${error.priceId} (${error.provider}: ${error.code}) — run the sync again`);
|
|
974
1272
|
return {
|
|
975
1273
|
lines,
|
|
976
1274
|
providerErrors: result.providerErrors.length
|
|
@@ -983,16 +1281,22 @@ function currentCatalog(steward, target) {
|
|
|
983
1281
|
throw error;
|
|
984
1282
|
}));
|
|
985
1283
|
}
|
|
1284
|
+
/** What the catalog defines, per capability it needs (the refusal names it). */
|
|
1285
|
+
const CAPABILITY_LABELS = {
|
|
1286
|
+
benefits: "benefits",
|
|
1287
|
+
meters: "meters",
|
|
1288
|
+
unlisted_plans: "unlisted plans"
|
|
1289
|
+
};
|
|
986
1290
|
/**
|
|
987
|
-
* Refuses a catalog whose benefits or
|
|
988
|
-
* drops the keys silently. `needed`: the capabilities the catalog needs
|
|
1291
|
+
* Refuses a catalog whose benefits, meters or unlisted plans steward does not understand (M27): an
|
|
1292
|
+
* older steward drops the keys silently. `needed`: the capabilities the catalog needs.
|
|
989
1293
|
*/
|
|
990
1294
|
async function requireCapabilities(steward, target, needed) {
|
|
991
1295
|
if (needed.length === 0) return;
|
|
992
1296
|
const me = await callSteward(target, () => steward.me());
|
|
993
1297
|
const missing = needed.filter((capability) => !(me.capabilities ?? []).includes(capability));
|
|
994
1298
|
if (missing.length === 0) return;
|
|
995
|
-
throw new CliError(`the catalog defines ${missing.join(" and ")} but steward at ${originOf(target.url)} does not support them (GET /v1/me capabilities has no ${missing.map((c) => `"${c}"`).join(", ")}; it would drop them silently). Update steward first; nothing was pushed.`);
|
|
1299
|
+
throw new CliError(`the catalog defines ${missing.map((c) => CAPABILITY_LABELS[c]).join(" and ")} but steward at ${originOf(target.url)} does not support them (GET /v1/me capabilities has no ${missing.map((c) => `"${c}"`).join(", ")}; it would drop them silently). Update steward first; nothing was pushed.`);
|
|
996
1300
|
}
|
|
997
1301
|
async function catalogCommand(ctx, out, args) {
|
|
998
1302
|
const [sub, ...rest] = args;
|
|
@@ -1000,7 +1304,7 @@ async function catalogCommand(ctx, out, args) {
|
|
|
1000
1304
|
out.out(CATALOG_USAGE);
|
|
1001
1305
|
return sub === void 0 ? 2 : 0;
|
|
1002
1306
|
}
|
|
1003
|
-
if (sub !== "push") throw new UsageError(`
|
|
1307
|
+
if (sub !== "push") throw new UsageError(`unknown subcommand: catalog ${sub} (details: steward catalog --help)`);
|
|
1004
1308
|
const { values, positionals } = parse(rest, PUSH_OPTIONS, "catalog push");
|
|
1005
1309
|
if (values.help) {
|
|
1006
1310
|
out.out(CATALOG_USAGE);
|
|
@@ -1011,7 +1315,11 @@ async function catalogCommand(ctx, out, args) {
|
|
|
1011
1315
|
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
1012
1316
|
out.err(connectionLine(target));
|
|
1013
1317
|
const steward = clientFor(ctx, target);
|
|
1014
|
-
await requireCapabilities(steward, target, [
|
|
1318
|
+
await requireCapabilities(steward, target, [
|
|
1319
|
+
...definesBenefits(input) ? ["benefits"] : [],
|
|
1320
|
+
...definesMeters(input) ? ["meters"] : [],
|
|
1321
|
+
...definesUnlistedPlans(input) ? ["unlisted_plans"] : []
|
|
1322
|
+
]);
|
|
1015
1323
|
const diff = diffCatalog(await currentCatalog(steward, target), input);
|
|
1016
1324
|
for (const line of describeDiff(diff)) out.out(line);
|
|
1017
1325
|
const priceChanges = priceChangeCount(diff);
|
|
@@ -1208,33 +1516,34 @@ async function creditsCommand(ctx, out, args) {
|
|
|
1208
1516
|
}
|
|
1209
1517
|
//#endregion
|
|
1210
1518
|
//#region src/commands/doctor.ts
|
|
1211
|
-
const DOCTOR_USAGE = `
|
|
1519
|
+
const DOCTOR_USAGE = `Usage: steward doctor [--json]
|
|
1212
1520
|
|
|
1213
|
-
GET /v1/doctor
|
|
1214
|
-
hosted (
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1521
|
+
The GET /v1/doctor report. Sections in order: status, catalog, provider, settings,
|
|
1522
|
+
hosted (page readiness), endpoints (delivery diagnosis), dunning, emails and, for a
|
|
1523
|
+
product with meters, metering/events/overage; at the end the errors, warnings and info
|
|
1524
|
+
lists. If APP_URL is set it is compared with steward's appUrl and allowed return
|
|
1525
|
+
origins.
|
|
1218
1526
|
|
|
1219
|
-
|
|
1220
|
-
STEWARD_ADMIN_API_KEY).
|
|
1221
|
-
|
|
1222
|
-
|
|
1527
|
+
Connection: STEWARD_URL + STEWARD_API_KEY (if both are missing, STEWARD_ADMIN_URL +
|
|
1528
|
+
STEWARD_ADMIN_API_KEY). If even one steward connection variable is in the
|
|
1529
|
+
environment, the connection and APP_URL are read only from the environment
|
|
1530
|
+
(./.env.local is not read); otherwise from ./.env.local. The source and the target's
|
|
1531
|
+
origin are written to stderr.
|
|
1223
1532
|
|
|
1224
|
-
|
|
1225
|
-
|
|
1533
|
+
Exit code: 0 ready; 1 the report is not ok (a warning of error severity) or APP_URL
|
|
1534
|
+
is not allowed in steward.
|
|
1226
1535
|
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
events, meters, overage)
|
|
1230
|
-
rollup
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1536
|
+
Metering: for a product whose catalog defines meters, the "metering" line shows the
|
|
1537
|
+
meters and metered prices (GET /v1/catalog) and steward's capabilities (GET /v1/me:
|
|
1538
|
+
events, meters, overage); then come the report's "events" section (pending events,
|
|
1539
|
+
rollup lag, a sample of the last 7 days: unmatched event names, invalid values,
|
|
1540
|
+
meters without events) and "overage" section (charge mode, metered prices,
|
|
1541
|
+
subscriptions without a locked rate, carried charges). Metering warnings are in the
|
|
1542
|
+
lists below as usual.
|
|
1234
1543
|
|
|
1235
|
-
--json
|
|
1236
|
-
cliMetering:
|
|
1237
|
-
/** `APP_URL` (
|
|
1544
|
+
--json writes the report as JSON (+ cliWarnings: the local APP_URL comparison;
|
|
1545
|
+
cliMetering: the catalog and capability facts of the metering line)`;
|
|
1546
|
+
/** `APP_URL` (the product's own address; the checkout `successUrl` is built from it) ↔ steward settings. */
|
|
1238
1547
|
function appUrlWarnings(appUrl, report) {
|
|
1239
1548
|
if (appUrl === void 0) return [];
|
|
1240
1549
|
let origin;
|
|
@@ -1244,18 +1553,18 @@ function appUrlWarnings(appUrl, report) {
|
|
|
1244
1553
|
return [{
|
|
1245
1554
|
code: "app_url_env_invalid",
|
|
1246
1555
|
severity: "error",
|
|
1247
|
-
message: "APP_URL
|
|
1556
|
+
message: "APP_URL is not a valid address"
|
|
1248
1557
|
}];
|
|
1249
1558
|
}
|
|
1250
1559
|
if (!report.settings.returnOrigins.includes(origin)) return [{
|
|
1251
1560
|
code: "app_url_not_allowed",
|
|
1252
1561
|
severity: "error",
|
|
1253
|
-
message: `APP_URL origin
|
|
1562
|
+
message: `APP_URL origin (${origin}) is not an allowed return origin in steward (appUrl: ${report.settings.appUrl ?? "none"}): checkout gets return_url_not_allowed — steward settings set --app-url ${origin}`
|
|
1254
1563
|
}];
|
|
1255
1564
|
if (report.settings.appUrl !== null && originOf(report.settings.appUrl) !== origin) return [{
|
|
1256
1565
|
code: "app_url_mismatch",
|
|
1257
1566
|
severity: "warning",
|
|
1258
|
-
message: `APP_URL (${origin}) steward appUrl
|
|
1567
|
+
message: `APP_URL (${origin}) differs from steward's appUrl (${report.settings.appUrl}): the hosted page's "back to product" link goes to appUrl`
|
|
1259
1568
|
}];
|
|
1260
1569
|
return [];
|
|
1261
1570
|
}
|
|
@@ -1326,9 +1635,9 @@ const SEVERITY_ORDER = [
|
|
|
1326
1635
|
"info"
|
|
1327
1636
|
];
|
|
1328
1637
|
const SEVERITY_TITLE = {
|
|
1329
|
-
error: "
|
|
1330
|
-
warning: "
|
|
1331
|
-
info: "
|
|
1638
|
+
error: "errors",
|
|
1639
|
+
warning: "warnings",
|
|
1640
|
+
info: "info"
|
|
1332
1641
|
};
|
|
1333
1642
|
const yesNo = (value) => value ? "✓" : "✗";
|
|
1334
1643
|
function countBySeverity(warnings) {
|
|
@@ -1337,34 +1646,34 @@ function countBySeverity(warnings) {
|
|
|
1337
1646
|
warnings: warnings.filter((w) => w.severity === "warning").length
|
|
1338
1647
|
};
|
|
1339
1648
|
}
|
|
1340
|
-
/**
|
|
1649
|
+
/** The full human-readable report. */
|
|
1341
1650
|
function formatDoctorReport(report, cliWarnings, metering = null) {
|
|
1342
1651
|
const all = [...report.warnings, ...cliWarnings];
|
|
1343
1652
|
const { errors, warnings } = countBySeverity(all);
|
|
1344
1653
|
const ready = errors === 0;
|
|
1345
1654
|
const lines = [];
|
|
1346
1655
|
lines.push(`steward doctor — ${report.product.code} (${report.product.name}) · ${report.checkedAt}`);
|
|
1347
|
-
lines.push(`
|
|
1656
|
+
lines.push(`status ${ready ? "READY ✓" : "PROBLEMS ✗"} (${plural(errors, "error")}, ${plural(warnings, "warning")})`);
|
|
1348
1657
|
lines.push("");
|
|
1349
1658
|
const { catalog, provider, settings, hosted } = report;
|
|
1350
|
-
lines.push(`
|
|
1659
|
+
lines.push(`catalog synced ${yesNo(catalog.synced)}${catalog.version !== null ? ` · version ${catalog.version}` : ""} · ${plural(catalog.plans, "plan")} · ${plural(catalog.sellablePrices, "sellable price")} · ${catalog.unsellablePrices.length} unsellable`);
|
|
1351
1660
|
for (const price of catalog.unsellablePrices) lines.push(` ✗ ${price.planCode} ${price.interval}×${price.intervalCount} ${price.currency}: ${price.reason}`);
|
|
1352
|
-
const providerState = !provider.configured ? "
|
|
1353
|
-
const providerError = provider.lastError ? ` ·
|
|
1354
|
-
lines.push(`
|
|
1355
|
-
lines.push(`
|
|
1661
|
+
const providerState = !provider.configured ? "not configured ✗" : provider.healthy === false ? "unreachable !" : "configured ✓";
|
|
1662
|
+
const providerError = provider.lastError ? ` · last error ${provider.lastError.code} (${provider.lastError.operation}, ${provider.lastError.at})` : "";
|
|
1663
|
+
lines.push(`provider ${provider.id}${provider.environment !== null ? ` · ${provider.environment}` : ""} · ${providerState}${providerError}`);
|
|
1664
|
+
lines.push(`settings appUrl ${settings.appUrl ?? "none"} · return origins: ${settings.returnOrigins.length > 0 ? settings.returnOrigins.join(", ") : "none"}`);
|
|
1356
1665
|
const missing = [...hosted.branding.missing.map((field) => `branding.${field}`), ...hosted.legalLinks.missing];
|
|
1357
|
-
lines.push(`hosted ${hosted.ready ? "
|
|
1358
|
-
if (report.endpoints.length === 0) lines.push("
|
|
1666
|
+
lines.push(`hosted ${hosted.ready ? "ready ✓" : `not ready ✗${missing.length > 0 ? ` (missing: ${missing.join(", ")})` : ""}`}`);
|
|
1667
|
+
if (report.endpoints.length === 0) lines.push("endpoints none");
|
|
1359
1668
|
else {
|
|
1360
|
-
lines.push("
|
|
1669
|
+
lines.push("endpoints");
|
|
1361
1670
|
for (const endpoint of report.endpoints) {
|
|
1362
|
-
const types = endpoint.eventTypes === null ? "
|
|
1363
|
-
const last = endpoint.lastDelivery ? ` ·
|
|
1364
|
-
lines.push(` ${endpoint.id} ${endpoint.status} ${endpoint.diagnosis} ${endpoint.url} [${types}] ·
|
|
1671
|
+
const types = endpoint.eventTypes === null ? "no filter (0.1 types)" : endpoint.eventTypes.join(",");
|
|
1672
|
+
const last = endpoint.lastDelivery ? ` · last delivery ${endpoint.lastDelivery.status}${endpoint.lastDelivery.httpStatus !== null ? ` ${endpoint.lastDelivery.httpStatus}` : ""}` : "";
|
|
1673
|
+
lines.push(` ${endpoint.id} ${endpoint.status} ${endpoint.diagnosis} ${endpoint.url} [${types}] · pending ${endpoint.pending} · dead ${endpoint.dead}${last}`);
|
|
1365
1674
|
}
|
|
1366
1675
|
}
|
|
1367
|
-
lines.push(`dunning ${report.dunning.dryRun ? "dry-run (
|
|
1676
|
+
lines.push(`dunning ${report.dunning.dryRun ? "dry-run (no suspension/termination)" : "active"}`);
|
|
1368
1677
|
if (report.emails) {
|
|
1369
1678
|
const { emails } = report;
|
|
1370
1679
|
const problems = [...emails.transportConfigured ? [] : ["no transport"], ...emails.senderConfigured ? [] : ["no sender"]];
|
|
@@ -1405,7 +1714,7 @@ async function doctorCommand(ctx, out, args) {
|
|
|
1405
1714
|
const target = requireReadTarget(env);
|
|
1406
1715
|
const appUrl = env.get("APP_URL");
|
|
1407
1716
|
out.err(connectionLine(target));
|
|
1408
|
-
if (appUrl === void 0) out.err(`APP_URL
|
|
1717
|
+
if (appUrl === void 0) out.err(`APP_URL not set (${env.source}): skipped the steward appUrl comparison`);
|
|
1409
1718
|
const steward = clientFor(ctx, target);
|
|
1410
1719
|
const report = await callSteward(target, () => steward.doctor());
|
|
1411
1720
|
const cliWarnings = appUrlWarnings(appUrl, report);
|
|
@@ -1840,11 +2149,11 @@ async function repriceCommand(ctx, out, args) {
|
|
|
1840
2149
|
}
|
|
1841
2150
|
//#endregion
|
|
1842
2151
|
//#region src/commands/settings.ts
|
|
1843
|
-
const SETTINGS_USAGE = `
|
|
2152
|
+
const SETTINGS_USAGE = `Usage:
|
|
1844
2153
|
steward settings get
|
|
1845
2154
|
steward settings set [--app-url <url>] [--privacy-url <url>] [--terms-url <url>]
|
|
1846
2155
|
[--branding <json>] [--default-locale tr|en]
|
|
1847
|
-
[--checkout-ttl <
|
|
2156
|
+
[--checkout-ttl <minutes>] [--portal-ttl <minutes>]
|
|
1848
2157
|
[--extra-return-origins <a,b>] [--emails <json>]
|
|
1849
2158
|
[--billing-payment-due-days <1-60>] [--billing-min-invoice-minor <n>]
|
|
1850
2159
|
[--billing-allow-multiple-subscriptions true|false]
|
|
@@ -1852,10 +2161,10 @@ const SETTINGS_USAGE = `Kullanım:
|
|
|
1852
2161
|
[--metering-late-grace-minutes <0-1440>] [--events-retention-days <45-400>]
|
|
1853
2162
|
[--provider <id>]
|
|
1854
2163
|
|
|
1855
|
-
|
|
1856
|
-
(--privacy-url "")
|
|
1857
|
-
'{"name":"Acme","supportEmail":"
|
|
1858
|
-
|
|
2164
|
+
Product settings (GET/PATCH /v1/admin/settings). A field not given is unchanged; an
|
|
2165
|
+
empty value (--privacy-url "") clears the field, --branding null clears the branding,
|
|
2166
|
+
--branding '{"name":"Acme","supportEmail":"support@acme.com"}' merges shallowly (clear a
|
|
2167
|
+
field with null). --extra-return-origins "" empties the list.
|
|
1859
2168
|
--emails '{"billingPath":"/{LOCALE}/billing","templates":{"invoice_issued":{"enabled":false}}}'
|
|
1860
2169
|
sets billing emails (sender: from.name, from.address; templates merge per
|
|
1861
2170
|
template, null resets a field or template; --emails null resets all).
|
|
@@ -1874,7 +2183,7 @@ kept after receipt, once their period is closed (default 120). "" restores the d
|
|
|
1874
2183
|
--provider sets the payment provider for NEW checkouts and payment sessions (open ones keep
|
|
1875
2184
|
theirs); steward accepts only a provider configured in its deployment (iyzico, fake…).
|
|
1876
2185
|
|
|
1877
|
-
|
|
2186
|
+
Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
|
|
1878
2187
|
const SET_OPTIONS = {
|
|
1879
2188
|
...HELP_OPTION,
|
|
1880
2189
|
"app-url": { type: "string" },
|
|
@@ -1895,7 +2204,7 @@ const SET_OPTIONS = {
|
|
|
1895
2204
|
provider: { type: "string" }
|
|
1896
2205
|
};
|
|
1897
2206
|
const orNull = (value) => value.trim() === "" ? null : value.trim();
|
|
1898
|
-
/**
|
|
2207
|
+
/** A patch from the flags; validated with the contract schema (if invalid no request is sent). */
|
|
1899
2208
|
function buildSettingsPatch(values) {
|
|
1900
2209
|
const patch = {};
|
|
1901
2210
|
if (values["app-url"] !== void 0) patch.appUrl = orNull(values["app-url"]);
|
|
@@ -1909,9 +2218,9 @@ function buildSettingsPatch(values) {
|
|
|
1909
2218
|
try {
|
|
1910
2219
|
branding = JSON.parse(text);
|
|
1911
2220
|
} catch {
|
|
1912
|
-
throw new UsageError("--branding: JSON
|
|
2221
|
+
throw new UsageError("--branding: must be a JSON object, e.g. '{\"name\":\"Acme\",\"supportEmail\":\"support@acme.com\"}'");
|
|
1913
2222
|
}
|
|
1914
|
-
if (typeof branding !== "object" || branding === null || Array.isArray(branding)) throw new UsageError("--branding: JSON
|
|
2223
|
+
if (typeof branding !== "object" || branding === null || Array.isArray(branding)) throw new UsageError("--branding: must be a JSON object");
|
|
1915
2224
|
patch.branding = branding;
|
|
1916
2225
|
}
|
|
1917
2226
|
}
|
|
@@ -1954,9 +2263,9 @@ function buildSettingsPatch(values) {
|
|
|
1954
2263
|
if (Object.keys(metering).length > 0) patch.metering = metering;
|
|
1955
2264
|
const retention = values["events-retention-days"];
|
|
1956
2265
|
if (retention !== void 0) patch.events = { retentionDays: retention.trim() === "" ? null : parsePositiveInt(retention, "--events-retention-days", { max: 400 }) };
|
|
1957
|
-
if (Object.keys(patch).length === 0) throw new UsageError(`
|
|
2266
|
+
if (Object.keys(patch).length === 0) throw new UsageError(`at least one settings flag is required (details: steward settings --help)`);
|
|
1958
2267
|
const parsed = ProductSettingsPatchSchema.safeParse(patch);
|
|
1959
|
-
if (!parsed.success) throw new UsageError(`
|
|
2268
|
+
if (!parsed.success) throw new UsageError(`invalid settings (no request was sent)\n${parsed.error.issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(root)"}: ${issue.message}`).join("\n")}`);
|
|
1960
2269
|
return patch;
|
|
1961
2270
|
}
|
|
1962
2271
|
async function settingsCommand(ctx, out, args) {
|
|
@@ -1990,46 +2299,48 @@ async function settingsCommand(ctx, out, args) {
|
|
|
1990
2299
|
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
1991
2300
|
out.err(connectionLine(target));
|
|
1992
2301
|
const settings = await callSteward(target, () => clientFor(ctx, target).admin.settings.update(patch));
|
|
1993
|
-
out.err(`
|
|
2302
|
+
out.err(`settings updated → ${originOf(target.url)} (${Object.keys(patch).join(", ")})`);
|
|
1994
2303
|
if (patch.metering?.chargeMode === "live") out.err("note: overage is now added to renewal invoices; it should follow one full usage cycle observed in dry_run");
|
|
1995
2304
|
out.out(JSON.stringify(settings, null, 2));
|
|
1996
2305
|
return 0;
|
|
1997
2306
|
}
|
|
1998
|
-
throw new UsageError(`
|
|
2307
|
+
throw new UsageError(`unknown subcommand: settings ${sub} (details: steward settings --help)`);
|
|
1999
2308
|
}
|
|
2000
2309
|
//#endregion
|
|
2001
2310
|
//#region src/main.ts
|
|
2002
|
-
const CLI_VERSION = "0.
|
|
2311
|
+
const CLI_VERSION = "0.9.0";
|
|
2003
2312
|
const USAGE = `steward — Steward CLI (@stewardhq/cli ${CLI_VERSION})
|
|
2004
2313
|
|
|
2005
|
-
|
|
2314
|
+
Usage: steward <command> [options]
|
|
2006
2315
|
|
|
2007
|
-
|
|
2008
|
-
doctor [--json]
|
|
2009
|
-
catalog push <
|
|
2010
|
-
settings get | set [
|
|
2011
|
-
endpoints list | add | rotate | deactivate webhook
|
|
2316
|
+
Commands:
|
|
2317
|
+
doctor [--json] setup diagnosis (GET /v1/doctor)
|
|
2318
|
+
catalog push <file> [--yes] catalog sync (PUT /v1/admin/catalog)
|
|
2319
|
+
settings get | set [flags] product settings (/v1/admin/settings)
|
|
2320
|
+
endpoints list | add | rotate | deactivate webhook endpoints; the secret goes only to the --out file
|
|
2012
2321
|
keys list | create | revoke API keys; the key goes only to the --out file
|
|
2013
2322
|
dunning get | set <policy.json> dunning policy (/v1/admin/dunning-policy)
|
|
2014
2323
|
reprice --plan <code> --notice-days <n> move a plan's subscribers to its current price
|
|
2015
|
-
bank-transfers list | record
|
|
2324
|
+
bank-transfers list | record | fx-report bank transfer reconciliation (/v1/admin/bank-transfers)
|
|
2016
2325
|
credits adjust <ref> <meter> --units=<n> credit entry, negative = adjustment
|
|
2326
|
+
accounts get | metadata set | unset read an account; set or remove metadata keys
|
|
2017
2327
|
meters get | recompute | close-periods an account's meters; metering repairs (admin)
|
|
2018
2328
|
events send | redeliver send one event; redeliver webhook events (admin)
|
|
2019
2329
|
|
|
2020
|
-
|
|
2021
|
-
meters
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2330
|
+
Connection: admin commands use STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY; doctor,
|
|
2331
|
+
accounts, meters and events use STEWARD_URL + STEWARD_API_KEY (or the admin pair). If even
|
|
2332
|
+
one of these four variables is in the environment, all of them (and APP_URL) are read from
|
|
2333
|
+
the environment and ./.env.local is not read at all; otherwise from ./.env.local. The source
|
|
2334
|
+
in use is written to stderr (connection: …). Changes send X-Actor-Ref operator:<user>.
|
|
2335
|
+
The CLI never writes secrets to the terminal and never calls kubectl.
|
|
2026
2336
|
|
|
2027
|
-
|
|
2337
|
+
Details: steward <command> --help`;
|
|
2028
2338
|
const COMMANDS = {
|
|
2029
2339
|
doctor: doctorCommand,
|
|
2030
2340
|
catalog: catalogCommand,
|
|
2031
2341
|
settings: settingsCommand,
|
|
2032
2342
|
endpoints: endpointsCommand,
|
|
2343
|
+
accounts: accountsCommand,
|
|
2033
2344
|
meters: metersCommand,
|
|
2034
2345
|
events: eventsCommand,
|
|
2035
2346
|
keys: keysCommand,
|
|
@@ -2055,7 +2366,7 @@ async function main(argv, ctx) {
|
|
|
2055
2366
|
}
|
|
2056
2367
|
const command = Object.hasOwn(COMMANDS, name) ? COMMANDS[name] : void 0;
|
|
2057
2368
|
if (command === void 0) {
|
|
2058
|
-
out.err(`steward:
|
|
2369
|
+
out.err(`steward: unknown command: ${name}\n\n${USAGE}`);
|
|
2059
2370
|
return 2;
|
|
2060
2371
|
}
|
|
2061
2372
|
try {
|
|
@@ -2069,7 +2380,7 @@ async function main(argv, ctx) {
|
|
|
2069
2380
|
out.err(`steward ${name}: ${describeStewardError(error)}`);
|
|
2070
2381
|
return 1;
|
|
2071
2382
|
}
|
|
2072
|
-
out.err(`steward ${name}:
|
|
2383
|
+
out.err(`steward ${name}: unexpected error:${error instanceof Error ? error.message : String(error)}`);
|
|
2073
2384
|
return 1;
|
|
2074
2385
|
}
|
|
2075
2386
|
}
|