@stewardhq/cli 0.11.0 → 0.13.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 +13 -2
  2. package/dist/bin.js +389 -18
  3. package/package.json +3 -3
package/README.md CHANGED
@@ -25,6 +25,8 @@ ESM, Node ≥ 22. Its only runtime dependency is `@stewardhq/sdk`.
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` |
27
27
  | `steward endpoints deactivate <id>` | Not reversible |
28
+ | `steward discounts list [--archived] [--json]` / `steward discounts create --name <text> (--percent <n> \| --amount <CUR:minor>…) --duration once\|repeating\|forever [--months <n>] [--code <code>] [--plans a,b] [--starts <iso>] [--ends <iso>] [--max <n>] [--per-customer <n>\|unlimited]` / `steward discounts update <id> […]` / `steward discounts archive <id> [--yes]` | Discounts and discount codes (`/v1/admin/discounts`): a share or an amount per currency off a plan's base price, for the first invoice, a number of months or every invoice. `update` takes `none` to clear an optional field; the value and duration are fixed once redeemed. `create` warns when a sellable price would fall under the payment provider's minimum |
29
+ | `steward email-smtp get [--json]` / `steward email-smtp set --file <path> \| --stdin` / `steward email-smtp clear [--yes]` / `steward email-smtp verify [--to <address>] [--json]` | The product's own SMTP account for its billing emails (`/v1/admin/email-smtp`; otherwise the installation's). `set` reads the URL (`smtp://user:pass@host:587` or `smtps://…:465`) from a file or a pipe, never from an argument or a terminal; steward never returns it (`get` shows the host). `verify` asks `MAIL FROM` (the product's sender) and `RCPT TO`, stops before `DATA`, and exits 1 with the failed step and the server's reply when the account refuses |
28
30
  | `steward keys list [--json]` | The product's API keys: prefix, scope, status (active, expired, revoked), expiry, last use |
29
31
  | `steward keys create --name <n> --scope product\|checkout\|admin --out <file> [--expires-days <n> \| --no-expiry] [--force]` | Generates the key locally and writes it only to `--out`; steward stores its hash. An admin key always expires (default 90 days) |
30
32
  | `steward keys revoke <prefix>` | A key cannot revoke itself (use another admin key) |
@@ -42,7 +44,7 @@ Exit codes: 0 success, 1 error (or doctor not ready), 2 incorrect usage.
42
44
 
43
45
  ## Connection settings
44
46
 
45
- - Admin commands (`catalog`, `settings`, `endpoints`, `keys`, `dunning`, `reprice`, `credits`,
47
+ - Admin commands (`catalog`, `settings`, `endpoints`, `discounts`, `email-smtp`, `keys`, `dunning`, `reprice`, `credits`,
46
48
  `bank-transfers`, `invoices`, `meters recompute|close-periods`, `events redeliver`): `STEWARD_ADMIN_URL` +
47
49
  `STEWARD_ADMIN_API_KEY`. The URL is the address where your steward serves `/v1`, for example
48
50
  `https://billing.example.com`: its public address if the deployment exposes `/v1` there,
@@ -69,6 +71,9 @@ Exit codes: 0 success, 1 error (or doctor not ready), 2 incorrect usage.
69
71
  newline). If the file exists, no request is sent without `--force`; if the request fails, no
70
72
  secret file is left behind. The operator moves the secret into the product's Secret and
71
73
  deletes the file.
74
+ - `email-smtp set`: the SMTP URL (it carries the mailbox password) is read from `--file` or `--stdin`, never
75
+ from an argument (shell history) or an interactive terminal (echo); it is validated before the request and
76
+ never printed. Delete the file afterwards.
72
77
  - The CLI does not call `kubectl`; creating Secrets and rolling out is the operator's job.
73
78
 
74
79
  ## Catalog file
@@ -140,6 +145,12 @@ Release: bump the version in `cli/package.json` and push the `cli-v<version>` ta
140
145
  be published on npm. The notes of 0.4.0 to 0.10.0 are in
141
146
  [this file at `cli-v0.10.0`](https://github.com/z9cloud/steward/blob/cli-v0.10.0/cli/README.md#versions).
142
147
 
148
+ - **0.13.0** (`@stewardhq/sdk` 0.13): `steward discounts list|create|update|archive` (discounts and discount codes;
149
+ needs a steward with `/v1/admin/discounts`, 0.13.0 or later). `create` warns when a sellable price would fall
150
+ under the payment provider's minimum.
151
+ - **0.12.0** (`@stewardhq/sdk` 0.12): `steward email-smtp get|set --file|--stdin|clear|verify` (the product's own
152
+ SMTP account for its billing emails; needs a steward with `/v1/admin/email-smtp`). `steward doctor` shows which
153
+ SMTP the emails go through, the product account's host and its recent failures.
143
154
  - **0.11.0** (`@stewardhq/sdk` 0.11, which removes the contract names steward no longer produces):
144
155
  `steward grants list` (the product's active grants and their accounts' live subscriptions; needs a steward with
145
156
  `GET /v1/admin/grants`). `steward settings set --display-time-zone <iana>` (the zone of customer-facing dates;
@@ -152,7 +163,7 @@ be published on npm. The notes of 0.4.0 to 0.10.0 are in
152
163
  the provider's webhook, automatic renewal and the legal settings.
153
164
 
154
165
  When packed, the `@stewardhq/sdk` dependency turns from `workspace:^` into the range of the
155
- SDK version current at that time (0.11.0 → `^0.11.0`).
166
+ SDK version current at that time (0.13.0 → `^0.13.0`).
156
167
 
157
168
  ## License
158
169
 
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 { 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";
5
+ import { ACCOUNT_INCLUDES, AccountMetadataPatchInputSchema, ApiKeyCreateInputSchema, BankTransferRecordInputSchema, CatalogSyncInputSchema, CodeSchema, CreditAdjustmentInputSchema, DateTimeSchema, DiscountCreateInputSchema, DiscountUpdateInputSchema, DunningPolicySchema, EmailSmtpVerifyInputSchema, 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, SmtpUrlSchema, 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";
@@ -773,7 +773,7 @@ product moves over with a "new,old" list. Delete the file after moving it. Witho
773
773
  endpoint).
774
774
 
775
775
  Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
776
- function schemaProblems(issues) {
776
+ function schemaProblems$1(issues) {
777
777
  return issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(root)"}: ${issue.message}`).join("\n");
778
778
  }
779
779
  const lastDeliveryText = (endpoint) => {
@@ -798,7 +798,7 @@ async function endpointsCommand(ctx, out, args) {
798
798
  ...HELP_OPTION,
799
799
  json: { type: "boolean" }
800
800
  }, "endpoints");
801
- if (values.help) return help$5(out);
801
+ if (values.help) return help$7(out);
802
802
  expectPositionals(positionals, 0, 0, "endpoints");
803
803
  const target = requireAdminTarget(await resolveEnv(ctx));
804
804
  out.err(connectionLine(target));
@@ -833,7 +833,7 @@ async function endpointsCommand(ctx, out, args) {
833
833
  description: { type: "string" },
834
834
  force: { type: "boolean" }
835
835
  }, ENDPOINTS_USAGE);
836
- if (values.help) return help$5(out);
836
+ if (values.help) return help$7(out);
837
837
  expectPositionals(positionals, 0, 0, "endpoints");
838
838
  const url = requireOption(values.url, "--url", "endpoints");
839
839
  const file = requireOption(values.out, "--out", "endpoints");
@@ -845,7 +845,7 @@ async function endpointsCommand(ctx, out, args) {
845
845
  ...values.description !== void 0 ? { description: values.description } : {}
846
846
  };
847
847
  const parsed = WebhookEndpointCreateInputSchema.safeParse(input);
848
- if (!parsed.success) throw new UsageError(`invalid endpoint (no request was sent)\n${schemaProblems(parsed.error.issues)}`);
848
+ if (!parsed.success) throw new UsageError(`invalid endpoint (no request was sent)\n${schemaProblems$1(parsed.error.issues)}`);
849
849
  const target = requireAdminTarget(await resolveEnv(ctx));
850
850
  out.err(connectionLine(target));
851
851
  const steward = clientFor(ctx, target);
@@ -864,13 +864,13 @@ async function endpointsCommand(ctx, out, args) {
864
864
  out: { type: "string" },
865
865
  force: { type: "boolean" }
866
866
  }, "endpoints");
867
- if (values.help) return help$5(out);
867
+ if (values.help) return help$7(out);
868
868
  expectPositionals(positionals, 1, 1, "endpoints");
869
869
  const id = positionals[0];
870
870
  const file = requireOption(values.out, "--out", "endpoints");
871
871
  const secret = generateWebhookSecret();
872
872
  const parsed = WebhookEndpointRotateInputSchema.safeParse({ secret });
873
- if (!parsed.success) throw new UsageError(`invalid secret\n${schemaProblems(parsed.error.issues)}`);
873
+ if (!parsed.success) throw new UsageError(`invalid secret\n${schemaProblems$1(parsed.error.issues)}`);
874
874
  const target = requireAdminTarget(await resolveEnv(ctx));
875
875
  out.err(connectionLine(target));
876
876
  const steward = clientFor(ctx, target);
@@ -883,7 +883,7 @@ async function endpointsCommand(ctx, out, args) {
883
883
  }
884
884
  if (sub === "deactivate") {
885
885
  const { values, positionals } = parse(rest, { ...HELP_OPTION }, "endpoints");
886
- if (values.help) return help$5(out);
886
+ if (values.help) return help$7(out);
887
887
  expectPositionals(positionals, 1, 1, "endpoints");
888
888
  const target = requireAdminTarget(await resolveEnv(ctx));
889
889
  out.err(connectionLine(target));
@@ -893,7 +893,7 @@ async function endpointsCommand(ctx, out, args) {
893
893
  }
894
894
  throw new UsageError(`unknown subcommand: endpoints ${sub} (details: steward endpoints --help)`);
895
895
  }
896
- function help$5(out) {
896
+ function help$7(out) {
897
897
  out.out(ENDPOINTS_USAGE);
898
898
  return 0;
899
899
  }
@@ -965,7 +965,7 @@ async function bankTransfersCommand(ctx, out, args) {
965
965
  currency: { type: "string" },
966
966
  json: { type: "boolean" }
967
967
  }, "bank-transfers");
968
- if (values.help) return help$4(out);
968
+ if (values.help) return help$6(out);
969
969
  expectPositionals(positionals, 0, 0, "bank-transfers");
970
970
  const status = values.status ?? "pending";
971
971
  if (status !== "pending" && status !== "expired") throw new UsageError("--status: pending or expired");
@@ -1027,7 +1027,7 @@ async function bankTransfersCommand(ctx, out, args) {
1027
1027
  },
1028
1028
  json: { type: "boolean" }
1029
1029
  }, "bank-transfers");
1030
- if (values.help) return help$4(out);
1030
+ if (values.help) return help$6(out);
1031
1031
  expectPositionals(positionals, 1, 1, "bank-transfers");
1032
1032
  const receivedAt = requireOption(values["received-at"], "--received-at", "bank-transfers");
1033
1033
  if (!WITH_OFFSET$1.test(receivedAt)) throw new UsageError("--received-at: ISO-8601 with an offset (2026-09-28T10:15:00+03:00)");
@@ -1071,7 +1071,7 @@ async function bankTransfersCommand(ctx, out, args) {
1071
1071
  json: { type: "boolean" },
1072
1072
  csv: { type: "boolean" }
1073
1073
  }, "bank-transfers");
1074
- if (values.help) return help$4(out);
1074
+ if (values.help) return help$6(out);
1075
1075
  expectPositionals(positionals, 0, 0, "bank-transfers");
1076
1076
  if (values.json && values.csv) throw new UsageError("--json or --csv, not both");
1077
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)");
@@ -1136,7 +1136,7 @@ function csvField(value) {
1136
1136
  const text = typeof value === "string" && /^[=+\-@]/.test(value) ? `'${value}` : String(value);
1137
1137
  return /[",\n\r]/.test(text) ? `"${text.replace(/"/g, "\"\"")}"` : text;
1138
1138
  }
1139
- function help$4(out) {
1139
+ function help$6(out) {
1140
1140
  out.out(BANK_TRANSFERS_USAGE);
1141
1141
  return 0;
1142
1142
  }
@@ -1681,7 +1681,8 @@ function formatDoctorReport(report, cliWarnings, metering = null) {
1681
1681
  const { emails } = report;
1682
1682
  const problems = [...emails.transportConfigured ? [] : ["no transport"], ...emails.senderConfigured ? [] : ["no sender"]];
1683
1683
  const disabled = emails.disabledTemplates.length > 0 ? ` · disabled: ${emails.disabledTemplates.join(", ")}` : "";
1684
- lines.push(`emails ${emails.ready ? "ready ✓" : `not sending ✗${problems.length > 0 ? ` (${problems.join(", ")})` : ""}`}${disabled}`);
1684
+ const via = emails.transport === "product" ? ` · own SMTP ${emails.smtpHost ?? ""}${emails.smtpRecentFailures ? ` (${emails.smtpRecentFailures} failed in 24 h, last ${emails.smtpLastFailure ?? "?"})` : ""}` : emails.transport === "installation" ? " · installation's SMTP" : "";
1685
+ lines.push(`emails ${emails.ready ? "ready ✓" : `not sending ✗${problems.length > 0 ? ` (${problems.join(", ")})` : ""}`}${via}${disabled}`);
1685
1686
  }
1686
1687
  if (report.apiKeys) {
1687
1688
  lines.push(report.apiKeys.length === 0 ? "api keys none active" : "api keys");
@@ -1757,7 +1758,7 @@ async function dunningCommand(ctx, out, args) {
1757
1758
  ...HELP_OPTION,
1758
1759
  json: { type: "boolean" }
1759
1760
  }, "dunning");
1760
- if (values.help) return help$3(out);
1761
+ if (values.help) return help$5(out);
1761
1762
  expectPositionals(positionals, 0, 0, "dunning");
1762
1763
  const target = requireAdminTarget(await resolveEnv(ctx));
1763
1764
  out.err(connectionLine(target));
@@ -1774,7 +1775,7 @@ async function dunningCommand(ctx, out, args) {
1774
1775
  short: "y"
1775
1776
  }
1776
1777
  }, "dunning");
1777
- if (values.help) return help$3(out);
1778
+ if (values.help) return help$5(out);
1778
1779
  expectPositionals(positionals, 1, 1, "dunning");
1779
1780
  const file = positionals[0];
1780
1781
  let json;
@@ -1807,10 +1808,370 @@ async function dunningCommand(ctx, out, args) {
1807
1808
  }
1808
1809
  throw new UsageError(`unknown subcommand: dunning ${sub} (see: steward dunning --help)`);
1809
1810
  }
1810
- function help$3(out) {
1811
+ function help$5(out) {
1811
1812
  out.out(DUNNING_USAGE);
1812
1813
  return 0;
1813
1814
  }
1815
+ // src/commands/discounts.ts
1816
+ const DISCOUNTS_USAGE = `Usage:
1817
+ steward discounts list [--archived] [--json]
1818
+ steward discounts create --name <text> (--percent <n> | --amount <CUR:minor>...) --duration once|repeating|forever
1819
+ [--months <n>] [--code <code>] [--plans <a,b>] [--starts <iso>] [--ends <iso>]
1820
+ [--max <n>] [--per-customer <n>|unlimited] [--json]
1821
+ steward discounts update <id> [--name …] [--code <code>|none] [--plans <a,b>|none] [--starts <iso>|none]
1822
+ [--ends <iso>|none] [--max <n>|none] [--per-customer <n>|unlimited]
1823
+ [--percent … | --amount …] [--duration … --months …] [--json]
1824
+ steward discounts archive <id> [--yes]
1825
+
1826
+ The product's discounts (/v1/admin/discounts): a share (--percent 20, up to 99.99) or an amount per
1827
+ currency in minor units (--amount USD:500 --amount EUR:450) off a plan's base price, for the first
1828
+ invoice (once), --months calendar months (repeating) or every invoice (forever). A discount with
1829
+ --code is entered by the customer on the hosted checkout; one without is applied by the product
1830
+ (checkout.create({ discountId })). Codes are case-insensitive. --plans restricts it (default:
1831
+ every listed plan). --per-customer defaults to 1. Once redeemed, its value and duration no
1832
+ longer change; archive it and create another instead.
1833
+
1834
+ create warns when the discount would bring a sellable price of the catalog to zero or under the
1835
+ payment provider's minimum charge (such a price refuses the code at checkout).
1836
+
1837
+ Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
1838
+ /** The provider minimums the warning knows (Stripe's; the service refuses below them at checkout). */
1839
+ const PROVIDER_MINIMUMS = { stripe: {
1840
+ EUR: 50,
1841
+ GBP: 30,
1842
+ USD: 50
1843
+ } };
1844
+ const OPTIONS$1 = {
1845
+ ...HELP_OPTION,
1846
+ name: { type: "string" },
1847
+ percent: { type: "string" },
1848
+ amount: {
1849
+ type: "string",
1850
+ multiple: true
1851
+ },
1852
+ duration: { type: "string" },
1853
+ months: { type: "string" },
1854
+ code: { type: "string" },
1855
+ plans: { type: "string" },
1856
+ starts: { type: "string" },
1857
+ ends: { type: "string" },
1858
+ max: { type: "string" },
1859
+ "per-customer": { type: "string" },
1860
+ json: { type: "boolean" }
1861
+ };
1862
+ const NONE = "none";
1863
+ /** `20` / `12.5` → basis points (2000 / 1250). */
1864
+ function parsePercent(value) {
1865
+ const trimmed = value.trim().replace(/%$/, "");
1866
+ if (!/^\d{1,2}(\.\d{1,2})?$/.test(trimmed)) throw new UsageError("--percent: a number between 0.01 and 99.99");
1867
+ const bps = Math.round(Number(trimmed) * 100);
1868
+ if (bps < 1 || bps > 9999) throw new UsageError("--percent: a number between 0.01 and 99.99");
1869
+ return bps;
1870
+ }
1871
+ /** `USD:500` (repeatable) → `{ USD: 500 }`. */
1872
+ function parseAmounts(values) {
1873
+ const out = {};
1874
+ for (const value of values) {
1875
+ const match = /^([A-Za-z]{3}):(\d+)$/.exec(value.trim());
1876
+ if (!match) throw new UsageError(`--amount: <CUR:minor>, e.g. USD:500 (got ${JSON.stringify(value)})`);
1877
+ out[match[1].toUpperCase()] = Number(match[2]);
1878
+ }
1879
+ return out;
1880
+ }
1881
+ /** The fields shared by create and update (update: `none` clears an optional one). */
1882
+ function fieldsOf(values, update) {
1883
+ const clearable = (value, read) => value === void 0 ? void 0 : update && value.trim() === NONE ? null : read(value);
1884
+ const fields = {
1885
+ name: values.name,
1886
+ code: clearable(values.code, (v) => v.trim()),
1887
+ duration: values.duration,
1888
+ durationInMonths: values.months !== void 0 ? parsePositiveInt(values.months, "--months", { max: 120 }) : void 0,
1889
+ planCodes: values.plans !== void 0 ? values.plans.trim() === NONE ? [] : parseList(values.plans) : void 0,
1890
+ startsAt: clearable(values.starts, (v) => v.trim()),
1891
+ endsAt: clearable(values.ends, (v) => v.trim()),
1892
+ maxRedemptions: clearable(values.max, (v) => parsePositiveInt(v, "--max")),
1893
+ maxRedemptionsPerCustomer: values["per-customer"] === void 0 ? void 0 : values["per-customer"].trim() === "unlimited" ? null : parsePositiveInt(values["per-customer"], "--per-customer")
1894
+ };
1895
+ if (values.percent !== void 0 && values.amount !== void 0) throw new UsageError("give --percent or --amount, not both");
1896
+ if (values.percent !== void 0) Object.assign(fields, {
1897
+ type: "percentage",
1898
+ basisPoints: parsePercent(values.percent)
1899
+ });
1900
+ if (values.amount !== void 0) Object.assign(fields, {
1901
+ type: "fixed",
1902
+ amounts: parseAmounts(values.amount)
1903
+ });
1904
+ return Object.fromEntries(Object.entries(fields).filter(([, v]) => v !== void 0));
1905
+ }
1906
+ function problems(issues) {
1907
+ return issues.map((issue) => ` - ${issue.path.map(String).join(".") || "input"}: ${issue.message}`).join("\n");
1908
+ }
1909
+ function buildCreateInput(values) {
1910
+ const parsed = DiscountCreateInputSchema.safeParse(fieldsOf(values, false));
1911
+ if (!parsed.success) throw new UsageError(`invalid discount (no request was sent)\n${problems(parsed.error.issues)}`);
1912
+ return parsed.data;
1913
+ }
1914
+ function buildUpdateInput(values) {
1915
+ const fields = fieldsOf(values, true);
1916
+ if (Object.keys(fields).length === 0) throw new UsageError("nothing to change (details: steward discounts --help)");
1917
+ const parsed = DiscountUpdateInputSchema.safeParse(fields);
1918
+ if (!parsed.success) throw new UsageError(`invalid change (no request was sent)\n${problems(parsed.error.issues)}`);
1919
+ return parsed.data;
1920
+ }
1921
+ const money = (minor, currency) => `${(minor / 100).toFixed(2)} ${currency}`;
1922
+ /**
1923
+ * The catalog's sellable prices the discount would bring to zero or under the provider's minimum
1924
+ * (the hosted checkout refuses the code there: `discount_below_minimum`). The total is the price
1925
+ * minus the discount, with tax added for a tax-exclusive price; an approximation of the service's
1926
+ * rule, good enough to warn.
1927
+ */
1928
+ function belowMinimumWarnings(catalog, discount, provider) {
1929
+ const minimums = provider && PROVIDER_MINIMUMS[provider] || {};
1930
+ const plans = new Map(catalog.plans.map((p) => [p.code, p]));
1931
+ const warnings = [];
1932
+ for (const price of catalog.prices) {
1933
+ const plan = plans.get(price.planCode);
1934
+ if (!plan?.sellable) continue;
1935
+ const listed = plan.listed !== false;
1936
+ if (discount.planCodes.length > 0 ? !discount.planCodes.includes(price.planCode) : !listed) continue;
1937
+ const off = discount.type === "percentage" ? Math.round(price.amountMinor * (discount.basisPoints ?? 0) / 1e4) : discount.amounts?.[price.currency];
1938
+ if (off === void 0) continue;
1939
+ const net = Math.max(0, price.amountMinor - off);
1940
+ const total = price.taxInclusive ? net : net + Math.round(net * price.taxRateBps / 1e4);
1941
+ const minimum = minimums[price.currency] ?? 0;
1942
+ if (total <= 0 || total < minimum) warnings.push(`${price.planCode}/${price.interval} ${money(price.amountMinor, price.currency)} → ${money(total, price.currency)}` + (minimum > 0 ? ` (under ${provider}'s minimum ${money(minimum, price.currency)})` : " (nothing left to charge)"));
1943
+ }
1944
+ return warnings;
1945
+ }
1946
+ function describe$1(d) {
1947
+ const value = d.type === "percentage" ? `${(d.basisPoints ?? 0) / 100}%` : Object.entries(d.amounts ?? {}).map(([c, m]) => money(m, c)).join(", ");
1948
+ const term = d.duration === "repeating" ? `${d.durationInMonths} months` : d.duration;
1949
+ const limits = [
1950
+ d.maxRedemptions !== null ? `max ${d.maxRedemptions}` : null,
1951
+ `per customer ${d.maxRedemptionsPerCustomer ?? "unlimited"}`,
1952
+ d.planCodes.length > 0 ? `plans ${d.planCodes.join(",")}` : null,
1953
+ d.startsAt ? `from ${d.startsAt}` : null,
1954
+ d.endsAt ? `until ${d.endsAt}` : null
1955
+ ].filter(Boolean);
1956
+ return `${d.id} ${d.code ?? "(no code)"} ${d.name} ${value} ${term} redeemed ${d.redemptions.redeemed}, reserved ${d.redemptions.reserved} ${limits.join(" · ")}${d.archivedAt ? ` archived ${d.archivedAt}` : ""}`;
1957
+ }
1958
+ async function discountsCommand(ctx, out, args) {
1959
+ const [sub, ...rest] = args;
1960
+ if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
1961
+ out.out(DISCOUNTS_USAGE);
1962
+ return sub === void 0 ? 2 : 0;
1963
+ }
1964
+ if (sub === "list") {
1965
+ const { values, positionals } = parse(rest, {
1966
+ ...HELP_OPTION,
1967
+ archived: { type: "boolean" },
1968
+ json: { type: "boolean" }
1969
+ }, "discounts");
1970
+ if (values.help) return help$4(out);
1971
+ expectPositionals(positionals, 0, 0, "discounts");
1972
+ const target = requireAdminTarget(await resolveEnv(ctx));
1973
+ out.err(connectionLine(target));
1974
+ const list = await callSteward(target, () => clientFor(ctx, target).admin.discounts.list({ archived: values.archived === true }));
1975
+ if (values.json) out.out(JSON.stringify(list, null, 2));
1976
+ else if (list.discounts.length === 0) out.out("no discounts");
1977
+ else for (const d of list.discounts) out.out(describe$1(d));
1978
+ return 0;
1979
+ }
1980
+ if (sub === "create") {
1981
+ const { values, positionals } = parse(rest, OPTIONS$1, "discounts");
1982
+ if (values.help) return help$4(out);
1983
+ expectPositionals(positionals, 0, 0, "discounts");
1984
+ const input = buildCreateInput(values);
1985
+ const target = requireAdminTarget(await resolveEnv(ctx));
1986
+ out.err(connectionLine(target));
1987
+ const client = clientFor(ctx, target);
1988
+ const created = await callSteward(target, () => client.admin.discounts.create(input));
1989
+ if (values.json) out.out(JSON.stringify(created, null, 2));
1990
+ else out.out(`discount created → ${originOf(target.url)}\n ${describe$1(created)}`);
1991
+ try {
1992
+ const [catalog, settings] = await Promise.all([client.catalog.get(), client.admin.settings.get()]);
1993
+ for (const warning of belowMinimumWarnings(catalog, created, settings.provider)) out.err(`warning: ${warning}; the code is refused for this price at checkout`);
1994
+ } catch {}
1995
+ return 0;
1996
+ }
1997
+ if (sub === "update") {
1998
+ const { values, positionals } = parse(rest, OPTIONS$1, "discounts");
1999
+ if (values.help) return help$4(out);
2000
+ expectPositionals(positionals, 1, 1, "discounts");
2001
+ const id = discountId(positionals[0]);
2002
+ const input = buildUpdateInput(values);
2003
+ const target = requireAdminTarget(await resolveEnv(ctx));
2004
+ out.err(connectionLine(target));
2005
+ const updated = await callSteward(target, () => clientFor(ctx, target).admin.discounts.update(id, input));
2006
+ if (values.json) out.out(JSON.stringify(updated, null, 2));
2007
+ else out.out(`discount updated → ${originOf(target.url)}\n ${describe$1(updated)}`);
2008
+ return 0;
2009
+ }
2010
+ if (sub === "archive") {
2011
+ const { values, positionals } = parse(rest, {
2012
+ ...HELP_OPTION,
2013
+ yes: { type: "boolean" }
2014
+ }, "discounts");
2015
+ if (values.help) return help$4(out);
2016
+ expectPositionals(positionals, 1, 1, "discounts");
2017
+ const id = discountId(positionals[0]);
2018
+ const target = requireAdminTarget(await resolveEnv(ctx));
2019
+ out.err(connectionLine(target));
2020
+ if (!await confirm(ctx, `Archive discount ${id} at ${originOf(target.url)}? It can no longer be redeemed; running subscriptions keep it.`, {
2021
+ yes: values.yes === true,
2022
+ notConfirmed: "the discount was not archived"
2023
+ })) {
2024
+ out.err("not archived");
2025
+ return 1;
2026
+ }
2027
+ const archived = await callSteward(target, () => clientFor(ctx, target).admin.discounts.archive(id));
2028
+ out.out(`discount archived → ${originOf(target.url)}\n ${describe$1(archived)}`);
2029
+ return 0;
2030
+ }
2031
+ throw new UsageError(`unknown subcommand: discounts ${sub} (details: steward discounts --help)`);
2032
+ }
2033
+ function discountId(value) {
2034
+ if (!IdSchema.safeParse(value).success) throw new UsageError(`not a discount id: ${JSON.stringify(value)}`);
2035
+ return value;
2036
+ }
2037
+ function help$4(out) {
2038
+ out.out(DISCOUNTS_USAGE);
2039
+ return 0;
2040
+ }
2041
+ // src/commands/email-smtp.ts
2042
+ const EMAIL_SMTP_USAGE = `Usage:
2043
+ steward email-smtp get [--json]
2044
+ steward email-smtp set --file <path> | --stdin
2045
+ steward email-smtp clear [--yes]
2046
+ steward email-smtp verify [--to <address>] [--json]
2047
+
2048
+ The product's own SMTP account for its billing emails (/v1/admin/email-smtp). Without one,
2049
+ the product's emails go through the installation's SMTP (STEWARD_SMTP_URL).
2050
+
2051
+ set reads the URL (smtp://user:pass@host:587 or smtps://user:pass@host:465; reserved
2052
+ characters in the password percent-encoded) from a file or from a pipe, never from an
2053
+ argument, so it stays out of shell history. Steward stores it encrypted and never returns
2054
+ it: get, doctor and the audit trail show only the host. clear goes back to the
2055
+ installation's SMTP.
2056
+
2057
+ verify logs in to the SMTP the product sends with and asks MAIL FROM (the product's sender,
2058
+ settings.emails.from.address) and RCPT TO (--to, default the sender), then stops before
2059
+ DATA: no email is sent. Exit code 1 when the account refuses.
2060
+
2061
+ Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
2062
+ function schemaProblems(issues) {
2063
+ return issues.map((issue) => ` - ${issue.path.map(String).join(".") || "url"}: ${issue.message}`).join("\n");
2064
+ }
2065
+ const tlsText = (secure) => secure ? "TLS (smtps)" : "STARTTLS when offered";
2066
+ function describe(smtp) {
2067
+ if (!smtp.configured) return [`own account none`, `sends with ${smtp.transport === "installation" ? "the installation's SMTP (STEWARD_SMTP_URL)" : "nothing: no SMTP configured, emails are not sent"}`];
2068
+ return [`own account ${smtp.host}:${smtp.port} · ${tlsText(smtp.secure)} · set ${smtp.updatedAt}`, `sends with the product's own account`];
2069
+ }
2070
+ async function readUrl(ctx, values) {
2071
+ if (values.file === void 0 === (values.stdin !== true)) throw new UsageError("give exactly one of --file <path> or --stdin (details: steward email-smtp --help)");
2072
+ let text;
2073
+ if (values.file !== void 0) try {
2074
+ text = await readFile(resolve(ctx.cwd, values.file), "utf8");
2075
+ } catch (error) {
2076
+ throw new CliError(`could not read ${values.file} (${errnoCode(error) ?? "error"}); no request was sent`);
2077
+ }
2078
+ else {
2079
+ text = await ctx.readStdin();
2080
+ if (text === null) throw new UsageError("--stdin needs the URL piped in (e.g. steward email-smtp set --stdin < smtp-url.txt); it is not read from a terminal");
2081
+ }
2082
+ return text.trim();
2083
+ }
2084
+ async function emailSmtpCommand(ctx, out, args) {
2085
+ const [sub, ...rest] = args;
2086
+ if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
2087
+ out.out(EMAIL_SMTP_USAGE);
2088
+ return sub === void 0 ? 2 : 0;
2089
+ }
2090
+ if (sub === "get") {
2091
+ const { values, positionals } = parse(rest, {
2092
+ ...HELP_OPTION,
2093
+ json: { type: "boolean" }
2094
+ }, "email-smtp");
2095
+ if (values.help) return help$3(out);
2096
+ expectPositionals(positionals, 0, 0, "email-smtp");
2097
+ const target = requireAdminTarget(await resolveEnv(ctx));
2098
+ out.err(connectionLine(target));
2099
+ const smtp = await callSteward(target, () => clientFor(ctx, target).admin.emailSmtp.get());
2100
+ if (values.json) out.out(JSON.stringify(smtp, null, 2));
2101
+ else for (const line of describe(smtp)) out.out(line);
2102
+ return 0;
2103
+ }
2104
+ if (sub === "set") {
2105
+ const { values, positionals } = parse(rest, {
2106
+ ...HELP_OPTION,
2107
+ file: { type: "string" },
2108
+ stdin: { type: "boolean" }
2109
+ }, "email-smtp");
2110
+ if (values.help) return help$3(out);
2111
+ expectPositionals(positionals, 0, 0, "email-smtp");
2112
+ const url = await readUrl(ctx, values);
2113
+ const parsed = SmtpUrlSchema.safeParse(url);
2114
+ if (!parsed.success) throw new UsageError(`invalid SMTP URL (no request was sent)\n${schemaProblems(parsed.error.issues)}`);
2115
+ const target = requireAdminTarget(await resolveEnv(ctx));
2116
+ out.err(connectionLine(target));
2117
+ const smtp = await callSteward(target, () => clientFor(ctx, target).admin.emailSmtp.set({ url: parsed.data }));
2118
+ out.out(`email SMTP account set → ${originOf(target.url)}`);
2119
+ for (const line of describe(smtp)) out.out(` ${line}`);
2120
+ out.err("Check it without sending an email: steward email-smtp verify");
2121
+ return 0;
2122
+ }
2123
+ if (sub === "clear") {
2124
+ const { values, positionals } = parse(rest, {
2125
+ ...HELP_OPTION,
2126
+ yes: { type: "boolean" }
2127
+ }, "email-smtp");
2128
+ if (values.help) return help$3(out);
2129
+ expectPositionals(positionals, 0, 0, "email-smtp");
2130
+ const target = requireAdminTarget(await resolveEnv(ctx));
2131
+ out.err(connectionLine(target));
2132
+ if (!await confirm(ctx, `Remove the product's own SMTP account at ${originOf(target.url)}? Emails go back to the installation's SMTP.`, {
2133
+ yes: values.yes === true,
2134
+ notConfirmed: "the SMTP account was not removed"
2135
+ })) {
2136
+ out.err("not removed");
2137
+ return 1;
2138
+ }
2139
+ const smtp = await callSteward(target, () => clientFor(ctx, target).admin.emailSmtp.clear());
2140
+ out.out(`email SMTP account removed → ${originOf(target.url)}`);
2141
+ for (const line of describe(smtp)) out.out(` ${line}`);
2142
+ return 0;
2143
+ }
2144
+ if (sub === "verify") {
2145
+ const { values, positionals } = parse(rest, {
2146
+ ...HELP_OPTION,
2147
+ to: { type: "string" },
2148
+ json: { type: "boolean" }
2149
+ }, "email-smtp");
2150
+ if (values.help) return help$3(out);
2151
+ expectPositionals(positionals, 0, 0, "email-smtp");
2152
+ const input = EmailSmtpVerifyInputSchema.safeParse(values.to !== void 0 ? { to: values.to } : {});
2153
+ if (!input.success) throw new UsageError("--to: must be an email address");
2154
+ const target = requireAdminTarget(await resolveEnv(ctx));
2155
+ out.err(connectionLine(target));
2156
+ const result = await callSteward(target, () => clientFor(ctx, target).admin.emailSmtp.verify(input.data));
2157
+ if (values.json) out.out(JSON.stringify(result, null, 2));
2158
+ else {
2159
+ const via = result.transport === "product" ? "product's own account" : "installation's SMTP";
2160
+ out.out(`${result.ok ? "ok ✓" : "refused ✗"} ${result.host} (${via}) MAIL FROM ${result.from} RCPT TO ${result.to}`);
2161
+ if (!result.ok) {
2162
+ out.out(` failed at ${result.stage} (${result.code ?? "unknown"})`);
2163
+ if (result.reply !== null) out.out(` server ${result.reply}`);
2164
+ }
2165
+ out.err("No email was sent (the session ended before DATA).");
2166
+ }
2167
+ return result.ok ? 0 : 1;
2168
+ }
2169
+ throw new UsageError(`unknown subcommand: email-smtp ${sub} (details: steward email-smtp --help)`);
2170
+ }
2171
+ function help$3(out) {
2172
+ out.out(EMAIL_SMTP_USAGE);
2173
+ return 0;
2174
+ }
1814
2175
  // src/commands/events.ts
1815
2176
  const EVENTS_USAGE = `Usage:
1816
2177
  steward events send <ref> <name> [--meta key=value]… [--external-id <id>]
@@ -2960,7 +3321,7 @@ function help(out) {
2960
3321
  return 0;
2961
3322
  }
2962
3323
  // src/main.ts
2963
- const CLI_VERSION = "0.11.0";
3324
+ const CLI_VERSION = "0.13.0";
2964
3325
  const USAGE = `steward — Steward CLI (@stewardhq/cli ${CLI_VERSION})
2965
3326
 
2966
3327
  Usage: steward <command> [options]
@@ -2970,6 +3331,8 @@ Commands:
2970
3331
  catalog push <file> [--yes] catalog sync (PUT /v1/admin/catalog)
2971
3332
  settings get | set [flags] product settings (/v1/admin/settings)
2972
3333
  endpoints list | add | rotate | deactivate webhook endpoints; the secret goes only to the --out file
3334
+ discounts list | create | update | archive discounts and discount codes; archived, never deleted
3335
+ email-smtp get | set | clear | verify the product's own SMTP account; the URL only from a file or pipe
2973
3336
  keys list | create | revoke API keys; the key goes only to the --out file
2974
3337
  dunning get | set <policy.json> dunning policy (/v1/admin/dunning-policy)
2975
3338
  reprice --plan <code> --notice-days <n> move a plan's subscribers to its current price
@@ -2996,6 +3359,8 @@ const COMMANDS = {
2996
3359
  catalog: catalogCommand,
2997
3360
  settings: settingsCommand,
2998
3361
  endpoints: endpointsCommand,
3362
+ discounts: discountsCommand,
3363
+ "email-smtp": emailSmtpCommand,
2999
3364
  accounts: accountsCommand,
3000
3365
  meters: metersCommand,
3001
3366
  events: eventsCommand,
@@ -3071,6 +3436,12 @@ const ctx = {
3071
3436
  } finally {
3072
3437
  terminal.close();
3073
3438
  }
3439
+ },
3440
+ readStdin: async () => {
3441
+ if (process.stdin.isTTY) return null;
3442
+ const chunks = [];
3443
+ for await (const chunk of process.stdin) chunks.push(chunk);
3444
+ return Buffer.concat(chunks).toString("utf8");
3074
3445
  }
3075
3446
  };
3076
3447
  process.exitCode = await main(process.argv.slice(2), ctx);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stewardhq/cli",
3
- "version": "0.11.0",
3
+ "version": "0.13.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,11 +28,11 @@
28
28
  "registry": "https://registry.npmjs.org"
29
29
  },
30
30
  "dependencies": {
31
- "@stewardhq/sdk": "^0.11.0"
31
+ "@stewardhq/sdk": "^0.13.0"
32
32
  },
33
33
  "devDependencies": {
34
34
  "@types/node": "^26.6.5",
35
- "tsdown": "^0.23.1",
35
+ "tsdown": "0.23.1",
36
36
  "tsx": "^4.23.15",
37
37
  "typescript": "^7.0.2",
38
38
  "vitest": "^5.0.5"