@stewardhq/cli 0.7.0 → 0.8.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 +16 -5
- package/dist/bin.js +307 -175
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@ ESM, Node ≥ 22. Its only runtime dependency is `@stewardhq/sdk`.
|
|
|
14
14
|
| Command | What it does |
|
|
15
15
|
| --- | --- |
|
|
16
16
|
| `steward doctor [--json]` | `GET /v1/doctor`; `APP_URL` ↔ steward `appUrl` / return origins. Exits 1 when not ready. For a product with meters, a `metering` line (the catalog's meters and metered prices, and steward's `events`, `meters`, `overage` capabilities) plus the report's `events` section (backlog, rollup lag, unmatched event names in the last 7 days' sample, invalid values, meters receiving no events) and `overage` section (`chargeMode`, metered price, subscriptions with no locked rate, rolled-over records) |
|
|
17
|
-
| `steward catalog push <file> [--yes]` | `PUT /v1/admin/catalog`; version and counts. Before the push: benefit, price, meter, credit and metered price diff against the current catalog; price and metered price changes need confirmation (prompt, or `--yes`); a catalog with benefits needs the `benefits` capability, one with meters the `meters` capability (`GET /v1/me`) |
|
|
17
|
+
| `steward catalog push <file> [--yes]` | `PUT /v1/admin/catalog`; version and counts. Before the push: benefit, price, meter, credit and metered price diff against the current catalog; price and metered price changes need confirmation (prompt, or `--yes`); a catalog with benefits needs the `benefits` capability, one with meters the `meters` capability, one with an unlisted plan the `unlisted_plans` capability (`GET /v1/me`) |
|
|
18
18
|
| `steward meters get <ref> [--periods <n>] [--json]` | `GET /v1/accounts/:ref/meters`: per meter the open period, usage, credit, balance, standing and estimated overage; `--periods` adds the most recent closed periods |
|
|
19
19
|
| `steward events send <ref> <name> [--meta k=v]… [--external-id <id>] [--timestamp <iso>] [--json]` | A single event via `POST /v1/events/ingest` (for local trials); when `externalId` is omitted one is generated and printed. Exits 1 on a rejected event |
|
|
20
20
|
| `steward settings get` | `GET /v1/admin/settings` |
|
|
@@ -31,7 +31,7 @@ ESM, Node ≥ 22. Its only runtime dependency is `@stewardhq/sdk`.
|
|
|
31
31
|
| `steward meters recompute <ref> [--meter <code>]` / `steward meters close-periods <ref> [--meter <code>] [--force]` | Metering repairs (admin) |
|
|
32
32
|
| `steward credits adjust <ref> <meter> --units=<n> --reason <text>` | A credit ledger entry; negative units = adjustment |
|
|
33
33
|
| `steward events redeliver <eventId>…` | Requeues every delivery of webhook events (admin) |
|
|
34
|
-
| `steward bank-transfers list [--status pending\|expired]` / `steward bank-transfers record <code> --amount <minor> --currency <CUR> --received-at <iso> --bank-ref <ref> […] [--yes]` | Bank transfer reconciliation; recording asks for confirmation |
|
|
34
|
+
| `steward bank-transfers list [--status pending\|expired] [--rate <rate>]` / `steward bank-transfers record <code> --amount <minor> --currency <CUR> --received-at <iso> --bank-ref <ref> [--rate <rate>] […] [--yes]` / `steward bank-transfers fx-report [--from <iso>] [--to <iso>] [--json\|--csv]` | Bank transfer reconciliation; recording asks for confirmation. `--rate`: a transfer in another currency than the item's, at the exchange rate you enter (`list --rate` previews the expected amounts); `fx-report`: those payments for the accountant |
|
|
35
35
|
|
|
36
36
|
Exit codes: 0 success, 1 error (or doctor not ready), 2 incorrect usage.
|
|
37
37
|
|
|
@@ -52,9 +52,8 @@ Exit codes: 0 success, 1 error (or doctor not ready), 2 incorrect usage.
|
|
|
52
52
|
`.env.local`. That way, when the environment is set for a port-forwarded production target,
|
|
53
53
|
a product repo's `.env.local` cannot redirect it.
|
|
54
54
|
- Commands print the source they used to stderr (not the values — the pair names and the
|
|
55
|
-
origin).
|
|
56
|
-
|
|
57
|
-
(`ortam` = environment, the alternative being `.env.local`).
|
|
55
|
+
origin), e.g. `connection: environment · STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY →
|
|
56
|
+
http://localhost:13002` (the source is `environment` or `.env.local`).
|
|
58
57
|
- Changes carry `X-Actor-Ref: operator:<operating system user>`.
|
|
59
58
|
|
|
60
59
|
## Secrets
|
|
@@ -92,6 +91,11 @@ counted a period: steward refuses the push with `422 meter_locked`, and the new
|
|
|
92
91
|
meter code. A catalog with `meters` or `meteredPrices` is pushed only when `GET /v1/me` lists the
|
|
93
92
|
`meters` capability.
|
|
94
93
|
|
|
94
|
+
Unlisted plans: a plan with `listed: false` is sellable but not offered in the hosted portal's
|
|
95
|
+
"Change plan". The diff shows a plan that becomes unlisted, or listed again (`plan listing`). A
|
|
96
|
+
catalog with an unlisted plan is pushed only when `GET /v1/me` lists the `unlisted_plans`
|
|
97
|
+
capability: an older steward would drop the key and offer the plan.
|
|
98
|
+
|
|
95
99
|
## Meters and events
|
|
96
100
|
|
|
97
101
|
- `steward meters get <ref>` prints the account's meter reading (the numbers the product sees
|
|
@@ -114,6 +118,13 @@ Release: bump the version in `cli/package.json` and push the `cli-v<version>` ta
|
|
|
114
118
|
be published on npm. **The first version on npmjs is 0.5.0** (2026-09-21); 0.4.0 was not
|
|
115
119
|
published.
|
|
116
120
|
|
|
121
|
+
- **0.8.0** (`@stewardhq/sdk` 0.8, bank transfers in another currency, issue #55):
|
|
122
|
+
`bank-transfers record --rate`, `bank-transfers list --rate [--currency]`,
|
|
123
|
+
`bank-transfers fx-report [--from] [--to] [--json|--csv]`. Unlisted plans: `catalog push` shows
|
|
124
|
+
the `plan listing` diff and requires the `unlisted_plans` capability for a plan with
|
|
125
|
+
`listed: false`. Help, errors, `doctor` and `endpoints` output and the connection line are now
|
|
126
|
+
in English (they were partly Turkish); flags, command names, JSON output and exit codes are
|
|
127
|
+
unchanged.
|
|
117
128
|
- **0.7.0** (`@stewardhq/sdk` 0.7, admin operations, issue #57): `steward keys`, `steward dunning`,
|
|
118
129
|
`steward reprice`, `steward credits adjust`, `steward bank-transfers`, `steward meters recompute` and
|
|
119
130
|
`close-periods`, `steward events redeliver`, `settings set --provider`. These replace the pod CLI
|
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 { 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));
|
|
@@ -395,7 +406,7 @@ async function readDotenvFile(path) {
|
|
|
395
406
|
//#endregion
|
|
396
407
|
//#region src/env.ts
|
|
397
408
|
const ENV_LOCAL = ".env.local";
|
|
398
|
-
/**
|
|
409
|
+
/** If even one of these is in the process environment, `.env.local` is not read. */
|
|
399
410
|
const CONNECTION_VARIABLES = [
|
|
400
411
|
"STEWARD_URL",
|
|
401
412
|
"STEWARD_API_KEY",
|
|
@@ -417,7 +428,7 @@ const clean = (value) => {
|
|
|
417
428
|
async function resolveEnv(ctx) {
|
|
418
429
|
const fromEnv = CONNECTION_VARIABLES.some((name) => clean(ctx.env[name]) !== void 0);
|
|
419
430
|
const local = fromEnv ? null : await readDotenvFile(join(ctx.cwd, ENV_LOCAL));
|
|
420
|
-
const source = local === null ? "
|
|
431
|
+
const source = local === null ? "environment" : ".env.local";
|
|
421
432
|
const get = (name) => local === null ? clean(ctx.env[name]) : clean(local.get(name));
|
|
422
433
|
return {
|
|
423
434
|
source,
|
|
@@ -442,21 +453,21 @@ async function resolveEnv(ctx) {
|
|
|
442
453
|
}
|
|
443
454
|
function whereMissing(env) {
|
|
444
455
|
switch (env.envLocal) {
|
|
445
|
-
case "skipped": return `
|
|
446
|
-
case "read": return
|
|
447
|
-
case "missing": return `
|
|
456
|
+
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)`;
|
|
457
|
+
case "read": return `not set in ./${ENV_LOCAL} (no steward connection variable in the environment)`;
|
|
458
|
+
case "missing": return `not set (environment variable or ./${ENV_LOCAL}; no such file)`;
|
|
448
459
|
}
|
|
449
460
|
}
|
|
450
461
|
const ADMIN_HINT = "Set them as environment variables or in ./.env.local. Admin: STEWARD_ADMIN_URL=https://billing.zone9.cloud once /v1 is exposed (docs/runbook.md), or a port-forward (http://localhost:13002), which is also the only way to register a cluster-internal (*.svc.cluster.local) webhook endpoint; the admin key comes from the operator Secret as an environment variable.";
|
|
451
462
|
function pairError(names, missing, env) {
|
|
452
|
-
return new CliError(`${names.url} + ${names.key}
|
|
463
|
+
return new CliError(`${names.url} + ${names.key} required: ${missing.join(" and ")} ${whereMissing(env)}.\n${ADMIN_HINT}`);
|
|
453
464
|
}
|
|
454
465
|
function requireAdminTarget(env) {
|
|
455
466
|
const pair = env.pair(ADMIN_PAIR);
|
|
456
467
|
if ("missing" in pair) throw pairError(ADMIN_PAIR, pair.missing, env);
|
|
457
468
|
return pair;
|
|
458
469
|
}
|
|
459
|
-
/**
|
|
470
|
+
/** The product pair; if both are unset, the admin pair (`GET /v1/doctor` is open to both). A half pair is an error. */
|
|
460
471
|
function requireReadTarget(env) {
|
|
461
472
|
const product = env.pair(PRODUCT_PAIR);
|
|
462
473
|
if (!("missing" in product)) return product;
|
|
@@ -464,28 +475,28 @@ function requireReadTarget(env) {
|
|
|
464
475
|
const admin = env.pair(ADMIN_PAIR);
|
|
465
476
|
if (!("missing" in admin)) return admin;
|
|
466
477
|
if (admin.present.length > 0) throw pairError(ADMIN_PAIR, admin.missing, env);
|
|
467
|
-
throw new CliError(`${PRODUCT_PAIR.url} + ${PRODUCT_PAIR.key} (
|
|
478
|
+
throw new CliError(`${PRODUCT_PAIR.url} + ${PRODUCT_PAIR.key} (or ${ADMIN_PAIR.url} + ${ADMIN_PAIR.key}) required: ${whereMissing(env)}.\n${ADMIN_HINT}`);
|
|
468
479
|
}
|
|
469
|
-
/**
|
|
480
|
+
/** The source and pair in use and the target's origin (a stderr line; no key value). */
|
|
470
481
|
function connectionLine(target) {
|
|
471
|
-
return `
|
|
482
|
+
return `connection: ${target.source} · ${target.pair.url} + ${target.pair.key} → ${originOf(target.url)}`;
|
|
472
483
|
}
|
|
473
|
-
/**
|
|
484
|
+
/** `operator:<name>` from the operating system user name (the contract's `type[:id]` form). */
|
|
474
485
|
function actorRefOf(username) {
|
|
475
486
|
const id = username.replace(/[^A-Za-z0-9_.@-]/g, "_").slice(0, 190);
|
|
476
487
|
return id === "" ? "operator" : `operator:${id}`;
|
|
477
488
|
}
|
|
478
|
-
/**
|
|
489
|
+
/** The target's origin (credentials and path are not printed). */
|
|
479
490
|
function originOf(url) {
|
|
480
491
|
try {
|
|
481
492
|
return new URL(url).origin;
|
|
482
493
|
} catch {
|
|
483
|
-
return "(
|
|
494
|
+
return "(invalid address)";
|
|
484
495
|
}
|
|
485
496
|
}
|
|
486
497
|
/**
|
|
487
|
-
*
|
|
488
|
-
*
|
|
498
|
+
* A client bound to the target. The same URL/key is given as both the product and the admin base:
|
|
499
|
+
* the command only calls the methods that fit the target's scope.
|
|
489
500
|
*/
|
|
490
501
|
function clientFor(ctx, target, options = {}) {
|
|
491
502
|
return createSteward({
|
|
@@ -500,7 +511,7 @@ function clientFor(ctx, target, options = {}) {
|
|
|
500
511
|
retries: options.retries === false ? { attempts: 0 } : { sleep: ctx.sleep }
|
|
501
512
|
});
|
|
502
513
|
}
|
|
503
|
-
/**
|
|
514
|
+
/** A steward call: an SDK error becomes a `CliError` carrying the target's origin. */
|
|
504
515
|
async function callSteward(target, fn) {
|
|
505
516
|
try {
|
|
506
517
|
return await fn();
|
|
@@ -514,26 +525,26 @@ const CODE_HINTS = {
|
|
|
514
525
|
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
526
|
metered_price_tax_mismatch: " — a metered price needs the tax terms (taxInclusive, taxRateBps) of its plan's base price in that currency"
|
|
516
527
|
};
|
|
517
|
-
/** SDK
|
|
528
|
+
/** Turns an SDK error into a one-line user message (no values or keys). */
|
|
518
529
|
function describeStewardError(error, target) {
|
|
519
530
|
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 `
|
|
531
|
+
const request = error.requestId !== void 0 ? ` [request ${error.requestId}]` : "";
|
|
532
|
+
if (error instanceof StewardNetworkError) return `could not reach steward${where}: ${error.code === "timeout" ? "timed out" : "could not connect"}. Is the address right, is the port-forward running?`;
|
|
533
|
+
if (error instanceof StewardConfigError) return `configuration error: ${error.message}`;
|
|
523
534
|
if (error instanceof StewardApiError) {
|
|
524
|
-
const hint = error.httpStatus === 401 ? " —
|
|
535
|
+
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
536
|
const message = error.message !== error.code ? `: ${error.message}` : "";
|
|
526
|
-
return `steward
|
|
537
|
+
return `steward error${where}: ${error.code} (HTTP ${error.httpStatus})${message}${hint}${request}`;
|
|
527
538
|
}
|
|
528
|
-
return `steward
|
|
539
|
+
return `steward response does not match the contract${where}: ${error.code} (HTTP ${error.httpStatus}) — the CLI and steward versions may be incompatible${request}`;
|
|
529
540
|
}
|
|
530
541
|
//#endregion
|
|
531
542
|
//#region src/secret-file.ts
|
|
532
543
|
async function withSecretFile(cwd, out, secret, options, action) {
|
|
533
544
|
const target = resolve(cwd, out);
|
|
534
545
|
try {
|
|
535
|
-
if ((await lstat(target)).isDirectory()) throw new CliError(`--out
|
|
536
|
-
if (!options.force) throw new CliError(`${out}
|
|
546
|
+
if ((await lstat(target)).isDirectory()) throw new CliError(`--out is a folder: ${out}`);
|
|
547
|
+
if (!options.force) throw new CliError(`${out} already exists; use --force to overwrite it (no request was sent)`);
|
|
537
548
|
} catch (error) {
|
|
538
549
|
if (error instanceof CliError) throw error;
|
|
539
550
|
if (errnoCode(error) !== "ENOENT") throw error;
|
|
@@ -546,8 +557,8 @@ async function withSecretFile(cwd, out, secret, options, action) {
|
|
|
546
557
|
});
|
|
547
558
|
} catch (error) {
|
|
548
559
|
const code = errnoCode(error);
|
|
549
|
-
if (code === "ENOENT") throw new CliError(`--out
|
|
550
|
-
throw new CliError(`
|
|
560
|
+
if (code === "ENOENT") throw new CliError(`--out folder does not exist: ${relative(cwd, dirname(target)) || "."}`);
|
|
561
|
+
throw new CliError(`could not write the secret file (${code ?? "error"}): ${out} (no request was sent)`);
|
|
551
562
|
}
|
|
552
563
|
let value;
|
|
553
564
|
try {
|
|
@@ -577,23 +588,24 @@ async function withSecretFile(cwd, out, secret, options, action) {
|
|
|
577
588
|
}
|
|
578
589
|
//#endregion
|
|
579
590
|
//#region src/commands/endpoints.ts
|
|
580
|
-
const ENDPOINTS_USAGE = `
|
|
591
|
+
const ENDPOINTS_USAGE = `Usage:
|
|
581
592
|
steward endpoints list [--json]
|
|
582
|
-
steward endpoints add --url <url> --out <
|
|
583
|
-
steward endpoints rotate <id> --out <
|
|
593
|
+
steward endpoints add --url <url> --out <file> [--event-types <a,b>] [--description <text>] [--force]
|
|
594
|
+
steward endpoints rotate <id> --out <file> [--force]
|
|
584
595
|
steward endpoints deactivate <id>
|
|
585
596
|
|
|
586
|
-
Webhook
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
597
|
+
Webhook endpoints (/v1/admin/webhook-endpoints). The signing secret (whsec_…) is
|
|
598
|
+
generated on this machine and written ONLY to the --out file (0600, no trailing
|
|
599
|
+
newline); it is not written to the terminal and steward never returns it in any
|
|
600
|
+
response. If the file exists, no request is sent without --force. The operator moves
|
|
601
|
+
the secret into the product's Secret (the CLI does not call kubectl); on rotation the
|
|
602
|
+
product moves over with a "new,old" list. Delete the file after moving it. Without
|
|
603
|
+
--event-types only account.state_changed. deactivate cannot be undone (open a new
|
|
604
|
+
endpoint).
|
|
593
605
|
|
|
594
|
-
|
|
606
|
+
Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
|
|
595
607
|
function schemaProblems(issues) {
|
|
596
|
-
return issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(
|
|
608
|
+
return issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(root)"}: ${issue.message}`).join("\n");
|
|
597
609
|
}
|
|
598
610
|
const lastDeliveryText = (endpoint) => {
|
|
599
611
|
const last = endpoint.lastDelivery;
|
|
@@ -605,7 +617,7 @@ function table(rows) {
|
|
|
605
617
|
const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
|
|
606
618
|
return rows.map((row) => row.map((cell, column) => column === row.length - 1 ? cell : cell.padEnd(widths[column])).join(" "));
|
|
607
619
|
}
|
|
608
|
-
const typesText = (endpoint) => endpoint.eventTypes === null ? "(
|
|
620
|
+
const typesText = (endpoint) => endpoint.eventTypes === null ? "(no filter: 0.1 types)" : endpoint.eventTypes.join(",");
|
|
609
621
|
async function endpointsCommand(ctx, out, args) {
|
|
610
622
|
const [sub, ...rest] = args;
|
|
611
623
|
if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
|
|
@@ -623,13 +635,13 @@ async function endpointsCommand(ctx, out, args) {
|
|
|
623
635
|
out.err(connectionLine(target));
|
|
624
636
|
const { items } = await callSteward(target, () => clientFor(ctx, target).admin.endpoints.list());
|
|
625
637
|
if (values.json) out.out(JSON.stringify(items, null, 2));
|
|
626
|
-
else if (items.length === 0) out.out("
|
|
638
|
+
else if (items.length === 0) out.out("no endpoints — steward endpoints add --url <url> --out <file>");
|
|
627
639
|
else {
|
|
628
640
|
const rows = [[
|
|
629
641
|
"ID",
|
|
630
|
-
"
|
|
631
|
-
"
|
|
632
|
-
"
|
|
642
|
+
"STATUS",
|
|
643
|
+
"EVENTS",
|
|
644
|
+
"LAST DELIVERY",
|
|
633
645
|
"URL"
|
|
634
646
|
]];
|
|
635
647
|
for (const e of items) rows.push([
|
|
@@ -664,17 +676,17 @@ async function endpointsCommand(ctx, out, args) {
|
|
|
664
676
|
...values.description !== void 0 ? { description: values.description } : {}
|
|
665
677
|
};
|
|
666
678
|
const parsed = WebhookEndpointCreateInputSchema.safeParse(input);
|
|
667
|
-
if (!parsed.success) throw new UsageError(`endpoint
|
|
679
|
+
if (!parsed.success) throw new UsageError(`invalid endpoint (no request was sent)\n${schemaProblems(parsed.error.issues)}`);
|
|
668
680
|
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
669
681
|
out.err(connectionLine(target));
|
|
670
682
|
const steward = clientFor(ctx, target);
|
|
671
683
|
const result = await withSecretFile(ctx.cwd, file, secret, { force: values.force === true }, () => callSteward(target, () => steward.admin.endpoints.create(input)));
|
|
672
684
|
const endpoint = result.value;
|
|
673
|
-
out.out(`endpoint
|
|
685
|
+
out.out(`endpoint created → ${originOf(target.url)}`);
|
|
674
686
|
out.out(` id ${endpoint.id}`);
|
|
675
687
|
out.out(` url ${endpoint.url}`);
|
|
676
|
-
out.out(`
|
|
677
|
-
secretNotice(out, result.path, result.fallback, "
|
|
688
|
+
out.out(` events ${typesText(endpoint)}`);
|
|
689
|
+
secretNotice(out, result.path, result.fallback, "Move the secret into the product's Secret (STEWARD_WEBHOOK_SECRET), then delete the file.");
|
|
678
690
|
return 0;
|
|
679
691
|
}
|
|
680
692
|
if (sub === "rotate") {
|
|
@@ -689,15 +701,15 @@ async function endpointsCommand(ctx, out, args) {
|
|
|
689
701
|
const file = requireOption(values.out, "--out", "endpoints");
|
|
690
702
|
const secret = generateWebhookSecret();
|
|
691
703
|
const parsed = WebhookEndpointRotateInputSchema.safeParse({ secret });
|
|
692
|
-
if (!parsed.success) throw new UsageError(`
|
|
704
|
+
if (!parsed.success) throw new UsageError(`invalid secret\n${schemaProblems(parsed.error.issues)}`);
|
|
693
705
|
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
694
706
|
out.err(connectionLine(target));
|
|
695
707
|
const steward = clientFor(ctx, target);
|
|
696
708
|
const result = await withSecretFile(ctx.cwd, file, secret, { force: values.force === true }, () => callSteward(target, () => steward.admin.endpoints.rotate(id, { secret })));
|
|
697
|
-
out.out(`
|
|
709
|
+
out.out(`secret rotated → ${originOf(target.url)}`);
|
|
698
710
|
out.out(` id ${result.value.id}`);
|
|
699
711
|
out.out(` url ${result.value.url}`);
|
|
700
|
-
secretNotice(out, result.path, result.fallback, "
|
|
712
|
+
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
713
|
return 0;
|
|
702
714
|
}
|
|
703
715
|
if (sub === "deactivate") {
|
|
@@ -707,10 +719,10 @@ async function endpointsCommand(ctx, out, args) {
|
|
|
707
719
|
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
708
720
|
out.err(connectionLine(target));
|
|
709
721
|
const endpoint = await callSteward(target, () => clientFor(ctx, target).admin.endpoints.deactivate(positionals[0]));
|
|
710
|
-
out.out(`endpoint
|
|
722
|
+
out.out(`endpoint deactivated → ${originOf(target.url)}: ${endpoint.id} (${endpoint.url}, status ${endpoint.status})`);
|
|
711
723
|
return 0;
|
|
712
724
|
}
|
|
713
|
-
throw new UsageError(`
|
|
725
|
+
throw new UsageError(`unknown subcommand: endpoints ${sub} (details: steward endpoints --help)`);
|
|
714
726
|
}
|
|
715
727
|
function help$3(out) {
|
|
716
728
|
out.out(ENDPOINTS_USAGE);
|
|
@@ -725,16 +737,22 @@ function secretNotice(out, path, fallback, next) {
|
|
|
725
737
|
//#endregion
|
|
726
738
|
//#region src/commands/bank-transfers.ts
|
|
727
739
|
const BANK_TRANSFERS_USAGE = `Usage:
|
|
728
|
-
steward bank-transfers list [--status pending|expired] [--
|
|
740
|
+
steward bank-transfers list [--status pending|expired] [--rate <rate> [--currency <CUR>]]
|
|
741
|
+
[--json]
|
|
729
742
|
steward bank-transfers record <code> --amount <minor> --currency <CUR> --received-at <iso>
|
|
730
|
-
--bank-ref <ref> [--
|
|
743
|
+
--bank-ref <ref> [--rate <rate>]
|
|
744
|
+
[--checkout <id> [--accept-expired] | --invoice <id>]
|
|
731
745
|
[--yes] [--json]
|
|
746
|
+
steward bank-transfers fx-report [--from <iso>] [--to <iso>] [--json | --csv]
|
|
732
747
|
|
|
733
748
|
Bank transfer (havale/EFT) reconciliation (/v1/admin/bank-transfers).
|
|
734
749
|
|
|
735
750
|
list: what the bank statement is matched against. pending (default): checkouts waiting for a
|
|
736
751
|
transfer and unpaid invoices of accounts with an order code, by deadline; expired: checkouts
|
|
737
|
-
that expired in the last 30 days.
|
|
752
|
+
that expired in the last 30 days. --rate previews a transfer in another currency: next to each
|
|
753
|
+
item the product lets be paid in another currency (settings.billing.bankTransfer.settleIn) it
|
|
754
|
+
shows the amount expected at that rate (--currency names it when an item accepts several). It
|
|
755
|
+
writes nothing.
|
|
738
756
|
|
|
739
757
|
record: a transfer seen on the bank account. <code> is the order code from the transfer
|
|
740
758
|
description (case and dashes are forgiven). Only a checkout or unpaid invoice waiting for
|
|
@@ -745,6 +763,18 @@ number; one payment per reference. When several items match, name one with --che
|
|
|
745
763
|
A refused transfer is refunded through the bank. Recording needs confirmation (a prompt on a
|
|
746
764
|
terminal, otherwise --yes): it starts a subscription or pays an invoice.
|
|
747
765
|
|
|
766
|
+
record --rate: a transfer in another currency than the item's (a USD invoice paid with TRY,
|
|
767
|
+
when the product allows it). --rate is the exchange rate you enter: --currency per 1 unit of
|
|
768
|
+
the item's currency, up to 6 decimal places (34.5218). The item matches when --amount is
|
|
769
|
+
within the product's tolerance (fxToleranceBps, default 0.5%) of its amount at that rate, and
|
|
770
|
+
is settled in its own currency. --rate is required for such a transfer and refused for one in
|
|
771
|
+
the item's currency. Steward never looks a rate up.
|
|
772
|
+
|
|
773
|
+
fx-report: the payments received in another currency (invoice number and date, amount settled,
|
|
774
|
+
amount received, the rate entered, received date), latest first; --from (inclusive) and --to
|
|
775
|
+
(exclusive) are ISO-8601 with an offset, by received date. The accountant's input for
|
|
776
|
+
exchange-difference invoices, which steward does not issue.
|
|
777
|
+
|
|
748
778
|
Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
|
|
749
779
|
const WITH_OFFSET = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/;
|
|
750
780
|
async function bankTransfersCommand(ctx, out, args) {
|
|
@@ -757,21 +787,32 @@ async function bankTransfersCommand(ctx, out, args) {
|
|
|
757
787
|
const { values, positionals } = parse(rest, {
|
|
758
788
|
...HELP_OPTION,
|
|
759
789
|
status: { type: "string" },
|
|
790
|
+
rate: { type: "string" },
|
|
791
|
+
currency: { type: "string" },
|
|
760
792
|
json: { type: "boolean" }
|
|
761
793
|
}, "bank-transfers");
|
|
762
794
|
if (values.help) return help$2(out);
|
|
763
795
|
expectPositionals(positionals, 0, 0, "bank-transfers");
|
|
764
796
|
const status = values.status ?? "pending";
|
|
765
797
|
if (status !== "pending" && status !== "expired") throw new UsageError("--status: pending or expired");
|
|
798
|
+
const rate = values.rate !== void 0 ? parseRate(values.rate) : void 0;
|
|
799
|
+
if (values.currency !== void 0 && rate === void 0) throw new UsageError("--currency needs --rate");
|
|
800
|
+
const currency = values.currency?.toUpperCase();
|
|
801
|
+
if (currency !== void 0 && !/^[A-Z]{3}$/.test(currency)) throw new UsageError("--currency: an ISO-4217 code (TRY)");
|
|
802
|
+
const preview = {
|
|
803
|
+
...rate !== void 0 ? { rate } : {},
|
|
804
|
+
...currency !== void 0 ? { currency } : {}
|
|
805
|
+
};
|
|
766
806
|
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
767
807
|
out.err(connectionLine(target));
|
|
768
|
-
const { items } = await callSteward(target, () => clientFor(ctx, target).admin.bankTransfers.list(status));
|
|
808
|
+
const { items } = await callSteward(target, () => clientFor(ctx, target).admin.bankTransfers.list(status, preview));
|
|
769
809
|
if (values.json) out.out(JSON.stringify(items, null, 2));
|
|
770
810
|
else if (items.length === 0) out.out(`no ${status} bank transfers`);
|
|
771
811
|
else {
|
|
772
812
|
const rows = [[
|
|
773
813
|
"CODE",
|
|
774
814
|
"AMOUNT",
|
|
815
|
+
...rate !== void 0 ? [`EXPECTED @ ${rate}`] : [],
|
|
775
816
|
"DEADLINE",
|
|
776
817
|
"KIND",
|
|
777
818
|
"PLAN",
|
|
@@ -781,6 +822,7 @@ async function bankTransfersCommand(ctx, out, args) {
|
|
|
781
822
|
for (const i of items) rows.push([
|
|
782
823
|
i.code ?? "-",
|
|
783
824
|
formatMinor(i.totalMinor, i.currency),
|
|
825
|
+
...rate !== void 0 ? [i.expectedMinor !== void 0 && i.expectedCurrency !== void 0 ? formatMinor(i.expectedMinor, i.expectedCurrency) : "-"] : [],
|
|
784
826
|
i.deadline ?? "-",
|
|
785
827
|
i.kind,
|
|
786
828
|
i.planCode ?? "-",
|
|
@@ -798,6 +840,7 @@ async function bankTransfersCommand(ctx, out, args) {
|
|
|
798
840
|
currency: { type: "string" },
|
|
799
841
|
"received-at": { type: "string" },
|
|
800
842
|
"bank-ref": { type: "string" },
|
|
843
|
+
rate: { type: "string" },
|
|
801
844
|
checkout: { type: "string" },
|
|
802
845
|
invoice: { type: "string" },
|
|
803
846
|
"accept-expired": { type: "boolean" },
|
|
@@ -817,6 +860,7 @@ async function bankTransfersCommand(ctx, out, args) {
|
|
|
817
860
|
currency: requireOption(values.currency, "--currency", "bank-transfers").toUpperCase(),
|
|
818
861
|
receivedAt,
|
|
819
862
|
bankRef: requireOption(values["bank-ref"], "--bank-ref", "bank-transfers"),
|
|
863
|
+
...values.rate !== void 0 ? { rate: parseRate(values.rate) } : {},
|
|
820
864
|
...values.checkout !== void 0 ? { checkoutSessionId: values.checkout } : {},
|
|
821
865
|
...values.invoice !== void 0 ? { invoiceId: values.invoice } : {},
|
|
822
866
|
...values["accept-expired"] ? { acceptExpired: true } : {}
|
|
@@ -825,7 +869,7 @@ async function bankTransfersCommand(ctx, out, args) {
|
|
|
825
869
|
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
870
|
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
827
871
|
out.err(connectionLine(target));
|
|
828
|
-
if (!await confirm(ctx, `Record ${formatMinor(input.amountMinor, input.currency)} for order code ${input.code} (bank ref ${input.bankRef})?`, {
|
|
872
|
+
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
873
|
yes: values.yes === true,
|
|
830
874
|
notConfirmed: "nothing was recorded"
|
|
831
875
|
})) {
|
|
@@ -837,11 +881,83 @@ async function bankTransfersCommand(ctx, out, args) {
|
|
|
837
881
|
out.out(JSON.stringify(recorded, null, 2));
|
|
838
882
|
return 0;
|
|
839
883
|
}
|
|
840
|
-
|
|
884
|
+
const settled = recorded.fxRate !== void 0 && recorded.settledAmountMinor !== void 0 && recorded.settledCurrency !== void 0 ? ` (settled ${formatMinor(recorded.settledAmountMinor, recorded.settledCurrency)} at ${recorded.fxRate})` : "";
|
|
885
|
+
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);
|
|
886
|
+
return 0;
|
|
887
|
+
}
|
|
888
|
+
if (sub === "fx-report") {
|
|
889
|
+
const { values, positionals } = parse(rest, {
|
|
890
|
+
...HELP_OPTION,
|
|
891
|
+
from: { type: "string" },
|
|
892
|
+
to: { type: "string" },
|
|
893
|
+
json: { type: "boolean" },
|
|
894
|
+
csv: { type: "boolean" }
|
|
895
|
+
}, "bank-transfers");
|
|
896
|
+
if (values.help) return help$2(out);
|
|
897
|
+
expectPositionals(positionals, 0, 0, "bank-transfers");
|
|
898
|
+
if (values.json && values.csv) throw new UsageError("--json or --csv, not both");
|
|
899
|
+
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)");
|
|
900
|
+
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)");
|
|
901
|
+
const range = {
|
|
902
|
+
...values.from !== void 0 ? { from: values.from } : {},
|
|
903
|
+
...values.to !== void 0 ? { to: values.to } : {}
|
|
904
|
+
};
|
|
905
|
+
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
906
|
+
out.err(connectionLine(target));
|
|
907
|
+
const { items } = await callSteward(target, () => clientFor(ctx, target).admin.bankTransfers.fxReport(range));
|
|
908
|
+
if (values.json) out.out(JSON.stringify(items, null, 2));
|
|
909
|
+
else if (values.csv) {
|
|
910
|
+
out.out("invoice_number,invoice_date,amount_minor,currency,received_minor,received_currency,fx_rate,received_at,bank_ref,account,payment_id");
|
|
911
|
+
for (const i of items) out.out([
|
|
912
|
+
i.invoiceNumber ?? "",
|
|
913
|
+
i.invoiceIssuedAt ?? "",
|
|
914
|
+
i.amountMinor,
|
|
915
|
+
i.currency,
|
|
916
|
+
i.receivedAmountMinor,
|
|
917
|
+
i.receivedCurrency,
|
|
918
|
+
i.fxRate,
|
|
919
|
+
i.receivedAt,
|
|
920
|
+
i.bankRef,
|
|
921
|
+
i.accountRef,
|
|
922
|
+
i.paymentId
|
|
923
|
+
].map(csvField).join(","));
|
|
924
|
+
} else if (items.length === 0) out.out("no bank transfers in another currency");
|
|
925
|
+
else {
|
|
926
|
+
const rows = [[
|
|
927
|
+
"INVOICE",
|
|
928
|
+
"INVOICE DATE",
|
|
929
|
+
"AMOUNT",
|
|
930
|
+
"RECEIVED",
|
|
931
|
+
"RATE",
|
|
932
|
+
"RECEIVED AT",
|
|
933
|
+
"BANK REF",
|
|
934
|
+
"ACCOUNT"
|
|
935
|
+
]];
|
|
936
|
+
for (const i of items) rows.push([
|
|
937
|
+
i.invoiceNumber ?? "-",
|
|
938
|
+
i.invoiceIssuedAt ?? "-",
|
|
939
|
+
formatMinor(i.amountMinor, i.currency),
|
|
940
|
+
formatMinor(i.receivedAmountMinor, i.receivedCurrency),
|
|
941
|
+
i.fxRate,
|
|
942
|
+
i.receivedAt,
|
|
943
|
+
i.bankRef,
|
|
944
|
+
i.accountRef
|
|
945
|
+
]);
|
|
946
|
+
for (const line of table(rows)) out.out(line);
|
|
947
|
+
}
|
|
841
948
|
return 0;
|
|
842
949
|
}
|
|
843
950
|
throw new UsageError(`unknown subcommand: bank-transfers ${sub} (see: steward bank-transfers --help)`);
|
|
844
951
|
}
|
|
952
|
+
function parseRate(value) {
|
|
953
|
+
if (!FxRateSchema.safeParse(value).success) throw new UsageError("--rate: a positive decimal with at most 6 decimal places (34.5218)");
|
|
954
|
+
return value;
|
|
955
|
+
}
|
|
956
|
+
/** RFC 4180 quoting; a leading = + - @ is prefixed so a spreadsheet does not read the field as a formula. */
|
|
957
|
+
function csvField(value) {
|
|
958
|
+
const text = typeof value === "string" && /^[=+\-@]/.test(value) ? `'${value}` : String(value);
|
|
959
|
+
return /[",\n\r]/.test(text) ? `"${text.replace(/"/g, "\"\"")}"` : text;
|
|
960
|
+
}
|
|
845
961
|
function help$2(out) {
|
|
846
962
|
out.out(BANK_TRANSFERS_USAGE);
|
|
847
963
|
return 0;
|
|
@@ -864,7 +980,7 @@ function pickExport(mod, file) {
|
|
|
864
980
|
if (mod.default !== void 0) return mod.default;
|
|
865
981
|
const candidates = Object.values(mod).filter(hasSyncInput);
|
|
866
982
|
if (candidates.length === 1) return candidates[0];
|
|
867
|
-
throw new CliError(`${file}:
|
|
983
|
+
throw new CliError(`${file}: no catalog found — expected \`export const catalog = defineCatalog(…)\` or a default export`);
|
|
868
984
|
}
|
|
869
985
|
async function loadCatalogFile(ctx, file) {
|
|
870
986
|
const path = resolve(ctx.cwd, file);
|
|
@@ -875,46 +991,46 @@ async function loadCatalogFile(ctx, file) {
|
|
|
875
991
|
try {
|
|
876
992
|
text = await readFile(path, "utf8");
|
|
877
993
|
} catch (error) {
|
|
878
|
-
throw new CliError(errnoCode(error) === "ENOENT" ? `
|
|
994
|
+
throw new CliError(errnoCode(error) === "ENOENT" ? `catalog file does not exist: ${file}` : `could not read the catalog file: ${file}`);
|
|
879
995
|
}
|
|
880
996
|
try {
|
|
881
997
|
exported = JSON.parse(text);
|
|
882
998
|
} catch {
|
|
883
|
-
throw new CliError(`${file}:
|
|
999
|
+
throw new CliError(`${file}: not valid JSON`);
|
|
884
1000
|
}
|
|
885
1001
|
} else if (MODULE_EXTENSIONS.has(ext) || TS_EXTENSIONS.has(ext)) {
|
|
886
|
-
if (TS_EXTENSIONS.has(ext) && !ctx.typescript) throw new CliError(`${file}:
|
|
1002
|
+
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
1003
|
let mod;
|
|
888
1004
|
try {
|
|
889
1005
|
await readFile(path);
|
|
890
1006
|
} catch (error) {
|
|
891
|
-
throw new CliError(errnoCode(error) === "ENOENT" ? `
|
|
1007
|
+
throw new CliError(errnoCode(error) === "ENOENT" ? `catalog file does not exist: ${file}` : `could not read the catalog file: ${file}`);
|
|
892
1008
|
}
|
|
893
1009
|
try {
|
|
894
1010
|
mod = await ctx.importModule(pathToFileURL(path).href);
|
|
895
1011
|
} catch (error) {
|
|
896
|
-
throw new CliError(
|
|
1012
|
+
throw new CliError(`could not load ${file}: ${error instanceof Error ? error.message : String(error)}`);
|
|
897
1013
|
}
|
|
898
1014
|
exported = pickExport(mod, file);
|
|
899
|
-
} else throw new UsageError(`
|
|
1015
|
+
} else throw new UsageError(`the catalog file must be .ts, .mts, .js, .mjs, .cjs or .json: ${file}`);
|
|
900
1016
|
let input;
|
|
901
1017
|
try {
|
|
902
1018
|
input = hasSyncInput(exported) ? exported.toSyncInput() : exported;
|
|
903
1019
|
} catch (error) {
|
|
904
|
-
throw new CliError(`${file}: toSyncInput()
|
|
1020
|
+
throw new CliError(`${file}: toSyncInput() failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
905
1021
|
}
|
|
906
1022
|
const parsed = CatalogSyncInputSchema.safeParse(input);
|
|
907
|
-
if (!parsed.success) throw new CliError(`${file}:
|
|
1023
|
+
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
1024
|
return input;
|
|
909
1025
|
}
|
|
910
1026
|
//#endregion
|
|
911
1027
|
//#region src/commands/catalog.ts
|
|
912
|
-
const CATALOG_USAGE = `
|
|
1028
|
+
const CATALOG_USAGE = `Usage: steward catalog push <file> [--yes]
|
|
913
1029
|
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
(\`export const catalog = defineCatalog(…)\`
|
|
917
|
-
(
|
|
1030
|
+
Syncs the catalog definition to steward (PUT /v1/admin/catalog), then prints the version
|
|
1031
|
+
and the counts. File: .ts/.mts (Node type stripping, Node ≥ 22.18), .js/.mjs/.cjs
|
|
1032
|
+
(\`export const catalog = defineCatalog(…)\` or a default export) or .json
|
|
1033
|
+
(the sync body). No request is sent for an invalid catalog.
|
|
918
1034
|
|
|
919
1035
|
Before pushing, prints what changes against steward's current catalog: benefits
|
|
920
1036
|
(new, changed, archived, plan benefit lists) and prices (new, deactivated, amount or
|
|
@@ -931,8 +1047,13 @@ are fixed once it has counted a period (422 meter_locked: use a new meter code).
|
|
|
931
1047
|
catalog with meters or metered prices is pushed only to a steward whose GET /v1/me
|
|
932
1048
|
lists the "meters" capability.
|
|
933
1049
|
|
|
934
|
-
|
|
935
|
-
|
|
1050
|
+
Unlisted plans: a plan with "listed: false" is sellable but not offered in the hosted
|
|
1051
|
+
portal's "Change plan"; the diff shows a plan that becomes unlisted or listed. Such a
|
|
1052
|
+
catalog is pushed only to a steward whose GET /v1/me lists the "unlisted_plans"
|
|
1053
|
+
capability (an older steward would offer the plan).
|
|
1054
|
+
|
|
1055
|
+
Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).
|
|
1056
|
+
Exit code 1: a price could not be created at the provider (run the sync again);
|
|
936
1057
|
the push was refused or not confirmed.`;
|
|
937
1058
|
const PUSH_OPTIONS = {
|
|
938
1059
|
...HELP_OPTION,
|
|
@@ -942,20 +1063,20 @@ const PUSH_OPTIONS = {
|
|
|
942
1063
|
}
|
|
943
1064
|
};
|
|
944
1065
|
const list = (items) => items.length > 0 ? items.join(", ") : "-";
|
|
945
|
-
/**
|
|
1066
|
+
/** Sync + version read; the summary lines and whether there were provider errors. */
|
|
946
1067
|
async function pushCatalog(steward, target, input) {
|
|
947
1068
|
const result = await callSteward(target, () => steward.admin.catalog.sync(input));
|
|
948
|
-
const version = (await callSteward(target, () => steward.catalog.read())).etag?.replace(/^W\//, "").replace(/"/g, "") ?? "
|
|
1069
|
+
const version = (await callSteward(target, () => steward.catalog.read())).etag?.replace(/^W\//, "").replace(/"/g, "") ?? "unknown";
|
|
949
1070
|
const benefitCount = Object.keys(input.benefits ?? {}).length;
|
|
950
1071
|
const meterCount = Object.keys(input.meters ?? {}).length;
|
|
951
1072
|
const meteredCount = (input.meteredPrices ?? []).length;
|
|
952
1073
|
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("
|
|
1074
|
+
const lines = [`catalog synced → ${originOf(target.url)}`];
|
|
1075
|
+
lines.push(` version ${version}`);
|
|
1076
|
+
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}`);
|
|
1077
|
+
if (result.unchanged) lines.push(" changes none");
|
|
957
1078
|
else {
|
|
958
|
-
lines.push(`
|
|
1079
|
+
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
1080
|
const changedBenefits = result.changedBenefits ?? [];
|
|
960
1081
|
const archivedBenefits = result.archivedBenefits ?? [];
|
|
961
1082
|
if (changedBenefits.length > 0 || archivedBenefits.length > 0) lines.push(` benefits changed: ${list(changedBenefits)} · archived: ${list(archivedBenefits)}`);
|
|
@@ -970,7 +1091,7 @@ async function pushCatalog(steward, target, input) {
|
|
|
970
1091
|
];
|
|
971
1092
|
if (created.length + updated.length + deactivated.length > 0) lines.push(` metered new ${created.length} · updated in place ${updated.length} · deactivated ${deactivated.length}`);
|
|
972
1093
|
}
|
|
973
|
-
for (const error of result.providerErrors) lines.push(` ✗
|
|
1094
|
+
for (const error of result.providerErrors) lines.push(` ✗ provider error: price ${error.priceId} (${error.provider}: ${error.code}) — run the sync again`);
|
|
974
1095
|
return {
|
|
975
1096
|
lines,
|
|
976
1097
|
providerErrors: result.providerErrors.length
|
|
@@ -983,16 +1104,22 @@ function currentCatalog(steward, target) {
|
|
|
983
1104
|
throw error;
|
|
984
1105
|
}));
|
|
985
1106
|
}
|
|
1107
|
+
/** What the catalog defines, per capability it needs (the refusal names it). */
|
|
1108
|
+
const CAPABILITY_LABELS = {
|
|
1109
|
+
benefits: "benefits",
|
|
1110
|
+
meters: "meters",
|
|
1111
|
+
unlisted_plans: "unlisted plans"
|
|
1112
|
+
};
|
|
986
1113
|
/**
|
|
987
|
-
* Refuses a catalog whose benefits or
|
|
988
|
-
* drops the keys silently. `needed`: the capabilities the catalog needs
|
|
1114
|
+
* Refuses a catalog whose benefits, meters or unlisted plans steward does not understand (M27): an
|
|
1115
|
+
* older steward drops the keys silently. `needed`: the capabilities the catalog needs.
|
|
989
1116
|
*/
|
|
990
1117
|
async function requireCapabilities(steward, target, needed) {
|
|
991
1118
|
if (needed.length === 0) return;
|
|
992
1119
|
const me = await callSteward(target, () => steward.me());
|
|
993
1120
|
const missing = needed.filter((capability) => !(me.capabilities ?? []).includes(capability));
|
|
994
1121
|
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.`);
|
|
1122
|
+
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
1123
|
}
|
|
997
1124
|
async function catalogCommand(ctx, out, args) {
|
|
998
1125
|
const [sub, ...rest] = args;
|
|
@@ -1000,7 +1127,7 @@ async function catalogCommand(ctx, out, args) {
|
|
|
1000
1127
|
out.out(CATALOG_USAGE);
|
|
1001
1128
|
return sub === void 0 ? 2 : 0;
|
|
1002
1129
|
}
|
|
1003
|
-
if (sub !== "push") throw new UsageError(`
|
|
1130
|
+
if (sub !== "push") throw new UsageError(`unknown subcommand: catalog ${sub} (details: steward catalog --help)`);
|
|
1004
1131
|
const { values, positionals } = parse(rest, PUSH_OPTIONS, "catalog push");
|
|
1005
1132
|
if (values.help) {
|
|
1006
1133
|
out.out(CATALOG_USAGE);
|
|
@@ -1011,7 +1138,11 @@ async function catalogCommand(ctx, out, args) {
|
|
|
1011
1138
|
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
1012
1139
|
out.err(connectionLine(target));
|
|
1013
1140
|
const steward = clientFor(ctx, target);
|
|
1014
|
-
await requireCapabilities(steward, target, [
|
|
1141
|
+
await requireCapabilities(steward, target, [
|
|
1142
|
+
...definesBenefits(input) ? ["benefits"] : [],
|
|
1143
|
+
...definesMeters(input) ? ["meters"] : [],
|
|
1144
|
+
...definesUnlistedPlans(input) ? ["unlisted_plans"] : []
|
|
1145
|
+
]);
|
|
1015
1146
|
const diff = diffCatalog(await currentCatalog(steward, target), input);
|
|
1016
1147
|
for (const line of describeDiff(diff)) out.out(line);
|
|
1017
1148
|
const priceChanges = priceChangeCount(diff);
|
|
@@ -1208,33 +1339,34 @@ async function creditsCommand(ctx, out, args) {
|
|
|
1208
1339
|
}
|
|
1209
1340
|
//#endregion
|
|
1210
1341
|
//#region src/commands/doctor.ts
|
|
1211
|
-
const DOCTOR_USAGE = `
|
|
1342
|
+
const DOCTOR_USAGE = `Usage: steward doctor [--json]
|
|
1212
1343
|
|
|
1213
|
-
GET /v1/doctor
|
|
1214
|
-
hosted (
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1344
|
+
The GET /v1/doctor report. Sections in order: status, catalog, provider, settings,
|
|
1345
|
+
hosted (page readiness), endpoints (delivery diagnosis), dunning, emails and, for a
|
|
1346
|
+
product with meters, metering/events/overage; at the end the errors, warnings and info
|
|
1347
|
+
lists. If APP_URL is set it is compared with steward's appUrl and allowed return
|
|
1348
|
+
origins.
|
|
1218
1349
|
|
|
1219
|
-
|
|
1220
|
-
STEWARD_ADMIN_API_KEY).
|
|
1221
|
-
|
|
1222
|
-
|
|
1350
|
+
Connection: STEWARD_URL + STEWARD_API_KEY (if both are missing, STEWARD_ADMIN_URL +
|
|
1351
|
+
STEWARD_ADMIN_API_KEY). If even one steward connection variable is in the
|
|
1352
|
+
environment, the connection and APP_URL are read only from the environment
|
|
1353
|
+
(./.env.local is not read); otherwise from ./.env.local. The source and the target's
|
|
1354
|
+
origin are written to stderr.
|
|
1223
1355
|
|
|
1224
|
-
|
|
1225
|
-
|
|
1356
|
+
Exit code: 0 ready; 1 the report is not ok (a warning of error severity) or APP_URL
|
|
1357
|
+
is not allowed in steward.
|
|
1226
1358
|
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
events, meters, overage)
|
|
1230
|
-
rollup
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1359
|
+
Metering: for a product whose catalog defines meters, the "metering" line shows the
|
|
1360
|
+
meters and metered prices (GET /v1/catalog) and steward's capabilities (GET /v1/me:
|
|
1361
|
+
events, meters, overage); then come the report's "events" section (pending events,
|
|
1362
|
+
rollup lag, a sample of the last 7 days: unmatched event names, invalid values,
|
|
1363
|
+
meters without events) and "overage" section (charge mode, metered prices,
|
|
1364
|
+
subscriptions without a locked rate, carried charges). Metering warnings are in the
|
|
1365
|
+
lists below as usual.
|
|
1234
1366
|
|
|
1235
|
-
--json
|
|
1236
|
-
cliMetering:
|
|
1237
|
-
/** `APP_URL` (
|
|
1367
|
+
--json writes the report as JSON (+ cliWarnings: the local APP_URL comparison;
|
|
1368
|
+
cliMetering: the catalog and capability facts of the metering line)`;
|
|
1369
|
+
/** `APP_URL` (the product's own address; the checkout `successUrl` is built from it) ↔ steward settings. */
|
|
1238
1370
|
function appUrlWarnings(appUrl, report) {
|
|
1239
1371
|
if (appUrl === void 0) return [];
|
|
1240
1372
|
let origin;
|
|
@@ -1244,18 +1376,18 @@ function appUrlWarnings(appUrl, report) {
|
|
|
1244
1376
|
return [{
|
|
1245
1377
|
code: "app_url_env_invalid",
|
|
1246
1378
|
severity: "error",
|
|
1247
|
-
message: "APP_URL
|
|
1379
|
+
message: "APP_URL is not a valid address"
|
|
1248
1380
|
}];
|
|
1249
1381
|
}
|
|
1250
1382
|
if (!report.settings.returnOrigins.includes(origin)) return [{
|
|
1251
1383
|
code: "app_url_not_allowed",
|
|
1252
1384
|
severity: "error",
|
|
1253
|
-
message: `APP_URL origin
|
|
1385
|
+
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
1386
|
}];
|
|
1255
1387
|
if (report.settings.appUrl !== null && originOf(report.settings.appUrl) !== origin) return [{
|
|
1256
1388
|
code: "app_url_mismatch",
|
|
1257
1389
|
severity: "warning",
|
|
1258
|
-
message: `APP_URL (${origin}) steward appUrl
|
|
1390
|
+
message: `APP_URL (${origin}) differs from steward's appUrl (${report.settings.appUrl}): the hosted page's "back to product" link goes to appUrl`
|
|
1259
1391
|
}];
|
|
1260
1392
|
return [];
|
|
1261
1393
|
}
|
|
@@ -1326,9 +1458,9 @@ const SEVERITY_ORDER = [
|
|
|
1326
1458
|
"info"
|
|
1327
1459
|
];
|
|
1328
1460
|
const SEVERITY_TITLE = {
|
|
1329
|
-
error: "
|
|
1330
|
-
warning: "
|
|
1331
|
-
info: "
|
|
1461
|
+
error: "errors",
|
|
1462
|
+
warning: "warnings",
|
|
1463
|
+
info: "info"
|
|
1332
1464
|
};
|
|
1333
1465
|
const yesNo = (value) => value ? "✓" : "✗";
|
|
1334
1466
|
function countBySeverity(warnings) {
|
|
@@ -1337,34 +1469,34 @@ function countBySeverity(warnings) {
|
|
|
1337
1469
|
warnings: warnings.filter((w) => w.severity === "warning").length
|
|
1338
1470
|
};
|
|
1339
1471
|
}
|
|
1340
|
-
/**
|
|
1472
|
+
/** The full human-readable report. */
|
|
1341
1473
|
function formatDoctorReport(report, cliWarnings, metering = null) {
|
|
1342
1474
|
const all = [...report.warnings, ...cliWarnings];
|
|
1343
1475
|
const { errors, warnings } = countBySeverity(all);
|
|
1344
1476
|
const ready = errors === 0;
|
|
1345
1477
|
const lines = [];
|
|
1346
1478
|
lines.push(`steward doctor — ${report.product.code} (${report.product.name}) · ${report.checkedAt}`);
|
|
1347
|
-
lines.push(`
|
|
1479
|
+
lines.push(`status ${ready ? "READY ✓" : "PROBLEMS ✗"} (${plural(errors, "error")}, ${plural(warnings, "warning")})`);
|
|
1348
1480
|
lines.push("");
|
|
1349
1481
|
const { catalog, provider, settings, hosted } = report;
|
|
1350
|
-
lines.push(`
|
|
1482
|
+
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
1483
|
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(`
|
|
1484
|
+
const providerState = !provider.configured ? "not configured ✗" : provider.healthy === false ? "unreachable !" : "configured ✓";
|
|
1485
|
+
const providerError = provider.lastError ? ` · last error ${provider.lastError.code} (${provider.lastError.operation}, ${provider.lastError.at})` : "";
|
|
1486
|
+
lines.push(`provider ${provider.id}${provider.environment !== null ? ` · ${provider.environment}` : ""} · ${providerState}${providerError}`);
|
|
1487
|
+
lines.push(`settings appUrl ${settings.appUrl ?? "none"} · return origins: ${settings.returnOrigins.length > 0 ? settings.returnOrigins.join(", ") : "none"}`);
|
|
1356
1488
|
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("
|
|
1489
|
+
lines.push(`hosted ${hosted.ready ? "ready ✓" : `not ready ✗${missing.length > 0 ? ` (missing: ${missing.join(", ")})` : ""}`}`);
|
|
1490
|
+
if (report.endpoints.length === 0) lines.push("endpoints none");
|
|
1359
1491
|
else {
|
|
1360
|
-
lines.push("
|
|
1492
|
+
lines.push("endpoints");
|
|
1361
1493
|
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}] ·
|
|
1494
|
+
const types = endpoint.eventTypes === null ? "no filter (0.1 types)" : endpoint.eventTypes.join(",");
|
|
1495
|
+
const last = endpoint.lastDelivery ? ` · last delivery ${endpoint.lastDelivery.status}${endpoint.lastDelivery.httpStatus !== null ? ` ${endpoint.lastDelivery.httpStatus}` : ""}` : "";
|
|
1496
|
+
lines.push(` ${endpoint.id} ${endpoint.status} ${endpoint.diagnosis} ${endpoint.url} [${types}] · pending ${endpoint.pending} · dead ${endpoint.dead}${last}`);
|
|
1365
1497
|
}
|
|
1366
1498
|
}
|
|
1367
|
-
lines.push(`dunning ${report.dunning.dryRun ? "dry-run (
|
|
1499
|
+
lines.push(`dunning ${report.dunning.dryRun ? "dry-run (no suspension/termination)" : "active"}`);
|
|
1368
1500
|
if (report.emails) {
|
|
1369
1501
|
const { emails } = report;
|
|
1370
1502
|
const problems = [...emails.transportConfigured ? [] : ["no transport"], ...emails.senderConfigured ? [] : ["no sender"]];
|
|
@@ -1405,7 +1537,7 @@ async function doctorCommand(ctx, out, args) {
|
|
|
1405
1537
|
const target = requireReadTarget(env);
|
|
1406
1538
|
const appUrl = env.get("APP_URL");
|
|
1407
1539
|
out.err(connectionLine(target));
|
|
1408
|
-
if (appUrl === void 0) out.err(`APP_URL
|
|
1540
|
+
if (appUrl === void 0) out.err(`APP_URL not set (${env.source}): skipped the steward appUrl comparison`);
|
|
1409
1541
|
const steward = clientFor(ctx, target);
|
|
1410
1542
|
const report = await callSteward(target, () => steward.doctor());
|
|
1411
1543
|
const cliWarnings = appUrlWarnings(appUrl, report);
|
|
@@ -1840,11 +1972,11 @@ async function repriceCommand(ctx, out, args) {
|
|
|
1840
1972
|
}
|
|
1841
1973
|
//#endregion
|
|
1842
1974
|
//#region src/commands/settings.ts
|
|
1843
|
-
const SETTINGS_USAGE = `
|
|
1975
|
+
const SETTINGS_USAGE = `Usage:
|
|
1844
1976
|
steward settings get
|
|
1845
1977
|
steward settings set [--app-url <url>] [--privacy-url <url>] [--terms-url <url>]
|
|
1846
1978
|
[--branding <json>] [--default-locale tr|en]
|
|
1847
|
-
[--checkout-ttl <
|
|
1979
|
+
[--checkout-ttl <minutes>] [--portal-ttl <minutes>]
|
|
1848
1980
|
[--extra-return-origins <a,b>] [--emails <json>]
|
|
1849
1981
|
[--billing-payment-due-days <1-60>] [--billing-min-invoice-minor <n>]
|
|
1850
1982
|
[--billing-allow-multiple-subscriptions true|false]
|
|
@@ -1852,10 +1984,10 @@ const SETTINGS_USAGE = `Kullanım:
|
|
|
1852
1984
|
[--metering-late-grace-minutes <0-1440>] [--events-retention-days <45-400>]
|
|
1853
1985
|
[--provider <id>]
|
|
1854
1986
|
|
|
1855
|
-
|
|
1856
|
-
(--privacy-url "")
|
|
1857
|
-
'{"name":"Acme","supportEmail":"
|
|
1858
|
-
|
|
1987
|
+
Product settings (GET/PATCH /v1/admin/settings). A field not given is unchanged; an
|
|
1988
|
+
empty value (--privacy-url "") clears the field, --branding null clears the branding,
|
|
1989
|
+
--branding '{"name":"Acme","supportEmail":"support@acme.com"}' merges shallowly (clear a
|
|
1990
|
+
field with null). --extra-return-origins "" empties the list.
|
|
1859
1991
|
--emails '{"billingPath":"/{LOCALE}/billing","templates":{"invoice_issued":{"enabled":false}}}'
|
|
1860
1992
|
sets billing emails (sender: from.name, from.address; templates merge per
|
|
1861
1993
|
template, null resets a field or template; --emails null resets all).
|
|
@@ -1874,7 +2006,7 @@ kept after receipt, once their period is closed (default 120). "" restores the d
|
|
|
1874
2006
|
--provider sets the payment provider for NEW checkouts and payment sessions (open ones keep
|
|
1875
2007
|
theirs); steward accepts only a provider configured in its deployment (iyzico, fake…).
|
|
1876
2008
|
|
|
1877
|
-
|
|
2009
|
+
Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
|
|
1878
2010
|
const SET_OPTIONS = {
|
|
1879
2011
|
...HELP_OPTION,
|
|
1880
2012
|
"app-url": { type: "string" },
|
|
@@ -1895,7 +2027,7 @@ const SET_OPTIONS = {
|
|
|
1895
2027
|
provider: { type: "string" }
|
|
1896
2028
|
};
|
|
1897
2029
|
const orNull = (value) => value.trim() === "" ? null : value.trim();
|
|
1898
|
-
/**
|
|
2030
|
+
/** A patch from the flags; validated with the contract schema (if invalid no request is sent). */
|
|
1899
2031
|
function buildSettingsPatch(values) {
|
|
1900
2032
|
const patch = {};
|
|
1901
2033
|
if (values["app-url"] !== void 0) patch.appUrl = orNull(values["app-url"]);
|
|
@@ -1909,9 +2041,9 @@ function buildSettingsPatch(values) {
|
|
|
1909
2041
|
try {
|
|
1910
2042
|
branding = JSON.parse(text);
|
|
1911
2043
|
} catch {
|
|
1912
|
-
throw new UsageError("--branding: JSON
|
|
2044
|
+
throw new UsageError("--branding: must be a JSON object, e.g. '{\"name\":\"Acme\",\"supportEmail\":\"support@acme.com\"}'");
|
|
1913
2045
|
}
|
|
1914
|
-
if (typeof branding !== "object" || branding === null || Array.isArray(branding)) throw new UsageError("--branding: JSON
|
|
2046
|
+
if (typeof branding !== "object" || branding === null || Array.isArray(branding)) throw new UsageError("--branding: must be a JSON object");
|
|
1915
2047
|
patch.branding = branding;
|
|
1916
2048
|
}
|
|
1917
2049
|
}
|
|
@@ -1954,9 +2086,9 @@ function buildSettingsPatch(values) {
|
|
|
1954
2086
|
if (Object.keys(metering).length > 0) patch.metering = metering;
|
|
1955
2087
|
const retention = values["events-retention-days"];
|
|
1956
2088
|
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(`
|
|
2089
|
+
if (Object.keys(patch).length === 0) throw new UsageError(`at least one settings flag is required (details: steward settings --help)`);
|
|
1958
2090
|
const parsed = ProductSettingsPatchSchema.safeParse(patch);
|
|
1959
|
-
if (!parsed.success) throw new UsageError(`
|
|
2091
|
+
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
2092
|
return patch;
|
|
1961
2093
|
}
|
|
1962
2094
|
async function settingsCommand(ctx, out, args) {
|
|
@@ -1990,41 +2122,41 @@ async function settingsCommand(ctx, out, args) {
|
|
|
1990
2122
|
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
1991
2123
|
out.err(connectionLine(target));
|
|
1992
2124
|
const settings = await callSteward(target, () => clientFor(ctx, target).admin.settings.update(patch));
|
|
1993
|
-
out.err(`
|
|
2125
|
+
out.err(`settings updated → ${originOf(target.url)} (${Object.keys(patch).join(", ")})`);
|
|
1994
2126
|
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
2127
|
out.out(JSON.stringify(settings, null, 2));
|
|
1996
2128
|
return 0;
|
|
1997
2129
|
}
|
|
1998
|
-
throw new UsageError(`
|
|
2130
|
+
throw new UsageError(`unknown subcommand: settings ${sub} (details: steward settings --help)`);
|
|
1999
2131
|
}
|
|
2000
2132
|
//#endregion
|
|
2001
2133
|
//#region src/main.ts
|
|
2002
|
-
const CLI_VERSION = "0.
|
|
2134
|
+
const CLI_VERSION = "0.8.0";
|
|
2003
2135
|
const USAGE = `steward — Steward CLI (@stewardhq/cli ${CLI_VERSION})
|
|
2004
2136
|
|
|
2005
|
-
|
|
2137
|
+
Usage: steward <command> [options]
|
|
2006
2138
|
|
|
2007
|
-
|
|
2008
|
-
doctor [--json]
|
|
2009
|
-
catalog push <
|
|
2010
|
-
settings get | set [
|
|
2011
|
-
endpoints list | add | rotate | deactivate webhook
|
|
2139
|
+
Commands:
|
|
2140
|
+
doctor [--json] setup diagnosis (GET /v1/doctor)
|
|
2141
|
+
catalog push <file> [--yes] catalog sync (PUT /v1/admin/catalog)
|
|
2142
|
+
settings get | set [flags] product settings (/v1/admin/settings)
|
|
2143
|
+
endpoints list | add | rotate | deactivate webhook endpoints; the secret goes only to the --out file
|
|
2012
2144
|
keys list | create | revoke API keys; the key goes only to the --out file
|
|
2013
2145
|
dunning get | set <policy.json> dunning policy (/v1/admin/dunning-policy)
|
|
2014
2146
|
reprice --plan <code> --notice-days <n> move a plan's subscribers to its current price
|
|
2015
|
-
bank-transfers list | record
|
|
2147
|
+
bank-transfers list | record | fx-report bank transfer reconciliation (/v1/admin/bank-transfers)
|
|
2016
2148
|
credits adjust <ref> <meter> --units=<n> credit entry, negative = adjustment
|
|
2017
2149
|
meters get | recompute | close-periods an account's meters; metering repairs (admin)
|
|
2018
2150
|
events send | redeliver send one event; redeliver webhook events (admin)
|
|
2019
2151
|
|
|
2020
|
-
|
|
2021
|
-
meters
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2152
|
+
Connection: admin commands use STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY; doctor,
|
|
2153
|
+
meters and events use STEWARD_URL + STEWARD_API_KEY (or the admin pair). If even one of
|
|
2154
|
+
these four variables is in the environment, all of them (and APP_URL) are read from the
|
|
2155
|
+
environment and ./.env.local is not read at all; otherwise from ./.env.local. The source
|
|
2156
|
+
in use is written to stderr (connection: …). Changes send X-Actor-Ref operator:<user>.
|
|
2157
|
+
The CLI never writes secrets to the terminal and never calls kubectl.
|
|
2026
2158
|
|
|
2027
|
-
|
|
2159
|
+
Details: steward <command> --help`;
|
|
2028
2160
|
const COMMANDS = {
|
|
2029
2161
|
doctor: doctorCommand,
|
|
2030
2162
|
catalog: catalogCommand,
|
|
@@ -2055,7 +2187,7 @@ async function main(argv, ctx) {
|
|
|
2055
2187
|
}
|
|
2056
2188
|
const command = Object.hasOwn(COMMANDS, name) ? COMMANDS[name] : void 0;
|
|
2057
2189
|
if (command === void 0) {
|
|
2058
|
-
out.err(`steward:
|
|
2190
|
+
out.err(`steward: unknown command: ${name}\n\n${USAGE}`);
|
|
2059
2191
|
return 2;
|
|
2060
2192
|
}
|
|
2061
2193
|
try {
|
|
@@ -2069,7 +2201,7 @@ async function main(argv, ctx) {
|
|
|
2069
2201
|
out.err(`steward ${name}: ${describeStewardError(error)}`);
|
|
2070
2202
|
return 1;
|
|
2071
2203
|
}
|
|
2072
|
-
out.err(`steward ${name}:
|
|
2204
|
+
out.err(`steward ${name}: unexpected error:${error instanceof Error ? error.message : String(error)}`);
|
|
2073
2205
|
return 1;
|
|
2074
2206
|
}
|
|
2075
2207
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stewardhq/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "Steward CLI: doctor, catalog push, settings and webhook endpoint management.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"homepage": "https://github.com/z9cloud/steward/tree/main/cli#readme",
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
"registry": "https://registry.npmjs.org"
|
|
29
29
|
},
|
|
30
30
|
"dependencies": {
|
|
31
|
-
"@stewardhq/sdk": "^0.
|
|
31
|
+
"@stewardhq/sdk": "^0.8.0"
|
|
32
32
|
},
|
|
33
33
|
"devDependencies": {
|
|
34
34
|
"@types/node": "^24.19.0",
|