@stewardhq/cli 0.10.0 → 0.11.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.
Files changed (3) hide show
  1. package/README.md +17 -35
  2. package/dist/bin.js +589 -82
  3. package/package.json +5 -5
package/README.md CHANGED
@@ -20,7 +20,7 @@ ESM, Node ≥ 22. Its only runtime dependency is `@stewardhq/sdk`.
20
20
  | `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 |
21
21
  | `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 |
22
22
  | `steward settings get` | `GET /v1/admin/settings` |
23
- | `steward settings set [--app-url] [--privacy-url] [--terms-url] [--branding <json>] [--default-locale tr\|en] [--checkout-ttl <min>] [--portal-ttl <min>] [--extra-return-origins a,b] [--emails <json>] [--billing-payment-due-days <1-60>] [--billing-min-invoice-minor <n>] [--billing-allow-multiple-subscriptions true\|false] [--metering-charge-mode off\|dry_run\|live] [--metering-late-grace-minutes <0-1440>] [--events-retention-days <45-400>]` | `PATCH /v1/admin/settings`; an empty value clears the field (billing, metering and events flags: restores the default) |
23
+ | `steward settings set [--app-url] [--privacy-url] [--terms-url] [--branding <json>] [--default-locale tr\|en] [--display-time-zone <iana>] [--default-country <XX>] [--checkout-ttl <min>] [--portal-ttl <min>] [--extra-return-origins a,b] [--emails <json>] [--billing-payment-due-days <1-60>] [--billing-min-invoice-minor <n>] [--billing-allow-multiple-subscriptions true\|false] [--metering-charge-mode off\|dry_run\|live] [--metering-late-grace-minutes <0-1440>] [--events-retention-days <45-400>] [--tax-provider price\|none] [--tax-exemption-reason-en <text>] [--tax-exemption-reason-tr <text>] [--consumer-markets <XX,YY>]` | `PATCH /v1/admin/settings`; an empty value clears the field (billing, metering, events and tax flags: restores the default) |
24
24
  | `steward endpoints list [--json]` | Endpoints and their last delivery |
25
25
  | `steward endpoints add --url <url> --out <file> [--event-types a,b] [--description <text>] [--force]` | Generates the secret locally and writes it only to `--out` |
26
26
  | `steward endpoints rotate <id> --out <file> [--force]` | New secret to `--out`; the product transitions with `new,old` |
@@ -35,6 +35,8 @@ ESM, Node ≥ 22. Its only runtime dependency is `@stewardhq/sdk`.
35
35
  | `steward events redeliver <eventId>…` | Requeues every delivery of webhook events (admin) |
36
36
  | `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 |
37
37
  | `steward invoices list [--status draft\|issued\|void\|all] [--payment-status <status>] [--limit <n>] [--json]` / `steward invoices issue <id> --number <number> [--external-ref <ref>] [--issued-at <iso>] [--document <file.pdf>] [--yes]` | `GET /v1/admin/invoices`: the invoices not cut in the external system yet (`draft`, the default), oldest first; `POST /v1/invoices/:id/issue`: writes the external invoice number and marks the invoice issued (once; asks for confirmation, the customer is emailed) |
38
+ | `steward grants list [--plan <code>] [--subscription none\|live\|any] [--limit <n>] [--after <grant id>] [--json]` | `GET /v1/admin/grants`: the product's active grants (not revoked, started, not ended), one line per grant, with the account and its live subscriptions. `--subscription none`: accounts with no live subscription, e.g. granted a plan but paying for nothing; `--plan`: one plan's grants (an unknown code is refused). A cut list names the next `--after` on stderr |
39
+ | `steward tax thresholds list [--json]` / `steward tax thresholds set <code> --scope <scope> --currency <CUR> [--amount-minor <n>] [--transactions <n>] [--country <XX>] [--region <XX>] [--home-country <XX>] [--period calendar_year\|rolling_12_months] [--warn-at-bps <n>] [--fx-rate <CUR>=<rate>]… [--note <text>]` / `steward tax thresholds delete <code>` / `steward tax sales [--from <iso>] [--to <iso>] [--json\|--csv]` | Tax registration thresholds (`/v1/admin/tax/thresholds`; none ship, the accountant defines them; `set` replaces one whole, audited) with each one's counted sales, share and status; `sales`: paid sales per month, buyer country, region, kind, currency and tax treatment (`GET /v1/admin/sales`) |
38
40
 
39
41
  Exit codes: 0 success, 1 error (or doctor not ready), 2 incorrect usage.
40
42
 
@@ -135,42 +137,22 @@ capability: an older steward would drop the key and offer the plan.
135
137
 
136
138
  Release: bump the version in `cli/package.json` and push the `cli-v<version>` tag
137
139
  (`.github/workflows/cli-publish.yml`); the `@stewardhq/sdk` version it depends on must already
138
- be published on npm. **The first version on npmjs is 0.5.0** (2026-09-21); 0.4.0 was not
139
- published.
140
-
141
- - **0.10.0** (`@stewardhq/sdk` 0.10, which adds `admin.invoices.list`):
142
- `steward invoices list` (the invoices not issued yet, i.e. without the external system's number)
143
- and `steward invoices issue <id> --number <number>` (writes that number). `bank-transfers list`
144
- shows an `INVOICE NO` column.
145
- - **0.9.0** (`@stewardhq/sdk` 0.9, which adds `accounts.updateMetadata`):
146
- `steward accounts get`, `steward accounts metadata set` and `unset` (single metadata keys, merged
147
- by steward in one atomic write; requires the `account_metadata` capability). Also: the connection
148
- hint and the "could not reach steward" hint no longer name one deployment's host or assume a
149
- particular way of reaching steward (messages only).
150
- - **0.8.0** (`@stewardhq/sdk` 0.8, bank transfers in another currency, issue #55):
151
- `bank-transfers record --rate`, `bank-transfers list --rate [--currency]`,
152
- `bank-transfers fx-report [--from] [--to] [--json|--csv]`. Unlisted plans: `catalog push` shows
153
- the `plan listing` diff and requires the `unlisted_plans` capability for a plan with
154
- `listed: false`. Help, errors, `doctor` and `endpoints` output and the connection line are now
155
- in English (they were partly Turkish); flags, command names, JSON output and exit codes are
156
- unchanged.
157
- - **0.7.0** (`@stewardhq/sdk` 0.7, admin operations, issue #57): `steward keys`, `steward dunning`,
158
- `steward reprice`, `steward credits adjust`, `steward bank-transfers`, `steward meters recompute` and
159
- `close-periods`, `steward events redeliver`, `settings set --provider`. These replace the pod CLI
160
- commands of the same jobs. `doctor` lists the active API keys with age, last use and expiry; the
161
- connection hint names the public admin host.
162
- - **0.5.0** (`@stewardhq/sdk` 0.5, metering phase 2): `steward meters get`, `steward events
163
- send`; meter, credit and metered price diff in `catalog push` (a metered price change asks
164
- for confirmation; a catalog with meters is not pushed without the `meters` capability);
165
- `settings set --metering-charge-mode`, `--metering-late-grace-minutes`,
166
- `--events-retention-days`; the `metering` line in `doctor` plus the report's `events` and
167
- `overage` sections.
168
- - **0.4.0** (`@stewardhq/sdk` 0.4, billing core phase 1): benefit and price diff, price change
169
- confirmation, the `benefits` capability gate, `settings set --billing-*`; `steward dev`
170
- removed (breaking).
140
+ be published on npm. The notes of 0.4.0 to 0.10.0 are in
141
+ [this file at `cli-v0.10.0`](https://github.com/z9cloud/steward/blob/cli-v0.10.0/cli/README.md#versions).
142
+
143
+ - **0.11.0** (`@stewardhq/sdk` 0.11, which removes the contract names steward no longer produces):
144
+ `steward grants list` (the product's active grants and their accounts' live subscriptions; needs a steward with
145
+ `GET /v1/admin/grants`). `steward settings set --display-time-zone <iana>` (the zone of customer-facing dates;
146
+ `""` restores `Europe/Istanbul`). `steward tax thresholds list|set|delete` and `steward tax sales` (needs a steward
147
+ with `/v1/admin/tax/thresholds` and `/v1/admin/sales`); `steward settings set --tax-provider`,
148
+ `--tax-exemption-reason-en|-tr`, `--consumer-markets`. `steward settings set --default-country <XX>`,
149
+ `--billing-renewal-notice-intervals`, `--billing-renewal-notice-days`, `--billing-invoice-line-text iso|localized`,
150
+ `--seller`, `--withdrawal-waiver`, `--card-on-file`. `steward invoices list --from|--to` and `--csv` (the export
151
+ for an accounting system). `steward bank-transfers record --override-billing-currency`. `steward doctor` shows
152
+ the provider's webhook, automatic renewal and the legal settings.
171
153
 
172
154
  When packed, the `@stewardhq/sdk` dependency turns from `workspace:^` into the range of the
173
- SDK version current at that time (0.5.0 → `^0.5.0`).
155
+ SDK version current at that time (0.11.0 → `^0.11.0`).
174
156
 
175
157
  ## License
176
158
 
package/dist/bin.js CHANGED
@@ -2,13 +2,13 @@
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 { ACCOUNT_INCLUDES, AccountMetadataPatchInputSchema, ApiKeyCreateInputSchema, BankTransferRecordInputSchema, CatalogSyncInputSchema, CreditAdjustmentInputSchema, DunningPolicySchema, EventsIngestInputSchema, FxRateSchema, InvoiceIssueInputSchema, InvoicePaymentStatusSchema, InvoiceStatusSchema, 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, CodeSchema, CreditAdjustmentInputSchema, DateTimeSchema, DunningPolicySchema, EventsIngestInputSchema, FxRateSchema, GRANT_LIST_DEFAULT_LIMIT, GRANT_LIST_MAX_LIMIT, GrantListSubscriptionFilterSchema, INVOICE_LINE_TEXTS, IdSchema, InvoiceIssueInputSchema, InvoicePaymentStatusSchema, InvoiceStatusSchema, METER_CHARGE_MODES, MeterCreditPropertiesSchema, ProductSettingsPatchSchema, RepriceInputSchema, SALES_REPORT_MAX_MONTHS, StewardApiError, StewardConfigError, StewardError, StewardNetworkError, TAX_PROVIDERS, TAX_THRESHOLD_PERIODS, TAX_THRESHOLD_SCOPES, TaxThresholdInputSchema, WebhookEndpointCreateInputSchema, WebhookEndpointRotateInputSchema, createSteward, generateApiKeyToken, generateWebhookSecret, plainDecimalOf, taxIdTypeOf } 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";
9
9
  import { randomUUID } from "node:crypto";
10
10
  import { pathToFileURL } from "node:url";
11
- //#region src/io.ts
11
+ // 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) {
@@ -41,8 +41,7 @@ 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;
43
43
  }
44
- //#endregion
45
- //#region src/args.ts
44
+ // src/args.ts
46
45
  const HELP_OPTION = { help: {
47
46
  type: "boolean",
48
47
  short: "h"
@@ -105,8 +104,7 @@ function parseBoolean(value, flag) {
105
104
  ].includes(text)) return false;
106
105
  throw new UsageError(`${flag}: must be true or false`);
107
106
  }
108
- //#endregion
109
- //#region src/catalog-diff.ts
107
+ // src/catalog-diff.ts
110
108
  /** A catalog that defines benefits needs a steward with the `benefits` capability (M27). */
111
109
  function definesBenefits(input) {
112
110
  return Object.keys(input.benefits ?? {}).length > 0;
@@ -138,7 +136,7 @@ function formatMinor(amountMinor, currency) {
138
136
  return `${amountMinor} ${currency} (minor units)`;
139
137
  }
140
138
  }
141
- const percent = (bps) => `${bps / 100}%`;
139
+ const percent$1 = (bps) => `${bps / 100}%`;
142
140
  /** Units as exact text with grouping (`2,000,000`, `0.25`). */
143
141
  const unitsText = (value) => new Intl.NumberFormat("en", { maximumFractionDigits: 6 }).format(plainDecimalOf(value));
144
142
  const meteredKey = (p) => `${p.planCode}/${p.meter}/${p.currency}`;
@@ -286,7 +284,7 @@ function diffCatalog(current, file) {
286
284
  function describePriceChange({ label, currency, from, to }) {
287
285
  const parts = [];
288
286
  if (from.amountMinor !== to.amountMinor) parts.push(`${formatMinor(from.amountMinor, currency)} → ${formatMinor(to.amountMinor, currency)}`);
289
- if (from.taxRateBps !== to.taxRateBps) parts.push(`tax rate ${percent(from.taxRateBps)} → ${percent(to.taxRateBps)}`);
287
+ if (from.taxRateBps !== to.taxRateBps) parts.push(`tax rate ${percent$1(from.taxRateBps)} → ${percent$1(to.taxRateBps)}`);
290
288
  if (from.taxInclusive !== to.taxInclusive) parts.push(`tax ${from.taxInclusive ? "inclusive" : "exclusive"} → ${to.taxInclusive ? "inclusive" : "exclusive"}`);
291
289
  return `${from.amountMinor === to.amountMinor ? `${label} ${formatMinor(to.amountMinor, currency)}` : label}: ${parts.join(", ")}`;
292
290
  }
@@ -305,7 +303,7 @@ function describeMeteredPriceChange({ label, currency, from, to }) {
305
303
  const cap = (minor) => minor === null ? "none" : formatMinor(minor, currency);
306
304
  parts.push(`cap ${cap(from.capMinor)} → ${cap(to.capMinor)}`);
307
305
  }
308
- if (from.taxRateBps !== to.taxRateBps) parts.push(`tax rate ${percent(from.taxRateBps)} → ${percent(to.taxRateBps)}`);
306
+ if (from.taxRateBps !== to.taxRateBps) parts.push(`tax rate ${percent$1(from.taxRateBps)} → ${percent$1(to.taxRateBps)}`);
309
307
  if (from.taxInclusive !== to.taxInclusive) parts.push(`tax ${from.taxInclusive ? "inclusive" : "exclusive"} → ${to.taxInclusive ? "inclusive" : "exclusive"}`);
310
308
  return `${label}: ${parts.join(", ")}`;
311
309
  }
@@ -359,8 +357,7 @@ function describeDiff(diff) {
359
357
  function priceChangeCount(diff) {
360
358
  return diff.prices.changed.length + diff.meteredPrices.changed.length;
361
359
  }
362
- //#endregion
363
- //#region src/dotenv.ts
360
+ // src/dotenv.ts
364
361
  const LINE = /^(\s*)(export\s+)?([A-Za-z_][A-Za-z0-9_.-]*)\s*=(.*)$/;
365
362
  function unquote(rest) {
366
363
  const value = rest.trim();
@@ -391,8 +388,7 @@ async function readDotenvFile(path) {
391
388
  throw error;
392
389
  }
393
390
  }
394
- //#endregion
395
- //#region src/env.ts
391
+ // src/env.ts
396
392
  const ENV_LOCAL = ".env.local";
397
393
  /** If even one of these is in the process environment, `.env.local` is not read. */
398
394
  const CONNECTION_VARIABLES = [
@@ -526,8 +522,7 @@ function describeStewardError(error, target) {
526
522
  }
527
523
  return `steward response does not match the contract${where}: ${error.code} (HTTP ${error.httpStatus}) — the CLI and steward versions may be incompatible${request}`;
528
524
  }
529
- //#endregion
530
- //#region src/commands/accounts.ts
525
+ // src/commands/accounts.ts
531
526
  const ACCOUNTS_USAGE = `Usage:
532
527
  steward accounts get <ref> [--include <a,b>] [--json]
533
528
  steward accounts metadata set <ref> <key>=<value>… [--reason <text>] [--json]
@@ -703,8 +698,7 @@ async function accountsCommand(ctx, out, args) {
703
698
  if (sub === "metadata") return metadataCommand(ctx, out, rest);
704
699
  throw new UsageError(`unknown subcommand: accounts ${sub} (see: steward accounts --help)`);
705
700
  }
706
- //#endregion
707
- //#region src/confirm.ts
701
+ // src/confirm.ts
708
702
  /**
709
703
  * Asks before a change that cannot be taken back; `yes` (`--yes`) skips the question. Without a
710
704
  * terminal (CI, pipes) the command needs `--yes`: `notConfirmed` says what was not done.
@@ -715,8 +709,7 @@ async function confirm(ctx, question, options) {
715
709
  if (answer === null) throw new CliError(`confirmation needed: run again with --yes (${options.notConfirmed})`);
716
710
  return /^y(es)?$/i.test(answer.trim());
717
711
  }
718
- //#endregion
719
- //#region src/secret-file.ts
712
+ // src/secret-file.ts
720
713
  async function withSecretFile(cwd, out, secret, options, action) {
721
714
  const target = resolve(cwd, out);
722
715
  try {
@@ -763,8 +756,7 @@ async function withSecretFile(cwd, out, secret, options, action) {
763
756
  };
764
757
  }
765
758
  }
766
- //#endregion
767
- //#region src/commands/endpoints.ts
759
+ // src/commands/endpoints.ts
768
760
  const ENDPOINTS_USAGE = `Usage:
769
761
  steward endpoints list [--json]
770
762
  steward endpoints add --url <url> --out <file> [--event-types <a,b>] [--description <text>] [--force]
@@ -806,7 +798,7 @@ async function endpointsCommand(ctx, out, args) {
806
798
  ...HELP_OPTION,
807
799
  json: { type: "boolean" }
808
800
  }, "endpoints");
809
- if (values.help) return help$4(out);
801
+ if (values.help) return help$5(out);
810
802
  expectPositionals(positionals, 0, 0, "endpoints");
811
803
  const target = requireAdminTarget(await resolveEnv(ctx));
812
804
  out.err(connectionLine(target));
@@ -841,7 +833,7 @@ async function endpointsCommand(ctx, out, args) {
841
833
  description: { type: "string" },
842
834
  force: { type: "boolean" }
843
835
  }, ENDPOINTS_USAGE);
844
- if (values.help) return help$4(out);
836
+ if (values.help) return help$5(out);
845
837
  expectPositionals(positionals, 0, 0, "endpoints");
846
838
  const url = requireOption(values.url, "--url", "endpoints");
847
839
  const file = requireOption(values.out, "--out", "endpoints");
@@ -872,7 +864,7 @@ async function endpointsCommand(ctx, out, args) {
872
864
  out: { type: "string" },
873
865
  force: { type: "boolean" }
874
866
  }, "endpoints");
875
- if (values.help) return help$4(out);
867
+ if (values.help) return help$5(out);
876
868
  expectPositionals(positionals, 1, 1, "endpoints");
877
869
  const id = positionals[0];
878
870
  const file = requireOption(values.out, "--out", "endpoints");
@@ -891,7 +883,7 @@ async function endpointsCommand(ctx, out, args) {
891
883
  }
892
884
  if (sub === "deactivate") {
893
885
  const { values, positionals } = parse(rest, { ...HELP_OPTION }, "endpoints");
894
- if (values.help) return help$4(out);
886
+ if (values.help) return help$5(out);
895
887
  expectPositionals(positionals, 1, 1, "endpoints");
896
888
  const target = requireAdminTarget(await resolveEnv(ctx));
897
889
  out.err(connectionLine(target));
@@ -901,7 +893,7 @@ async function endpointsCommand(ctx, out, args) {
901
893
  }
902
894
  throw new UsageError(`unknown subcommand: endpoints ${sub} (details: steward endpoints --help)`);
903
895
  }
904
- function help$4(out) {
896
+ function help$5(out) {
905
897
  out.out(ENDPOINTS_USAGE);
906
898
  return 0;
907
899
  }
@@ -911,15 +903,14 @@ function secretNotice(out, path, fallback, next) {
911
903
  out.out(` secret ${path} (0600; not written to the terminal)`);
912
904
  out.err(next);
913
905
  }
914
- //#endregion
915
- //#region src/commands/bank-transfers.ts
906
+ // src/commands/bank-transfers.ts
916
907
  const BANK_TRANSFERS_USAGE = `Usage:
917
908
  steward bank-transfers list [--status pending|expired] [--rate <rate> [--currency <CUR>]]
918
909
  [--json]
919
910
  steward bank-transfers record <code> --amount <minor> --currency <CUR> --received-at <iso>
920
911
  --bank-ref <ref> [--rate <rate>]
921
912
  [--checkout <id> [--accept-expired] | --invoice <id>]
922
- [--yes] [--json]
913
+ [--override-billing-currency] [--yes] [--json]
923
914
  steward bank-transfers fx-report [--from <iso>] [--to <iso>] [--json | --csv]
924
915
 
925
916
  Bank transfer (havale/EFT) reconciliation (/v1/admin/bank-transfers).
@@ -949,6 +940,10 @@ within the product's tolerance (fxToleranceBps, default 0.5%) of its amount at t
949
940
  is settled in its own currency. --rate is required for such a transfer and refused for one in
950
941
  the item's currency. Steward never looks a rate up.
951
942
 
943
+ record --override-billing-currency: settle a checkout that is not in the account's billing
944
+ currency (another payment fixed it after the checkout opened; refused with currency_mismatch
945
+ otherwise). Not needed for an invoice, nor for a checkout the product opened with the override.
946
+
952
947
  fx-report: the payments received in another currency (invoice number and date, amount settled,
953
948
  amount received, the rate entered, received date), latest first; --from (inclusive) and --to
954
949
  (exclusive) are ISO-8601 with an offset, by received date. The accountant's input for
@@ -970,7 +965,7 @@ async function bankTransfersCommand(ctx, out, args) {
970
965
  currency: { type: "string" },
971
966
  json: { type: "boolean" }
972
967
  }, "bank-transfers");
973
- if (values.help) return help$3(out);
968
+ if (values.help) return help$4(out);
974
969
  expectPositionals(positionals, 0, 0, "bank-transfers");
975
970
  const status = values.status ?? "pending";
976
971
  if (status !== "pending" && status !== "expired") throw new UsageError("--status: pending or expired");
@@ -1025,13 +1020,14 @@ async function bankTransfersCommand(ctx, out, args) {
1025
1020
  checkout: { type: "string" },
1026
1021
  invoice: { type: "string" },
1027
1022
  "accept-expired": { type: "boolean" },
1023
+ "override-billing-currency": { type: "boolean" },
1028
1024
  yes: {
1029
1025
  type: "boolean",
1030
1026
  short: "y"
1031
1027
  },
1032
1028
  json: { type: "boolean" }
1033
1029
  }, "bank-transfers");
1034
- if (values.help) return help$3(out);
1030
+ if (values.help) return help$4(out);
1035
1031
  expectPositionals(positionals, 1, 1, "bank-transfers");
1036
1032
  const receivedAt = requireOption(values["received-at"], "--received-at", "bank-transfers");
1037
1033
  if (!WITH_OFFSET$1.test(receivedAt)) throw new UsageError("--received-at: ISO-8601 with an offset (2026-09-28T10:15:00+03:00)");
@@ -1044,7 +1040,8 @@ async function bankTransfersCommand(ctx, out, args) {
1044
1040
  ...values.rate !== void 0 ? { rate: parseRate(values.rate) } : {},
1045
1041
  ...values.checkout !== void 0 ? { checkoutSessionId: values.checkout } : {},
1046
1042
  ...values.invoice !== void 0 ? { invoiceId: values.invoice } : {},
1047
- ...values["accept-expired"] ? { acceptExpired: true } : {}
1043
+ ...values["accept-expired"] ? { acceptExpired: true } : {},
1044
+ ...values["override-billing-currency"] ? { overrideBillingCurrency: true } : {}
1048
1045
  };
1049
1046
  const parsed = BankTransferRecordInputSchema.safeParse(input);
1050
1047
  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")}`);
@@ -1074,7 +1071,7 @@ async function bankTransfersCommand(ctx, out, args) {
1074
1071
  json: { type: "boolean" },
1075
1072
  csv: { type: "boolean" }
1076
1073
  }, "bank-transfers");
1077
- if (values.help) return help$3(out);
1074
+ if (values.help) return help$4(out);
1078
1075
  expectPositionals(positionals, 0, 0, "bank-transfers");
1079
1076
  if (values.json && values.csv) throw new UsageError("--json or --csv, not both");
1080
1077
  if (values.from !== void 0 && !WITH_OFFSET$1.test(values.from)) throw new UsageError("--from: ISO-8601 with an offset (2026-09-01T00:00:00+03:00)");
@@ -1139,12 +1136,11 @@ function csvField(value) {
1139
1136
  const text = typeof value === "string" && /^[=+\-@]/.test(value) ? `'${value}` : String(value);
1140
1137
  return /[",\n\r]/.test(text) ? `"${text.replace(/"/g, "\"\"")}"` : text;
1141
1138
  }
1142
- function help$3(out) {
1139
+ function help$4(out) {
1143
1140
  out.out(BANK_TRANSFERS_USAGE);
1144
1141
  return 0;
1145
1142
  }
1146
- //#endregion
1147
- //#region src/catalog-file.ts
1143
+ // src/catalog-file.ts
1148
1144
  const MODULE_EXTENSIONS = /* @__PURE__ */ new Set([
1149
1145
  ".js",
1150
1146
  ".mjs",
@@ -1204,8 +1200,7 @@ async function loadCatalogFile(ctx, file) {
1204
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")}`);
1205
1201
  return input;
1206
1202
  }
1207
- //#endregion
1208
- //#region src/commands/catalog.ts
1203
+ // src/commands/catalog.ts
1209
1204
  const CATALOG_USAGE = `Usage: steward catalog push <file> [--yes]
1210
1205
 
1211
1206
  Syncs the catalog definition to steward (PUT /v1/admin/catalog), then prints the version
@@ -1340,8 +1335,7 @@ async function catalogCommand(ctx, out, args) {
1340
1335
  for (const line of lines) out.out(line);
1341
1336
  return providerErrors > 0 ? 1 : 0;
1342
1337
  }
1343
- //#endregion
1344
- //#region src/commands/meters.ts
1338
+ // src/commands/meters.ts
1345
1339
  const METERS_USAGE = `Usage:
1346
1340
  steward meters get <ref> [--periods <n>] [--json]
1347
1341
  steward meters recompute <ref> [--meter <code>] [--json]
@@ -1464,8 +1458,7 @@ async function metersCommand(ctx, out, args) {
1464
1458
  else for (const line of formatMeters(meters, periods)) out.out(line);
1465
1459
  return 0;
1466
1460
  }
1467
- //#endregion
1468
- //#region src/commands/credits.ts
1461
+ // src/commands/credits.ts
1469
1462
  const CREDITS_USAGE = `Usage: steward credits adjust <ref> <meter> --units=<n> --reason <text> [--json]
1470
1463
 
1471
1464
  One credit ledger entry for the meter's current usage period of account <ref>
@@ -1518,8 +1511,7 @@ async function creditsCommand(ctx, out, args) {
1518
1511
  if (read !== void 0) out.out(` balance ${formatUnitsText(read.balance)} · standing ${read.standing}`);
1519
1512
  return 0;
1520
1513
  }
1521
- //#endregion
1522
- //#region src/commands/doctor.ts
1514
+ // src/commands/doctor.ts
1523
1515
  const DOCTOR_USAGE = `Usage: steward doctor [--json]
1524
1516
 
1525
1517
  The GET /v1/doctor report. Sections in order: status, catalog, provider, settings,
@@ -1663,11 +1655,18 @@ function formatDoctorReport(report, cliWarnings, metering = null) {
1663
1655
  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`);
1664
1656
  for (const price of catalog.unsellablePrices) lines.push(` ✗ ${price.planCode} ${price.interval}×${price.intervalCount} ${price.currency}: ${price.reason}`);
1665
1657
  const providerState = !provider.configured ? "not configured ✗" : provider.healthy === false ? "unreachable !" : "configured ✓";
1658
+ const webhook = provider.webhook ? ` · webhook ${provider.webhook.configured ? `configured ✓ (last event ${provider.webhook.lastEventAt ?? "never"})` : "not configured ✗"}${provider.webhook.openDisputes > 0 ? ` · ${provider.webhook.openDisputes} open dispute(s) !` : ""}` : "";
1659
+ const renewal = provider.automaticRenewal ? ` · automatic renewal active ✓ (${provider.automaticRenewal.subscriptionsWithCard} with a saved card, ${provider.automaticRenewal.subscriptionsWithoutCard} without; renewal notice ${provider.automaticRenewal.renewalNotice ? `${provider.automaticRenewal.renewalNotice.daysBefore} days before, ${provider.automaticRenewal.renewalNotice.intervals.join("/")}` : "off"})` : provider.configured ? " · automatic renewal off (invoice e-mail and pay page)" : "";
1666
1660
  const providerError = provider.lastError ? ` · last error ${provider.lastError.code} (${provider.lastError.operation}, ${provider.lastError.at})` : "";
1667
- lines.push(`provider ${provider.id}${provider.environment !== null ? ` · ${provider.environment}` : ""} · ${providerState}${providerError}`);
1661
+ lines.push(`provider ${provider.id}${provider.environment !== null ? ` · ${provider.environment}` : ""} · ${providerState}${webhook}${renewal}${providerError}`);
1668
1662
  lines.push(`settings appUrl ${settings.appUrl ?? "none"} · return origins: ${settings.returnOrigins.length > 0 ? settings.returnOrigins.join(", ") : "none"}`);
1669
1663
  const missing = [...hosted.branding.missing.map((field) => `branding.${field}`), ...hosted.legalLinks.missing];
1670
1664
  lines.push(`hosted ${hosted.ready ? "ready ✓" : `not ready ✗${missing.length > 0 ? ` (missing: ${missing.join(", ")})` : ""}`}`);
1665
+ if (report.legal) {
1666
+ const legal = report.legal;
1667
+ const mark = (set) => set ? "✓" : "✗";
1668
+ lines.push(`legal seller ${mark(legal.seller)} · withdrawal waiver ${legal.withdrawalWaiver ? `${legal.withdrawalWaiver.version} ✓` : "✗"}` + (legal.cardSaved ? ` · card-on-file consent ${legal.cardOnFile ? `${legal.cardOnFile.version} ✓` : "✗"}` : "") + (legal.pendingErasures > 0 ? ` · ${legal.pendingErasures} provider erasure(s) pending !` : ""));
1669
+ }
1671
1670
  if (report.endpoints.length === 0) lines.push("endpoints none");
1672
1671
  else {
1673
1672
  lines.push("endpoints");
@@ -1732,8 +1731,7 @@ async function doctorCommand(ctx, out, args) {
1732
1731
  else for (const line of formatDoctorReport(report, cliWarnings, metering)) out.out(line);
1733
1732
  return failed ? 1 : 0;
1734
1733
  }
1735
- //#endregion
1736
- //#region src/commands/dunning.ts
1734
+ // src/commands/dunning.ts
1737
1735
  const DUNNING_USAGE = `Usage:
1738
1736
  steward dunning get [--json]
1739
1737
  steward dunning set <policy.json> [--yes]
@@ -1759,7 +1757,7 @@ async function dunningCommand(ctx, out, args) {
1759
1757
  ...HELP_OPTION,
1760
1758
  json: { type: "boolean" }
1761
1759
  }, "dunning");
1762
- if (values.help) return help$2(out);
1760
+ if (values.help) return help$3(out);
1763
1761
  expectPositionals(positionals, 0, 0, "dunning");
1764
1762
  const target = requireAdminTarget(await resolveEnv(ctx));
1765
1763
  out.err(connectionLine(target));
@@ -1776,7 +1774,7 @@ async function dunningCommand(ctx, out, args) {
1776
1774
  short: "y"
1777
1775
  }
1778
1776
  }, "dunning");
1779
- if (values.help) return help$2(out);
1777
+ if (values.help) return help$3(out);
1780
1778
  expectPositionals(positionals, 1, 1, "dunning");
1781
1779
  const file = positionals[0];
1782
1780
  let json;
@@ -1809,12 +1807,11 @@ async function dunningCommand(ctx, out, args) {
1809
1807
  }
1810
1808
  throw new UsageError(`unknown subcommand: dunning ${sub} (see: steward dunning --help)`);
1811
1809
  }
1812
- function help$2(out) {
1810
+ function help$3(out) {
1813
1811
  out.out(DUNNING_USAGE);
1814
1812
  return 0;
1815
1813
  }
1816
- //#endregion
1817
- //#region src/commands/events.ts
1814
+ // src/commands/events.ts
1818
1815
  const EVENTS_USAGE = `Usage:
1819
1816
  steward events send <ref> <name> [--meta key=value]… [--external-id <id>]
1820
1817
  [--timestamp <iso>] [--json]
@@ -1940,11 +1937,89 @@ async function redeliverCommand(ctx, out, args) {
1940
1937
  }
1941
1938
  return 0;
1942
1939
  }
1943
- //#endregion
1944
- //#region src/commands/invoices.ts
1940
+ // src/commands/grants.ts
1941
+ const GRANTS_USAGE = `Usage:
1942
+ steward grants list [--plan <code>] [--subscription none|live|any] [--limit <n>]
1943
+ [--after <grant id>] [--json]
1944
+
1945
+ The product's active grants (not revoked, started, not ended), one line per grant, with the
1946
+ account and its live subscriptions (GET /v1/admin/grants).
1947
+
1948
+ --plan: only the grants of that plan (a code the product never had is refused). Without it,
1949
+ grants of named benefits or overrides only are listed too (plan -).
1950
+ --subscription: none = accounts with no live subscription (active, past_due, suspended), e.g.
1951
+ granted a plan but paying for nothing; live = accounts with one; any (default) = both.
1952
+ --limit: 1–${GRANT_LIST_MAX_LIMIT}, default ${GRANT_LIST_DEFAULT_LIMIT}; a cut list says so on stderr with the --after
1953
+ value of the next page.
1954
+
1955
+ Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
1956
+ async function grantsCommand(ctx, out, args) {
1957
+ const [sub, ...rest] = args;
1958
+ if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
1959
+ out.out(GRANTS_USAGE);
1960
+ return sub === void 0 ? 2 : 0;
1961
+ }
1962
+ if (sub === "list") {
1963
+ const { values, positionals } = parse(rest, {
1964
+ ...HELP_OPTION,
1965
+ plan: { type: "string" },
1966
+ subscription: { type: "string" },
1967
+ limit: { type: "string" },
1968
+ after: { type: "string" },
1969
+ json: { type: "boolean" }
1970
+ }, "grants");
1971
+ if (values.help) {
1972
+ out.out(GRANTS_USAGE);
1973
+ return 0;
1974
+ }
1975
+ expectPositionals(positionals, 0, 0, "grants");
1976
+ if (values.plan !== void 0 && !CodeSchema.safeParse(values.plan).success) throw new UsageError("--plan: a plan code");
1977
+ const subscription = GrantListSubscriptionFilterSchema.optional().safeParse(values.subscription);
1978
+ if (!subscription.success) throw new UsageError("--subscription: none, live or any");
1979
+ if (values.after !== void 0 && !IdSchema.safeParse(values.after).success) throw new UsageError("--after: a grant id");
1980
+ const limit = values.limit !== void 0 ? parsePositiveInt(values.limit, "--limit", { max: GRANT_LIST_MAX_LIMIT }) : void 0;
1981
+ const filter = {
1982
+ ...values.plan !== void 0 ? { plan: values.plan } : {},
1983
+ ...subscription.data !== void 0 ? { subscription: subscription.data } : {},
1984
+ ...limit !== void 0 ? { limit } : {},
1985
+ ...values.after !== void 0 ? { after: values.after } : {}
1986
+ };
1987
+ const target = requireAdminTarget(await resolveEnv(ctx));
1988
+ out.err(connectionLine(target));
1989
+ const { items, hasMore } = await callSteward(target, () => clientFor(ctx, target).admin.grants.list(filter));
1990
+ if (values.json) out.out(JSON.stringify(items, null, 2));
1991
+ else if (items.length === 0) out.out("no active grants");
1992
+ else {
1993
+ const rows = [[
1994
+ "ACCOUNT",
1995
+ "NAME",
1996
+ "PLAN",
1997
+ "ENDS",
1998
+ "SUBSCRIPTIONS",
1999
+ "GRANT",
2000
+ "REASON"
2001
+ ]];
2002
+ for (const g of items) rows.push([
2003
+ g.accountRef,
2004
+ g.accountDisplayName || "-",
2005
+ g.planCode ?? "-",
2006
+ g.endsAt ?? "-",
2007
+ g.liveSubscriptions.map((s) => `${s.planCode}/${s.interval} ${s.status}`).join(", ") || "-",
2008
+ g.grantId,
2009
+ g.reason
2010
+ ]);
2011
+ for (const line of table(rows)) out.out(line);
2012
+ }
2013
+ const last = items.at(-1);
2014
+ if (hasMore && last !== void 0) out.err(`more grants than the ${limit ?? GRANT_LIST_DEFAULT_LIMIT} listed; next page: --after ${last.grantId}`);
2015
+ return 0;
2016
+ }
2017
+ throw new UsageError(`unknown subcommand: grants ${sub} (see: steward grants --help)`);
2018
+ }
2019
+ // src/commands/invoices.ts
1945
2020
  const INVOICES_USAGE = `Usage:
1946
2021
  steward invoices list [--status draft|issued|void|all] [--payment-status <status>]
1947
- [--limit <n>] [--json]
2022
+ [--from <iso>] [--to <iso>] [--limit <n>] [--json | --csv]
1948
2023
  steward invoices issue <id> --number <number> [--external-ref <ref>] [--issued-at <iso>]
1949
2024
  [--document <file.pdf>] [--yes] [--json]
1950
2025
 
@@ -1952,8 +2027,15 @@ Tracking which invoices have been cut in the external system (e-Arşiv, the acco
1952
2027
 
1953
2028
  list: the product's invoices, oldest first (GET /v1/admin/invoices). draft (default): the ones
1954
2029
  not issued yet, i.e. with no number of the external system; issued: the ones that have it; all:
1955
- every status. --payment-status narrows it (unpaid, paid, …). --limit: 1–500, default 100; a
1956
- cut list says so on stderr.
2030
+ every status. --payment-status narrows it (unpaid, paid, …). --from (inclusive) and --to
2031
+ (exclusive), ISO-8601 with an offset, keep the invoices written in that window. --limit: 1–500,
2032
+ default 100; a cut list says so on stderr.
2033
+
2034
+ --csv is the export for an accounting system that issues the invoices (one row per invoice, a
2035
+ header row first): the invoice, its amounts in minor units, the tax decision (treatment, reason,
2036
+ tax country), the period, the payment (date, method, reference), the buyer copy (kind, names,
2037
+ contact, address with postal code, region and country, tax ID with its type) and the lines as a
2038
+ JSON array. Columns are only ever added at the end. --json prints the items as the API returns them.
1957
2039
 
1958
2040
  issue: writes the number the invoice got in the external system and marks it issued
1959
2041
  (POST /v1/invoices/:id/issue). --number is unique within the product. --external-ref is any
@@ -1976,11 +2058,17 @@ async function invoicesCommand(ctx, out, args) {
1976
2058
  ...HELP_OPTION,
1977
2059
  status: { type: "string" },
1978
2060
  "payment-status": { type: "string" },
2061
+ from: { type: "string" },
2062
+ to: { type: "string" },
1979
2063
  limit: { type: "string" },
1980
- json: { type: "boolean" }
2064
+ json: { type: "boolean" },
2065
+ csv: { type: "boolean" }
1981
2066
  }, "invoices");
1982
- if (values.help) return help$1(out);
2067
+ if (values.help) return help$2(out);
1983
2068
  expectPositionals(positionals, 0, 0, "invoices");
2069
+ if (values.json && values.csv) throw new UsageError("--json and --csv: choose one");
2070
+ if (values.from !== void 0 && !DateTimeSchema.safeParse(values.from).success) throw new UsageError("--from: ISO-8601 with an offset, e.g. 2026-10-01T00:00:00Z");
2071
+ if (values.to !== void 0 && !DateTimeSchema.safeParse(values.to).success) throw new UsageError("--to: ISO-8601 with an offset, e.g. 2026-10-01T00:00:00Z");
1984
2072
  const statusText = values.status ?? "draft";
1985
2073
  const status = statusText === "all" ? void 0 : InvoiceStatusSchema.safeParse(statusText).data;
1986
2074
  if (statusText !== "all" && status === void 0) throw new UsageError("--status: draft, issued, void or all");
@@ -1990,13 +2078,18 @@ async function invoicesCommand(ctx, out, args) {
1990
2078
  const filter = {
1991
2079
  ...status !== void 0 ? { status } : {},
1992
2080
  ...paymentStatus.data !== void 0 ? { paymentStatus: paymentStatus.data } : {},
2081
+ ...values.from !== void 0 ? { from: values.from } : {},
2082
+ ...values.to !== void 0 ? { to: values.to } : {},
1993
2083
  ...limit !== void 0 ? { limit } : {}
1994
2084
  };
1995
2085
  const target = requireAdminTarget(await resolveEnv(ctx));
1996
2086
  out.err(connectionLine(target));
1997
2087
  const { items, hasMore } = await callSteward(target, () => clientFor(ctx, target).admin.invoices.list(filter));
1998
2088
  if (values.json) out.out(JSON.stringify(items, null, 2));
1999
- else if (items.length === 0) out.out(`no ${status ?? ""} invoices`.replace(" ", " "));
2089
+ else if (values.csv) {
2090
+ out.out(INVOICE_EXPORT_COLUMNS.join(","));
2091
+ for (const invoice of items) out.out(invoiceExportRow(invoice).map(csvCell$1).join(","));
2092
+ } else if (items.length === 0) out.out(`no ${status ?? ""} invoices`.replace(" ", " "));
2000
2093
  else {
2001
2094
  const rows = [[
2002
2095
  "CREATED",
@@ -2034,7 +2127,7 @@ async function invoicesCommand(ctx, out, args) {
2034
2127
  },
2035
2128
  json: { type: "boolean" }
2036
2129
  }, "invoices");
2037
- if (values.help) return help$1(out);
2130
+ if (values.help) return help$2(out);
2038
2131
  expectPositionals(positionals, 1, 1, "invoices");
2039
2132
  const id = positionals[0];
2040
2133
  const number = requireOption(values.number, "--number", "invoices").trim();
@@ -2068,6 +2161,93 @@ async function invoicesCommand(ctx, out, args) {
2068
2161
  }
2069
2162
  throw new UsageError(`unknown subcommand: invoices ${sub} (see: steward invoices --help)`);
2070
2163
  }
2164
+ const INVOICE_EXPORT_COLUMNS = [
2165
+ "id",
2166
+ "number",
2167
+ "status",
2168
+ "createdAt",
2169
+ "issuedAt",
2170
+ "accountRef",
2171
+ "billingReason",
2172
+ "currency",
2173
+ "subtotalMinor",
2174
+ "taxMinor",
2175
+ "totalMinor",
2176
+ "taxRateBps",
2177
+ "taxTreatment",
2178
+ "taxReason",
2179
+ "taxCountry",
2180
+ "periodStart",
2181
+ "periodEnd",
2182
+ "paymentStatus",
2183
+ "paidAt",
2184
+ "paymentMethod",
2185
+ "paymentRef",
2186
+ "buyerKind",
2187
+ "buyerContactName",
2188
+ "buyerCompanyName",
2189
+ "buyerEmail",
2190
+ "buyerPhone",
2191
+ "buyerAddress",
2192
+ "buyerCity",
2193
+ "buyerPostalCode",
2194
+ "buyerRegion",
2195
+ "buyerCountry",
2196
+ "buyerTaxIdType",
2197
+ "buyerTaxId",
2198
+ "buyerTaxOffice",
2199
+ "lines"
2200
+ ];
2201
+ function invoiceExportRow(invoice) {
2202
+ const buyer = invoice.buyer;
2203
+ const values = {
2204
+ id: invoice.id,
2205
+ number: invoice.number,
2206
+ status: invoice.status,
2207
+ createdAt: invoice.createdAt,
2208
+ issuedAt: invoice.issuedAt,
2209
+ accountRef: invoice.accountRef,
2210
+ billingReason: invoice.billingReason ?? null,
2211
+ currency: invoice.currency,
2212
+ subtotalMinor: invoice.subtotalMinor,
2213
+ taxMinor: invoice.taxMinor,
2214
+ totalMinor: invoice.totalMinor,
2215
+ taxRateBps: invoice.taxRateBps,
2216
+ taxTreatment: invoice.taxTreatment ?? null,
2217
+ taxReason: invoice.taxReason ?? null,
2218
+ taxCountry: invoice.taxCountry ?? null,
2219
+ periodStart: invoice.periodStart ?? null,
2220
+ periodEnd: invoice.periodEnd ?? null,
2221
+ paymentStatus: invoice.paymentStatus ?? null,
2222
+ paidAt: invoice.paidAt ?? null,
2223
+ paymentMethod: invoice.paymentMethod ?? null,
2224
+ paymentRef: invoice.paymentRef ?? null,
2225
+ buyerKind: buyer.kind,
2226
+ buyerContactName: buyer.contactName,
2227
+ buyerCompanyName: buyer.companyName ?? null,
2228
+ buyerEmail: buyer.email,
2229
+ buyerPhone: buyer.phone,
2230
+ buyerAddress: buyer.address,
2231
+ buyerCity: buyer.city,
2232
+ buyerPostalCode: buyer.postalCode ?? null,
2233
+ buyerRegion: buyer.region ?? null,
2234
+ buyerCountry: buyer.country,
2235
+ buyerTaxIdType: buyer.taxId !== void 0 ? taxIdTypeOf(buyer.country, buyer.taxIdType) : null,
2236
+ buyerTaxId: buyer.taxId ?? null,
2237
+ buyerTaxOffice: buyer.taxOffice ?? null,
2238
+ lines: JSON.stringify(invoice.lines.map((line) => ({
2239
+ description: line.description,
2240
+ quantity: line.quantity,
2241
+ unitAmountMinor: line.unitAmountMinor,
2242
+ amountMinor: line.amountMinor
2243
+ })))
2244
+ };
2245
+ return INVOICE_EXPORT_COLUMNS.map((column) => values[column]);
2246
+ }
2247
+ const csvCell$1 = (value) => {
2248
+ const cell = value === null ? "" : String(value);
2249
+ return /[",\n\r]/.test(cell) ? `"${cell.replace(/"/g, "\"\"")}"` : cell;
2250
+ };
2071
2251
  /** Reads the PDF to attach; the same checks as steward's (PDF signature, at most 5 MB) before anything is sent. */
2072
2252
  async function readDocument(ctx, file) {
2073
2253
  let bytes;
@@ -2080,12 +2260,11 @@ async function readDocument(ctx, file) {
2080
2260
  if (bytes.length > MAX_DOCUMENT_BYTES) throw new UsageError(`--document: ${file} is larger than 5 MB`);
2081
2261
  return bytes;
2082
2262
  }
2083
- function help$1(out) {
2263
+ function help$2(out) {
2084
2264
  out.out(INVOICES_USAGE);
2085
2265
  return 0;
2086
2266
  }
2087
- //#endregion
2088
- //#region src/commands/keys.ts
2267
+ // src/commands/keys.ts
2089
2268
  const KEYS_USAGE = `Usage:
2090
2269
  steward keys list [--json]
2091
2270
  steward keys create --name <name> --scope product|checkout|admin --out <file>
@@ -2123,7 +2302,7 @@ async function keysCommand(ctx, out, args) {
2123
2302
  ...HELP_OPTION,
2124
2303
  json: { type: "boolean" }
2125
2304
  }, "keys");
2126
- if (values.help) return help(out);
2305
+ if (values.help) return help$1(out);
2127
2306
  expectPositionals(positionals, 0, 0, "keys");
2128
2307
  const target = requireAdminTarget(await resolveEnv(ctx));
2129
2308
  out.err(connectionLine(target));
@@ -2161,7 +2340,7 @@ async function keysCommand(ctx, out, args) {
2161
2340
  "no-expiry": { type: "boolean" },
2162
2341
  force: { type: "boolean" }
2163
2342
  }, "keys");
2164
- if (values.help) return help(out);
2343
+ if (values.help) return help$1(out);
2165
2344
  expectPositionals(positionals, 0, 0, "keys");
2166
2345
  const name = requireOption(values.name, "--name", "keys");
2167
2346
  const scope = requireOption(values.scope, "--scope", "keys");
@@ -2192,7 +2371,7 @@ async function keysCommand(ctx, out, args) {
2192
2371
  }
2193
2372
  if (sub === "revoke") {
2194
2373
  const { values, positionals } = parse(rest, { ...HELP_OPTION }, "keys");
2195
- if (values.help) return help(out);
2374
+ if (values.help) return help$1(out);
2196
2375
  expectPositionals(positionals, 1, 1, "keys");
2197
2376
  const target = requireAdminTarget(await resolveEnv(ctx));
2198
2377
  out.err(connectionLine(target));
@@ -2202,12 +2381,11 @@ async function keysCommand(ctx, out, args) {
2202
2381
  }
2203
2382
  throw new UsageError(`unknown subcommand: keys ${sub} (see: steward keys --help)`);
2204
2383
  }
2205
- function help(out) {
2384
+ function help$1(out) {
2206
2385
  out.out(KEYS_USAGE);
2207
2386
  return 0;
2208
2387
  }
2209
- //#endregion
2210
- //#region src/commands/reprice.ts
2388
+ // src/commands/reprice.ts
2211
2389
  const REPRICE_USAGE = `Usage: steward reprice --plan <code> --notice-days <n> [--dry-run] [--yes] [--json]
2212
2390
 
2213
2391
  Moves the live subscriptions of a plan to the plan's current price and metered rates
@@ -2295,19 +2473,24 @@ async function repriceCommand(ctx, out, args) {
2295
2473
  else out.out(`scheduled → ${originOf(target.url)}: ${result.scheduled} subscription${result.scheduled === 1 ? "" : "s"} (one notice e-mail each)`);
2296
2474
  return 0;
2297
2475
  }
2298
- //#endregion
2299
- //#region src/commands/settings.ts
2476
+ // src/commands/settings.ts
2300
2477
  const SETTINGS_USAGE = `Usage:
2301
2478
  steward settings get
2302
2479
  steward settings set [--app-url <url>] [--privacy-url <url>] [--terms-url <url>]
2303
- [--branding <json>] [--default-locale tr|en]
2480
+ [--branding <json>] [--default-locale tr|en] [--display-time-zone <iana>]
2481
+ [--default-country <XX>]
2304
2482
  [--checkout-ttl <minutes>] [--portal-ttl <minutes>]
2305
2483
  [--extra-return-origins <a,b>] [--emails <json>]
2306
2484
  [--billing-payment-due-days <1-60>] [--billing-min-invoice-minor <n>]
2307
2485
  [--billing-allow-multiple-subscriptions true|false]
2486
+ [--billing-renewal-notice-intervals <year,month>] [--billing-renewal-notice-days <1-90>]
2487
+ [--billing-invoice-line-text iso|localized]
2308
2488
  [--metering-charge-mode off|dry_run|live]
2309
2489
  [--metering-late-grace-minutes <0-1440>] [--events-retention-days <45-400>]
2310
2490
  [--provider <id>]
2491
+ [--tax-provider price|none] [--tax-exemption-reason-en <text>]
2492
+ [--tax-exemption-reason-tr <text>] [--consumer-markets <XX,YY>]
2493
+ [--seller <json>] [--withdrawal-waiver <json>] [--card-on-file <json>]
2311
2494
 
2312
2495
  Product settings (GET/PATCH /v1/admin/settings). A field not given is unchanged; an
2313
2496
  empty value (--privacy-url "") clears the field, --branding null clears the branding,
@@ -2321,15 +2504,41 @@ invoice to its due date (default 7), --billing-min-invoice-minor smallest amount
2321
2504
  steward invoices on its own, in minor units (default 1000), and
2322
2505
  --billing-allow-multiple-subscriptions (default false: a checkout for an account with
2323
2506
  a live subscription is 409 already_subscribed; true: only a second subscription to the
2324
- same plan is). An empty value ("") restores the field's default.
2507
+ same plan is). --billing-renewal-notice-intervals lists the plan intervals that get the
2508
+ renewal notice e-mail (e.g. year; default none: no notice) and --billing-renewal-notice-days
2509
+ how many days before the renewal it is sent (default 30). --billing-invoice-line-text decides
2510
+ how new invoice lines are written: iso (default) ISO dates and the product's default language,
2511
+ localized the buyer's language with dates written in it. An empty value ("") restores the
2512
+ field's default.
2325
2513
  Metering (settings.metering, settings.events): --metering-charge-mode prices overage
2326
2514
  at the end of a usage period: dry_run (default) records the charge without invoicing
2327
2515
  it, live adds it to the renewal invoice, off prices nothing — run one full cycle in
2328
2516
  dry_run before live. --metering-late-grace-minutes how long a period waits for late
2329
2517
  events before it closes (default 60). --events-retention-days how long raw events are
2330
2518
  kept after receipt, once their period is closed (default 120). "" restores the default.
2519
+ --default-locale is the language of hosted pages and emails when the call, the session and
2520
+ the account name none steward supports. --display-time-zone is the IANA zone customer-facing
2521
+ dates are shown in (default Europe/Istanbul; a time of day names the zone); "" restores it.
2522
+ --default-country is the ISO country code (e.g. TR, DE, US) the hosted checkout and portal
2523
+ forms start on when the buyer has no stored profile (default TR); "" restores the default.
2331
2524
  --provider sets the payment provider for NEW checkouts and payment sessions (open ones keep
2332
2525
  theirs); steward accepts only a provider configured in its deployment (iyzico, fake…).
2526
+ Tax (settings.tax): --tax-provider decides the tax of invoices written from now on: price
2527
+ (default) the price's own rate; none no tax charged, every invoice exempt with the exemption
2528
+ wording (while the seller is under its thresholds; see steward tax --help).
2529
+ --tax-exemption-reason-en / -tr is that wording per language (the seller's legal wording; doctor
2530
+ warns while the provider is none and it is unset). --consumer-markets lists the countries open
2531
+ to individual buyers (e.g. AT,BE,…,US): a consumer elsewhere is refused at checkout, a business
2532
+ buyer never; "" opens every country (the default). "" restores a field's default.
2533
+ Legal (settings.legal; the texts are the seller's own, steward ships none; each is replaced as a
2534
+ whole, "" or null removes it): --seller is the seller's identity shown in the footer of hosted
2535
+ pages and e-mails, '{"legalName":"Acme Ltd","address":"1 Example Street, Example City",
2536
+ "taxId":"XX123456789","registrationNumber":"12345678"}'.
2537
+ --withdrawal-waiver is the checkbox consumers tick at checkout to waive the right of withdrawal,
2538
+ '{"version":"2026-10","text":{"en":"…"},"url":"https://…","countries":["DE","FR"]}' (countries
2539
+ empty or left out: every consumer). --card-on-file is the checkbox a card payer ticks when the
2540
+ card is saved for renewals (Stripe), '{"version":"2026-10","text":{"en":"…"}}'. Each acceptance
2541
+ is recorded with the version.
2333
2542
 
2334
2543
  Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
2335
2544
  const SET_OPTIONS = {
@@ -2339,6 +2548,8 @@ const SET_OPTIONS = {
2339
2548
  "terms-url": { type: "string" },
2340
2549
  branding: { type: "string" },
2341
2550
  "default-locale": { type: "string" },
2551
+ "display-time-zone": { type: "string" },
2552
+ "default-country": { type: "string" },
2342
2553
  "checkout-ttl": { type: "string" },
2343
2554
  "portal-ttl": { type: "string" },
2344
2555
  "extra-return-origins": { type: "string" },
@@ -2346,12 +2557,35 @@ const SET_OPTIONS = {
2346
2557
  "billing-payment-due-days": { type: "string" },
2347
2558
  "billing-min-invoice-minor": { type: "string" },
2348
2559
  "billing-allow-multiple-subscriptions": { type: "string" },
2560
+ "billing-renewal-notice-intervals": { type: "string" },
2561
+ "billing-renewal-notice-days": { type: "string" },
2562
+ "billing-invoice-line-text": { type: "string" },
2349
2563
  "metering-charge-mode": { type: "string" },
2350
2564
  "metering-late-grace-minutes": { type: "string" },
2351
2565
  "events-retention-days": { type: "string" },
2352
- provider: { type: "string" }
2566
+ provider: { type: "string" },
2567
+ "tax-provider": { type: "string" },
2568
+ "tax-exemption-reason-en": { type: "string" },
2569
+ "tax-exemption-reason-tr": { type: "string" },
2570
+ "consumer-markets": { type: "string" },
2571
+ seller: { type: "string" },
2572
+ "withdrawal-waiver": { type: "string" },
2573
+ "card-on-file": { type: "string" }
2353
2574
  };
2354
2575
  const orNull = (value) => value.trim() === "" ? null : value.trim();
2576
+ /** A JSON object flag; "" or null → null (clear). */
2577
+ function jsonObjectOrNull(value, flag) {
2578
+ const text = value.trim();
2579
+ if (text === "" || text === "null") return null;
2580
+ let parsed;
2581
+ try {
2582
+ parsed = JSON.parse(text);
2583
+ } catch {
2584
+ throw new UsageError(`--${flag}: must be a JSON object (see steward settings --help)`);
2585
+ }
2586
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new UsageError(`--${flag}: must be a JSON object`);
2587
+ return parsed;
2588
+ }
2355
2589
  /** A patch from the flags; validated with the contract schema (if invalid no request is sent). */
2356
2590
  function buildSettingsPatch(values) {
2357
2591
  const patch = {};
@@ -2387,6 +2621,8 @@ function buildSettingsPatch(values) {
2387
2621
  }
2388
2622
  }
2389
2623
  if (values["default-locale"] !== void 0) patch.defaultLocale = values["default-locale"].trim();
2624
+ if (values["display-time-zone"] !== void 0) patch.displayTimeZone = orNull(values["display-time-zone"]);
2625
+ if (values["default-country"] !== void 0) patch.defaultCountry = orNull(values["default-country"])?.toUpperCase() ?? null;
2390
2626
  if (values.provider !== void 0) patch.provider = values.provider.trim();
2391
2627
  if (values["checkout-ttl"] !== void 0) patch.checkoutTtlMinutes = parsePositiveInt(values["checkout-ttl"], "--checkout-ttl");
2392
2628
  if (values["portal-ttl"] !== void 0) patch.portalTtlMinutes = parsePositiveInt(values["portal-ttl"], "--portal-ttl");
@@ -2398,6 +2634,18 @@ function buildSettingsPatch(values) {
2398
2634
  if (minInvoice !== void 0) billing.minInvoiceMinor = minInvoice.trim() === "" ? null : parseNonNegativeInt(minInvoice, "--billing-min-invoice-minor");
2399
2635
  const multiple = values["billing-allow-multiple-subscriptions"];
2400
2636
  if (multiple !== void 0) billing.allowMultipleSubscriptions = multiple.trim() === "" ? null : parseBoolean(multiple, "--billing-allow-multiple-subscriptions");
2637
+ const renewalNotice = {};
2638
+ const noticeIntervals = values["billing-renewal-notice-intervals"];
2639
+ if (noticeIntervals !== void 0) renewalNotice.intervals = noticeIntervals.trim() === "" ? null : parseList(noticeIntervals);
2640
+ const noticeDays = values["billing-renewal-notice-days"];
2641
+ if (noticeDays !== void 0) renewalNotice.daysBefore = noticeDays.trim() === "" ? null : parsePositiveInt(noticeDays, "--billing-renewal-notice-days", { max: 90 });
2642
+ if (Object.keys(renewalNotice).length > 0) billing.renewalNotice = renewalNotice;
2643
+ const lineText = values["billing-invoice-line-text"];
2644
+ if (lineText !== void 0) {
2645
+ const style = lineText.trim();
2646
+ if (style !== "" && !INVOICE_LINE_TEXTS.includes(style)) throw new UsageError(`--billing-invoice-line-text: one of ${INVOICE_LINE_TEXTS.join(", ")}`);
2647
+ billing.invoiceLineText = style === "" ? null : style;
2648
+ }
2401
2649
  if (Object.keys(billing).length > 0) patch.billing = billing;
2402
2650
  const metering = {};
2403
2651
  const chargeMode = values["metering-charge-mode"];
@@ -2411,6 +2659,27 @@ function buildSettingsPatch(values) {
2411
2659
  if (Object.keys(metering).length > 0) patch.metering = metering;
2412
2660
  const retention = values["events-retention-days"];
2413
2661
  if (retention !== void 0) patch.events = { retentionDays: retention.trim() === "" ? null : parsePositiveInt(retention, "--events-retention-days", { max: 400 }) };
2662
+ const tax = {};
2663
+ const taxProvider = values["tax-provider"];
2664
+ if (taxProvider !== void 0) {
2665
+ const id = taxProvider.trim();
2666
+ if (id !== "" && !TAX_PROVIDERS.includes(id)) throw new UsageError(`--tax-provider: one of ${TAX_PROVIDERS.join(", ")}`);
2667
+ tax.provider = id === "" ? null : id;
2668
+ }
2669
+ const reasons = {};
2670
+ for (const locale of ["en", "tr"]) {
2671
+ const reason = values[`tax-exemption-reason-${locale}`];
2672
+ if (reason !== void 0) reasons[locale] = orNull(reason);
2673
+ }
2674
+ if (Object.keys(reasons).length > 0) tax.exemptionReason = reasons;
2675
+ const markets = values["consumer-markets"];
2676
+ if (markets !== void 0) tax.consumerMarkets = markets.trim() === "" ? null : parseList(markets).map((country) => country.toUpperCase());
2677
+ if (Object.keys(tax).length > 0) patch.tax = tax;
2678
+ const legal = {};
2679
+ if (values.seller !== void 0) legal.seller = jsonObjectOrNull(values.seller, "seller");
2680
+ if (values["withdrawal-waiver"] !== void 0) legal.withdrawalWaiver = jsonObjectOrNull(values["withdrawal-waiver"], "withdrawal-waiver");
2681
+ if (values["card-on-file"] !== void 0) legal.cardOnFile = jsonObjectOrNull(values["card-on-file"], "card-on-file");
2682
+ if (Object.keys(legal).length > 0) patch.legal = legal;
2414
2683
  if (Object.keys(patch).length === 0) throw new UsageError(`at least one settings flag is required (details: steward settings --help)`);
2415
2684
  const parsed = ProductSettingsPatchSchema.safeParse(patch);
2416
2685
  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")}`);
@@ -2454,9 +2723,244 @@ async function settingsCommand(ctx, out, args) {
2454
2723
  }
2455
2724
  throw new UsageError(`unknown subcommand: settings ${sub} (details: steward settings --help)`);
2456
2725
  }
2457
- //#endregion
2458
- //#region src/main.ts
2459
- const CLI_VERSION = "0.10.0";
2726
+ // src/commands/tax.ts
2727
+ const TAX_USAGE = `Usage:
2728
+ steward tax thresholds list [--json]
2729
+ steward tax thresholds set <code> --scope <scope> --currency <XXX>
2730
+ [--amount-minor <n>] [--transactions <n>]
2731
+ [--country <XX>] [--region <XX>] [--home-country <XX>]
2732
+ [--period calendar_year|rolling_12_months] [--warn-at-bps <1-10000>]
2733
+ [--fx-rate <XXX>=<rate> ...] [--note <text>]
2734
+ steward tax thresholds delete <code>
2735
+ steward tax sales [--from <iso>] [--to <iso>] [--json | --csv]
2736
+
2737
+ Tax registration thresholds and the sales they count (/v1/admin/tax/thresholds,
2738
+ /v1/admin/sales). Steward ships with no threshold: the seller's tax adviser decides which apply,
2739
+ how much and how they are counted; enter each with "set".
2740
+
2741
+ Scopes (--scope): company_turnover (every paid sale), eu_cross_border_consumer (individual
2742
+ buyers in an EU member state other than --home-country, the seller's), country (buyers in
2743
+ --country), us_state (buyers in the US state --region, e.g. CA). A threshold has an amount
2744
+ (--amount-minor, minor units of --currency), a number of sales (--transactions) or both; it
2745
+ counts its --period (default calendar_year, UTC) and warns at --warn-at-bps of its limit
2746
+ (default 8000 = 80%). Sales in another currency count at --fx-rate (units of --currency per 1
2747
+ unit of the sale's, e.g. --fx-rate USD=0.92 --fx-rate GBP=1.17); without a rate they are not
2748
+ counted and doctor warns. "set" replaces the whole threshold; every change is audited.
2749
+
2750
+ A sale is a payment steward collected, by its date, attributed to the buyer's declared country
2751
+ and region on the invoice it paid, net of refunds.
2752
+
2753
+ sales: paid sales per UTC month, buyer country, region, buyer kind, currency and tax treatment,
2754
+ with counts and totals (the threshold evidence). --from inclusive, --to exclusive (ISO-8601 with
2755
+ an offset); default: this calendar year up to now; at most ${SALES_REPORT_MAX_MONTHS} months.
2756
+
2757
+ Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
2758
+ const percent = (bps) => bps === null ? "-" : `${(bps / 100).toFixed(2)}%`;
2759
+ function scopeText(t) {
2760
+ switch (t.scope) {
2761
+ case "country": return `country ${t.country}`;
2762
+ case "us_state": return `us_state ${t.region}`;
2763
+ case "eu_cross_border_consumer": return `eu_cross_border_consumer (home ${t.homeCountry})`;
2764
+ default: return t.scope;
2765
+ }
2766
+ }
2767
+ function limitText(t) {
2768
+ return [t.amountMinor !== null ? `${t.amountMinor} ${t.currency}` : null, t.transactions !== null ? `${t.transactions} sales` : null].filter((part) => part !== null).join(" / ");
2769
+ }
2770
+ /** `USD=0.92` flags → the rates map (the contract checks each rate). */
2771
+ function parseFxRates(values) {
2772
+ const rates = {};
2773
+ for (const value of values ?? []) {
2774
+ const match = /^([A-Za-z]{3})=(.+)$/.exec(value.trim());
2775
+ if (!match) throw new UsageError("--fx-rate: <currency>=<rate>, e.g. USD=0.92");
2776
+ rates[match[1].toUpperCase()] = match[2].trim();
2777
+ }
2778
+ return rates;
2779
+ }
2780
+ /** The threshold from the flags; validated with the contract schema (if invalid no request is sent). */
2781
+ function buildThresholdInput(values) {
2782
+ const text = (name) => typeof values[name] === "string" ? values[name].trim() : void 0;
2783
+ const input = {
2784
+ scope: text("scope"),
2785
+ currency: text("currency")?.toUpperCase(),
2786
+ fxRates: parseFxRates(values["fx-rate"])
2787
+ };
2788
+ const amount = text("amount-minor");
2789
+ if (amount !== void 0) input.amountMinor = parsePositiveInt(amount, "--amount-minor");
2790
+ const transactions = text("transactions");
2791
+ if (transactions !== void 0) input.transactions = parsePositiveInt(transactions, "--transactions");
2792
+ if (text("country") !== void 0) input.country = text("country").toUpperCase();
2793
+ if (text("region") !== void 0) input.region = text("region").toUpperCase();
2794
+ if (text("home-country") !== void 0) input.homeCountry = text("home-country").toUpperCase();
2795
+ if (text("period") !== void 0) input.period = text("period");
2796
+ const warnAt = text("warn-at-bps");
2797
+ if (warnAt !== void 0) input.warnAtBps = parsePositiveInt(warnAt, "--warn-at-bps", { max: 1e4 });
2798
+ if (text("note") !== void 0) input.note = text("note");
2799
+ const parsed = TaxThresholdInputSchema.safeParse(input);
2800
+ if (!parsed.success) throw new UsageError(`invalid threshold (no request was sent)\n${parsed.error.issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(root)"}: ${issue.message}`).join("\n")}\nscopes: ${TAX_THRESHOLD_SCOPES.join(", ")}; periods: ${TAX_THRESHOLD_PERIODS.join(", ")}`);
2801
+ return input;
2802
+ }
2803
+ const csvCell = (value) => {
2804
+ const cell = value === null ? "" : String(value);
2805
+ return /[",\n]/.test(cell) ? `"${cell.replace(/"/g, "\"\"")}"` : cell;
2806
+ };
2807
+ const SALES_COLUMNS = [
2808
+ "month",
2809
+ "country",
2810
+ "region",
2811
+ "buyerKind",
2812
+ "currency",
2813
+ "taxTreatment",
2814
+ "sales",
2815
+ "amountMinor",
2816
+ "taxMinor",
2817
+ "refundedMinor"
2818
+ ];
2819
+ function salesRow(item) {
2820
+ return SALES_COLUMNS.map((column) => item[column]);
2821
+ }
2822
+ async function taxCommand(ctx, out, args) {
2823
+ const [sub, ...rest] = args;
2824
+ if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
2825
+ out.out(TAX_USAGE);
2826
+ return sub === void 0 ? 2 : 0;
2827
+ }
2828
+ if (sub === "thresholds") {
2829
+ const [action, ...more] = rest;
2830
+ if (action === "list") {
2831
+ const { values, positionals } = parse(more, {
2832
+ ...HELP_OPTION,
2833
+ json: { type: "boolean" }
2834
+ }, "tax");
2835
+ if (values.help) return help(out);
2836
+ expectPositionals(positionals, 0, 0, "tax");
2837
+ const target = requireAdminTarget(await resolveEnv(ctx));
2838
+ out.err(connectionLine(target));
2839
+ const { items } = await callSteward(target, () => clientFor(ctx, target).admin.tax.thresholds.list());
2840
+ if (values.json) out.out(JSON.stringify(items, null, 2));
2841
+ else if (items.length === 0) out.out("no tax thresholds (enter the ones that apply: steward tax thresholds set --help)");
2842
+ else {
2843
+ const rows = [[
2844
+ "CODE",
2845
+ "SCOPE",
2846
+ "LIMIT",
2847
+ "PERIOD",
2848
+ "COUNTED",
2849
+ "AMOUNT",
2850
+ "SALES",
2851
+ "STATUS"
2852
+ ]];
2853
+ for (const t of items) rows.push([
2854
+ t.code,
2855
+ scopeText(t),
2856
+ limitText(t),
2857
+ `${t.usage.from.slice(0, 10)} – ${t.usage.to.slice(0, 10)}`,
2858
+ `${t.usage.amountMinor} ${t.currency} / ${t.usage.transactions} sales`,
2859
+ percent(t.usage.amountShareBps),
2860
+ percent(t.usage.transactionShareBps),
2861
+ t.usage.status
2862
+ ]);
2863
+ for (const line of table(rows)) out.out(line);
2864
+ for (const t of items) for (const u of t.usage.unconverted) out.err(`${t.code}: ${u.transactions} sale(s) in ${u.currency} (${u.amountMinor}) not counted: no --fx-rate ${u.currency}=…`);
2865
+ }
2866
+ return 0;
2867
+ }
2868
+ if (action === "set") {
2869
+ const { values, positionals } = parse(more, {
2870
+ ...HELP_OPTION,
2871
+ scope: { type: "string" },
2872
+ currency: { type: "string" },
2873
+ "amount-minor": { type: "string" },
2874
+ transactions: { type: "string" },
2875
+ country: { type: "string" },
2876
+ region: { type: "string" },
2877
+ "home-country": { type: "string" },
2878
+ period: { type: "string" },
2879
+ "warn-at-bps": { type: "string" },
2880
+ "fx-rate": {
2881
+ type: "string",
2882
+ multiple: true
2883
+ },
2884
+ note: { type: "string" }
2885
+ }, "tax");
2886
+ if (values.help) return help(out);
2887
+ expectPositionals(positionals, 1, 1, "tax");
2888
+ const code = positionals[0];
2889
+ if (!CodeSchema.safeParse(code).success) throw new UsageError("<code>: lowercase letters, digits and _ (e.g. small_business)");
2890
+ const input = buildThresholdInput(values);
2891
+ const target = requireAdminTarget(await resolveEnv(ctx));
2892
+ out.err(connectionLine(target));
2893
+ const stored = await callSteward(target, () => clientFor(ctx, target).admin.tax.thresholds.set(code, input));
2894
+ out.err(`threshold ${code} stored → ${originOf(target.url)}`);
2895
+ out.out(JSON.stringify(stored, null, 2));
2896
+ return 0;
2897
+ }
2898
+ if (action === "delete") {
2899
+ const { values, positionals } = parse(more, { ...HELP_OPTION }, "tax");
2900
+ if (values.help) return help(out);
2901
+ expectPositionals(positionals, 1, 1, "tax");
2902
+ const code = positionals[0];
2903
+ if (!CodeSchema.safeParse(code).success) throw new UsageError("<code>: lowercase letters, digits and _");
2904
+ const target = requireAdminTarget(await resolveEnv(ctx));
2905
+ out.err(connectionLine(target));
2906
+ await callSteward(target, () => clientFor(ctx, target).admin.tax.thresholds.delete(code));
2907
+ out.out(`threshold ${code} deleted → ${originOf(target.url)}`);
2908
+ return 0;
2909
+ }
2910
+ throw new UsageError(`unknown subcommand: tax thresholds${action !== void 0 ? ` ${action}` : ""} (see: steward tax --help)`);
2911
+ }
2912
+ if (sub === "sales") {
2913
+ const { values, positionals } = parse(rest, {
2914
+ ...HELP_OPTION,
2915
+ from: { type: "string" },
2916
+ to: { type: "string" },
2917
+ json: { type: "boolean" },
2918
+ csv: { type: "boolean" }
2919
+ }, "tax");
2920
+ if (values.help) return help(out);
2921
+ expectPositionals(positionals, 0, 0, "tax");
2922
+ if (values.json && values.csv) throw new UsageError("--json and --csv: choose one");
2923
+ if (values.from !== void 0 && !DateTimeSchema.safeParse(values.from).success) throw new UsageError("--from: ISO-8601 with an offset, e.g. 2026-01-01T00:00:00Z");
2924
+ if (values.to !== void 0 && !DateTimeSchema.safeParse(values.to).success) throw new UsageError("--to: ISO-8601 with an offset, e.g. 2026-01-01T00:00:00Z");
2925
+ const range = {
2926
+ ...values.from !== void 0 ? { from: values.from } : {},
2927
+ ...values.to !== void 0 ? { to: values.to } : {}
2928
+ };
2929
+ const target = requireAdminTarget(await resolveEnv(ctx));
2930
+ out.err(connectionLine(target));
2931
+ const report = await callSteward(target, () => clientFor(ctx, target).admin.tax.sales(range));
2932
+ out.err(`sales ${report.from} – ${report.to}`);
2933
+ if (values.json) out.out(JSON.stringify(report, null, 2));
2934
+ else if (values.csv) {
2935
+ out.out(SALES_COLUMNS.join(","));
2936
+ for (const item of report.items) out.out(salesRow(item).map(csvCell).join(","));
2937
+ } else if (report.items.length === 0) out.out("no paid sales in the period");
2938
+ else {
2939
+ const rows = [[
2940
+ "MONTH",
2941
+ "COUNTRY",
2942
+ "REGION",
2943
+ "KIND",
2944
+ "CURRENCY",
2945
+ "TREATMENT",
2946
+ "SALES",
2947
+ "AMOUNT",
2948
+ "TAX",
2949
+ "REFUNDED"
2950
+ ]];
2951
+ for (const item of report.items) rows.push(salesRow(item).map((cell) => cell === null ? "-" : String(cell)));
2952
+ for (const line of table(rows)) out.out(line);
2953
+ }
2954
+ return 0;
2955
+ }
2956
+ throw new UsageError(`unknown subcommand: tax ${sub} (see: steward tax --help)`);
2957
+ }
2958
+ function help(out) {
2959
+ out.out(TAX_USAGE);
2960
+ return 0;
2961
+ }
2962
+ // src/main.ts
2963
+ const CLI_VERSION = "0.11.0";
2460
2964
  const USAGE = `steward — Steward CLI (@stewardhq/cli ${CLI_VERSION})
2461
2965
 
2462
2966
  Usage: steward <command> [options]
@@ -2471,10 +2975,13 @@ Commands:
2471
2975
  reprice --plan <code> --notice-days <n> move a plan's subscribers to its current price
2472
2976
  bank-transfers list | record | fx-report bank transfer reconciliation (/v1/admin/bank-transfers)
2473
2977
  invoices list | issue invoices not issued yet; write the external invoice number
2978
+ grants list active grants; --subscription none: paying for nothing
2474
2979
  credits adjust <ref> <meter> --units=<n> credit entry, negative = adjustment
2475
2980
  accounts get | metadata set | unset read an account; set or remove metadata keys
2476
2981
  meters get | recompute | close-periods an account's meters; metering repairs (admin)
2477
2982
  events send | redeliver send one event; redeliver webhook events (admin)
2983
+ tax thresholds list | set | delete tax registration thresholds and their counters
2984
+ tax sales [--from] [--to] [--csv] paid sales per month and buyer country (admin)
2478
2985
 
2479
2986
  Connection: admin commands use STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY; doctor,
2480
2987
  accounts, meters and events use STEWARD_URL + STEWARD_API_KEY (or the admin pair). If even
@@ -2497,7 +3004,9 @@ const COMMANDS = {
2497
3004
  reprice: repriceCommand,
2498
3005
  "bank-transfers": bankTransfersCommand,
2499
3006
  invoices: invoicesCommand,
2500
- credits: creditsCommand
3007
+ grants: grantsCommand,
3008
+ credits: creditsCommand,
3009
+ tax: taxCommand
2501
3010
  };
2502
3011
  async function main(argv, ctx) {
2503
3012
  const out = createOutput(ctx.stdout, ctx.stderr);
@@ -2534,8 +3043,7 @@ async function main(argv, ctx) {
2534
3043
  return 1;
2535
3044
  }
2536
3045
  }
2537
- //#endregion
2538
- //#region src/bin.ts
3046
+ // src/bin.ts
2539
3047
  const ctx = {
2540
3048
  cwd: process.cwd(),
2541
3049
  env: process.env,
@@ -2566,5 +3074,4 @@ const ctx = {
2566
3074
  }
2567
3075
  };
2568
3076
  process.exitCode = await main(process.argv.slice(2), ctx);
2569
- //#endregion
2570
3077
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stewardhq/cli",
3
- "version": "0.10.0",
3
+ "version": "0.11.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,14 +28,14 @@
28
28
  "registry": "https://registry.npmjs.org"
29
29
  },
30
30
  "dependencies": {
31
- "@stewardhq/sdk": "^0.10.0"
31
+ "@stewardhq/sdk": "^0.11.0"
32
32
  },
33
33
  "devDependencies": {
34
- "@types/node": "^26.6.4",
35
- "tsdown": "^0.23.0",
34
+ "@types/node": "^26.6.5",
35
+ "tsdown": "^0.23.1",
36
36
  "tsx": "^4.23.15",
37
37
  "typescript": "^7.0.2",
38
- "vitest": "^5.0.3"
38
+ "vitest": "^5.0.5"
39
39
  },
40
40
  "scripts": {
41
41
  "build": "tsdown",