@stewardhq/cli 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +34 -8
  2. package/dist/bin.js +1309 -603
  3. package/package.json +2 -2
package/dist/bin.js CHANGED
@@ -2,15 +2,15 @@
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 { CatalogSyncInputSchema, EventsIngestInputSchema, METER_CHARGE_MODES, MeterCreditPropertiesSchema, ProductSettingsPatchSchema, StewardApiError, StewardConfigError, StewardError, StewardNetworkError, WebhookEndpointCreateInputSchema, WebhookEndpointRotateInputSchema, createSteward, generateWebhookSecret, plainDecimalOf } from "@stewardhq/sdk";
5
+ import { ApiKeyCreateInputSchema, BankTransferRecordInputSchema, CatalogSyncInputSchema, CreditAdjustmentInputSchema, DunningPolicySchema, EventsIngestInputSchema, FxRateSchema, METER_CHARGE_MODES, MeterCreditPropertiesSchema, ProductSettingsPatchSchema, RepriceInputSchema, StewardApiError, StewardConfigError, StewardError, StewardNetworkError, WebhookEndpointCreateInputSchema, WebhookEndpointRotateInputSchema, createSteward, generateApiKeyToken, generateWebhookSecret, plainDecimalOf } from "@stewardhq/sdk";
6
6
  import { parseArgs } from "node:util";
7
- import { link, lstat, readFile, rename, unlink, writeFile } from "node:fs/promises";
8
7
  import { basename, dirname, extname, join, relative, resolve } from "node:path";
9
- import { pathToFileURL } from "node:url";
8
+ import { link, lstat, readFile, rename, unlink, writeFile } from "node:fs/promises";
10
9
  import { randomUUID } from "node:crypto";
10
+ import { pathToFileURL } from "node:url";
11
11
  //#region src/io.ts
12
12
  const SECRET_PATTERN = /\b(whsec_|stw_)[A-Za-z0-9_\-+/=]+/g;
13
- /** Sır biçimindeki değerleri maskeler (`whsec_***`). */
13
+ /** Masks secret-shaped values (`whsec_***`). */
14
14
  function redactSecrets(text) {
15
15
  return text.replace(SECRET_PATTERN, "$1***");
16
16
  }
@@ -20,7 +20,7 @@ function createOutput(stdout, stderr) {
20
20
  err: (line = "") => stderr.write(`${redactSecrets(line)}\n`)
21
21
  };
22
22
  }
23
- /** Kullanıcıya gösterilecek, yığın izi basılmayan hata. */
23
+ /** An error shown to the user, without a stack trace. */
24
24
  var CliError = class extends Error {
25
25
  exitCode;
26
26
  constructor(message, exitCode = 1) {
@@ -29,14 +29,14 @@ var CliError = class extends Error {
29
29
  this.exitCode = exitCode;
30
30
  }
31
31
  };
32
- /** Yanlış kullanım (bilinmeyen bayrak, eksik argüman): çıkış kodu 2. */
32
+ /** Wrong usage (unknown flag, missing argument): exit code 2. */
33
33
  var UsageError = class extends CliError {
34
34
  constructor(message) {
35
35
  super(message, 2);
36
36
  this.name = "UsageError";
37
37
  }
38
38
  };
39
- /** `node:fs` hatasının kodu (`ENOENT`…). */
39
+ /** The code of a `node:fs` error (`ENOENT`…). */
40
40
  function errnoCode(error) {
41
41
  const code = typeof error === "object" && error !== null ? error.code : void 0;
42
42
  return typeof code === "string" ? code : void 0;
@@ -47,8 +47,8 @@ const HELP_OPTION = { help: {
47
47
  type: "boolean",
48
48
  short: "h"
49
49
  } };
50
- const hint = (command) => ` (ayrıntı: steward ${command} --help)`;
51
- /** `command`: hata mesajındaki yardım ipucu için komut adı (`endpoints`). */
50
+ const hint = (command) => ` (details: steward ${command} --help)`;
51
+ /** `command`: the command name for the help hint in the error message (`endpoints`). */
52
52
  function parse(args, options, command) {
53
53
  try {
54
54
  return parseArgs({
@@ -61,24 +61,24 @@ function parse(args, options, command) {
61
61
  throw new UsageError(`${error instanceof Error ? error.message : String(error)}${hint(command)}`);
62
62
  }
63
63
  }
64
- /** Konumsal argüman sayısı `[min, max]` aralığında olmalı. */
64
+ /** The number of positional arguments must be within `[min, max]`. */
65
65
  function expectPositionals(positionals, min, max, command) {
66
- if (positionals.length < min) throw new UsageError(`eksik argüman${hint(command)}`);
67
- if (positionals.length > max) throw new UsageError(`beklenmeyen argüman: ${positionals.slice(max).join(" ")}${hint(command)}`);
66
+ if (positionals.length < min) throw new UsageError(`missing argument${hint(command)}`);
67
+ if (positionals.length > max) throw new UsageError(`unexpected argument: ${positionals.slice(max).join(" ")}${hint(command)}`);
68
68
  }
69
69
  function requireOption(value, flag, command) {
70
- if (value === void 0 || value.trim() === "") throw new UsageError(`${flag} gerekli${hint(command)}`);
70
+ if (value === void 0 || value.trim() === "") throw new UsageError(`${flag} is required${hint(command)}`);
71
71
  return value;
72
72
  }
73
73
  /** `a, b,,c` → `["a", "b", "c"]`. */
74
74
  function parseList(value) {
75
75
  return value.split(",").map((item) => item.trim()).filter((item) => item !== "");
76
76
  }
77
- /** Pozitif tam sayı (yalnızca rakam). */
77
+ /** Positive integer (digits only). */
78
78
  function parsePositiveInt(value, flag, { max = Number.MAX_SAFE_INTEGER } = {}) {
79
79
  const trimmed = value.trim();
80
80
  const n = /^\d+$/.test(trimmed) ? Number(trimmed) : NaN;
81
- if (!Number.isSafeInteger(n) || n < 1 || n > max) throw new UsageError(`${flag}: 1–${max} arası tam sayı olmalı`);
81
+ if (!Number.isSafeInteger(n) || n < 1 || n > max) throw new UsageError(`${flag}: must be an integer between 1 and ${max}`);
82
82
  return n;
83
83
  }
84
84
  /** Non-negative integer (digits only), e.g. an amount in minor units. */
@@ -106,67 +106,6 @@ function parseBoolean(value, flag) {
106
106
  throw new UsageError(`${flag}: must be true or false`);
107
107
  }
108
108
  //#endregion
109
- //#region src/catalog-file.ts
110
- const MODULE_EXTENSIONS = /* @__PURE__ */ new Set([
111
- ".js",
112
- ".mjs",
113
- ".cjs"
114
- ]);
115
- const TS_EXTENSIONS = /* @__PURE__ */ new Set([
116
- ".ts",
117
- ".mts",
118
- ".cts"
119
- ]);
120
- const hasSyncInput = (value) => typeof value === "object" && value !== null && typeof value.toSyncInput === "function";
121
- function pickExport(mod, file) {
122
- if (mod.catalog !== void 0) return mod.catalog;
123
- if (mod.default !== void 0) return mod.default;
124
- const candidates = Object.values(mod).filter(hasSyncInput);
125
- if (candidates.length === 1) return candidates[0];
126
- throw new CliError(`${file}: katalog bulunamadı — \`export const catalog = defineCatalog(…)\` ya da default export bekleniyor`);
127
- }
128
- async function loadCatalogFile(ctx, file) {
129
- const path = resolve(ctx.cwd, file);
130
- const ext = extname(path).toLowerCase();
131
- let exported;
132
- if (ext === ".json") {
133
- let text;
134
- try {
135
- text = await readFile(path, "utf8");
136
- } catch (error) {
137
- throw new CliError(errnoCode(error) === "ENOENT" ? `katalog dosyası yok: ${file}` : `katalog dosyası okunamadı: ${file}`);
138
- }
139
- try {
140
- exported = JSON.parse(text);
141
- } catch {
142
- throw new CliError(`${file}: geçerli JSON değil`);
143
- }
144
- } else if (MODULE_EXTENSIONS.has(ext) || TS_EXTENSIONS.has(ext)) {
145
- if (TS_EXTENSIONS.has(ext) && !ctx.typescript) throw new CliError(`${file}: bu Node sürümü TypeScript dosyasını doğrudan yükleyemiyor (${process.version}). Node ≥ 22.18 kullanın, \`NODE_OPTIONS=--experimental-strip-types\` verin ya da kataloğu .mjs/.json olarak dışa aktarın.`);
146
- let mod;
147
- try {
148
- await readFile(path);
149
- } catch (error) {
150
- throw new CliError(errnoCode(error) === "ENOENT" ? `katalog dosyası yok: ${file}` : `katalog dosyası okunamadı: ${file}`);
151
- }
152
- try {
153
- mod = await ctx.importModule(pathToFileURL(path).href);
154
- } catch (error) {
155
- throw new CliError(`${file} yüklenemedi: ${error instanceof Error ? error.message : String(error)}`);
156
- }
157
- exported = pickExport(mod, file);
158
- } else throw new UsageError(`katalog dosyası .ts, .mts, .js, .mjs, .cjs ya da .json olmalı: ${file}`);
159
- let input;
160
- try {
161
- input = hasSyncInput(exported) ? exported.toSyncInput() : exported;
162
- } catch (error) {
163
- throw new CliError(`${file}: toSyncInput() hata verdi: ${error instanceof Error ? error.message : String(error)}`);
164
- }
165
- const parsed = CatalogSyncInputSchema.safeParse(input);
166
- if (!parsed.success) throw new CliError(`${file}: katalog geçersiz (istek gönderilmedi)\n${parsed.error.issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(kök)"}: ${issue.message}`).join("\n")}`);
167
- return input;
168
- }
169
- //#endregion
170
109
  //#region src/catalog-diff.ts
171
110
  /** A catalog that defines benefits needs a steward with the `benefits` capability (M27). */
172
111
  function definesBenefits(input) {
@@ -176,6 +115,10 @@ function definesBenefits(input) {
176
115
  function definesMeters(input) {
177
116
  return Object.keys(input.meters ?? {}).length > 0 || (input.meteredPrices ?? []).length > 0;
178
117
  }
118
+ /** A catalog with an unlisted plan needs a steward with the `unlisted_plans` capability: an older one would offer the plan. */
119
+ function definesUnlistedPlans(input) {
120
+ return input.plans.some((plan) => plan.listed === false);
121
+ }
179
122
  const isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
180
123
  /** JSON with sorted object keys: key order does not count as a change. */
181
124
  const canonical = (value) => JSON.stringify(value ?? null, (_key, v) => isPlainObject(v) ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) : v);
@@ -287,6 +230,11 @@ function diffCatalog(current, file) {
287
230
  removed
288
231
  });
289
232
  }
233
+ const currentListing = new Map((current?.plans ?? []).map((plan) => [plan.code, plan.listed ?? true]));
234
+ const planListing = input.plans.filter((plan) => (currentListing.get(plan.code) ?? true) !== plan.listed).map((plan) => ({
235
+ plan: plan.code,
236
+ listed: plan.listed
237
+ }));
290
238
  const currentPrices = new Map((current?.prices ?? []).map((price) => [priceKey(price), price]));
291
239
  const inputKeys = new Set(input.prices.map(priceKey));
292
240
  const prices = {
@@ -328,6 +276,7 @@ function diffCatalog(current, file) {
328
276
  return {
329
277
  benefits,
330
278
  planBenefits,
279
+ planListing,
331
280
  prices,
332
281
  meters: diffMeters(current, input),
333
282
  credits,
@@ -379,6 +328,7 @@ function describeDiff(diff) {
379
328
  if (diff.benefits.changed.length > 0) row("changed benefits", list$1(diff.benefits.changed));
380
329
  if (diff.benefits.archived.length > 0) row("archived benefits", `${list$1(diff.benefits.archived)} (accounts that have them lose them)`);
381
330
  for (const { plan, added, removed } of diff.planBenefits) row("plan benefits", `${plan}: ${[...added.map((code) => `+${code}`), ...removed.map((code) => `-${code}`)].join(" ")}`);
331
+ for (const { plan, listed } of diff.planListing) row("plan listing", `${plan}: ${listed ? "listed (offered" : "unlisted (not offered"} in the portal's "Change plan")`);
382
332
  for (const price of diff.prices.added) row("new price", price);
383
333
  for (const price of diff.prices.deactivated) row("deactivated price", price);
384
334
  for (const change of diff.prices.changed) row("price change", describePriceChange(change));
@@ -410,6 +360,18 @@ function priceChangeCount(diff) {
410
360
  return diff.prices.changed.length + diff.meteredPrices.changed.length;
411
361
  }
412
362
  //#endregion
363
+ //#region src/confirm.ts
364
+ /**
365
+ * Asks before a change that cannot be taken back; `yes` (`--yes`) skips the question. Without a
366
+ * terminal (CI, pipes) the command needs `--yes`: `notConfirmed` says what was not done.
367
+ */
368
+ async function confirm(ctx, question, options) {
369
+ if (options.yes) return true;
370
+ const answer = await ctx.prompt(`${question} [y/N] `);
371
+ if (answer === null) throw new CliError(`confirmation needed: run again with --yes (${options.notConfirmed})`);
372
+ return /^y(es)?$/i.test(answer.trim());
373
+ }
374
+ //#endregion
413
375
  //#region src/dotenv.ts
414
376
  const LINE = /^(\s*)(export\s+)?([A-Za-z_][A-Za-z0-9_.-]*)\s*=(.*)$/;
415
377
  function unquote(rest) {
@@ -444,7 +406,7 @@ async function readDotenvFile(path) {
444
406
  //#endregion
445
407
  //#region src/env.ts
446
408
  const ENV_LOCAL = ".env.local";
447
- /** Biri bile süreç ortamındaysa `.env.local` okunmaz. */
409
+ /** If even one of these is in the process environment, `.env.local` is not read. */
448
410
  const CONNECTION_VARIABLES = [
449
411
  "STEWARD_URL",
450
412
  "STEWARD_API_KEY",
@@ -466,7 +428,7 @@ const clean = (value) => {
466
428
  async function resolveEnv(ctx) {
467
429
  const fromEnv = CONNECTION_VARIABLES.some((name) => clean(ctx.env[name]) !== void 0);
468
430
  const local = fromEnv ? null : await readDotenvFile(join(ctx.cwd, ENV_LOCAL));
469
- const source = local === null ? "ortam" : ".env.local";
431
+ const source = local === null ? "environment" : ".env.local";
470
432
  const get = (name) => local === null ? clean(ctx.env[name]) : clean(local.get(name));
471
433
  return {
472
434
  source,
@@ -491,21 +453,21 @@ async function resolveEnv(ctx) {
491
453
  }
492
454
  function whereMissing(env) {
493
455
  switch (env.envLocal) {
494
- case "skipped": return `ortamda tanımlı değil (ortamda steward bağlantı değişkeni olduğu için ./${ENV_LOCAL} okunmadı; kaynaklar karıştırılmaz)`;
495
- case "read": return `./${ENV_LOCAL}'de tanımlı değil (ortamda steward bağlantı değişkeni yok)`;
496
- case "missing": return `tanımlı değil (ortam değişkeni ya da ./${ENV_LOCAL}; dosya yok)`;
456
+ case "skipped": return `not set in the environment (./${ENV_LOCAL} was not read because a steward connection variable is in the environment; sources are not mixed)`;
457
+ case "read": return `not set in ./${ENV_LOCAL} (no steward connection variable in the environment)`;
458
+ case "missing": return `not set (environment variable or ./${ENV_LOCAL}; no such file)`;
497
459
  }
498
460
  }
499
- const ADMIN_HINT = "Bunları ortam değişkeni ya da ./.env.local olarak verin. Cluster'da: admin ucunu port-forward edin (STEWARD_ADMIN_URL=http://localhost:13002) ve admin anahtarını operatör Secret'ından ortam değişkeni olarak verin.";
461
+ const ADMIN_HINT = "Set them as environment variables or in ./.env.local. Admin: STEWARD_ADMIN_URL=https://billing.zone9.cloud once /v1 is exposed (docs/runbook.md), or a port-forward (http://localhost:13002), which is also the only way to register a cluster-internal (*.svc.cluster.local) webhook endpoint; the admin key comes from the operator Secret as an environment variable.";
500
462
  function pairError(names, missing, env) {
501
- return new CliError(`${names.url} + ${names.key} gerekli: ${missing.join(" ve ")} ${whereMissing(env)}.\n${ADMIN_HINT}`);
463
+ return new CliError(`${names.url} + ${names.key} required: ${missing.join(" and ")} ${whereMissing(env)}.\n${ADMIN_HINT}`);
502
464
  }
503
465
  function requireAdminTarget(env) {
504
466
  const pair = env.pair(ADMIN_PAIR);
505
467
  if ("missing" in pair) throw pairError(ADMIN_PAIR, pair.missing, env);
506
468
  return pair;
507
469
  }
508
- /** Ürün çifti; ikisi de tanımsızsa admin çifti (`GET /v1/doctor` ikisine de açık). Yarım çift hatadır. */
470
+ /** The product pair; if both are unset, the admin pair (`GET /v1/doctor` is open to both). A half pair is an error. */
509
471
  function requireReadTarget(env) {
510
472
  const product = env.pair(PRODUCT_PAIR);
511
473
  if (!("missing" in product)) return product;
@@ -513,28 +475,28 @@ function requireReadTarget(env) {
513
475
  const admin = env.pair(ADMIN_PAIR);
514
476
  if (!("missing" in admin)) return admin;
515
477
  if (admin.present.length > 0) throw pairError(ADMIN_PAIR, admin.missing, env);
516
- throw new CliError(`${PRODUCT_PAIR.url} + ${PRODUCT_PAIR.key} (ya da ${ADMIN_PAIR.url} + ${ADMIN_PAIR.key}) gerekli: ${whereMissing(env)}.\n${ADMIN_HINT}`);
478
+ throw new CliError(`${PRODUCT_PAIR.url} + ${PRODUCT_PAIR.key} (or ${ADMIN_PAIR.url} + ${ADMIN_PAIR.key}) required: ${whereMissing(env)}.\n${ADMIN_HINT}`);
517
479
  }
518
- /** Kullanılan kaynak, çift ve hedefin origin'i (stderr satırı; anahtar değeri yok). */
480
+ /** The source and pair in use and the target's origin (a stderr line; no key value). */
519
481
  function connectionLine(target) {
520
- return `bağlantı: ${target.source} · ${target.pair.url} + ${target.pair.key} → ${originOf(target.url)}`;
482
+ return `connection: ${target.source} · ${target.pair.url} + ${target.pair.key} → ${originOf(target.url)}`;
521
483
  }
522
- /** İşletim sistemi kullanıcı adından `operator:<ad>` (sözleşmenin `tür[:kimlik]` biçimi). */
484
+ /** `operator:<name>` from the operating system user name (the contract's `type[:id]` form). */
523
485
  function actorRefOf(username) {
524
486
  const id = username.replace(/[^A-Za-z0-9_.@-]/g, "_").slice(0, 190);
525
487
  return id === "" ? "operator" : `operator:${id}`;
526
488
  }
527
- /** Hedefin origin'i (kimlik bilgisi ve yol yazdırılmaz). */
489
+ /** The target's origin (credentials and path are not printed). */
528
490
  function originOf(url) {
529
491
  try {
530
492
  return new URL(url).origin;
531
493
  } catch {
532
- return "(geçersiz adres)";
494
+ return "(invalid address)";
533
495
  }
534
496
  }
535
497
  /**
536
- * Hedefe bağlı istemci. Aynı URL/anahtar hem ürün hem admin tabanı olarak verilir:
537
- * komut yalnızca hedefin kapsamına uygun metotları çağırır.
498
+ * A client bound to the target. The same URL/key is given as both the product and the admin base:
499
+ * the command only calls the methods that fit the target's scope.
538
500
  */
539
501
  function clientFor(ctx, target, options = {}) {
540
502
  return createSteward({
@@ -549,7 +511,7 @@ function clientFor(ctx, target, options = {}) {
549
511
  retries: options.retries === false ? { attempts: 0 } : { sleep: ctx.sleep }
550
512
  });
551
513
  }
552
- /** Steward çağrısı: SDK hatası hedefin origin'iyle `CliError`'a çevrilir. */
514
+ /** A steward call: an SDK error becomes a `CliError` carrying the target's origin. */
553
515
  async function callSteward(target, fn) {
554
516
  try {
555
517
  return await fn();
@@ -563,223 +525,902 @@ const CODE_HINTS = {
563
525
  meter_locked: " — a meter's filter and aggregation are fixed once it has counted a period: give the new rule a new meter code",
564
526
  metered_price_tax_mismatch: " — a metered price needs the tax terms (taxInclusive, taxRateBps) of its plan's base price in that currency"
565
527
  };
566
- /** SDK hatasını tek satırlık kullanıcı mesajına çevirir (değer/anahtar içermez). */
528
+ /** Turns an SDK error into a one-line user message (no values or keys). */
567
529
  function describeStewardError(error, target) {
568
530
  const where = target ? ` (${originOf(target.url)})` : "";
569
- const request = error.requestId !== void 0 ? ` [istek ${error.requestId}]` : "";
570
- if (error instanceof StewardNetworkError) return `steward'a ulaşılamadı${where}: ${error.code === "timeout" ? "zaman aşımı" : "bağlantı kurulamadı"}. Adres doğru mu, port-forward açık mı?`;
571
- if (error instanceof StewardConfigError) return `yapılandırma hatası: ${error.message}`;
531
+ const request = error.requestId !== void 0 ? ` [request ${error.requestId}]` : "";
532
+ if (error instanceof StewardNetworkError) return `could not reach steward${where}: ${error.code === "timeout" ? "timed out" : "could not connect"}. Is the address right, is the port-forward running?`;
533
+ if (error instanceof StewardConfigError) return `configuration error: ${error.message}`;
572
534
  if (error instanceof StewardApiError) {
573
- const hint = error.httpStatus === 401 ? " — anahtar geçersiz ya da iptal edilmiş" : error.httpStatus === 403 ? " — bu işlem admin kapsamlı anahtar ister" : Object.hasOwn(CODE_HINTS, error.code) ? CODE_HINTS[error.code] : "";
535
+ const hint = error.httpStatus === 401 ? " — the key is invalid or revoked" : error.httpStatus === 403 ? " — this operation needs an admin-scoped key" : Object.hasOwn(CODE_HINTS, error.code) ? CODE_HINTS[error.code] : "";
574
536
  const message = error.message !== error.code ? `: ${error.message}` : "";
575
- return `steward hatası${where}: ${error.code} (HTTP ${error.httpStatus})${message}${hint}${request}`;
537
+ return `steward error${where}: ${error.code} (HTTP ${error.httpStatus})${message}${hint}${request}`;
576
538
  }
577
- return `steward yanıtı sözleşmeye uymuyor${where}: ${error.code} (HTTP ${error.httpStatus}) — CLI ile steward sürümleri uyumsuz olabilir${request}`;
539
+ return `steward response does not match the contract${where}: ${error.code} (HTTP ${error.httpStatus}) — the CLI and steward versions may be incompatible${request}`;
578
540
  }
579
541
  //#endregion
580
- //#region src/commands/catalog.ts
581
- const CATALOG_USAGE = `Kullanım: steward catalog push <dosya> [--yes]
582
-
583
- Katalog tanımını steward'a senkronlar (PUT /v1/admin/catalog), sonra sürümü ve
584
- sayıları yazar. Dosya: .ts/.mts (Node tip ayıklaması, Node ≥ 22.18), .js/.mjs/.cjs
585
- (\`export const catalog = defineCatalog(…)\` ya da default export) veya .json
586
- (senkron gövdesi). Geçersiz katalogda istek gönderilmez.
587
-
588
- Before pushing, prints what changes against steward's current catalog: benefits
589
- (new, changed, archived, plan benefit lists) and prices (new, deactivated, amount or
590
- tax terms changed). A changed price is updated in place: existing subscriptions keep
591
- the amount they locked, new subscriptions pay the new amount, a tax change applies to
592
- every invoice written from now on. Price changes need confirmation: a prompt on a
593
- terminal, otherwise --yes (-y). A catalog with benefits is pushed only to a steward
594
- whose GET /v1/me lists the "benefits" capability (an older steward would drop them).
595
-
596
- Metering: the diff also lists meters (new, changed, rule changed, archived), changed
597
- credits (meter_credit benefits) and metered prices (new, deactivated, changed; a
598
- changed metered price needs the same confirmation). A meter's filter and aggregation
599
- are fixed once it has counted a period (422 meter_locked: use a new meter code). A
600
- catalog with meters or metered prices is pushed only to a steward whose GET /v1/me
601
- lists the "meters" capability.
602
-
603
- Bağlantı: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (ortam, yoksa ./.env.local).
604
- Çıkış kodu 1: sağlayıcıda karşılığı açılamayan fiyat var (senkronu yeniden koşun);
605
- the push was refused or not confirmed.`;
606
- const PUSH_OPTIONS = {
607
- ...HELP_OPTION,
608
- yes: {
609
- type: "boolean",
610
- short: "y"
542
+ //#region src/secret-file.ts
543
+ async function withSecretFile(cwd, out, secret, options, action) {
544
+ const target = resolve(cwd, out);
545
+ try {
546
+ if ((await lstat(target)).isDirectory()) throw new CliError(`--out is a folder: ${out}`);
547
+ if (!options.force) throw new CliError(`${out} already exists; use --force to overwrite it (no request was sent)`);
548
+ } catch (error) {
549
+ if (error instanceof CliError) throw error;
550
+ if (errnoCode(error) !== "ENOENT") throw error;
611
551
  }
612
- };
613
- const list = (items) => items.length > 0 ? items.join(", ") : "-";
614
- /** Senkron + sürüm okuması; özet satırları ve sağlayıcı hatası olup olmadığı. */
615
- async function pushCatalog(steward, target, input) {
616
- const result = await callSteward(target, () => steward.admin.catalog.sync(input));
617
- const version = (await callSteward(target, () => steward.catalog.read())).etag?.replace(/^W\//, "").replace(/"/g, "") ?? "bilinmiyor";
618
- const benefitCount = Object.keys(input.benefits ?? {}).length;
619
- const meterCount = Object.keys(input.meters ?? {}).length;
620
- const meteredCount = (input.meteredPrices ?? []).length;
621
- const metering = `${meterCount > 0 ? ` · ${meterCount} meter${meterCount === 1 ? "" : "s"}` : ""}${meteredCount > 0 ? ` · ${meteredCount} metered price${meteredCount === 1 ? "" : "s"}` : ""}`;
622
- const lines = [`katalog senkronlandı → ${originOf(target.url)}`];
623
- lines.push(` sürüm ${version}`);
624
- lines.push(` tanım ${input.plans.length} plan · ${input.features.length} feature · ${input.prices.length} fiyat${benefitCount > 0 ? ` · ${benefitCount} benefit` : ""}${metering} · varsayılan plan ${input.defaultPlanCode}`);
625
- if (result.unchanged) lines.push(" değişiklik yok");
626
- else {
627
- lines.push(` değişiklik yeni fiyat ${result.createdPrices.length} · pasif fiyat ${result.deactivatedPrices.length} · değişen plan: ${list(result.changedPlans)} · emekli plan: ${list(result.retiredPlans)} · kaldırılan feature: ${list(result.removedFeatures)}${result.defaultPlanChanged ? " · varsayılan plan değişti" : ""}`);
628
- const changedBenefits = result.changedBenefits ?? [];
629
- const archivedBenefits = result.archivedBenefits ?? [];
630
- if (changedBenefits.length > 0 || archivedBenefits.length > 0) lines.push(` benefits changed: ${list(changedBenefits)} · archived: ${list(archivedBenefits)}`);
631
- if ((result.updatedPrices ?? []).length > 0) lines.push(` prices updated in place: ${result.updatedPrices.length}`);
632
- const changedMeters = result.changedMeters ?? [];
633
- const archivedMeters = result.archivedMeters ?? [];
634
- if (changedMeters.length > 0 || archivedMeters.length > 0) lines.push(` meters changed: ${list(changedMeters)} · archived: ${list(archivedMeters)}`);
635
- const [created, updated, deactivated] = [
636
- result.createdMeteredPrices ?? [],
637
- result.updatedMeteredPrices ?? [],
638
- result.deactivatedMeteredPrices ?? []
639
- ];
640
- if (created.length + updated.length + deactivated.length > 0) lines.push(` metered new ${created.length} · updated in place ${updated.length} · deactivated ${deactivated.length}`);
552
+ const temp = join(dirname(target), `.${basename(target)}.${randomUUID().slice(0, 8)}.tmp`);
553
+ try {
554
+ await writeFile(temp, secret, {
555
+ mode: 384,
556
+ flag: "wx"
557
+ });
558
+ } catch (error) {
559
+ const code = errnoCode(error);
560
+ if (code === "ENOENT") throw new CliError(`--out folder does not exist: ${relative(cwd, dirname(target)) || "."}`);
561
+ throw new CliError(`could not write the secret file (${code ?? "error"}): ${out} (no request was sent)`);
641
562
  }
642
- for (const error of result.providerErrors) lines.push(` ✗ sağlayıcı hatası: fiyat ${error.priceId} (${error.provider}: ${error.code}) — senkronu yeniden koşun`);
643
- return {
644
- lines,
645
- providerErrors: result.providerErrors.length
646
- };
647
- }
648
- /** The steward's current catalog; null before the first push (`404 catalog_not_configured`). */
649
- function currentCatalog(steward, target) {
650
- return callSteward(target, () => steward.catalog.get().catch((error) => {
651
- if (error instanceof StewardApiError && error.httpStatus === 404 && error.code === "catalog_not_configured") return null;
563
+ let value;
564
+ try {
565
+ value = await action();
566
+ } catch (error) {
567
+ await unlink(temp).catch(() => {});
652
568
  throw error;
653
- }));
654
- }
655
- /**
656
- * Refuses a catalog whose benefits or meters steward does not understand (M27): an older steward
657
- * drops the keys silently. `needed`: the capabilities the catalog needs (`benefits`, `meters`).
658
- */
659
- async function requireCapabilities(steward, target, needed) {
660
- if (needed.length === 0) return;
661
- const me = await callSteward(target, () => steward.me());
662
- const missing = needed.filter((capability) => !(me.capabilities ?? []).includes(capability));
663
- if (missing.length === 0) return;
664
- throw new CliError(`the catalog defines ${missing.join(" and ")} but steward at ${originOf(target.url)} does not support them (GET /v1/me capabilities has no ${missing.map((c) => `"${c}"`).join(", ")}; it would drop them silently). Update steward first; nothing was pushed.`);
665
- }
666
- async function catalogCommand(ctx, out, args) {
667
- const [sub, ...rest] = args;
668
- if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
669
- out.out(CATALOG_USAGE);
670
- return sub === void 0 ? 2 : 0;
671
569
  }
672
- if (sub !== "push") throw new UsageError(`bilinmeyen alt komut: catalog ${sub} (ayrıntı: steward catalog --help)`);
673
- const { values, positionals } = parse(rest, PUSH_OPTIONS, "catalog push");
674
- if (values.help) {
675
- out.out(CATALOG_USAGE);
676
- return 0;
677
- }
678
- expectPositionals(positionals, 1, 1, "catalog push");
679
- const input = await loadCatalogFile(ctx, positionals[0]);
680
- const target = requireAdminTarget(await resolveEnv(ctx));
681
- out.err(connectionLine(target));
682
- const steward = clientFor(ctx, target);
683
- await requireCapabilities(steward, target, [...definesBenefits(input) ? ["benefits"] : [], ...definesMeters(input) ? ["meters"] : []]);
684
- const diff = diffCatalog(await currentCatalog(steward, target), input);
685
- for (const line of describeDiff(diff)) out.out(line);
686
- const priceChanges = priceChangeCount(diff);
687
- if (priceChanges > 0 && !values.yes) {
688
- const question = `Apply ${priceChanges} price change${priceChanges === 1 ? "" : "s"}? [y/N] `;
689
- const answer = await ctx.prompt(question);
690
- if (answer === null) throw new CliError(`${priceChanges} price change${priceChanges === 1 ? "" : "s"} need${priceChanges === 1 ? "s" : ""} confirmation: run again with --yes (nothing was pushed)`);
691
- if (!/^y(es)?$/i.test(answer.trim())) {
692
- out.err("not confirmed; nothing was pushed");
693
- return 1;
570
+ try {
571
+ if (options.force) await rename(temp, target);
572
+ else {
573
+ await link(temp, target);
574
+ await unlink(temp).catch(() => {});
694
575
  }
576
+ return {
577
+ value,
578
+ path: out,
579
+ fallback: false
580
+ };
581
+ } catch {
582
+ return {
583
+ value,
584
+ path: relative(cwd, temp),
585
+ fallback: true
586
+ };
695
587
  }
696
- const { lines, providerErrors } = await pushCatalog(steward, target, input);
697
- for (const line of lines) out.out(line);
698
- return providerErrors > 0 ? 1 : 0;
699
588
  }
700
589
  //#endregion
701
- //#region src/commands/doctor.ts
702
- const DOCTOR_USAGE = `Kullanım: steward doctor [--json]
703
-
704
- GET /v1/doctor raporu. Bölümler sırayla: durum, katalog, sağlayıcı, ayarlar,
705
- hosted (sayfa hazırlığı), endpoint'ler (teslimat teşhisi), dunning, emails ve
706
- sayaçlı üründe metering/events/overage; sonda hatalar, uyarılar ve bilgi
707
- listeleri. APP_URL tanımlıysa steward'daki appUrl ve izinli dönüş
708
- origin'leriyle karşılaştırılır.
709
-
710
- Bağlantı: STEWARD_URL + STEWARD_API_KEY (ikisi de yoksa STEWARD_ADMIN_URL +
711
- STEWARD_ADMIN_API_KEY). Ortamda steward bağlantı değişkenlerinden biri bile
712
- varsa bağlantı ve APP_URL yalnızca ortamdan okunur (./.env.local okunmaz);
713
- yoksa ./.env.local'den. Kaynak ve hedefin origin'i stderr'e yazılır.
714
-
715
- Çıkış kodu: 0 hazır; 1 rapor ok değil (error önemde uyarı) ya da APP_URL
716
- steward'da izinli değil.
590
+ //#region src/commands/endpoints.ts
591
+ const ENDPOINTS_USAGE = `Usage:
592
+ steward endpoints list [--json]
593
+ steward endpoints add --url <url> --out <file> [--event-types <a,b>] [--description <text>] [--force]
594
+ steward endpoints rotate <id> --out <file> [--force]
595
+ steward endpoints deactivate <id>
717
596
 
718
- Ölçümleme: kataloğunda sayaç tanımlı üründe "metering" satırı sayaçları ve
719
- ölçümlü fiyatları (GET /v1/catalog) ve steward'ın yeteneklerini (GET /v1/me:
720
- events, meters, overage) yazar; ardından raporun "events" bölümü (bekleyen olay,
721
- rollup gecikmesi, son 7 günün örneği: eşleşmeyen olay adları, geçersiz değerler,
722
- olayı olmayan sayaçlar) ve "overage" bölümü (aşım kipi, ölçümlü fiyatlar, kilitli
723
- oranı olmayan abonelikler, devreden kayıtlar) gelir. Ölçümleme uyarıları her
724
- zamanki gibi alttaki listelerdedir.
597
+ Webhook endpoints (/v1/admin/webhook-endpoints). The signing secret (whsec_…) is
598
+ generated on this machine and written ONLY to the --out file (0600, no trailing
599
+ newline); it is not written to the terminal and steward never returns it in any
600
+ response. If the file exists, no request is sent without --force. The operator moves
601
+ the secret into the product's Secret (the CLI does not call kubectl); on rotation the
602
+ product moves over with a "new,old" list. Delete the file after moving it. Without
603
+ --event-types only account.state_changed. deactivate cannot be undone (open a new
604
+ endpoint).
725
605
 
726
- --json raporu JSON yazar (+ cliWarnings: yerel APP_URL karşılaştırması;
727
- cliMetering: metering satırının katalog ve yetenek bilgileri)`;
728
- /** `APP_URL` (ürünün kendi adresi; checkout `successUrl`'i bundan kurulur) ↔ steward ayarları. */
729
- function appUrlWarnings(appUrl, report) {
730
- if (appUrl === void 0) return [];
731
- let origin;
732
- try {
733
- origin = new URL(appUrl).origin;
734
- } catch {
735
- return [{
736
- code: "app_url_env_invalid",
737
- severity: "error",
738
- message: "APP_URL geçerli bir adres değil"
739
- }];
740
- }
741
- if (!report.settings.returnOrigins.includes(origin)) return [{
742
- code: "app_url_not_allowed",
743
- severity: "error",
744
- message: `APP_URL origin'i (${origin}) steward'da izinli dönüş origin'i değil (appUrl: ${report.settings.appUrl ?? "yok"}): checkout return_url_not_allowed alır — steward settings set --app-url ${origin}`
745
- }];
746
- if (report.settings.appUrl !== null && originOf(report.settings.appUrl) !== origin) return [{
747
- code: "app_url_mismatch",
748
- severity: "warning",
749
- message: `APP_URL (${origin}) steward appUrl'inden (${report.settings.appUrl}) farklı: hosted sayfanın "ürüne dön" bağı appUrl'e gider`
750
- }];
751
- return [];
606
+ Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
607
+ function schemaProblems(issues) {
608
+ return issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(root)"}: ${issue.message}`).join("\n");
752
609
  }
753
- /** The capabilities the metering section shows (M27). */
754
- const METERING_CAPABILITIES = [
755
- "events",
756
- "meters",
757
- "overage"
758
- ];
759
- /**
760
- * The metering section's facts: the catalog's meters and metered prices and steward's capabilities.
761
- * Null when the catalog carries no meters (a product that never defined one, an older steward, no
762
- * catalog yet) or cannot be read: the section is informational and never fails the doctor.
763
- */
764
- async function meteringSummary(steward) {
765
- try {
766
- const catalog = await steward.catalog.get();
767
- if (catalog.meters === void 0) return null;
768
- const me = await steward.me().catch(() => null);
769
- return {
770
- meters: Object.keys(catalog.meters),
771
- meteredPrices: (catalog.meteredPrices ?? []).length,
772
- capabilities: me?.capabilities ?? null
773
- };
774
- } catch {
775
- return null;
776
- }
610
+ const lastDeliveryText = (endpoint) => {
611
+ const last = endpoint.lastDelivery;
612
+ if (last === null) return "-";
613
+ return `${last.status}${last.httpStatus !== null ? ` ${last.httpStatus}` : ""}${last.error !== null ? ` ${last.error}` : ""} (${last.at})`;
614
+ };
615
+ /** Left-aligned columns; the last column is not padded. */
616
+ function table(rows) {
617
+ const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
618
+ return rows.map((row) => row.map((cell, column) => column === row.length - 1 ? cell : cell.padEnd(widths[column])).join(" "));
777
619
  }
778
- const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
779
- /** `name (count), …` of a sample list. */
780
- const counted = (items, key) => items.map((item) => `${item[key]} (${item.events})`).join(", ");
781
- /**
782
- * Lines of the metering sections: the CLI's catalog and capability facts (`metering`), then the
620
+ const typesText = (endpoint) => endpoint.eventTypes === null ? "(no filter: 0.1 types)" : endpoint.eventTypes.join(",");
621
+ async function endpointsCommand(ctx, out, args) {
622
+ const [sub, ...rest] = args;
623
+ if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
624
+ out.out(ENDPOINTS_USAGE);
625
+ return sub === void 0 ? 2 : 0;
626
+ }
627
+ if (sub === "list") {
628
+ const { values, positionals } = parse(rest, {
629
+ ...HELP_OPTION,
630
+ json: { type: "boolean" }
631
+ }, "endpoints");
632
+ if (values.help) return help$3(out);
633
+ expectPositionals(positionals, 0, 0, "endpoints");
634
+ const target = requireAdminTarget(await resolveEnv(ctx));
635
+ out.err(connectionLine(target));
636
+ const { items } = await callSteward(target, () => clientFor(ctx, target).admin.endpoints.list());
637
+ if (values.json) out.out(JSON.stringify(items, null, 2));
638
+ else if (items.length === 0) out.out("no endpoints — steward endpoints add --url <url> --out <file>");
639
+ else {
640
+ const rows = [[
641
+ "ID",
642
+ "STATUS",
643
+ "EVENTS",
644
+ "LAST DELIVERY",
645
+ "URL"
646
+ ]];
647
+ for (const e of items) rows.push([
648
+ e.id,
649
+ e.status,
650
+ typesText(e),
651
+ lastDeliveryText(e),
652
+ e.description !== null ? `${e.url} (${e.description})` : e.url
653
+ ]);
654
+ for (const line of table(rows)) out.out(line);
655
+ }
656
+ return 0;
657
+ }
658
+ if (sub === "add") {
659
+ const { values, positionals } = parse(rest, {
660
+ ...HELP_OPTION,
661
+ url: { type: "string" },
662
+ out: { type: "string" },
663
+ "event-types": { type: "string" },
664
+ description: { type: "string" },
665
+ force: { type: "boolean" }
666
+ }, ENDPOINTS_USAGE);
667
+ if (values.help) return help$3(out);
668
+ expectPositionals(positionals, 0, 0, "endpoints");
669
+ const url = requireOption(values.url, "--url", "endpoints");
670
+ const file = requireOption(values.out, "--out", "endpoints");
671
+ const secret = generateWebhookSecret();
672
+ const input = {
673
+ url,
674
+ secret,
675
+ ...values["event-types"] !== void 0 ? { eventTypes: parseList(values["event-types"]) } : {},
676
+ ...values.description !== void 0 ? { description: values.description } : {}
677
+ };
678
+ const parsed = WebhookEndpointCreateInputSchema.safeParse(input);
679
+ if (!parsed.success) throw new UsageError(`invalid endpoint (no request was sent)\n${schemaProblems(parsed.error.issues)}`);
680
+ const target = requireAdminTarget(await resolveEnv(ctx));
681
+ out.err(connectionLine(target));
682
+ const steward = clientFor(ctx, target);
683
+ const result = await withSecretFile(ctx.cwd, file, secret, { force: values.force === true }, () => callSteward(target, () => steward.admin.endpoints.create(input)));
684
+ const endpoint = result.value;
685
+ out.out(`endpoint created → ${originOf(target.url)}`);
686
+ out.out(` id ${endpoint.id}`);
687
+ out.out(` url ${endpoint.url}`);
688
+ out.out(` events ${typesText(endpoint)}`);
689
+ secretNotice(out, result.path, result.fallback, "Move the secret into the product's Secret (STEWARD_WEBHOOK_SECRET), then delete the file.");
690
+ return 0;
691
+ }
692
+ if (sub === "rotate") {
693
+ const { values, positionals } = parse(rest, {
694
+ ...HELP_OPTION,
695
+ out: { type: "string" },
696
+ force: { type: "boolean" }
697
+ }, "endpoints");
698
+ if (values.help) return help$3(out);
699
+ expectPositionals(positionals, 1, 1, "endpoints");
700
+ const id = positionals[0];
701
+ const file = requireOption(values.out, "--out", "endpoints");
702
+ const secret = generateWebhookSecret();
703
+ const parsed = WebhookEndpointRotateInputSchema.safeParse({ secret });
704
+ if (!parsed.success) throw new UsageError(`invalid secret\n${schemaProblems(parsed.error.issues)}`);
705
+ const target = requireAdminTarget(await resolveEnv(ctx));
706
+ out.err(connectionLine(target));
707
+ const steward = clientFor(ctx, target);
708
+ const result = await withSecretFile(ctx.cwd, file, secret, { force: values.force === true }, () => callSteward(target, () => steward.admin.endpoints.rotate(id, { secret })));
709
+ out.out(`secret rotated → ${originOf(target.url)}`);
710
+ out.out(` id ${result.value.id}`);
711
+ out.out(` url ${result.value.url}`);
712
+ secretNotice(out, result.path, result.fallback, "Set STEWARD_WEBHOOK_SECRET in the product's Secret to \"new,old\" and roll out; the old secret stays in steward as a second signature for the transition. Then delete the file.");
713
+ return 0;
714
+ }
715
+ if (sub === "deactivate") {
716
+ const { values, positionals } = parse(rest, { ...HELP_OPTION }, "endpoints");
717
+ if (values.help) return help$3(out);
718
+ expectPositionals(positionals, 1, 1, "endpoints");
719
+ const target = requireAdminTarget(await resolveEnv(ctx));
720
+ out.err(connectionLine(target));
721
+ const endpoint = await callSteward(target, () => clientFor(ctx, target).admin.endpoints.deactivate(positionals[0]));
722
+ out.out(`endpoint deactivated → ${originOf(target.url)}: ${endpoint.id} (${endpoint.url}, status ${endpoint.status})`);
723
+ return 0;
724
+ }
725
+ throw new UsageError(`unknown subcommand: endpoints ${sub} (details: steward endpoints --help)`);
726
+ }
727
+ function help$3(out) {
728
+ out.out(ENDPOINTS_USAGE);
729
+ return 0;
730
+ }
731
+ /** Where a generated secret went (`withSecretFile`); shared by `endpoints` and `keys`. */
732
+ function secretNotice(out, path, fallback, next) {
733
+ if (fallback) out.err(`! the secret could not be moved to the target file (it may have been created meanwhile); it is in ${path} (0600)`);
734
+ out.out(` secret ${path} (0600; not written to the terminal)`);
735
+ out.err(next);
736
+ }
737
+ //#endregion
738
+ //#region src/commands/bank-transfers.ts
739
+ const BANK_TRANSFERS_USAGE = `Usage:
740
+ steward bank-transfers list [--status pending|expired] [--rate <rate> [--currency <CUR>]]
741
+ [--json]
742
+ steward bank-transfers record <code> --amount <minor> --currency <CUR> --received-at <iso>
743
+ --bank-ref <ref> [--rate <rate>]
744
+ [--checkout <id> [--accept-expired] | --invoice <id>]
745
+ [--yes] [--json]
746
+ steward bank-transfers fx-report [--from <iso>] [--to <iso>] [--json | --csv]
747
+
748
+ Bank transfer (havale/EFT) reconciliation (/v1/admin/bank-transfers).
749
+
750
+ list: what the bank statement is matched against. pending (default): checkouts waiting for a
751
+ transfer and unpaid invoices of accounts with an order code, by deadline; expired: checkouts
752
+ that expired in the last 30 days. --rate previews a transfer in another currency: next to each
753
+ item the product lets be paid in another currency (settings.billing.bankTransfer.settleIn) it
754
+ shows the amount expected at that rate (--currency names it when an item accepts several). It
755
+ writes nothing.
756
+
757
+ record: a transfer seen on the bank account. <code> is the order code from the transfer
758
+ description (case and dashes are forgiven). Only a checkout or unpaid invoice waiting for
759
+ EXACTLY --amount (minor units, e.g. 125000 = 1,250.00) in --currency matches. --received-at
760
+ is ISO-8601 with an offset (2026-09-28T10:15:00+03:00). --bank-ref is the bank's transaction
761
+ number; one payment per reference. When several items match, name one with --checkout or
762
+ --invoice; an expired checkout is accepted only with --accept-expired --checkout <id>.
763
+ A refused transfer is refunded through the bank. Recording needs confirmation (a prompt on a
764
+ terminal, otherwise --yes): it starts a subscription or pays an invoice.
765
+
766
+ record --rate: a transfer in another currency than the item's (a USD invoice paid with TRY,
767
+ when the product allows it). --rate is the exchange rate you enter: --currency per 1 unit of
768
+ the item's currency, up to 6 decimal places (34.5218). The item matches when --amount is
769
+ within the product's tolerance (fxToleranceBps, default 0.5%) of its amount at that rate, and
770
+ is settled in its own currency. --rate is required for such a transfer and refused for one in
771
+ the item's currency. Steward never looks a rate up.
772
+
773
+ fx-report: the payments received in another currency (invoice number and date, amount settled,
774
+ amount received, the rate entered, received date), latest first; --from (inclusive) and --to
775
+ (exclusive) are ISO-8601 with an offset, by received date. The accountant's input for
776
+ exchange-difference invoices, which steward does not issue.
777
+
778
+ Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
779
+ const WITH_OFFSET = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/;
780
+ async function bankTransfersCommand(ctx, out, args) {
781
+ const [sub, ...rest] = args;
782
+ if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
783
+ out.out(BANK_TRANSFERS_USAGE);
784
+ return sub === void 0 ? 2 : 0;
785
+ }
786
+ if (sub === "list") {
787
+ const { values, positionals } = parse(rest, {
788
+ ...HELP_OPTION,
789
+ status: { type: "string" },
790
+ rate: { type: "string" },
791
+ currency: { type: "string" },
792
+ json: { type: "boolean" }
793
+ }, "bank-transfers");
794
+ if (values.help) return help$2(out);
795
+ expectPositionals(positionals, 0, 0, "bank-transfers");
796
+ const status = values.status ?? "pending";
797
+ if (status !== "pending" && status !== "expired") throw new UsageError("--status: pending or expired");
798
+ const rate = values.rate !== void 0 ? parseRate(values.rate) : void 0;
799
+ if (values.currency !== void 0 && rate === void 0) throw new UsageError("--currency needs --rate");
800
+ const currency = values.currency?.toUpperCase();
801
+ if (currency !== void 0 && !/^[A-Z]{3}$/.test(currency)) throw new UsageError("--currency: an ISO-4217 code (TRY)");
802
+ const preview = {
803
+ ...rate !== void 0 ? { rate } : {},
804
+ ...currency !== void 0 ? { currency } : {}
805
+ };
806
+ const target = requireAdminTarget(await resolveEnv(ctx));
807
+ out.err(connectionLine(target));
808
+ const { items } = await callSteward(target, () => clientFor(ctx, target).admin.bankTransfers.list(status, preview));
809
+ if (values.json) out.out(JSON.stringify(items, null, 2));
810
+ else if (items.length === 0) out.out(`no ${status} bank transfers`);
811
+ else {
812
+ const rows = [[
813
+ "CODE",
814
+ "AMOUNT",
815
+ ...rate !== void 0 ? [`EXPECTED @ ${rate}`] : [],
816
+ "DEADLINE",
817
+ "KIND",
818
+ "PLAN",
819
+ "ACCOUNT",
820
+ "ID"
821
+ ]];
822
+ for (const i of items) rows.push([
823
+ i.code ?? "-",
824
+ formatMinor(i.totalMinor, i.currency),
825
+ ...rate !== void 0 ? [i.expectedMinor !== void 0 && i.expectedCurrency !== void 0 ? formatMinor(i.expectedMinor, i.expectedCurrency) : "-"] : [],
826
+ i.deadline ?? "-",
827
+ i.kind,
828
+ i.planCode ?? "-",
829
+ i.accountRef,
830
+ i.id
831
+ ]);
832
+ for (const line of table(rows)) out.out(line);
833
+ }
834
+ return 0;
835
+ }
836
+ if (sub === "record") {
837
+ const { values, positionals } = parse(rest, {
838
+ ...HELP_OPTION,
839
+ amount: { type: "string" },
840
+ currency: { type: "string" },
841
+ "received-at": { type: "string" },
842
+ "bank-ref": { type: "string" },
843
+ rate: { type: "string" },
844
+ checkout: { type: "string" },
845
+ invoice: { type: "string" },
846
+ "accept-expired": { type: "boolean" },
847
+ yes: {
848
+ type: "boolean",
849
+ short: "y"
850
+ },
851
+ json: { type: "boolean" }
852
+ }, "bank-transfers");
853
+ if (values.help) return help$2(out);
854
+ expectPositionals(positionals, 1, 1, "bank-transfers");
855
+ const receivedAt = requireOption(values["received-at"], "--received-at", "bank-transfers");
856
+ if (!WITH_OFFSET.test(receivedAt)) throw new UsageError("--received-at: ISO-8601 with an offset (2026-09-28T10:15:00+03:00)");
857
+ const input = {
858
+ code: positionals[0],
859
+ amountMinor: parseNonNegativeInt(requireOption(values.amount, "--amount", "bank-transfers"), "--amount"),
860
+ currency: requireOption(values.currency, "--currency", "bank-transfers").toUpperCase(),
861
+ receivedAt,
862
+ bankRef: requireOption(values["bank-ref"], "--bank-ref", "bank-transfers"),
863
+ ...values.rate !== void 0 ? { rate: parseRate(values.rate) } : {},
864
+ ...values.checkout !== void 0 ? { checkoutSessionId: values.checkout } : {},
865
+ ...values.invoice !== void 0 ? { invoiceId: values.invoice } : {},
866
+ ...values["accept-expired"] ? { acceptExpired: true } : {}
867
+ };
868
+ const parsed = BankTransferRecordInputSchema.safeParse(input);
869
+ if (!parsed.success) throw new UsageError(`invalid transfer (nothing was sent)\n${parsed.error.issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(root)"}: ${issue.message}`).join("\n")}`);
870
+ const target = requireAdminTarget(await resolveEnv(ctx));
871
+ out.err(connectionLine(target));
872
+ if (!await confirm(ctx, `Record ${formatMinor(input.amountMinor, input.currency)}${input.rate !== void 0 ? ` at the rate ${input.rate}` : ""} for order code ${input.code} (bank ref ${input.bankRef})?`, {
873
+ yes: values.yes === true,
874
+ notConfirmed: "nothing was recorded"
875
+ })) {
876
+ out.err("not confirmed; nothing was recorded");
877
+ return 1;
878
+ }
879
+ const recorded = await callSteward(target, () => clientFor(ctx, target).admin.bankTransfers.record(input));
880
+ if (values.json) {
881
+ out.out(JSON.stringify(recorded, null, 2));
882
+ return 0;
883
+ }
884
+ const settled = recorded.fxRate !== void 0 && recorded.settledAmountMinor !== void 0 && recorded.settledCurrency !== void 0 ? ` (settled ${formatMinor(recorded.settledAmountMinor, recorded.settledCurrency)} at ${recorded.fxRate})` : "";
885
+ out.out((recorded.invoiceId !== null ? `recorded → ${originOf(target.url)}: account ${recorded.accountRef}, invoice ${recorded.invoiceId} paid${recorded.paidAfterWriteoff ? " (after write-off)" : ""}` : `recorded → ${originOf(target.url)}: account ${recorded.accountRef}, checkout ${recorded.checkoutSessionId} completed, subscription ${recorded.subscriptionId} started${recorded.replacedSubscriptionId !== null ? `, subscription ${recorded.replacedSubscriptionId} replaced` : ""}${recorded.acceptedAfterExpiry ? " (accepted after expiry)" : ""}`) + settled);
886
+ return 0;
887
+ }
888
+ if (sub === "fx-report") {
889
+ const { values, positionals } = parse(rest, {
890
+ ...HELP_OPTION,
891
+ from: { type: "string" },
892
+ to: { type: "string" },
893
+ json: { type: "boolean" },
894
+ csv: { type: "boolean" }
895
+ }, "bank-transfers");
896
+ if (values.help) return help$2(out);
897
+ expectPositionals(positionals, 0, 0, "bank-transfers");
898
+ if (values.json && values.csv) throw new UsageError("--json or --csv, not both");
899
+ if (values.from !== void 0 && !WITH_OFFSET.test(values.from)) throw new UsageError("--from: ISO-8601 with an offset (2026-09-01T00:00:00+03:00)");
900
+ if (values.to !== void 0 && !WITH_OFFSET.test(values.to)) throw new UsageError("--to: ISO-8601 with an offset (2026-10-01T00:00:00+03:00)");
901
+ const range = {
902
+ ...values.from !== void 0 ? { from: values.from } : {},
903
+ ...values.to !== void 0 ? { to: values.to } : {}
904
+ };
905
+ const target = requireAdminTarget(await resolveEnv(ctx));
906
+ out.err(connectionLine(target));
907
+ const { items } = await callSteward(target, () => clientFor(ctx, target).admin.bankTransfers.fxReport(range));
908
+ if (values.json) out.out(JSON.stringify(items, null, 2));
909
+ else if (values.csv) {
910
+ out.out("invoice_number,invoice_date,amount_minor,currency,received_minor,received_currency,fx_rate,received_at,bank_ref,account,payment_id");
911
+ for (const i of items) out.out([
912
+ i.invoiceNumber ?? "",
913
+ i.invoiceIssuedAt ?? "",
914
+ i.amountMinor,
915
+ i.currency,
916
+ i.receivedAmountMinor,
917
+ i.receivedCurrency,
918
+ i.fxRate,
919
+ i.receivedAt,
920
+ i.bankRef,
921
+ i.accountRef,
922
+ i.paymentId
923
+ ].map(csvField).join(","));
924
+ } else if (items.length === 0) out.out("no bank transfers in another currency");
925
+ else {
926
+ const rows = [[
927
+ "INVOICE",
928
+ "INVOICE DATE",
929
+ "AMOUNT",
930
+ "RECEIVED",
931
+ "RATE",
932
+ "RECEIVED AT",
933
+ "BANK REF",
934
+ "ACCOUNT"
935
+ ]];
936
+ for (const i of items) rows.push([
937
+ i.invoiceNumber ?? "-",
938
+ i.invoiceIssuedAt ?? "-",
939
+ formatMinor(i.amountMinor, i.currency),
940
+ formatMinor(i.receivedAmountMinor, i.receivedCurrency),
941
+ i.fxRate,
942
+ i.receivedAt,
943
+ i.bankRef,
944
+ i.accountRef
945
+ ]);
946
+ for (const line of table(rows)) out.out(line);
947
+ }
948
+ return 0;
949
+ }
950
+ throw new UsageError(`unknown subcommand: bank-transfers ${sub} (see: steward bank-transfers --help)`);
951
+ }
952
+ function parseRate(value) {
953
+ if (!FxRateSchema.safeParse(value).success) throw new UsageError("--rate: a positive decimal with at most 6 decimal places (34.5218)");
954
+ return value;
955
+ }
956
+ /** RFC 4180 quoting; a leading = + - @ is prefixed so a spreadsheet does not read the field as a formula. */
957
+ function csvField(value) {
958
+ const text = typeof value === "string" && /^[=+\-@]/.test(value) ? `'${value}` : String(value);
959
+ return /[",\n\r]/.test(text) ? `"${text.replace(/"/g, "\"\"")}"` : text;
960
+ }
961
+ function help$2(out) {
962
+ out.out(BANK_TRANSFERS_USAGE);
963
+ return 0;
964
+ }
965
+ //#endregion
966
+ //#region src/catalog-file.ts
967
+ const MODULE_EXTENSIONS = /* @__PURE__ */ new Set([
968
+ ".js",
969
+ ".mjs",
970
+ ".cjs"
971
+ ]);
972
+ const TS_EXTENSIONS = /* @__PURE__ */ new Set([
973
+ ".ts",
974
+ ".mts",
975
+ ".cts"
976
+ ]);
977
+ const hasSyncInput = (value) => typeof value === "object" && value !== null && typeof value.toSyncInput === "function";
978
+ function pickExport(mod, file) {
979
+ if (mod.catalog !== void 0) return mod.catalog;
980
+ if (mod.default !== void 0) return mod.default;
981
+ const candidates = Object.values(mod).filter(hasSyncInput);
982
+ if (candidates.length === 1) return candidates[0];
983
+ throw new CliError(`${file}: no catalog found — expected \`export const catalog = defineCatalog(…)\` or a default export`);
984
+ }
985
+ async function loadCatalogFile(ctx, file) {
986
+ const path = resolve(ctx.cwd, file);
987
+ const ext = extname(path).toLowerCase();
988
+ let exported;
989
+ if (ext === ".json") {
990
+ let text;
991
+ try {
992
+ text = await readFile(path, "utf8");
993
+ } catch (error) {
994
+ throw new CliError(errnoCode(error) === "ENOENT" ? `catalog file does not exist: ${file}` : `could not read the catalog file: ${file}`);
995
+ }
996
+ try {
997
+ exported = JSON.parse(text);
998
+ } catch {
999
+ throw new CliError(`${file}: not valid JSON`);
1000
+ }
1001
+ } else if (MODULE_EXTENSIONS.has(ext) || TS_EXTENSIONS.has(ext)) {
1002
+ if (TS_EXTENSIONS.has(ext) && !ctx.typescript) throw new CliError(`${file}: this Node version cannot load a TypeScript file directly (${process.version}). Use Node ≥ 22.18, set \`NODE_OPTIONS=--experimental-strip-types\` or export the catalog as .mjs/.json.`);
1003
+ let mod;
1004
+ try {
1005
+ await readFile(path);
1006
+ } catch (error) {
1007
+ throw new CliError(errnoCode(error) === "ENOENT" ? `catalog file does not exist: ${file}` : `could not read the catalog file: ${file}`);
1008
+ }
1009
+ try {
1010
+ mod = await ctx.importModule(pathToFileURL(path).href);
1011
+ } catch (error) {
1012
+ throw new CliError(`could not load ${file}: ${error instanceof Error ? error.message : String(error)}`);
1013
+ }
1014
+ exported = pickExport(mod, file);
1015
+ } else throw new UsageError(`the catalog file must be .ts, .mts, .js, .mjs, .cjs or .json: ${file}`);
1016
+ let input;
1017
+ try {
1018
+ input = hasSyncInput(exported) ? exported.toSyncInput() : exported;
1019
+ } catch (error) {
1020
+ throw new CliError(`${file}: toSyncInput() failed: ${error instanceof Error ? error.message : String(error)}`);
1021
+ }
1022
+ const parsed = CatalogSyncInputSchema.safeParse(input);
1023
+ if (!parsed.success) throw new CliError(`${file}: invalid catalog (no request was sent)\n${parsed.error.issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(root)"}: ${issue.message}`).join("\n")}`);
1024
+ return input;
1025
+ }
1026
+ //#endregion
1027
+ //#region src/commands/catalog.ts
1028
+ const CATALOG_USAGE = `Usage: steward catalog push <file> [--yes]
1029
+
1030
+ Syncs the catalog definition to steward (PUT /v1/admin/catalog), then prints the version
1031
+ and the counts. File: .ts/.mts (Node type stripping, Node ≥ 22.18), .js/.mjs/.cjs
1032
+ (\`export const catalog = defineCatalog(…)\` or a default export) or .json
1033
+ (the sync body). No request is sent for an invalid catalog.
1034
+
1035
+ Before pushing, prints what changes against steward's current catalog: benefits
1036
+ (new, changed, archived, plan benefit lists) and prices (new, deactivated, amount or
1037
+ tax terms changed). A changed price is updated in place: existing subscriptions keep
1038
+ the amount they locked, new subscriptions pay the new amount, a tax change applies to
1039
+ every invoice written from now on. Price changes need confirmation: a prompt on a
1040
+ terminal, otherwise --yes (-y). A catalog with benefits is pushed only to a steward
1041
+ whose GET /v1/me lists the "benefits" capability (an older steward would drop them).
1042
+
1043
+ Metering: the diff also lists meters (new, changed, rule changed, archived), changed
1044
+ credits (meter_credit benefits) and metered prices (new, deactivated, changed; a
1045
+ changed metered price needs the same confirmation). A meter's filter and aggregation
1046
+ are fixed once it has counted a period (422 meter_locked: use a new meter code). A
1047
+ catalog with meters or metered prices is pushed only to a steward whose GET /v1/me
1048
+ lists the "meters" capability.
1049
+
1050
+ Unlisted plans: a plan with "listed: false" is sellable but not offered in the hosted
1051
+ portal's "Change plan"; the diff shows a plan that becomes unlisted or listed. Such a
1052
+ catalog is pushed only to a steward whose GET /v1/me lists the "unlisted_plans"
1053
+ capability (an older steward would offer the plan).
1054
+
1055
+ Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).
1056
+ Exit code 1: a price could not be created at the provider (run the sync again);
1057
+ the push was refused or not confirmed.`;
1058
+ const PUSH_OPTIONS = {
1059
+ ...HELP_OPTION,
1060
+ yes: {
1061
+ type: "boolean",
1062
+ short: "y"
1063
+ }
1064
+ };
1065
+ const list = (items) => items.length > 0 ? items.join(", ") : "-";
1066
+ /** Sync + version read; the summary lines and whether there were provider errors. */
1067
+ async function pushCatalog(steward, target, input) {
1068
+ const result = await callSteward(target, () => steward.admin.catalog.sync(input));
1069
+ const version = (await callSteward(target, () => steward.catalog.read())).etag?.replace(/^W\//, "").replace(/"/g, "") ?? "unknown";
1070
+ const benefitCount = Object.keys(input.benefits ?? {}).length;
1071
+ const meterCount = Object.keys(input.meters ?? {}).length;
1072
+ const meteredCount = (input.meteredPrices ?? []).length;
1073
+ const metering = `${meterCount > 0 ? ` · ${meterCount} meter${meterCount === 1 ? "" : "s"}` : ""}${meteredCount > 0 ? ` · ${meteredCount} metered price${meteredCount === 1 ? "" : "s"}` : ""}`;
1074
+ const lines = [`catalog synced → ${originOf(target.url)}`];
1075
+ lines.push(` version ${version}`);
1076
+ lines.push(` defines ${input.plans.length} plan${input.plans.length === 1 ? "" : "s"} · ${input.features.length} feature${input.features.length === 1 ? "" : "s"} · ${input.prices.length} price${input.prices.length === 1 ? "" : "s"}${benefitCount > 0 ? ` · ${benefitCount} benefit${benefitCount === 1 ? "" : "s"}` : ""}${metering} · default plan ${input.defaultPlanCode}`);
1077
+ if (result.unchanged) lines.push(" changes none");
1078
+ else {
1079
+ lines.push(` changes new prices ${result.createdPrices.length} · deactivated prices ${result.deactivatedPrices.length} · changed plans: ${list(result.changedPlans)} · retired plans: ${list(result.retiredPlans)} · removed features: ${list(result.removedFeatures)}${result.defaultPlanChanged ? " · default plan changed" : ""}`);
1080
+ const changedBenefits = result.changedBenefits ?? [];
1081
+ const archivedBenefits = result.archivedBenefits ?? [];
1082
+ if (changedBenefits.length > 0 || archivedBenefits.length > 0) lines.push(` benefits changed: ${list(changedBenefits)} · archived: ${list(archivedBenefits)}`);
1083
+ if ((result.updatedPrices ?? []).length > 0) lines.push(` prices updated in place: ${result.updatedPrices.length}`);
1084
+ const changedMeters = result.changedMeters ?? [];
1085
+ const archivedMeters = result.archivedMeters ?? [];
1086
+ if (changedMeters.length > 0 || archivedMeters.length > 0) lines.push(` meters changed: ${list(changedMeters)} · archived: ${list(archivedMeters)}`);
1087
+ const [created, updated, deactivated] = [
1088
+ result.createdMeteredPrices ?? [],
1089
+ result.updatedMeteredPrices ?? [],
1090
+ result.deactivatedMeteredPrices ?? []
1091
+ ];
1092
+ if (created.length + updated.length + deactivated.length > 0) lines.push(` metered new ${created.length} · updated in place ${updated.length} · deactivated ${deactivated.length}`);
1093
+ }
1094
+ for (const error of result.providerErrors) lines.push(` ✗ provider error: price ${error.priceId} (${error.provider}: ${error.code}) — run the sync again`);
1095
+ return {
1096
+ lines,
1097
+ providerErrors: result.providerErrors.length
1098
+ };
1099
+ }
1100
+ /** The steward's current catalog; null before the first push (`404 catalog_not_configured`). */
1101
+ function currentCatalog(steward, target) {
1102
+ return callSteward(target, () => steward.catalog.get().catch((error) => {
1103
+ if (error instanceof StewardApiError && error.httpStatus === 404 && error.code === "catalog_not_configured") return null;
1104
+ throw error;
1105
+ }));
1106
+ }
1107
+ /** What the catalog defines, per capability it needs (the refusal names it). */
1108
+ const CAPABILITY_LABELS = {
1109
+ benefits: "benefits",
1110
+ meters: "meters",
1111
+ unlisted_plans: "unlisted plans"
1112
+ };
1113
+ /**
1114
+ * Refuses a catalog whose benefits, meters or unlisted plans steward does not understand (M27): an
1115
+ * older steward drops the keys silently. `needed`: the capabilities the catalog needs.
1116
+ */
1117
+ async function requireCapabilities(steward, target, needed) {
1118
+ if (needed.length === 0) return;
1119
+ const me = await callSteward(target, () => steward.me());
1120
+ const missing = needed.filter((capability) => !(me.capabilities ?? []).includes(capability));
1121
+ if (missing.length === 0) return;
1122
+ throw new CliError(`the catalog defines ${missing.map((c) => CAPABILITY_LABELS[c]).join(" and ")} but steward at ${originOf(target.url)} does not support them (GET /v1/me capabilities has no ${missing.map((c) => `"${c}"`).join(", ")}; it would drop them silently). Update steward first; nothing was pushed.`);
1123
+ }
1124
+ async function catalogCommand(ctx, out, args) {
1125
+ const [sub, ...rest] = args;
1126
+ if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
1127
+ out.out(CATALOG_USAGE);
1128
+ return sub === void 0 ? 2 : 0;
1129
+ }
1130
+ if (sub !== "push") throw new UsageError(`unknown subcommand: catalog ${sub} (details: steward catalog --help)`);
1131
+ const { values, positionals } = parse(rest, PUSH_OPTIONS, "catalog push");
1132
+ if (values.help) {
1133
+ out.out(CATALOG_USAGE);
1134
+ return 0;
1135
+ }
1136
+ expectPositionals(positionals, 1, 1, "catalog push");
1137
+ const input = await loadCatalogFile(ctx, positionals[0]);
1138
+ const target = requireAdminTarget(await resolveEnv(ctx));
1139
+ out.err(connectionLine(target));
1140
+ const steward = clientFor(ctx, target);
1141
+ await requireCapabilities(steward, target, [
1142
+ ...definesBenefits(input) ? ["benefits"] : [],
1143
+ ...definesMeters(input) ? ["meters"] : [],
1144
+ ...definesUnlistedPlans(input) ? ["unlisted_plans"] : []
1145
+ ]);
1146
+ const diff = diffCatalog(await currentCatalog(steward, target), input);
1147
+ for (const line of describeDiff(diff)) out.out(line);
1148
+ const priceChanges = priceChangeCount(diff);
1149
+ if (priceChanges > 0 && !values.yes) {
1150
+ const question = `Apply ${priceChanges} price change${priceChanges === 1 ? "" : "s"}? [y/N] `;
1151
+ const answer = await ctx.prompt(question);
1152
+ if (answer === null) throw new CliError(`${priceChanges} price change${priceChanges === 1 ? "" : "s"} need${priceChanges === 1 ? "s" : ""} confirmation: run again with --yes (nothing was pushed)`);
1153
+ if (!/^y(es)?$/i.test(answer.trim())) {
1154
+ out.err("not confirmed; nothing was pushed");
1155
+ return 1;
1156
+ }
1157
+ }
1158
+ const { lines, providerErrors } = await pushCatalog(steward, target, input);
1159
+ for (const line of lines) out.out(line);
1160
+ return providerErrors > 0 ? 1 : 0;
1161
+ }
1162
+ //#endregion
1163
+ //#region src/commands/meters.ts
1164
+ const METERS_USAGE = `Usage:
1165
+ steward meters get <ref> [--periods <n>] [--json]
1166
+ steward meters recompute <ref> [--meter <code>] [--json]
1167
+ steward meters close-periods <ref> [--meter <code>] [--force] [--json]
1168
+
1169
+ Reads an account's meters (GET /v1/accounts/:ref/meters): per meter the current usage
1170
+ period, units used, the period's credit, the balance, the standing (ok | low | exhausted)
1171
+ and, for a billable meter, the estimated overage so far. Nothing is written.
1172
+
1173
+ --periods <n> also list the last n closed periods (1–100; GET …/meters/periods)
1174
+ --json print the response as JSON
1175
+
1176
+ recompute (admin): rebuilds the account's OPEN usage period of every meter (or --meter) from
1177
+ the raw events, the repair of a wrongly counted period. Closed periods never change; running it
1178
+ again gives the same result. Prints each meter's consumption before and after.
1179
+
1180
+ close-periods (admin): closes the account's closing periods now instead of after the late
1181
+ window (recount from raw events, meter.period_closed). It waits for unrolled events unless
1182
+ --force (those then count in a later period as late). Open periods are never touched.
1183
+
1184
+ Connection: get uses STEWARD_URL + STEWARD_API_KEY (or, when neither is set, STEWARD_ADMIN_URL +
1185
+ STEWARD_ADMIN_API_KEY); recompute and close-periods use STEWARD_ADMIN_URL +
1186
+ STEWARD_ADMIN_API_KEY. Environment, otherwise ./.env.local.`;
1187
+ const REPAIR_OPTIONS = {
1188
+ ...HELP_OPTION,
1189
+ meter: { type: "string" },
1190
+ force: { type: "boolean" },
1191
+ json: { type: "boolean" }
1192
+ };
1193
+ async function repairCommand(ctx, out, sub, args) {
1194
+ const { values, positionals } = parse(args, REPAIR_OPTIONS, "meters");
1195
+ if (values.help) {
1196
+ out.out(METERS_USAGE);
1197
+ return 0;
1198
+ }
1199
+ expectPositionals(positionals, 1, 1, "meters");
1200
+ if (sub === "recompute" && values.force) throw new UsageError("--force is for close-periods");
1201
+ const ref = positionals[0];
1202
+ const meter = values.meter !== void 0 ? { meter: values.meter } : {};
1203
+ const target = requireAdminTarget(await resolveEnv(ctx));
1204
+ out.err(connectionLine(target));
1205
+ const steward = clientFor(ctx, target);
1206
+ if (sub === "recompute") {
1207
+ const result = await callSteward(target, () => steward.admin.meters.recompute(ref, meter));
1208
+ if (values.json) out.out(JSON.stringify(result, null, 2));
1209
+ else for (const item of result.items) out.out(item.periodStart === null ? ` ${item.meter} no open period` : ` ${item.meter} ${item.periodStart} → ${item.periodEnd} ${item.before} → ${item.after}`);
1210
+ return 0;
1211
+ }
1212
+ const result = await callSteward(target, () => steward.admin.meters.closePeriods(ref, {
1213
+ ...meter,
1214
+ ...values.force ? { force: true } : {}
1215
+ }));
1216
+ if (values.json) out.out(JSON.stringify(result, null, 2));
1217
+ else out.out(`${result.closed} period(s) closed, ${result.events} meter.period_closed event(s); ${result.pending} closing period(s) left`);
1218
+ return 0;
1219
+ }
1220
+ const GET_OPTIONS = {
1221
+ ...HELP_OPTION,
1222
+ periods: { type: "string" },
1223
+ json: { type: "boolean" }
1224
+ };
1225
+ /** Units of a meter read (a JSON number with at most 6 decimals) as exact text with grouping: `1,700,000.5`. */
1226
+ function formatUnitsText(value) {
1227
+ return new Intl.NumberFormat("en", { maximumFractionDigits: 6 }).format(plainDecimalOf(value));
1228
+ }
1229
+ function meterLines(code, meter, width) {
1230
+ const lines = [` ${code.padEnd(width)} ${meter.periodStart} → ${meter.periodEnd}`];
1231
+ const indent = " ".repeat(width + 4);
1232
+ lines.push(`${indent}used ${formatUnitsText(meter.consumedUnits)} · credit ${formatUnitsText(meter.creditedUnits)} · balance ${formatUnitsText(meter.balance)} · standing ${meter.standing}`);
1233
+ const included = meter.includedUnits === null ? "no credit included" : `included ${formatUnitsText(meter.includedUnits)} per period`;
1234
+ const billing = meter.billable && meter.amountDueMinor !== null && meter.currency !== null ? `billable: ${formatUnitsText(meter.overageUnits)} over the credit, estimated overage ${formatMinor(meter.amountDueMinor, meter.currency)}` : "not billable (no metered price)";
1235
+ lines.push(`${indent}${included} · ${billing}`);
1236
+ return lines;
1237
+ }
1238
+ /** Human-readable meter read (+ closed periods, newest first). */
1239
+ function formatMeters(meters, periods) {
1240
+ const lines = [`meters of ${meters.ref} · as of ${meters.asOf} · events received before ${meters.rolledUpThrough} are counted`];
1241
+ const codes = Object.keys(meters.meters);
1242
+ if (codes.length === 0) lines.push(" no meters (the product's catalog defines none)");
1243
+ else {
1244
+ const width = Math.max(...codes.map((code) => code.length));
1245
+ for (const code of codes) lines.push(...meterLines(code, meters.meters[code], width));
1246
+ }
1247
+ if (periods !== null) {
1248
+ lines.push("");
1249
+ if (periods.length === 0) lines.push("closed periods: none");
1250
+ else {
1251
+ lines.push("closed periods (newest first):");
1252
+ const width = Math.max(...periods.map((p) => p.meter.length));
1253
+ for (const period of periods) lines.push(` ${period.meter.padEnd(width)} ${period.periodStart} → ${period.periodEnd} used ${formatUnitsText(period.consumedUnits)} · credit ${formatUnitsText(period.creditedUnits)} · over ${formatUnitsText(period.overageUnits)}`);
1254
+ }
1255
+ }
1256
+ return lines;
1257
+ }
1258
+ async function metersCommand(ctx, out, args) {
1259
+ const [sub, ...rest] = args;
1260
+ if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
1261
+ out.out(METERS_USAGE);
1262
+ return sub === void 0 ? 2 : 0;
1263
+ }
1264
+ if (sub === "recompute" || sub === "close-periods") return repairCommand(ctx, out, sub, rest);
1265
+ if (sub !== "get") throw new UsageError(`unknown subcommand: meters ${sub} (see: steward meters --help)`);
1266
+ const { values, positionals } = parse(rest, GET_OPTIONS, "meters");
1267
+ if (values.help) {
1268
+ out.out(METERS_USAGE);
1269
+ return 0;
1270
+ }
1271
+ expectPositionals(positionals, 1, 1, "meters");
1272
+ const ref = positionals[0];
1273
+ const limit = values.periods === void 0 ? null : parsePositiveInt(values.periods, "--periods", { max: 100 });
1274
+ const target = requireReadTarget(await resolveEnv(ctx));
1275
+ out.err(connectionLine(target));
1276
+ const steward = clientFor(ctx, target);
1277
+ const meters = await callSteward(target, () => steward.meters.get(ref));
1278
+ const periods = limit === null ? null : (await callSteward(target, () => steward.meters.periods(ref, { limit }))).periods;
1279
+ if (values.json) out.out(JSON.stringify(periods === null ? meters : {
1280
+ ...meters,
1281
+ closedPeriods: periods
1282
+ }, null, 2));
1283
+ else for (const line of formatMeters(meters, periods)) out.out(line);
1284
+ return 0;
1285
+ }
1286
+ //#endregion
1287
+ //#region src/commands/credits.ts
1288
+ const CREDITS_USAGE = `Usage: steward credits adjust <ref> <meter> --units=<n> --reason <text> [--json]
1289
+
1290
+ One credit ledger entry for the meter's current usage period of account <ref>
1291
+ (POST /v1/admin/accounts/:ref/credits). Positive units add credit (manual_grant), negative
1292
+ units take it back (adjustment, e.g. events sent by mistake). Write a negative value with
1293
+ "=": --units=-2500. Units: a non-zero decimal with at most 6 places. --reason: 3–500
1294
+ characters, kept on the entry. Entries are never rewritten: a wrong one is corrected by
1295
+ another entry.
1296
+
1297
+ Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
1298
+ const UNITS = /^-?\d{1,16}(\.\d{1,6})?$/;
1299
+ async function creditsCommand(ctx, out, args) {
1300
+ const [sub, ...rest] = args;
1301
+ if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
1302
+ out.out(CREDITS_USAGE);
1303
+ return sub === void 0 ? 2 : 0;
1304
+ }
1305
+ if (sub !== "adjust") throw new UsageError(`unknown subcommand: credits ${sub} (see: steward credits --help)`);
1306
+ const { values, positionals } = parse(rest, {
1307
+ ...HELP_OPTION,
1308
+ units: { type: "string" },
1309
+ reason: { type: "string" },
1310
+ json: { type: "boolean" }
1311
+ }, "credits");
1312
+ if (values.help) {
1313
+ out.out(CREDITS_USAGE);
1314
+ return 0;
1315
+ }
1316
+ expectPositionals(positionals, 2, 2, "credits");
1317
+ const [ref, meter] = positionals;
1318
+ const unitsText = requireOption(values.units, "--units", "credits").trim();
1319
+ if (!UNITS.test(unitsText)) throw new UsageError(`--units: a decimal with at most 6 places, got ${unitsText}`);
1320
+ const input = {
1321
+ meter,
1322
+ units: Number(unitsText),
1323
+ reason: requireOption(values.reason, "--reason", "credits")
1324
+ };
1325
+ const parsed = CreditAdjustmentInputSchema.safeParse(input);
1326
+ if (!parsed.success) throw new UsageError(`invalid credit entry (nothing was sent)\n${parsed.error.issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(root)"}: ${issue.message}`).join("\n")}`);
1327
+ const target = requireAdminTarget(await resolveEnv(ctx));
1328
+ out.err(connectionLine(target));
1329
+ const result = await callSteward(target, () => clientFor(ctx, target).admin.credits.adjust(ref, parsed.data));
1330
+ if (values.json) {
1331
+ out.out(JSON.stringify(result, null, 2));
1332
+ return 0;
1333
+ }
1334
+ const { entry } = result;
1335
+ out.out(`${entry.kind} of ${formatUnitsText(entry.units)} ${entry.meter} written → ${originOf(target.url)} (period from ${entry.periodStart})`);
1336
+ const read = result.meters.meters[entry.meter];
1337
+ if (read !== void 0) out.out(` balance ${formatUnitsText(read.balance)} · standing ${read.standing}`);
1338
+ return 0;
1339
+ }
1340
+ //#endregion
1341
+ //#region src/commands/doctor.ts
1342
+ const DOCTOR_USAGE = `Usage: steward doctor [--json]
1343
+
1344
+ The GET /v1/doctor report. Sections in order: status, catalog, provider, settings,
1345
+ hosted (page readiness), endpoints (delivery diagnosis), dunning, emails and, for a
1346
+ product with meters, metering/events/overage; at the end the errors, warnings and info
1347
+ lists. If APP_URL is set it is compared with steward's appUrl and allowed return
1348
+ origins.
1349
+
1350
+ Connection: STEWARD_URL + STEWARD_API_KEY (if both are missing, STEWARD_ADMIN_URL +
1351
+ STEWARD_ADMIN_API_KEY). If even one steward connection variable is in the
1352
+ environment, the connection and APP_URL are read only from the environment
1353
+ (./.env.local is not read); otherwise from ./.env.local. The source and the target's
1354
+ origin are written to stderr.
1355
+
1356
+ Exit code: 0 ready; 1 the report is not ok (a warning of error severity) or APP_URL
1357
+ is not allowed in steward.
1358
+
1359
+ Metering: for a product whose catalog defines meters, the "metering" line shows the
1360
+ meters and metered prices (GET /v1/catalog) and steward's capabilities (GET /v1/me:
1361
+ events, meters, overage); then come the report's "events" section (pending events,
1362
+ rollup lag, a sample of the last 7 days: unmatched event names, invalid values,
1363
+ meters without events) and "overage" section (charge mode, metered prices,
1364
+ subscriptions without a locked rate, carried charges). Metering warnings are in the
1365
+ lists below as usual.
1366
+
1367
+ --json writes the report as JSON (+ cliWarnings: the local APP_URL comparison;
1368
+ cliMetering: the catalog and capability facts of the metering line)`;
1369
+ /** `APP_URL` (the product's own address; the checkout `successUrl` is built from it) ↔ steward settings. */
1370
+ function appUrlWarnings(appUrl, report) {
1371
+ if (appUrl === void 0) return [];
1372
+ let origin;
1373
+ try {
1374
+ origin = new URL(appUrl).origin;
1375
+ } catch {
1376
+ return [{
1377
+ code: "app_url_env_invalid",
1378
+ severity: "error",
1379
+ message: "APP_URL is not a valid address"
1380
+ }];
1381
+ }
1382
+ if (!report.settings.returnOrigins.includes(origin)) return [{
1383
+ code: "app_url_not_allowed",
1384
+ severity: "error",
1385
+ message: `APP_URL origin (${origin}) is not an allowed return origin in steward (appUrl: ${report.settings.appUrl ?? "none"}): checkout gets return_url_not_allowed — steward settings set --app-url ${origin}`
1386
+ }];
1387
+ if (report.settings.appUrl !== null && originOf(report.settings.appUrl) !== origin) return [{
1388
+ code: "app_url_mismatch",
1389
+ severity: "warning",
1390
+ message: `APP_URL (${origin}) differs from steward's appUrl (${report.settings.appUrl}): the hosted page's "back to product" link goes to appUrl`
1391
+ }];
1392
+ return [];
1393
+ }
1394
+ /** The capabilities the metering section shows (M27). */
1395
+ const METERING_CAPABILITIES = [
1396
+ "events",
1397
+ "meters",
1398
+ "overage"
1399
+ ];
1400
+ /**
1401
+ * The metering section's facts: the catalog's meters and metered prices and steward's capabilities.
1402
+ * Null when the catalog carries no meters (a product that never defined one, an older steward, no
1403
+ * catalog yet) or cannot be read: the section is informational and never fails the doctor.
1404
+ */
1405
+ async function meteringSummary(steward) {
1406
+ try {
1407
+ const catalog = await steward.catalog.get();
1408
+ if (catalog.meters === void 0) return null;
1409
+ const me = await steward.me().catch(() => null);
1410
+ return {
1411
+ meters: Object.keys(catalog.meters),
1412
+ meteredPrices: (catalog.meteredPrices ?? []).length,
1413
+ capabilities: me?.capabilities ?? null
1414
+ };
1415
+ } catch {
1416
+ return null;
1417
+ }
1418
+ }
1419
+ const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
1420
+ /** `name (count), …` of a sample list. */
1421
+ const counted = (items, key) => items.map((item) => `${item[key]} (${item.events})`).join(", ");
1422
+ /**
1423
+ * Lines of the metering sections: the CLI's catalog and capability facts (`metering`), then the
783
1424
  * report's own `events` and `overage` sections when steward sends them (a product with meters or
784
1425
  * metered prices; older steward sends neither).
785
1426
  */
@@ -817,9 +1458,9 @@ const SEVERITY_ORDER = [
817
1458
  "info"
818
1459
  ];
819
1460
  const SEVERITY_TITLE = {
820
- error: "hatalar",
821
- warning: "uyarılar",
822
- info: "bilgi"
1461
+ error: "errors",
1462
+ warning: "warnings",
1463
+ info: "info"
823
1464
  };
824
1465
  const yesNo = (value) => value ? "✓" : "✗";
825
1466
  function countBySeverity(warnings) {
@@ -828,40 +1469,47 @@ function countBySeverity(warnings) {
828
1469
  warnings: warnings.filter((w) => w.severity === "warning").length
829
1470
  };
830
1471
  }
831
- /** Tam insan okunur rapor. */
1472
+ /** The full human-readable report. */
832
1473
  function formatDoctorReport(report, cliWarnings, metering = null) {
833
1474
  const all = [...report.warnings, ...cliWarnings];
834
1475
  const { errors, warnings } = countBySeverity(all);
835
1476
  const ready = errors === 0;
836
1477
  const lines = [];
837
1478
  lines.push(`steward doctor — ${report.product.code} (${report.product.name}) · ${report.checkedAt}`);
838
- lines.push(`durum ${ready ? "HAZIR ✓" : "SORUN VAR ✗"} (${errors} hata, ${warnings} uyarı)`);
1479
+ lines.push(`status ${ready ? "READY ✓" : "PROBLEMS ✗"} (${plural(errors, "error")}, ${plural(warnings, "warning")})`);
839
1480
  lines.push("");
840
1481
  const { catalog, provider, settings, hosted } = report;
841
- lines.push(`katalog senkron ${yesNo(catalog.synced)}${catalog.version !== null ? ` · sürüm ${catalog.version}` : ""} · ${catalog.plans} plan · ${catalog.sellablePrices} satılabilir fiyat · ${catalog.unsellablePrices.length} satılamaz`);
1482
+ lines.push(`catalog synced ${yesNo(catalog.synced)}${catalog.version !== null ? ` · version ${catalog.version}` : ""} · ${plural(catalog.plans, "plan")} · ${plural(catalog.sellablePrices, "sellable price")} · ${catalog.unsellablePrices.length} unsellable`);
842
1483
  for (const price of catalog.unsellablePrices) lines.push(` ✗ ${price.planCode} ${price.interval}×${price.intervalCount} ${price.currency}: ${price.reason}`);
843
- const providerState = !provider.configured ? "yapılandırılmamış ✗" : provider.healthy === false ? "erişilemiyor !" : "yapılandırılmış ✓";
844
- const providerError = provider.lastError ? ` · son hata ${provider.lastError.code} (${provider.lastError.operation}, ${provider.lastError.at})` : "";
845
- lines.push(`sağlayıcı ${provider.id}${provider.environment !== null ? ` · ${provider.environment}` : ""} · ${providerState}${providerError}`);
846
- lines.push(`ayarlar appUrl ${settings.appUrl ?? "yok"} · dönüş origin'leri: ${settings.returnOrigins.length > 0 ? settings.returnOrigins.join(", ") : "yok"}`);
1484
+ const providerState = !provider.configured ? "not configured ✗" : provider.healthy === false ? "unreachable !" : "configured ✓";
1485
+ const providerError = provider.lastError ? ` · last error ${provider.lastError.code} (${provider.lastError.operation}, ${provider.lastError.at})` : "";
1486
+ lines.push(`provider ${provider.id}${provider.environment !== null ? ` · ${provider.environment}` : ""} · ${providerState}${providerError}`);
1487
+ lines.push(`settings appUrl ${settings.appUrl ?? "none"} · return origins: ${settings.returnOrigins.length > 0 ? settings.returnOrigins.join(", ") : "none"}`);
847
1488
  const missing = [...hosted.branding.missing.map((field) => `branding.${field}`), ...hosted.legalLinks.missing];
848
- lines.push(`hosted ${hosted.ready ? "hazır ✓" : `hazır değil ✗${missing.length > 0 ? ` (eksik: ${missing.join(", ")})` : ""}`}`);
849
- if (report.endpoints.length === 0) lines.push("endpoint'ler yok");
1489
+ lines.push(`hosted ${hosted.ready ? "ready ✓" : `not ready ✗${missing.length > 0 ? ` (missing: ${missing.join(", ")})` : ""}`}`);
1490
+ if (report.endpoints.length === 0) lines.push("endpoints none");
850
1491
  else {
851
- lines.push("endpoint'ler");
1492
+ lines.push("endpoints");
852
1493
  for (const endpoint of report.endpoints) {
853
- const types = endpoint.eventTypes === null ? "filtre yok (0.1 tipleri)" : endpoint.eventTypes.join(",");
854
- const last = endpoint.lastDelivery ? ` · son teslimat ${endpoint.lastDelivery.status}${endpoint.lastDelivery.httpStatus !== null ? ` ${endpoint.lastDelivery.httpStatus}` : ""}` : "";
855
- lines.push(` ${endpoint.id} ${endpoint.status} ${endpoint.diagnosis} ${endpoint.url} [${types}] · bekleyen ${endpoint.pending} · dead ${endpoint.dead}${last}`);
1494
+ const types = endpoint.eventTypes === null ? "no filter (0.1 types)" : endpoint.eventTypes.join(",");
1495
+ const last = endpoint.lastDelivery ? ` · last delivery ${endpoint.lastDelivery.status}${endpoint.lastDelivery.httpStatus !== null ? ` ${endpoint.lastDelivery.httpStatus}` : ""}` : "";
1496
+ lines.push(` ${endpoint.id} ${endpoint.status} ${endpoint.diagnosis} ${endpoint.url} [${types}] · pending ${endpoint.pending} · dead ${endpoint.dead}${last}`);
856
1497
  }
857
1498
  }
858
- lines.push(`dunning ${report.dunning.dryRun ? "dry-run (askı/sonlandırma uygulanmaz)" : "etkin"}`);
1499
+ lines.push(`dunning ${report.dunning.dryRun ? "dry-run (no suspension/termination)" : "active"}`);
859
1500
  if (report.emails) {
860
1501
  const { emails } = report;
861
1502
  const problems = [...emails.transportConfigured ? [] : ["no transport"], ...emails.senderConfigured ? [] : ["no sender"]];
862
1503
  const disabled = emails.disabledTemplates.length > 0 ? ` · disabled: ${emails.disabledTemplates.join(", ")}` : "";
863
1504
  lines.push(`emails ${emails.ready ? "ready ✓" : `not sending ✗${problems.length > 0 ? ` (${problems.join(", ")})` : ""}`}${disabled}`);
864
1505
  }
1506
+ if (report.apiKeys) {
1507
+ lines.push(report.apiKeys.length === 0 ? "api keys none active" : "api keys");
1508
+ for (const key of report.apiKeys) {
1509
+ const expiry = key.expiresAt === null ? "never expires" : `expires ${key.expiresAt}`;
1510
+ lines.push(` ${key.prefix} ${key.scope} ${key.name} · ${key.ageDays} day(s) old · last used ${key.lastUsedAt ?? "never"} · ${expiry}`);
1511
+ }
1512
+ }
865
1513
  lines.push(...formatMetering(report, metering));
866
1514
  for (const severity of SEVERITY_ORDER) {
867
1515
  const items = all.filter((w) => w.severity === severity);
@@ -876,232 +1524,120 @@ function formatDoctorReport(report, cliWarnings, metering = null) {
876
1524
  return lines;
877
1525
  }
878
1526
  async function doctorCommand(ctx, out, args) {
879
- const { values, positionals } = parse(args, {
880
- ...HELP_OPTION,
881
- json: { type: "boolean" }
882
- }, "doctor");
883
- if (values.help) {
884
- out.out(DOCTOR_USAGE);
885
- return 0;
886
- }
887
- expectPositionals(positionals, 0, 0, "doctor");
888
- const env = await resolveEnv(ctx);
889
- const target = requireReadTarget(env);
890
- const appUrl = env.get("APP_URL");
891
- out.err(connectionLine(target));
892
- if (appUrl === void 0) out.err(`APP_URL tanımlı değil (${env.source}): steward appUrl karşılaştırması atlandı`);
893
- const steward = clientFor(ctx, target);
894
- const report = await callSteward(target, () => steward.doctor());
895
- const cliWarnings = appUrlWarnings(appUrl, report);
896
- const failed = !report.ok || cliWarnings.some((w) => w.severity === "error");
897
- const metering = await meteringSummary(steward);
898
- if (values.json) out.out(JSON.stringify({
899
- ...report,
900
- cliWarnings,
901
- ...metering !== null ? { cliMetering: metering } : {}
902
- }, null, 2));
903
- else for (const line of formatDoctorReport(report, cliWarnings, metering)) out.out(line);
904
- return failed ? 1 : 0;
905
- }
906
- //#endregion
907
- //#region src/secret-file.ts
908
- async function withSecretFile(cwd, out, secret, options, action) {
909
- const target = resolve(cwd, out);
910
- try {
911
- if ((await lstat(target)).isDirectory()) throw new CliError(`--out bir klasör: ${out}`);
912
- if (!options.force) throw new CliError(`${out} zaten var; üzerine yazmak için --force (istek gönderilmedi)`);
913
- } catch (error) {
914
- if (error instanceof CliError) throw error;
915
- if (errnoCode(error) !== "ENOENT") throw error;
916
- }
917
- const temp = join(dirname(target), `.${basename(target)}.${randomUUID().slice(0, 8)}.tmp`);
918
- try {
919
- await writeFile(temp, secret, {
920
- mode: 384,
921
- flag: "wx"
922
- });
923
- } catch (error) {
924
- const code = errnoCode(error);
925
- if (code === "ENOENT") throw new CliError(`--out klasörü yok: ${relative(cwd, dirname(target)) || "."}`);
926
- throw new CliError(`sır dosyası yazılamadı (${code ?? "hata"}): ${out} (istek gönderilmedi)`);
927
- }
928
- let value;
929
- try {
930
- value = await action();
931
- } catch (error) {
932
- await unlink(temp).catch(() => {});
933
- throw error;
934
- }
935
- try {
936
- if (options.force) await rename(temp, target);
937
- else {
938
- await link(temp, target);
939
- await unlink(temp).catch(() => {});
940
- }
941
- return {
942
- value,
943
- path: out,
944
- fallback: false
945
- };
946
- } catch {
947
- return {
948
- value,
949
- path: relative(cwd, temp),
950
- fallback: true
951
- };
1527
+ const { values, positionals } = parse(args, {
1528
+ ...HELP_OPTION,
1529
+ json: { type: "boolean" }
1530
+ }, "doctor");
1531
+ if (values.help) {
1532
+ out.out(DOCTOR_USAGE);
1533
+ return 0;
952
1534
  }
1535
+ expectPositionals(positionals, 0, 0, "doctor");
1536
+ const env = await resolveEnv(ctx);
1537
+ const target = requireReadTarget(env);
1538
+ const appUrl = env.get("APP_URL");
1539
+ out.err(connectionLine(target));
1540
+ if (appUrl === void 0) out.err(`APP_URL not set (${env.source}): skipped the steward appUrl comparison`);
1541
+ const steward = clientFor(ctx, target);
1542
+ const report = await callSteward(target, () => steward.doctor());
1543
+ const cliWarnings = appUrlWarnings(appUrl, report);
1544
+ const failed = !report.ok || cliWarnings.some((w) => w.severity === "error");
1545
+ const metering = await meteringSummary(steward);
1546
+ if (values.json) out.out(JSON.stringify({
1547
+ ...report,
1548
+ cliWarnings,
1549
+ ...metering !== null ? { cliMetering: metering } : {}
1550
+ }, null, 2));
1551
+ else for (const line of formatDoctorReport(report, cliWarnings, metering)) out.out(line);
1552
+ return failed ? 1 : 0;
953
1553
  }
954
1554
  //#endregion
955
- //#region src/commands/endpoints.ts
956
- const ENDPOINTS_USAGE = `Kullanım:
957
- steward endpoints list [--json]
958
- steward endpoints add --url <url> --out <dosya> [--event-types <a,b>] [--description <metin>] [--force]
959
- steward endpoints rotate <id> --out <dosya> [--force]
960
- steward endpoints deactivate <id>
1555
+ //#region src/commands/dunning.ts
1556
+ const DUNNING_USAGE = `Usage:
1557
+ steward dunning get [--json]
1558
+ steward dunning set <policy.json> [--yes]
961
1559
 
962
- Webhook endpoint'leri (/v1/admin/webhook-endpoints). İmza sırrı (whsec_…) bu
963
- makinede üretilir ve YALNIZCA --out dosyasına yazılır (0600, satır sonu yok);
964
- terminale yazılmaz, steward hiçbir yanıtta geri vermez. Dosya varsa --force
965
- olmadan istek gönderilmez. Sırrı ürünün Secret'ına operatör taşır (CLI kubectl
966
- çağırmaz); rotasyonda ürün "yeni,eski" listesiyle geçer. Taşıdıktan sonra dosyayı
967
- silin. --event-types verilmezse yalnızca account.state_changed. deactivate geri
968
- alınmaz (yeni endpoint açılır).
1560
+ The product's dunning policy (/v1/admin/dunning-policy): what steward does after a renewal is
1561
+ not paid, by days since dunning started. Steps run in order:
1562
+ {"steps":[{"afterDays":1,"action":"retry_payment"},{"afterDays":7,"action":"suspend"},
1563
+ {"afterDays":30,"action":"terminate"}],"dryRun":false}
1564
+ retry_payment sends a payment reminder, suspend and terminate change the subscription.
1565
+ With "dryRun": true (the default) steps are only audited. Turning dryRun off needs
1566
+ confirmation (a prompt on a terminal, otherwise --yes): customers will be suspended.
969
1567
 
970
- Bağlantı: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (ortam, yoksa ./.env.local).`;
971
- function schemaProblems(issues) {
972
- return issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(kök)"}: ${issue.message}`).join("\n");
973
- }
974
- const lastDeliveryText = (endpoint) => {
975
- const last = endpoint.lastDelivery;
976
- if (last === null) return "-";
977
- return `${last.status}${last.httpStatus !== null ? ` ${last.httpStatus}` : ""}${last.error !== null ? ` ${last.error}` : ""} (${last.at})`;
978
- };
979
- function table(rows) {
980
- const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
981
- return rows.map((row) => row.map((cell, column) => column === row.length - 1 ? cell : cell.padEnd(widths[column])).join(" "));
982
- }
983
- const typesText = (endpoint) => endpoint.eventTypes === null ? "(filtre yok: 0.1 tipleri)" : endpoint.eventTypes.join(",");
984
- async function endpointsCommand(ctx, out, args) {
1568
+ Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
1569
+ const policyLines = (policy) => [...policy.steps.map((step) => ` day ${String(step.afterDays).padStart(3)} ${step.action}`), ` dry run ${policy.dryRun ? "yes (steps are only audited)" : "no"}`];
1570
+ async function dunningCommand(ctx, out, args) {
985
1571
  const [sub, ...rest] = args;
986
1572
  if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
987
- out.out(ENDPOINTS_USAGE);
1573
+ out.out(DUNNING_USAGE);
988
1574
  return sub === void 0 ? 2 : 0;
989
1575
  }
990
- if (sub === "list") {
1576
+ if (sub === "get") {
991
1577
  const { values, positionals } = parse(rest, {
992
1578
  ...HELP_OPTION,
993
1579
  json: { type: "boolean" }
994
- }, "endpoints");
995
- if (values.help) return help(out);
996
- expectPositionals(positionals, 0, 0, "endpoints");
997
- const target = requireAdminTarget(await resolveEnv(ctx));
998
- out.err(connectionLine(target));
999
- const { items } = await callSteward(target, () => clientFor(ctx, target).admin.endpoints.list());
1000
- if (values.json) out.out(JSON.stringify(items, null, 2));
1001
- else if (items.length === 0) out.out("endpoint yok — steward endpoints add --url <url> --out <dosya>");
1002
- else {
1003
- const rows = [[
1004
- "ID",
1005
- "DURUM",
1006
- "OLAYLAR",
1007
- "SON TESLİMAT",
1008
- "URL"
1009
- ]];
1010
- for (const e of items) rows.push([
1011
- e.id,
1012
- e.status,
1013
- typesText(e),
1014
- lastDeliveryText(e),
1015
- e.description !== null ? `${e.url} (${e.description})` : e.url
1016
- ]);
1017
- for (const line of table(rows)) out.out(line);
1018
- }
1019
- return 0;
1020
- }
1021
- if (sub === "add") {
1022
- const { values, positionals } = parse(rest, {
1023
- ...HELP_OPTION,
1024
- url: { type: "string" },
1025
- out: { type: "string" },
1026
- "event-types": { type: "string" },
1027
- description: { type: "string" },
1028
- force: { type: "boolean" }
1029
- }, ENDPOINTS_USAGE);
1030
- if (values.help) return help(out);
1031
- expectPositionals(positionals, 0, 0, "endpoints");
1032
- const url = requireOption(values.url, "--url", "endpoints");
1033
- const file = requireOption(values.out, "--out", "endpoints");
1034
- const secret = generateWebhookSecret();
1035
- const input = {
1036
- url,
1037
- secret,
1038
- ...values["event-types"] !== void 0 ? { eventTypes: parseList(values["event-types"]) } : {},
1039
- ...values.description !== void 0 ? { description: values.description } : {}
1040
- };
1041
- const parsed = WebhookEndpointCreateInputSchema.safeParse(input);
1042
- if (!parsed.success) throw new UsageError(`endpoint geçersiz (istek gönderilmedi)\n${schemaProblems(parsed.error.issues)}`);
1580
+ }, "dunning");
1581
+ if (values.help) return help$1(out);
1582
+ expectPositionals(positionals, 0, 0, "dunning");
1043
1583
  const target = requireAdminTarget(await resolveEnv(ctx));
1044
1584
  out.err(connectionLine(target));
1045
- const steward = clientFor(ctx, target);
1046
- const result = await withSecretFile(ctx.cwd, file, secret, { force: values.force === true }, () => callSteward(target, () => steward.admin.endpoints.create(input)));
1047
- const endpoint = result.value;
1048
- out.out(`endpoint oluşturuldu → ${originOf(target.url)}`);
1049
- out.out(` id ${endpoint.id}`);
1050
- out.out(` url ${endpoint.url}`);
1051
- out.out(` olaylar ${typesText(endpoint)}`);
1052
- secretNotice(out, result.path, result.fallback, "Sırrı ürünün Secret'ına (STEWARD_WEBHOOK_SECRET) taşıyın, sonra dosyayı silin.");
1585
+ const policy = await callSteward(target, () => clientFor(ctx, target).admin.dunning.get());
1586
+ if (values.json) out.out(JSON.stringify(policy, null, 2));
1587
+ else for (const line of policyLines(policy)) out.out(line);
1053
1588
  return 0;
1054
1589
  }
1055
- if (sub === "rotate") {
1590
+ if (sub === "set") {
1056
1591
  const { values, positionals } = parse(rest, {
1057
1592
  ...HELP_OPTION,
1058
- out: { type: "string" },
1059
- force: { type: "boolean" }
1060
- }, "endpoints");
1061
- if (values.help) return help(out);
1062
- expectPositionals(positionals, 1, 1, "endpoints");
1063
- const id = positionals[0];
1064
- const file = requireOption(values.out, "--out", "endpoints");
1065
- const secret = generateWebhookSecret();
1066
- const parsed = WebhookEndpointRotateInputSchema.safeParse({ secret });
1067
- if (!parsed.success) throw new UsageError(`sır geçersiz\n${schemaProblems(parsed.error.issues)}`);
1593
+ yes: {
1594
+ type: "boolean",
1595
+ short: "y"
1596
+ }
1597
+ }, "dunning");
1598
+ if (values.help) return help$1(out);
1599
+ expectPositionals(positionals, 1, 1, "dunning");
1600
+ const file = positionals[0];
1601
+ let json;
1602
+ try {
1603
+ json = JSON.parse(await readFile(resolve(ctx.cwd, file), "utf8"));
1604
+ } catch (error) {
1605
+ throw new CliError(`cannot read ${file}: ${error instanceof Error ? error.message : String(error)}`);
1606
+ }
1607
+ const parsed = DunningPolicySchema.strict().safeParse(json);
1608
+ if (!parsed.success) throw new UsageError(`invalid policy (nothing was sent)\n${parsed.error.issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(root)"}: ${issue.message}`).join("\n")}`);
1609
+ const policy = parsed.data;
1068
1610
  const target = requireAdminTarget(await resolveEnv(ctx));
1069
1611
  out.err(connectionLine(target));
1070
1612
  const steward = clientFor(ctx, target);
1071
- const result = await withSecretFile(ctx.cwd, file, secret, { force: values.force === true }, () => callSteward(target, () => steward.admin.endpoints.rotate(id, { secret })));
1072
- out.out(`sır döndürüldü → ${originOf(target.url)}`);
1073
- out.out(` id ${result.value.id}`);
1074
- out.out(` url ${result.value.url}`);
1075
- secretNotice(out, result.path, result.fallback, "Ürünün Secret'ında STEWARD_WEBHOOK_SECRET'ı \"yeni,eski\" yapın ve rollout edin; eski sır steward'da geçiş için ikinci imza olarak kalır. Sonra dosyayı silin.");
1076
- return 0;
1077
- }
1078
- if (sub === "deactivate") {
1079
- const { values, positionals } = parse(rest, { ...HELP_OPTION }, "endpoints");
1080
- if (values.help) return help(out);
1081
- expectPositionals(positionals, 1, 1, "endpoints");
1082
- const target = requireAdminTarget(await resolveEnv(ctx));
1083
- out.err(connectionLine(target));
1084
- const endpoint = await callSteward(target, () => clientFor(ctx, target).admin.endpoints.deactivate(positionals[0]));
1085
- out.out(`endpoint pasifleştirildi → ${originOf(target.url)}: ${endpoint.id} (${endpoint.url}, durum ${endpoint.status})`);
1613
+ const current = await callSteward(target, () => steward.admin.dunning.get());
1614
+ out.out("new policy:");
1615
+ for (const line of policyLines(policy)) out.out(line);
1616
+ if (current.dryRun && !policy.dryRun) {
1617
+ if (!await confirm(ctx, "This turns dry run off: suspend and terminate steps will change subscriptions. Continue?", {
1618
+ yes: values.yes === true,
1619
+ notConfirmed: "the policy was not changed"
1620
+ })) {
1621
+ out.err("not confirmed; the policy was not changed");
1622
+ return 1;
1623
+ }
1624
+ }
1625
+ const stored = await callSteward(target, () => steward.admin.dunning.set(policy));
1626
+ out.out(`policy stored → ${originOf(target.url)} (${stored.steps.length} step${stored.steps.length === 1 ? "" : "s"})`);
1086
1627
  return 0;
1087
1628
  }
1088
- throw new UsageError(`bilinmeyen alt komut: endpoints ${sub} (ayrıntı: steward endpoints --help)`);
1629
+ throw new UsageError(`unknown subcommand: dunning ${sub} (see: steward dunning --help)`);
1089
1630
  }
1090
- function help(out) {
1091
- out.out(ENDPOINTS_USAGE);
1631
+ function help$1(out) {
1632
+ out.out(DUNNING_USAGE);
1092
1633
  return 0;
1093
1634
  }
1094
- function secretNotice(out, path, fallback, next) {
1095
- if (fallback) {
1096
- out.err(`! sır hedef dosyaya taşınamadı (arada oluşturulmuş olabilir); sır ${path} dosyasında (0600)`);
1097
- out.out(` sır ${path} (0600; terminale yazılmadı)`);
1098
- } else out.out(` sır ${path} (0600; terminale yazılmadı)`);
1099
- out.err(next);
1100
- }
1101
1635
  //#endregion
1102
1636
  //#region src/commands/events.ts
1103
- const EVENTS_USAGE = `Usage: steward events send <ref> <name> [--meta key=value]… [--external-id <id>]
1104
- [--timestamp <iso>] [--json]
1637
+ const EVENTS_USAGE = `Usage:
1638
+ steward events send <ref> <name> [--meta key=value]… [--external-id <id>]
1639
+ [--timestamp <iso>] [--json]
1640
+ steward events redeliver <eventId> [<eventId>…]
1105
1641
 
1106
1642
  Sends one event for account <ref> (POST /v1/events/ingest), e.g. to try a meter locally.
1107
1643
  The event itself has no billing meaning: it counts as usage for the meters whose filter
@@ -1121,7 +1657,12 @@ Metadata must not carry personal data (names, e-mail addresses, phone numbers):
1121
1657
 
1122
1658
  Connection: STEWARD_URL + STEWARD_API_KEY (or, when neither is set, STEWARD_ADMIN_URL +
1123
1659
  STEWARD_ADMIN_API_KEY). Sent with X-Actor-Ref operator:<user>.
1124
- Exit code 1: the event was rejected (unknown or deleted account, timestamp out of range).`;
1660
+ Exit code 1: the event was rejected (unknown or deleted account, timestamp out of range).
1661
+
1662
+ redeliver (admin; STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY): requeues every delivery of a
1663
+ webhook event (evt_…; dead ones included) with attempts reset, after the receiver's problem is
1664
+ fixed. The dispatcher sends it on its next tick; an account's older events go first. When only
1665
+ the current state matters, the product calls POST /v1/accounts/:ref/resync instead.`;
1125
1666
  const SEND_OPTIONS = {
1126
1667
  ...HELP_OPTION,
1127
1668
  meta: {
@@ -1164,6 +1705,7 @@ async function eventsCommand(ctx, out, args) {
1164
1705
  out.out(EVENTS_USAGE);
1165
1706
  return sub === void 0 ? 2 : 0;
1166
1707
  }
1708
+ if (sub === "redeliver") return redeliverCommand(ctx, out, rest);
1167
1709
  if (sub !== "send") throw new UsageError(`unknown subcommand: events ${sub} (see: steward events --help)`);
1168
1710
  const { values, positionals } = parse(rest, SEND_OPTIONS, "events");
1169
1711
  if (values.help) {
@@ -1201,101 +1743,251 @@ async function eventsCommand(ctx, out, args) {
1201
1743
  }
1202
1744
  return 0;
1203
1745
  }
1746
+ async function redeliverCommand(ctx, out, args) {
1747
+ const { values, positionals } = parse(args, { ...HELP_OPTION }, "events");
1748
+ if (values.help) {
1749
+ out.out(EVENTS_USAGE);
1750
+ return 0;
1751
+ }
1752
+ expectPositionals(positionals, 1, 100, "events");
1753
+ const target = requireAdminTarget(await resolveEnv(ctx));
1754
+ out.err(connectionLine(target));
1755
+ const steward = clientFor(ctx, target);
1756
+ for (const eventId of positionals) {
1757
+ const result = await callSteward(target, () => steward.admin.events.redeliver(eventId));
1758
+ out.out(`${result.eventId} (${result.type}): ${result.deliveries.length} deliver${result.deliveries.length === 1 ? "y" : "ies"} requeued`);
1759
+ }
1760
+ return 0;
1761
+ }
1204
1762
  //#endregion
1205
- //#region src/commands/meters.ts
1206
- const METERS_USAGE = `Usage: steward meters get <ref> [--periods <n>] [--json]
1763
+ //#region src/commands/keys.ts
1764
+ const KEYS_USAGE = `Usage:
1765
+ steward keys list [--json]
1766
+ steward keys create --name <name> --scope product|checkout|admin --out <file>
1767
+ [--expires-days <n> | --no-expiry] [--force]
1768
+ steward keys revoke <prefix>
1207
1769
 
1208
- Reads an account's meters (GET /v1/accounts/:ref/meters): per meter the current usage
1209
- period, units used, the period's credit, the balance, the standing (ok | low | exhausted)
1210
- and, for a billable meter, the estimated overage so far. Nothing is written.
1770
+ The product's API keys (/v1/admin/api-keys). The key (stw_…) is generated on this machine and
1771
+ written ONLY to the --out file (0600, no trailing newline): never to the terminal, and steward
1772
+ never returns it. If the file exists, nothing is sent without --force. Move the key into the
1773
+ product's Secret (the CLI does not call kubectl), then delete the file.
1211
1774
 
1212
- --periods <n> also list the last n closed periods (1–100; GET …/meters/periods)
1213
- --json print the response as JSON
1775
+ --scope product: the product's backend; checkout: its web app (checkout, portal,
1776
+ state only); admin: these management commands
1777
+ --expires-days days until the key stops working (1–3650). Default: admin keys 90 days,
1778
+ other keys never. --no-expiry: never (not allowed for an admin key)
1214
1779
 
1215
- Connection: STEWARD_URL + STEWARD_API_KEY (or, when neither is set, STEWARD_ADMIN_URL +
1216
- STEWARD_ADMIN_API_KEY); environment, otherwise ./.env.local.`;
1217
- const GET_OPTIONS = {
1218
- ...HELP_OPTION,
1219
- periods: { type: "string" },
1220
- json: { type: "boolean" }
1221
- };
1222
- /** Units of a meter read (a JSON number with at most 6 decimals) as exact text with grouping: `1,700,000.5`. */
1223
- function formatUnitsText(value) {
1224
- return new Intl.NumberFormat("en", { maximumFractionDigits: 6 }).format(plainDecimalOf(value));
1225
- }
1226
- function meterLines(code, meter, width) {
1227
- const lines = [` ${code.padEnd(width)} ${meter.periodStart} → ${meter.periodEnd}`];
1228
- const indent = " ".repeat(width + 4);
1229
- lines.push(`${indent}used ${formatUnitsText(meter.consumedUnits)} · credit ${formatUnitsText(meter.creditedUnits)} · balance ${formatUnitsText(meter.balance)} · standing ${meter.standing}`);
1230
- const included = meter.includedUnits === null ? "no credit included" : `included ${formatUnitsText(meter.includedUnits)} per period`;
1231
- const billing = meter.billable && meter.amountDueMinor !== null && meter.currency !== null ? `billable: ${formatUnitsText(meter.overageUnits)} over the credit, estimated overage ${formatMinor(meter.amountDueMinor, meter.currency)}` : "not billable (no metered price)";
1232
- lines.push(`${indent}${included} · ${billing}`);
1233
- return lines;
1234
- }
1235
- /** Human-readable meter read (+ closed periods, newest first). */
1236
- function formatMeters(meters, periods) {
1237
- const lines = [`meters of ${meters.ref} · as of ${meters.asOf} · events received before ${meters.rolledUpThrough} are counted`];
1238
- const codes = Object.keys(meters.meters);
1239
- if (codes.length === 0) lines.push(" no meters (the product's catalog defines none)");
1240
- else {
1241
- const width = Math.max(...codes.map((code) => code.length));
1242
- for (const code of codes) lines.push(...meterLines(code, meters.meters[code], width));
1780
+ revoke takes the 12 hex characters after stw_ (keys list). A key cannot revoke itself: revoke
1781
+ the key you are using with another admin key or the pod CLI.
1782
+
1783
+ Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
1784
+ const SCOPES = [
1785
+ "product",
1786
+ "checkout",
1787
+ "admin"
1788
+ ];
1789
+ const keyStatus = (key, now = Date.now()) => key.revokedAt !== null ? "revoked" : key.expiresAt !== null && Date.parse(key.expiresAt) <= now ? "expired" : "active";
1790
+ async function keysCommand(ctx, out, args) {
1791
+ const [sub, ...rest] = args;
1792
+ if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
1793
+ out.out(KEYS_USAGE);
1794
+ return sub === void 0 ? 2 : 0;
1243
1795
  }
1244
- if (periods !== null) {
1245
- lines.push("");
1246
- if (periods.length === 0) lines.push("closed periods: none");
1247
- else {
1248
- lines.push("closed periods (newest first):");
1249
- const width = Math.max(...periods.map((p) => p.meter.length));
1250
- for (const period of periods) lines.push(` ${period.meter.padEnd(width)} ${period.periodStart} → ${period.periodEnd} used ${formatUnitsText(period.consumedUnits)} · credit ${formatUnitsText(period.creditedUnits)} · over ${formatUnitsText(period.overageUnits)}`);
1796
+ if (sub === "list") {
1797
+ const { values, positionals } = parse(rest, {
1798
+ ...HELP_OPTION,
1799
+ json: { type: "boolean" }
1800
+ }, "keys");
1801
+ if (values.help) return help(out);
1802
+ expectPositionals(positionals, 0, 0, "keys");
1803
+ const target = requireAdminTarget(await resolveEnv(ctx));
1804
+ out.err(connectionLine(target));
1805
+ const { items } = await callSteward(target, () => clientFor(ctx, target).admin.apiKeys.list());
1806
+ if (values.json) {
1807
+ out.out(JSON.stringify(items, null, 2));
1808
+ return 0;
1251
1809
  }
1810
+ const rows = [[
1811
+ "PREFIX",
1812
+ "SCOPE",
1813
+ "STATUS",
1814
+ "EXPIRES",
1815
+ "LAST USED",
1816
+ "NAME"
1817
+ ]];
1818
+ for (const k of items) rows.push([
1819
+ k.prefix,
1820
+ k.scope,
1821
+ keyStatus(k),
1822
+ k.expiresAt ?? "never",
1823
+ k.lastUsedAt ?? "-",
1824
+ k.name
1825
+ ]);
1826
+ for (const line of table(rows)) out.out(line);
1827
+ return 0;
1828
+ }
1829
+ if (sub === "create") {
1830
+ const { values, positionals } = parse(rest, {
1831
+ ...HELP_OPTION,
1832
+ name: { type: "string" },
1833
+ scope: { type: "string" },
1834
+ out: { type: "string" },
1835
+ "expires-days": { type: "string" },
1836
+ "no-expiry": { type: "boolean" },
1837
+ force: { type: "boolean" }
1838
+ }, "keys");
1839
+ if (values.help) return help(out);
1840
+ expectPositionals(positionals, 0, 0, "keys");
1841
+ const name = requireOption(values.name, "--name", "keys");
1842
+ const scope = requireOption(values.scope, "--scope", "keys");
1843
+ if (!SCOPES.includes(scope)) throw new UsageError(`--scope: one of ${SCOPES.join(", ")}`);
1844
+ const file = requireOption(values.out, "--out", "keys");
1845
+ if (values["expires-days"] !== void 0 && values["no-expiry"]) throw new UsageError("--expires-days and --no-expiry are mutually exclusive");
1846
+ const token = generateApiKeyToken();
1847
+ const input = {
1848
+ token,
1849
+ name,
1850
+ scope,
1851
+ ...values["expires-days"] !== void 0 ? { expiresInDays: parsePositiveInt(values["expires-days"], "--expires-days", { max: 3650 }) } : {},
1852
+ ...values["no-expiry"] ? { expiresInDays: null } : {}
1853
+ };
1854
+ const parsed = ApiKeyCreateInputSchema.safeParse(input);
1855
+ if (!parsed.success) throw new UsageError(`invalid key (nothing was sent)\n${parsed.error.issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(root)"}: ${issue.message}`).join("\n")}`);
1856
+ const target = requireAdminTarget(await resolveEnv(ctx));
1857
+ out.err(connectionLine(target));
1858
+ const steward = clientFor(ctx, target);
1859
+ const result = await withSecretFile(ctx.cwd, file, token, { force: values.force === true }, () => callSteward(target, () => steward.admin.apiKeys.create(input)));
1860
+ const key = result.value;
1861
+ out.out(`key created → ${originOf(target.url)}`);
1862
+ out.out(` prefix ${key.prefix}`);
1863
+ out.out(` scope ${key.scope}`);
1864
+ out.out(` expires ${key.expiresAt ?? "never"}`);
1865
+ secretNotice(out, result.path, result.fallback, "Move the key into the product's Secret, then delete the file.");
1866
+ return 0;
1867
+ }
1868
+ if (sub === "revoke") {
1869
+ const { values, positionals } = parse(rest, { ...HELP_OPTION }, "keys");
1870
+ if (values.help) return help(out);
1871
+ expectPositionals(positionals, 1, 1, "keys");
1872
+ const target = requireAdminTarget(await resolveEnv(ctx));
1873
+ out.err(connectionLine(target));
1874
+ const key = await callSteward(target, () => clientFor(ctx, target).admin.apiKeys.revoke(positionals[0]));
1875
+ out.out(`key revoked → ${originOf(target.url)}: ${key.prefix} (${key.scope}, ${key.name})`);
1876
+ return 0;
1252
1877
  }
1878
+ throw new UsageError(`unknown subcommand: keys ${sub} (see: steward keys --help)`);
1879
+ }
1880
+ function help(out) {
1881
+ out.out(KEYS_USAGE);
1882
+ return 0;
1883
+ }
1884
+ //#endregion
1885
+ //#region src/commands/reprice.ts
1886
+ const REPRICE_USAGE = `Usage: steward reprice --plan <code> --notice-days <n> [--dry-run] [--yes] [--json]
1887
+
1888
+ Moves the live subscriptions of a plan to the plan's current price and metered rates
1889
+ (POST /v1/admin/subscriptions/reprice): each one changes from its first period boundary at
1890
+ least <n> days away (0–3650) and gets one price change notice e-mail. Subscribers otherwise
1891
+ keep the amount they locked at checkout.
1892
+
1893
+ The command always lists first (a dry run: nothing written, no e-mail). Without --dry-run it
1894
+ then asks for confirmation (a prompt on a terminal, otherwise --yes) and runs it for real.
1895
+ Running it again is safe: an already scheduled subscription gets no second notice.
1896
+
1897
+ Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
1898
+ const OPTIONS = {
1899
+ ...HELP_OPTION,
1900
+ plan: { type: "string" },
1901
+ "notice-days": { type: "string" },
1902
+ "dry-run": { type: "boolean" },
1903
+ yes: {
1904
+ type: "boolean",
1905
+ short: "y"
1906
+ },
1907
+ json: { type: "boolean" }
1908
+ };
1909
+ function summary(result) {
1910
+ const count = (action) => result.items.filter((item) => item.action === action).length;
1911
+ const lines = result.items.map((item) => {
1912
+ const amounts = `${formatMinor(item.oldAmountMinor, item.currency)} → ${formatMinor(item.newAmountMinor, item.currency)}`;
1913
+ const rates = item.meteredRates?.length ? ` (+${item.meteredRates.length} metered rate${item.meteredRates.length === 1 ? "" : "s"})` : "";
1914
+ const when = item.action === "skip" ? `skip: ${item.reason ?? "-"}` : `${item.action} from ${item.effectiveAt}`;
1915
+ return ` ${item.accountRef} ${item.interval} ${amounts}${rates} ${when}`;
1916
+ });
1917
+ lines.push(`${count("schedule")} to schedule, ${count("already_scheduled")} already scheduled, ${count("skip")} skipped; effective not before ${result.effectiveNotBefore}`);
1253
1918
  return lines;
1254
1919
  }
1255
- async function metersCommand(ctx, out, args) {
1256
- const [sub, ...rest] = args;
1257
- if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
1258
- out.out(METERS_USAGE);
1259
- return sub === void 0 ? 2 : 0;
1260
- }
1261
- if (sub !== "get") throw new UsageError(`unknown subcommand: meters ${sub} (see: steward meters --help)`);
1262
- const { values, positionals } = parse(rest, GET_OPTIONS, "meters");
1920
+ async function repriceCommand(ctx, out, args) {
1921
+ const { values, positionals } = parse(args, OPTIONS, "reprice");
1263
1922
  if (values.help) {
1264
- out.out(METERS_USAGE);
1923
+ out.out(REPRICE_USAGE);
1265
1924
  return 0;
1266
1925
  }
1267
- expectPositionals(positionals, 1, 1, "meters");
1268
- const ref = positionals[0];
1269
- const limit = values.periods === void 0 ? null : parsePositiveInt(values.periods, "--periods", { max: 100 });
1270
- const target = requireReadTarget(await resolveEnv(ctx));
1926
+ if (args.length === 0) {
1927
+ out.out(REPRICE_USAGE);
1928
+ return 2;
1929
+ }
1930
+ expectPositionals(positionals, 0, 0, "reprice");
1931
+ const input = {
1932
+ planCode: requireOption(values.plan, "--plan", "reprice"),
1933
+ noticeDays: parseNonNegativeInt(requireOption(values["notice-days"], "--notice-days", "reprice"), "--notice-days")
1934
+ };
1935
+ const checked = RepriceInputSchema.safeParse({
1936
+ ...input,
1937
+ dryRun: true
1938
+ });
1939
+ if (!checked.success) throw new UsageError(`invalid request (nothing was sent)\n${checked.error.issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(root)"}: ${issue.message}`).join("\n")}`);
1940
+ const target = requireAdminTarget(await resolveEnv(ctx));
1271
1941
  out.err(connectionLine(target));
1272
1942
  const steward = clientFor(ctx, target);
1273
- const meters = await callSteward(target, () => steward.meters.get(ref));
1274
- const periods = limit === null ? null : (await callSteward(target, () => steward.meters.periods(ref, { limit }))).periods;
1275
- if (values.json) out.out(JSON.stringify(periods === null ? meters : {
1276
- ...meters,
1277
- closedPeriods: periods
1278
- }, null, 2));
1279
- else for (const line of formatMeters(meters, periods)) out.out(line);
1943
+ const preview = await callSteward(target, () => steward.admin.subscriptions.reprice({
1944
+ ...input,
1945
+ dryRun: true
1946
+ }));
1947
+ if (values["dry-run"]) {
1948
+ if (values.json) out.out(JSON.stringify(preview, null, 2));
1949
+ else for (const line of ["dry run (nothing written):", ...summary(preview)]) out.out(line);
1950
+ return 0;
1951
+ }
1952
+ if (!values.json) for (const line of ["dry run:", ...summary(preview)]) out.out(line);
1953
+ const toSchedule = preview.items.filter((item) => item.action === "schedule").length;
1954
+ if (toSchedule === 0) {
1955
+ out.out("nothing to schedule");
1956
+ return 0;
1957
+ }
1958
+ if (!await confirm(ctx, `Schedule ${toSchedule} subscription${toSchedule === 1 ? "" : "s"} and send the notice e-mails?`, {
1959
+ yes: values.yes === true,
1960
+ notConfirmed: "nothing was scheduled"
1961
+ })) {
1962
+ out.err("not confirmed; nothing was scheduled");
1963
+ return 1;
1964
+ }
1965
+ const result = await callSteward(target, () => steward.admin.subscriptions.reprice({
1966
+ ...input,
1967
+ dryRun: false
1968
+ }));
1969
+ if (values.json) out.out(JSON.stringify(result, null, 2));
1970
+ else out.out(`scheduled → ${originOf(target.url)}: ${result.scheduled} subscription${result.scheduled === 1 ? "" : "s"} (one notice e-mail each)`);
1280
1971
  return 0;
1281
1972
  }
1282
1973
  //#endregion
1283
1974
  //#region src/commands/settings.ts
1284
- const SETTINGS_USAGE = `Kullanım:
1975
+ const SETTINGS_USAGE = `Usage:
1285
1976
  steward settings get
1286
1977
  steward settings set [--app-url <url>] [--privacy-url <url>] [--terms-url <url>]
1287
1978
  [--branding <json>] [--default-locale tr|en]
1288
- [--checkout-ttl <dakika>] [--portal-ttl <dakika>]
1979
+ [--checkout-ttl <minutes>] [--portal-ttl <minutes>]
1289
1980
  [--extra-return-origins <a,b>] [--emails <json>]
1290
1981
  [--billing-payment-due-days <1-60>] [--billing-min-invoice-minor <n>]
1291
1982
  [--billing-allow-multiple-subscriptions true|false]
1292
1983
  [--metering-charge-mode off|dry_run|live]
1293
1984
  [--metering-late-grace-minutes <0-1440>] [--events-retention-days <45-400>]
1985
+ [--provider <id>]
1294
1986
 
1295
- Ürün ayarları (GET/PATCH /v1/admin/settings). Verilmeyen alan değişmez; boş değer
1296
- (--privacy-url "") alanı temizler, --branding null markayı temizler, --branding
1297
- '{"name":"Acme","supportEmail":"destek@acme.com"}' sığ birleşir (alanı null ile
1298
- temizleyin). --extra-return-origins "" listeyi boşaltır.
1987
+ Product settings (GET/PATCH /v1/admin/settings). A field not given is unchanged; an
1988
+ empty value (--privacy-url "") clears the field, --branding null clears the branding,
1989
+ --branding '{"name":"Acme","supportEmail":"support@acme.com"}' merges shallowly (clear a
1990
+ field with null). --extra-return-origins "" empties the list.
1299
1991
  --emails '{"billingPath":"/{LOCALE}/billing","templates":{"invoice_issued":{"enabled":false}}}'
1300
1992
  sets billing emails (sender: from.name, from.address; templates merge per
1301
1993
  template, null resets a field or template; --emails null resets all).
@@ -1311,8 +2003,10 @@ it, live adds it to the renewal invoice, off prices nothing — run one full cyc
1311
2003
  dry_run before live. --metering-late-grace-minutes how long a period waits for late
1312
2004
  events before it closes (default 60). --events-retention-days how long raw events are
1313
2005
  kept after receipt, once their period is closed (default 120). "" restores the default.
2006
+ --provider sets the payment provider for NEW checkouts and payment sessions (open ones keep
2007
+ theirs); steward accepts only a provider configured in its deployment (iyzico, fake…).
1314
2008
 
1315
- Bağlantı: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (ortam, yoksa ./.env.local).`;
2009
+ Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
1316
2010
  const SET_OPTIONS = {
1317
2011
  ...HELP_OPTION,
1318
2012
  "app-url": { type: "string" },
@@ -1329,10 +2023,11 @@ const SET_OPTIONS = {
1329
2023
  "billing-allow-multiple-subscriptions": { type: "string" },
1330
2024
  "metering-charge-mode": { type: "string" },
1331
2025
  "metering-late-grace-minutes": { type: "string" },
1332
- "events-retention-days": { type: "string" }
2026
+ "events-retention-days": { type: "string" },
2027
+ provider: { type: "string" }
1333
2028
  };
1334
2029
  const orNull = (value) => value.trim() === "" ? null : value.trim();
1335
- /** Bayraklardan yama; sözleşme şemasıyla doğrulanır (geçersizse istek gönderilmez). */
2030
+ /** A patch from the flags; validated with the contract schema (if invalid no request is sent). */
1336
2031
  function buildSettingsPatch(values) {
1337
2032
  const patch = {};
1338
2033
  if (values["app-url"] !== void 0) patch.appUrl = orNull(values["app-url"]);
@@ -1346,9 +2041,9 @@ function buildSettingsPatch(values) {
1346
2041
  try {
1347
2042
  branding = JSON.parse(text);
1348
2043
  } catch {
1349
- throw new UsageError("--branding: JSON nesnesi olmalı, ör. '{\"name\":\"Acme\",\"supportEmail\":\"destek@acme.com\"}'");
2044
+ throw new UsageError("--branding: must be a JSON object, e.g. '{\"name\":\"Acme\",\"supportEmail\":\"support@acme.com\"}'");
1350
2045
  }
1351
- if (typeof branding !== "object" || branding === null || Array.isArray(branding)) throw new UsageError("--branding: JSON nesnesi olmalı");
2046
+ if (typeof branding !== "object" || branding === null || Array.isArray(branding)) throw new UsageError("--branding: must be a JSON object");
1352
2047
  patch.branding = branding;
1353
2048
  }
1354
2049
  }
@@ -1367,6 +2062,7 @@ function buildSettingsPatch(values) {
1367
2062
  }
1368
2063
  }
1369
2064
  if (values["default-locale"] !== void 0) patch.defaultLocale = values["default-locale"].trim();
2065
+ if (values.provider !== void 0) patch.provider = values.provider.trim();
1370
2066
  if (values["checkout-ttl"] !== void 0) patch.checkoutTtlMinutes = parsePositiveInt(values["checkout-ttl"], "--checkout-ttl");
1371
2067
  if (values["portal-ttl"] !== void 0) patch.portalTtlMinutes = parsePositiveInt(values["portal-ttl"], "--portal-ttl");
1372
2068
  if (values["extra-return-origins"] !== void 0) patch.extraReturnOrigins = parseList(values["extra-return-origins"]);
@@ -1390,9 +2086,9 @@ function buildSettingsPatch(values) {
1390
2086
  if (Object.keys(metering).length > 0) patch.metering = metering;
1391
2087
  const retention = values["events-retention-days"];
1392
2088
  if (retention !== void 0) patch.events = { retentionDays: retention.trim() === "" ? null : parsePositiveInt(retention, "--events-retention-days", { max: 400 }) };
1393
- if (Object.keys(patch).length === 0) throw new UsageError(`en az bir ayar bayrağı gerekli (ayrıntı: steward settings --help)`);
2089
+ if (Object.keys(patch).length === 0) throw new UsageError(`at least one settings flag is required (details: steward settings --help)`);
1394
2090
  const parsed = ProductSettingsPatchSchema.safeParse(patch);
1395
- if (!parsed.success) throw new UsageError(`ayarlar geçersiz (istek gönderilmedi)\n${parsed.error.issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(kök)"}: ${issue.message}`).join("\n")}`);
2091
+ if (!parsed.success) throw new UsageError(`invalid settings (no request was sent)\n${parsed.error.issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(root)"}: ${issue.message}`).join("\n")}`);
1396
2092
  return patch;
1397
2093
  }
1398
2094
  async function settingsCommand(ctx, out, args) {
@@ -1426,43 +2122,53 @@ async function settingsCommand(ctx, out, args) {
1426
2122
  const target = requireAdminTarget(await resolveEnv(ctx));
1427
2123
  out.err(connectionLine(target));
1428
2124
  const settings = await callSteward(target, () => clientFor(ctx, target).admin.settings.update(patch));
1429
- out.err(`ayarlar güncellendi → ${originOf(target.url)} (${Object.keys(patch).join(", ")})`);
2125
+ out.err(`settings updated → ${originOf(target.url)} (${Object.keys(patch).join(", ")})`);
1430
2126
  if (patch.metering?.chargeMode === "live") out.err("note: overage is now added to renewal invoices; it should follow one full usage cycle observed in dry_run");
1431
2127
  out.out(JSON.stringify(settings, null, 2));
1432
2128
  return 0;
1433
2129
  }
1434
- throw new UsageError(`bilinmeyen alt komut: settings ${sub} (ayrıntı: steward settings --help)`);
2130
+ throw new UsageError(`unknown subcommand: settings ${sub} (details: steward settings --help)`);
1435
2131
  }
1436
2132
  //#endregion
1437
2133
  //#region src/main.ts
1438
- const CLI_VERSION = "0.6.0";
2134
+ const CLI_VERSION = "0.8.0";
1439
2135
  const USAGE = `steward — Steward CLI (@stewardhq/cli ${CLI_VERSION})
1440
2136
 
1441
- Kullanım: steward <komut> [seçenekler]
2137
+ Usage: steward <command> [options]
1442
2138
 
1443
- Komutlar:
1444
- doctor [--json] kurulum teşhisi (GET /v1/doctor)
1445
- catalog push <dosya> [--yes] katalog senkronu (PUT /v1/admin/catalog)
1446
- settings get | set [bayraklar] ürün ayarları (/v1/admin/settings)
1447
- endpoints list | add | rotate | deactivate webhook endpoint'leri; sır yalnızca --out dosyasına
1448
- meters get <ref> [--periods <n>] [--json] an account's meters (GET /v1/accounts/:ref/meters)
1449
- events send <ref> <name> [--meta k=v]… send one event (POST /v1/events/ingest; local try-out)
2139
+ Commands:
2140
+ doctor [--json] setup diagnosis (GET /v1/doctor)
2141
+ catalog push <file> [--yes] catalog sync (PUT /v1/admin/catalog)
2142
+ settings get | set [flags] product settings (/v1/admin/settings)
2143
+ endpoints list | add | rotate | deactivate webhook endpoints; the secret goes only to the --out file
2144
+ keys list | create | revoke API keys; the key goes only to the --out file
2145
+ dunning get | set <policy.json> dunning policy (/v1/admin/dunning-policy)
2146
+ reprice --plan <code> --notice-days <n> move a plan's subscribers to its current price
2147
+ bank-transfers list | record | fx-report bank transfer reconciliation (/v1/admin/bank-transfers)
2148
+ credits adjust <ref> <meter> --units=<n> credit entry, negative = adjustment
2149
+ meters get | recompute | close-periods an account's meters; metering repairs (admin)
2150
+ events send | redeliver send one event; redeliver webhook events (admin)
1450
2151
 
1451
- Bağlantı: yönetim komutları STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY, doctor,
1452
- meters ve events STEWARD_URL + STEWARD_API_KEY (yoksa admin çifti). Ortamda bu dört değişkenden
1453
- biri bile varsa hepsi (ve APP_URL) ortamdan okunur, ./.env.local hiç okunmaz;
1454
- yoksa ./.env.local'den. Kullanılan kaynak stderr'e yazılır (bağlantı: …).
1455
- Değişikliklerde X-Actor-Ref operator:<kullanıcı>. CLI sırları terminale yazmaz
1456
- ve kubectl çağırmaz.
2152
+ Connection: admin commands use STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY; doctor,
2153
+ meters and events use STEWARD_URL + STEWARD_API_KEY (or the admin pair). If even one of
2154
+ these four variables is in the environment, all of them (and APP_URL) are read from the
2155
+ environment and ./.env.local is not read at all; otherwise from ./.env.local. The source
2156
+ in use is written to stderr (connection: …). Changes send X-Actor-Ref operator:<user>.
2157
+ The CLI never writes secrets to the terminal and never calls kubectl.
1457
2158
 
1458
- Ayrıntı: steward <komut> --help`;
2159
+ Details: steward <command> --help`;
1459
2160
  const COMMANDS = {
1460
2161
  doctor: doctorCommand,
1461
2162
  catalog: catalogCommand,
1462
2163
  settings: settingsCommand,
1463
2164
  endpoints: endpointsCommand,
1464
2165
  meters: metersCommand,
1465
- events: eventsCommand
2166
+ events: eventsCommand,
2167
+ keys: keysCommand,
2168
+ dunning: dunningCommand,
2169
+ reprice: repriceCommand,
2170
+ "bank-transfers": bankTransfersCommand,
2171
+ credits: creditsCommand
1466
2172
  };
1467
2173
  async function main(argv, ctx) {
1468
2174
  const out = createOutput(ctx.stdout, ctx.stderr);
@@ -1481,7 +2187,7 @@ async function main(argv, ctx) {
1481
2187
  }
1482
2188
  const command = Object.hasOwn(COMMANDS, name) ? COMMANDS[name] : void 0;
1483
2189
  if (command === void 0) {
1484
- out.err(`steward: bilinmeyen komut: ${name}\n\n${USAGE}`);
2190
+ out.err(`steward: unknown command: ${name}\n\n${USAGE}`);
1485
2191
  return 2;
1486
2192
  }
1487
2193
  try {
@@ -1495,7 +2201,7 @@ async function main(argv, ctx) {
1495
2201
  out.err(`steward ${name}: ${describeStewardError(error)}`);
1496
2202
  return 1;
1497
2203
  }
1498
- out.err(`steward ${name}: beklenmeyen hata: ${error instanceof Error ? error.message : String(error)}`);
2204
+ out.err(`steward ${name}: unexpected error:${error instanceof Error ? error.message : String(error)}`);
1499
2205
  return 1;
1500
2206
  }
1501
2207
  }