@stewardhq/cli 0.5.0 → 0.7.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 (4) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +109 -77
  3. package/dist/bin.js +1040 -552
  4. package/package.json +14 -8
package/dist/bin.js CHANGED
@@ -2,12 +2,12 @@
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 { API_VERSION, AccountMetersSchema, CatalogSyncInputSchema, ErrorResponseSchema, EventsIngestInputSchema, EventsIngestResultSchema, HEADER_ACTOR_REF, HEADER_API_VERSION, HEADER_IDEMPOTENCY_KEY, HEADER_REQUEST_ID, METER_CHARGE_MODES, MeterCreditPropertiesSchema, MeterPeriodListSchema, ProductSettingsPatchSchema, StewardApiError, StewardConfigError, StewardContractError, StewardError, StewardNetworkError, WebhookEndpointCreateInputSchema, WebhookEndpointRotateInputSchema, createSteward, generateWebhookSecret, plainDecimalOf } from "@stewardhq/sdk";
5
+ import { ApiKeyCreateInputSchema, BankTransferRecordInputSchema, CatalogSyncInputSchema, CreditAdjustmentInputSchema, DunningPolicySchema, EventsIngestInputSchema, METER_CHARGE_MODES, MeterCreditPropertiesSchema, ProductSettingsPatchSchema, RepriceInputSchema, StewardApiError, StewardConfigError, StewardError, StewardNetworkError, WebhookEndpointCreateInputSchema, WebhookEndpointRotateInputSchema, createSteward, generateApiKeyToken, generateWebhookSecret, plainDecimalOf } from "@stewardhq/sdk";
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
13
  /** Sır biçimindeki değerleri maskeler (`whsec_***`). */
@@ -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) {
@@ -410,6 +349,18 @@ function priceChangeCount(diff) {
410
349
  return diff.prices.changed.length + diff.meteredPrices.changed.length;
411
350
  }
412
351
  //#endregion
352
+ //#region src/confirm.ts
353
+ /**
354
+ * Asks before a change that cannot be taken back; `yes` (`--yes`) skips the question. Without a
355
+ * terminal (CI, pipes) the command needs `--yes`: `notConfirmed` says what was not done.
356
+ */
357
+ async function confirm(ctx, question, options) {
358
+ if (options.yes) return true;
359
+ const answer = await ctx.prompt(`${question} [y/N] `);
360
+ if (answer === null) throw new CliError(`confirmation needed: run again with --yes (${options.notConfirmed})`);
361
+ return /^y(es)?$/i.test(answer.trim());
362
+ }
363
+ //#endregion
413
364
  //#region src/dotenv.ts
414
365
  const LINE = /^(\s*)(export\s+)?([A-Za-z_][A-Za-z0-9_.-]*)\s*=(.*)$/;
415
366
  function unquote(rest) {
@@ -496,7 +447,7 @@ function whereMissing(env) {
496
447
  case "missing": return `tanımlı değil (ortam değişkeni ya da ./${ENV_LOCAL}; dosya yok)`;
497
448
  }
498
449
  }
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.";
450
+ 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
451
  function pairError(names, missing, env) {
501
452
  return new CliError(`${names.url} + ${names.key} gerekli: ${missing.join(" ve ")} ${whereMissing(env)}.\n${ADMIN_HINT}`);
502
453
  }
@@ -577,160 +528,721 @@ function describeStewardError(error, target) {
577
528
  return `steward yanıtı sözleşmeye uymuyor${where}: ${error.code} (HTTP ${error.httpStatus}) — CLI ile steward sürümleri uyumsuz olabilir${request}`;
578
529
  }
579
530
  //#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"
531
+ //#region src/secret-file.ts
532
+ async function withSecretFile(cwd, out, secret, options, action) {
533
+ const target = resolve(cwd, out);
534
+ try {
535
+ if ((await lstat(target)).isDirectory()) throw new CliError(`--out bir klasör: ${out}`);
536
+ if (!options.force) throw new CliError(`${out} zaten var; üzerine yazmak için --force (istek gönderilmedi)`);
537
+ } catch (error) {
538
+ if (error instanceof CliError) throw error;
539
+ if (errnoCode(error) !== "ENOENT") throw error;
611
540
  }
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}`);
541
+ const temp = join(dirname(target), `.${basename(target)}.${randomUUID().slice(0, 8)}.tmp`);
542
+ try {
543
+ await writeFile(temp, secret, {
544
+ mode: 384,
545
+ flag: "wx"
546
+ });
547
+ } catch (error) {
548
+ const code = errnoCode(error);
549
+ if (code === "ENOENT") throw new CliError(`--out klasörü yok: ${relative(cwd, dirname(target)) || "."}`);
550
+ throw new CliError(`sır dosyası yazılamadı (${code ?? "hata"}): ${out} (istek gönderilmedi)`);
641
551
  }
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;
552
+ let value;
553
+ try {
554
+ value = await action();
555
+ } catch (error) {
556
+ await unlink(temp).catch(() => {});
652
557
  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
- }
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
558
  }
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;
559
+ try {
560
+ if (options.force) await rename(temp, target);
561
+ else {
562
+ await link(temp, target);
563
+ await unlink(temp).catch(() => {});
694
564
  }
565
+ return {
566
+ value,
567
+ path: out,
568
+ fallback: false
569
+ };
570
+ } catch {
571
+ return {
572
+ value,
573
+ path: relative(cwd, temp),
574
+ fallback: true
575
+ };
695
576
  }
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
577
  }
700
578
  //#endregion
701
- //#region src/commands/doctor.ts
702
- const DOCTOR_USAGE = `Kullanım: steward doctor [--json]
703
-
704
- GET /v1/doctor raporu: katalog, sağlayıcı, ayarlar, hosted sayfa hazırlığı,
705
- endpoint teslimat teşhisi ve uyarılar. APP_URL tanımlıysa steward'daki appUrl
706
- ve izinli dönüş origin'leriyle karşılaştırılır.
707
-
708
- Bağlantı: STEWARD_URL + STEWARD_API_KEY (ikisi de yoksa STEWARD_ADMIN_URL +
709
- STEWARD_ADMIN_API_KEY). Ortamda steward bağlantı değişkenlerinden biri bile
710
- varsa bağlantı ve APP_URL yalnızca ortamdan okunur (./.env.local okunmaz);
711
- yoksa ./.env.local'den. Kaynak ve hedefin origin'i stderr'e yazılır.
712
-
713
- Çıkış kodu: 0 hazır; 1 rapor ok değil (error önemde uyarı) ya da APP_URL
714
- steward'da izinli değil.
579
+ //#region src/commands/endpoints.ts
580
+ const ENDPOINTS_USAGE = `Kullanım:
581
+ steward endpoints list [--json]
582
+ steward endpoints add --url <url> --out <dosya> [--event-types <a,b>] [--description <metin>] [--force]
583
+ steward endpoints rotate <id> --out <dosya> [--force]
584
+ steward endpoints deactivate <id>
715
585
 
716
- Metering: for a product whose catalog defines meters, a "metering" line lists the
717
- meters and metered prices (GET /v1/catalog) and the steward capabilities (GET /v1/me:
718
- events, meters, overage); the report's "events" section (backlog, rollup lag, a sample
719
- of the last 7 days: unmatched event names, invalid values, meters without events) and
720
- "overage" section (charge mode, metered prices, subscriptions without a locked rate,
721
- carried charges) follow. Metering warnings are in the lists as usual.
586
+ Webhook endpoint'leri (/v1/admin/webhook-endpoints). İmza sırrı (whsec_…) bu
587
+ makinede üretilir ve YALNIZCA --out dosyasına yazılır (0600, satır sonu yok);
588
+ terminale yazılmaz, steward hiçbir yanıtta geri vermez. Dosya varsa --force
589
+ olmadan istek gönderilmez. Sırrı ürünün Secret'ına operatör taşır (CLI kubectl
590
+ çağırmaz); rotasyonda ürün "yeni,eski" listesiyle geçer. Taşıdıktan sonra dosyayı
591
+ silin. --event-types verilmezse yalnızca account.state_changed. deactivate geri
592
+ alınmaz (yeni endpoint açılır).
722
593
 
723
- --json raporu JSON yazar (+ cliWarnings: yerel APP_URL karşılaştırması;
724
- cliMetering: the metering line's catalog and capability facts)`;
725
- /** `APP_URL` (ürünün kendi adresi; checkout `successUrl`'i bundan kurulur) ↔ steward ayarları. */
726
- function appUrlWarnings(appUrl, report) {
727
- if (appUrl === void 0) return [];
728
- let origin;
729
- try {
730
- origin = new URL(appUrl).origin;
731
- } catch {
732
- return [{
733
- code: "app_url_env_invalid",
594
+ Bağlantı: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (ortam, yoksa ./.env.local).`;
595
+ function schemaProblems(issues) {
596
+ return issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(kök)"}: ${issue.message}`).join("\n");
597
+ }
598
+ const lastDeliveryText = (endpoint) => {
599
+ const last = endpoint.lastDelivery;
600
+ if (last === null) return "-";
601
+ return `${last.status}${last.httpStatus !== null ? ` ${last.httpStatus}` : ""}${last.error !== null ? ` ${last.error}` : ""} (${last.at})`;
602
+ };
603
+ /** Left-aligned columns; the last column is not padded. */
604
+ function table(rows) {
605
+ const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
606
+ return rows.map((row) => row.map((cell, column) => column === row.length - 1 ? cell : cell.padEnd(widths[column])).join(" "));
607
+ }
608
+ const typesText = (endpoint) => endpoint.eventTypes === null ? "(filtre yok: 0.1 tipleri)" : endpoint.eventTypes.join(",");
609
+ async function endpointsCommand(ctx, out, args) {
610
+ const [sub, ...rest] = args;
611
+ if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
612
+ out.out(ENDPOINTS_USAGE);
613
+ return sub === void 0 ? 2 : 0;
614
+ }
615
+ if (sub === "list") {
616
+ const { values, positionals } = parse(rest, {
617
+ ...HELP_OPTION,
618
+ json: { type: "boolean" }
619
+ }, "endpoints");
620
+ if (values.help) return help$3(out);
621
+ expectPositionals(positionals, 0, 0, "endpoints");
622
+ const target = requireAdminTarget(await resolveEnv(ctx));
623
+ out.err(connectionLine(target));
624
+ const { items } = await callSteward(target, () => clientFor(ctx, target).admin.endpoints.list());
625
+ if (values.json) out.out(JSON.stringify(items, null, 2));
626
+ else if (items.length === 0) out.out("endpoint yok — steward endpoints add --url <url> --out <dosya>");
627
+ else {
628
+ const rows = [[
629
+ "ID",
630
+ "DURUM",
631
+ "OLAYLAR",
632
+ "SON TESLİMAT",
633
+ "URL"
634
+ ]];
635
+ for (const e of items) rows.push([
636
+ e.id,
637
+ e.status,
638
+ typesText(e),
639
+ lastDeliveryText(e),
640
+ e.description !== null ? `${e.url} (${e.description})` : e.url
641
+ ]);
642
+ for (const line of table(rows)) out.out(line);
643
+ }
644
+ return 0;
645
+ }
646
+ if (sub === "add") {
647
+ const { values, positionals } = parse(rest, {
648
+ ...HELP_OPTION,
649
+ url: { type: "string" },
650
+ out: { type: "string" },
651
+ "event-types": { type: "string" },
652
+ description: { type: "string" },
653
+ force: { type: "boolean" }
654
+ }, ENDPOINTS_USAGE);
655
+ if (values.help) return help$3(out);
656
+ expectPositionals(positionals, 0, 0, "endpoints");
657
+ const url = requireOption(values.url, "--url", "endpoints");
658
+ const file = requireOption(values.out, "--out", "endpoints");
659
+ const secret = generateWebhookSecret();
660
+ const input = {
661
+ url,
662
+ secret,
663
+ ...values["event-types"] !== void 0 ? { eventTypes: parseList(values["event-types"]) } : {},
664
+ ...values.description !== void 0 ? { description: values.description } : {}
665
+ };
666
+ const parsed = WebhookEndpointCreateInputSchema.safeParse(input);
667
+ if (!parsed.success) throw new UsageError(`endpoint geçersiz (istek gönderilmedi)\n${schemaProblems(parsed.error.issues)}`);
668
+ const target = requireAdminTarget(await resolveEnv(ctx));
669
+ out.err(connectionLine(target));
670
+ const steward = clientFor(ctx, target);
671
+ const result = await withSecretFile(ctx.cwd, file, secret, { force: values.force === true }, () => callSteward(target, () => steward.admin.endpoints.create(input)));
672
+ const endpoint = result.value;
673
+ out.out(`endpoint oluşturuldu → ${originOf(target.url)}`);
674
+ out.out(` id ${endpoint.id}`);
675
+ out.out(` url ${endpoint.url}`);
676
+ out.out(` olaylar ${typesText(endpoint)}`);
677
+ secretNotice(out, result.path, result.fallback, "Sırrı ürünün Secret'ına (STEWARD_WEBHOOK_SECRET) taşıyın, sonra dosyayı silin.");
678
+ return 0;
679
+ }
680
+ if (sub === "rotate") {
681
+ const { values, positionals } = parse(rest, {
682
+ ...HELP_OPTION,
683
+ out: { type: "string" },
684
+ force: { type: "boolean" }
685
+ }, "endpoints");
686
+ if (values.help) return help$3(out);
687
+ expectPositionals(positionals, 1, 1, "endpoints");
688
+ const id = positionals[0];
689
+ const file = requireOption(values.out, "--out", "endpoints");
690
+ const secret = generateWebhookSecret();
691
+ const parsed = WebhookEndpointRotateInputSchema.safeParse({ secret });
692
+ if (!parsed.success) throw new UsageError(`sır geçersiz\n${schemaProblems(parsed.error.issues)}`);
693
+ const target = requireAdminTarget(await resolveEnv(ctx));
694
+ out.err(connectionLine(target));
695
+ const steward = clientFor(ctx, target);
696
+ const result = await withSecretFile(ctx.cwd, file, secret, { force: values.force === true }, () => callSteward(target, () => steward.admin.endpoints.rotate(id, { secret })));
697
+ out.out(`sır döndürüldü → ${originOf(target.url)}`);
698
+ out.out(` id ${result.value.id}`);
699
+ out.out(` url ${result.value.url}`);
700
+ 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.");
701
+ return 0;
702
+ }
703
+ if (sub === "deactivate") {
704
+ const { values, positionals } = parse(rest, { ...HELP_OPTION }, "endpoints");
705
+ if (values.help) return help$3(out);
706
+ expectPositionals(positionals, 1, 1, "endpoints");
707
+ const target = requireAdminTarget(await resolveEnv(ctx));
708
+ out.err(connectionLine(target));
709
+ const endpoint = await callSteward(target, () => clientFor(ctx, target).admin.endpoints.deactivate(positionals[0]));
710
+ out.out(`endpoint pasifleştirildi → ${originOf(target.url)}: ${endpoint.id} (${endpoint.url}, durum ${endpoint.status})`);
711
+ return 0;
712
+ }
713
+ throw new UsageError(`bilinmeyen alt komut: endpoints ${sub} (ayrıntı: steward endpoints --help)`);
714
+ }
715
+ function help$3(out) {
716
+ out.out(ENDPOINTS_USAGE);
717
+ return 0;
718
+ }
719
+ /** Where a generated secret went (`withSecretFile`); shared by `endpoints` and `keys`. */
720
+ function secretNotice(out, path, fallback, next) {
721
+ 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)`);
722
+ out.out(` secret ${path} (0600; not written to the terminal)`);
723
+ out.err(next);
724
+ }
725
+ //#endregion
726
+ //#region src/commands/bank-transfers.ts
727
+ const BANK_TRANSFERS_USAGE = `Usage:
728
+ steward bank-transfers list [--status pending|expired] [--json]
729
+ steward bank-transfers record <code> --amount <minor> --currency <CUR> --received-at <iso>
730
+ --bank-ref <ref> [--checkout <id> [--accept-expired] | --invoice <id>]
731
+ [--yes] [--json]
732
+
733
+ Bank transfer (havale/EFT) reconciliation (/v1/admin/bank-transfers).
734
+
735
+ list: what the bank statement is matched against. pending (default): checkouts waiting for a
736
+ transfer and unpaid invoices of accounts with an order code, by deadline; expired: checkouts
737
+ that expired in the last 30 days.
738
+
739
+ record: a transfer seen on the bank account. <code> is the order code from the transfer
740
+ description (case and dashes are forgiven). Only a checkout or unpaid invoice waiting for
741
+ EXACTLY --amount (minor units, e.g. 125000 = 1,250.00) in --currency matches. --received-at
742
+ is ISO-8601 with an offset (2026-09-28T10:15:00+03:00). --bank-ref is the bank's transaction
743
+ number; one payment per reference. When several items match, name one with --checkout or
744
+ --invoice; an expired checkout is accepted only with --accept-expired --checkout <id>.
745
+ A refused transfer is refunded through the bank. Recording needs confirmation (a prompt on a
746
+ terminal, otherwise --yes): it starts a subscription or pays an invoice.
747
+
748
+ Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
749
+ const WITH_OFFSET = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/;
750
+ async function bankTransfersCommand(ctx, out, args) {
751
+ const [sub, ...rest] = args;
752
+ if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
753
+ out.out(BANK_TRANSFERS_USAGE);
754
+ return sub === void 0 ? 2 : 0;
755
+ }
756
+ if (sub === "list") {
757
+ const { values, positionals } = parse(rest, {
758
+ ...HELP_OPTION,
759
+ status: { type: "string" },
760
+ json: { type: "boolean" }
761
+ }, "bank-transfers");
762
+ if (values.help) return help$2(out);
763
+ expectPositionals(positionals, 0, 0, "bank-transfers");
764
+ const status = values.status ?? "pending";
765
+ if (status !== "pending" && status !== "expired") throw new UsageError("--status: pending or expired");
766
+ const target = requireAdminTarget(await resolveEnv(ctx));
767
+ out.err(connectionLine(target));
768
+ const { items } = await callSteward(target, () => clientFor(ctx, target).admin.bankTransfers.list(status));
769
+ if (values.json) out.out(JSON.stringify(items, null, 2));
770
+ else if (items.length === 0) out.out(`no ${status} bank transfers`);
771
+ else {
772
+ const rows = [[
773
+ "CODE",
774
+ "AMOUNT",
775
+ "DEADLINE",
776
+ "KIND",
777
+ "PLAN",
778
+ "ACCOUNT",
779
+ "ID"
780
+ ]];
781
+ for (const i of items) rows.push([
782
+ i.code ?? "-",
783
+ formatMinor(i.totalMinor, i.currency),
784
+ i.deadline ?? "-",
785
+ i.kind,
786
+ i.planCode ?? "-",
787
+ i.accountRef,
788
+ i.id
789
+ ]);
790
+ for (const line of table(rows)) out.out(line);
791
+ }
792
+ return 0;
793
+ }
794
+ if (sub === "record") {
795
+ const { values, positionals } = parse(rest, {
796
+ ...HELP_OPTION,
797
+ amount: { type: "string" },
798
+ currency: { type: "string" },
799
+ "received-at": { type: "string" },
800
+ "bank-ref": { type: "string" },
801
+ checkout: { type: "string" },
802
+ invoice: { type: "string" },
803
+ "accept-expired": { type: "boolean" },
804
+ yes: {
805
+ type: "boolean",
806
+ short: "y"
807
+ },
808
+ json: { type: "boolean" }
809
+ }, "bank-transfers");
810
+ if (values.help) return help$2(out);
811
+ expectPositionals(positionals, 1, 1, "bank-transfers");
812
+ const receivedAt = requireOption(values["received-at"], "--received-at", "bank-transfers");
813
+ if (!WITH_OFFSET.test(receivedAt)) throw new UsageError("--received-at: ISO-8601 with an offset (2026-09-28T10:15:00+03:00)");
814
+ const input = {
815
+ code: positionals[0],
816
+ amountMinor: parseNonNegativeInt(requireOption(values.amount, "--amount", "bank-transfers"), "--amount"),
817
+ currency: requireOption(values.currency, "--currency", "bank-transfers").toUpperCase(),
818
+ receivedAt,
819
+ bankRef: requireOption(values["bank-ref"], "--bank-ref", "bank-transfers"),
820
+ ...values.checkout !== void 0 ? { checkoutSessionId: values.checkout } : {},
821
+ ...values.invoice !== void 0 ? { invoiceId: values.invoice } : {},
822
+ ...values["accept-expired"] ? { acceptExpired: true } : {}
823
+ };
824
+ const parsed = BankTransferRecordInputSchema.safeParse(input);
825
+ if (!parsed.success) throw new UsageError(`invalid transfer (nothing was sent)\n${parsed.error.issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(root)"}: ${issue.message}`).join("\n")}`);
826
+ const target = requireAdminTarget(await resolveEnv(ctx));
827
+ out.err(connectionLine(target));
828
+ if (!await confirm(ctx, `Record ${formatMinor(input.amountMinor, input.currency)} for order code ${input.code} (bank ref ${input.bankRef})?`, {
829
+ yes: values.yes === true,
830
+ notConfirmed: "nothing was recorded"
831
+ })) {
832
+ out.err("not confirmed; nothing was recorded");
833
+ return 1;
834
+ }
835
+ const recorded = await callSteward(target, () => clientFor(ctx, target).admin.bankTransfers.record(input));
836
+ if (values.json) {
837
+ out.out(JSON.stringify(recorded, null, 2));
838
+ return 0;
839
+ }
840
+ 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)" : ""}`);
841
+ return 0;
842
+ }
843
+ throw new UsageError(`unknown subcommand: bank-transfers ${sub} (see: steward bank-transfers --help)`);
844
+ }
845
+ function help$2(out) {
846
+ out.out(BANK_TRANSFERS_USAGE);
847
+ return 0;
848
+ }
849
+ //#endregion
850
+ //#region src/catalog-file.ts
851
+ const MODULE_EXTENSIONS = /* @__PURE__ */ new Set([
852
+ ".js",
853
+ ".mjs",
854
+ ".cjs"
855
+ ]);
856
+ const TS_EXTENSIONS = /* @__PURE__ */ new Set([
857
+ ".ts",
858
+ ".mts",
859
+ ".cts"
860
+ ]);
861
+ const hasSyncInput = (value) => typeof value === "object" && value !== null && typeof value.toSyncInput === "function";
862
+ function pickExport(mod, file) {
863
+ if (mod.catalog !== void 0) return mod.catalog;
864
+ if (mod.default !== void 0) return mod.default;
865
+ const candidates = Object.values(mod).filter(hasSyncInput);
866
+ if (candidates.length === 1) return candidates[0];
867
+ throw new CliError(`${file}: katalog bulunamadı — \`export const catalog = defineCatalog(…)\` ya da default export bekleniyor`);
868
+ }
869
+ async function loadCatalogFile(ctx, file) {
870
+ const path = resolve(ctx.cwd, file);
871
+ const ext = extname(path).toLowerCase();
872
+ let exported;
873
+ if (ext === ".json") {
874
+ let text;
875
+ try {
876
+ text = await readFile(path, "utf8");
877
+ } catch (error) {
878
+ throw new CliError(errnoCode(error) === "ENOENT" ? `katalog dosyası yok: ${file}` : `katalog dosyası okunamadı: ${file}`);
879
+ }
880
+ try {
881
+ exported = JSON.parse(text);
882
+ } catch {
883
+ throw new CliError(`${file}: geçerli JSON değil`);
884
+ }
885
+ } else if (MODULE_EXTENSIONS.has(ext) || TS_EXTENSIONS.has(ext)) {
886
+ 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.`);
887
+ let mod;
888
+ try {
889
+ await readFile(path);
890
+ } catch (error) {
891
+ throw new CliError(errnoCode(error) === "ENOENT" ? `katalog dosyası yok: ${file}` : `katalog dosyası okunamadı: ${file}`);
892
+ }
893
+ try {
894
+ mod = await ctx.importModule(pathToFileURL(path).href);
895
+ } catch (error) {
896
+ throw new CliError(`${file} yüklenemedi: ${error instanceof Error ? error.message : String(error)}`);
897
+ }
898
+ exported = pickExport(mod, file);
899
+ } else throw new UsageError(`katalog dosyası .ts, .mts, .js, .mjs, .cjs ya da .json olmalı: ${file}`);
900
+ let input;
901
+ try {
902
+ input = hasSyncInput(exported) ? exported.toSyncInput() : exported;
903
+ } catch (error) {
904
+ throw new CliError(`${file}: toSyncInput() hata verdi: ${error instanceof Error ? error.message : String(error)}`);
905
+ }
906
+ const parsed = CatalogSyncInputSchema.safeParse(input);
907
+ 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")}`);
908
+ return input;
909
+ }
910
+ //#endregion
911
+ //#region src/commands/catalog.ts
912
+ const CATALOG_USAGE = `Kullanım: steward catalog push <dosya> [--yes]
913
+
914
+ Katalog tanımını steward'a senkronlar (PUT /v1/admin/catalog), sonra sürümü ve
915
+ sayıları yazar. Dosya: .ts/.mts (Node tip ayıklaması, Node ≥ 22.18), .js/.mjs/.cjs
916
+ (\`export const catalog = defineCatalog(…)\` ya da default export) veya .json
917
+ (senkron gövdesi). Geçersiz katalogda istek gönderilmez.
918
+
919
+ Before pushing, prints what changes against steward's current catalog: benefits
920
+ (new, changed, archived, plan benefit lists) and prices (new, deactivated, amount or
921
+ tax terms changed). A changed price is updated in place: existing subscriptions keep
922
+ the amount they locked, new subscriptions pay the new amount, a tax change applies to
923
+ every invoice written from now on. Price changes need confirmation: a prompt on a
924
+ terminal, otherwise --yes (-y). A catalog with benefits is pushed only to a steward
925
+ whose GET /v1/me lists the "benefits" capability (an older steward would drop them).
926
+
927
+ Metering: the diff also lists meters (new, changed, rule changed, archived), changed
928
+ credits (meter_credit benefits) and metered prices (new, deactivated, changed; a
929
+ changed metered price needs the same confirmation). A meter's filter and aggregation
930
+ are fixed once it has counted a period (422 meter_locked: use a new meter code). A
931
+ catalog with meters or metered prices is pushed only to a steward whose GET /v1/me
932
+ lists the "meters" capability.
933
+
934
+ Bağlantı: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (ortam, yoksa ./.env.local).
935
+ Çıkış kodu 1: sağlayıcıda karşılığı açılamayan fiyat var (senkronu yeniden koşun);
936
+ the push was refused or not confirmed.`;
937
+ const PUSH_OPTIONS = {
938
+ ...HELP_OPTION,
939
+ yes: {
940
+ type: "boolean",
941
+ short: "y"
942
+ }
943
+ };
944
+ const list = (items) => items.length > 0 ? items.join(", ") : "-";
945
+ /** Senkron + sürüm okuması; özet satırları ve sağlayıcı hatası olup olmadığı. */
946
+ async function pushCatalog(steward, target, input) {
947
+ const result = await callSteward(target, () => steward.admin.catalog.sync(input));
948
+ const version = (await callSteward(target, () => steward.catalog.read())).etag?.replace(/^W\//, "").replace(/"/g, "") ?? "bilinmiyor";
949
+ const benefitCount = Object.keys(input.benefits ?? {}).length;
950
+ const meterCount = Object.keys(input.meters ?? {}).length;
951
+ const meteredCount = (input.meteredPrices ?? []).length;
952
+ const metering = `${meterCount > 0 ? ` · ${meterCount} meter${meterCount === 1 ? "" : "s"}` : ""}${meteredCount > 0 ? ` · ${meteredCount} metered price${meteredCount === 1 ? "" : "s"}` : ""}`;
953
+ const lines = [`katalog senkronlandı → ${originOf(target.url)}`];
954
+ lines.push(` sürüm ${version}`);
955
+ 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}`);
956
+ if (result.unchanged) lines.push(" değişiklik yok");
957
+ else {
958
+ 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" : ""}`);
959
+ const changedBenefits = result.changedBenefits ?? [];
960
+ const archivedBenefits = result.archivedBenefits ?? [];
961
+ if (changedBenefits.length > 0 || archivedBenefits.length > 0) lines.push(` benefits changed: ${list(changedBenefits)} · archived: ${list(archivedBenefits)}`);
962
+ if ((result.updatedPrices ?? []).length > 0) lines.push(` prices updated in place: ${result.updatedPrices.length}`);
963
+ const changedMeters = result.changedMeters ?? [];
964
+ const archivedMeters = result.archivedMeters ?? [];
965
+ if (changedMeters.length > 0 || archivedMeters.length > 0) lines.push(` meters changed: ${list(changedMeters)} · archived: ${list(archivedMeters)}`);
966
+ const [created, updated, deactivated] = [
967
+ result.createdMeteredPrices ?? [],
968
+ result.updatedMeteredPrices ?? [],
969
+ result.deactivatedMeteredPrices ?? []
970
+ ];
971
+ if (created.length + updated.length + deactivated.length > 0) lines.push(` metered new ${created.length} · updated in place ${updated.length} · deactivated ${deactivated.length}`);
972
+ }
973
+ for (const error of result.providerErrors) lines.push(` ✗ sağlayıcı hatası: fiyat ${error.priceId} (${error.provider}: ${error.code}) — senkronu yeniden koşun`);
974
+ return {
975
+ lines,
976
+ providerErrors: result.providerErrors.length
977
+ };
978
+ }
979
+ /** The steward's current catalog; null before the first push (`404 catalog_not_configured`). */
980
+ function currentCatalog(steward, target) {
981
+ return callSteward(target, () => steward.catalog.get().catch((error) => {
982
+ if (error instanceof StewardApiError && error.httpStatus === 404 && error.code === "catalog_not_configured") return null;
983
+ throw error;
984
+ }));
985
+ }
986
+ /**
987
+ * Refuses a catalog whose benefits or meters steward does not understand (M27): an older steward
988
+ * drops the keys silently. `needed`: the capabilities the catalog needs (`benefits`, `meters`).
989
+ */
990
+ async function requireCapabilities(steward, target, needed) {
991
+ if (needed.length === 0) return;
992
+ const me = await callSteward(target, () => steward.me());
993
+ const missing = needed.filter((capability) => !(me.capabilities ?? []).includes(capability));
994
+ if (missing.length === 0) return;
995
+ throw new CliError(`the catalog defines ${missing.join(" and ")} but steward at ${originOf(target.url)} does not support them (GET /v1/me capabilities has no ${missing.map((c) => `"${c}"`).join(", ")}; it would drop them silently). Update steward first; nothing was pushed.`);
996
+ }
997
+ async function catalogCommand(ctx, out, args) {
998
+ const [sub, ...rest] = args;
999
+ if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
1000
+ out.out(CATALOG_USAGE);
1001
+ return sub === void 0 ? 2 : 0;
1002
+ }
1003
+ if (sub !== "push") throw new UsageError(`bilinmeyen alt komut: catalog ${sub} (ayrıntı: steward catalog --help)`);
1004
+ const { values, positionals } = parse(rest, PUSH_OPTIONS, "catalog push");
1005
+ if (values.help) {
1006
+ out.out(CATALOG_USAGE);
1007
+ return 0;
1008
+ }
1009
+ expectPositionals(positionals, 1, 1, "catalog push");
1010
+ const input = await loadCatalogFile(ctx, positionals[0]);
1011
+ const target = requireAdminTarget(await resolveEnv(ctx));
1012
+ out.err(connectionLine(target));
1013
+ const steward = clientFor(ctx, target);
1014
+ await requireCapabilities(steward, target, [...definesBenefits(input) ? ["benefits"] : [], ...definesMeters(input) ? ["meters"] : []]);
1015
+ const diff = diffCatalog(await currentCatalog(steward, target), input);
1016
+ for (const line of describeDiff(diff)) out.out(line);
1017
+ const priceChanges = priceChangeCount(diff);
1018
+ if (priceChanges > 0 && !values.yes) {
1019
+ const question = `Apply ${priceChanges} price change${priceChanges === 1 ? "" : "s"}? [y/N] `;
1020
+ const answer = await ctx.prompt(question);
1021
+ if (answer === null) throw new CliError(`${priceChanges} price change${priceChanges === 1 ? "" : "s"} need${priceChanges === 1 ? "s" : ""} confirmation: run again with --yes (nothing was pushed)`);
1022
+ if (!/^y(es)?$/i.test(answer.trim())) {
1023
+ out.err("not confirmed; nothing was pushed");
1024
+ return 1;
1025
+ }
1026
+ }
1027
+ const { lines, providerErrors } = await pushCatalog(steward, target, input);
1028
+ for (const line of lines) out.out(line);
1029
+ return providerErrors > 0 ? 1 : 0;
1030
+ }
1031
+ //#endregion
1032
+ //#region src/commands/meters.ts
1033
+ const METERS_USAGE = `Usage:
1034
+ steward meters get <ref> [--periods <n>] [--json]
1035
+ steward meters recompute <ref> [--meter <code>] [--json]
1036
+ steward meters close-periods <ref> [--meter <code>] [--force] [--json]
1037
+
1038
+ Reads an account's meters (GET /v1/accounts/:ref/meters): per meter the current usage
1039
+ period, units used, the period's credit, the balance, the standing (ok | low | exhausted)
1040
+ and, for a billable meter, the estimated overage so far. Nothing is written.
1041
+
1042
+ --periods <n> also list the last n closed periods (1–100; GET …/meters/periods)
1043
+ --json print the response as JSON
1044
+
1045
+ recompute (admin): rebuilds the account's OPEN usage period of every meter (or --meter) from
1046
+ the raw events, the repair of a wrongly counted period. Closed periods never change; running it
1047
+ again gives the same result. Prints each meter's consumption before and after.
1048
+
1049
+ close-periods (admin): closes the account's closing periods now instead of after the late
1050
+ window (recount from raw events, meter.period_closed). It waits for unrolled events unless
1051
+ --force (those then count in a later period as late). Open periods are never touched.
1052
+
1053
+ Connection: get uses STEWARD_URL + STEWARD_API_KEY (or, when neither is set, STEWARD_ADMIN_URL +
1054
+ STEWARD_ADMIN_API_KEY); recompute and close-periods use STEWARD_ADMIN_URL +
1055
+ STEWARD_ADMIN_API_KEY. Environment, otherwise ./.env.local.`;
1056
+ const REPAIR_OPTIONS = {
1057
+ ...HELP_OPTION,
1058
+ meter: { type: "string" },
1059
+ force: { type: "boolean" },
1060
+ json: { type: "boolean" }
1061
+ };
1062
+ async function repairCommand(ctx, out, sub, args) {
1063
+ const { values, positionals } = parse(args, REPAIR_OPTIONS, "meters");
1064
+ if (values.help) {
1065
+ out.out(METERS_USAGE);
1066
+ return 0;
1067
+ }
1068
+ expectPositionals(positionals, 1, 1, "meters");
1069
+ if (sub === "recompute" && values.force) throw new UsageError("--force is for close-periods");
1070
+ const ref = positionals[0];
1071
+ const meter = values.meter !== void 0 ? { meter: values.meter } : {};
1072
+ const target = requireAdminTarget(await resolveEnv(ctx));
1073
+ out.err(connectionLine(target));
1074
+ const steward = clientFor(ctx, target);
1075
+ if (sub === "recompute") {
1076
+ const result = await callSteward(target, () => steward.admin.meters.recompute(ref, meter));
1077
+ if (values.json) out.out(JSON.stringify(result, null, 2));
1078
+ 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}`);
1079
+ return 0;
1080
+ }
1081
+ const result = await callSteward(target, () => steward.admin.meters.closePeriods(ref, {
1082
+ ...meter,
1083
+ ...values.force ? { force: true } : {}
1084
+ }));
1085
+ if (values.json) out.out(JSON.stringify(result, null, 2));
1086
+ else out.out(`${result.closed} period(s) closed, ${result.events} meter.period_closed event(s); ${result.pending} closing period(s) left`);
1087
+ return 0;
1088
+ }
1089
+ const GET_OPTIONS = {
1090
+ ...HELP_OPTION,
1091
+ periods: { type: "string" },
1092
+ json: { type: "boolean" }
1093
+ };
1094
+ /** Units of a meter read (a JSON number with at most 6 decimals) as exact text with grouping: `1,700,000.5`. */
1095
+ function formatUnitsText(value) {
1096
+ return new Intl.NumberFormat("en", { maximumFractionDigits: 6 }).format(plainDecimalOf(value));
1097
+ }
1098
+ function meterLines(code, meter, width) {
1099
+ const lines = [` ${code.padEnd(width)} ${meter.periodStart} → ${meter.periodEnd}`];
1100
+ const indent = " ".repeat(width + 4);
1101
+ lines.push(`${indent}used ${formatUnitsText(meter.consumedUnits)} · credit ${formatUnitsText(meter.creditedUnits)} · balance ${formatUnitsText(meter.balance)} · standing ${meter.standing}`);
1102
+ const included = meter.includedUnits === null ? "no credit included" : `included ${formatUnitsText(meter.includedUnits)} per period`;
1103
+ 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)";
1104
+ lines.push(`${indent}${included} · ${billing}`);
1105
+ return lines;
1106
+ }
1107
+ /** Human-readable meter read (+ closed periods, newest first). */
1108
+ function formatMeters(meters, periods) {
1109
+ const lines = [`meters of ${meters.ref} · as of ${meters.asOf} · events received before ${meters.rolledUpThrough} are counted`];
1110
+ const codes = Object.keys(meters.meters);
1111
+ if (codes.length === 0) lines.push(" no meters (the product's catalog defines none)");
1112
+ else {
1113
+ const width = Math.max(...codes.map((code) => code.length));
1114
+ for (const code of codes) lines.push(...meterLines(code, meters.meters[code], width));
1115
+ }
1116
+ if (periods !== null) {
1117
+ lines.push("");
1118
+ if (periods.length === 0) lines.push("closed periods: none");
1119
+ else {
1120
+ lines.push("closed periods (newest first):");
1121
+ const width = Math.max(...periods.map((p) => p.meter.length));
1122
+ 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)}`);
1123
+ }
1124
+ }
1125
+ return lines;
1126
+ }
1127
+ async function metersCommand(ctx, out, args) {
1128
+ const [sub, ...rest] = args;
1129
+ if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
1130
+ out.out(METERS_USAGE);
1131
+ return sub === void 0 ? 2 : 0;
1132
+ }
1133
+ if (sub === "recompute" || sub === "close-periods") return repairCommand(ctx, out, sub, rest);
1134
+ if (sub !== "get") throw new UsageError(`unknown subcommand: meters ${sub} (see: steward meters --help)`);
1135
+ const { values, positionals } = parse(rest, GET_OPTIONS, "meters");
1136
+ if (values.help) {
1137
+ out.out(METERS_USAGE);
1138
+ return 0;
1139
+ }
1140
+ expectPositionals(positionals, 1, 1, "meters");
1141
+ const ref = positionals[0];
1142
+ const limit = values.periods === void 0 ? null : parsePositiveInt(values.periods, "--periods", { max: 100 });
1143
+ const target = requireReadTarget(await resolveEnv(ctx));
1144
+ out.err(connectionLine(target));
1145
+ const steward = clientFor(ctx, target);
1146
+ const meters = await callSteward(target, () => steward.meters.get(ref));
1147
+ const periods = limit === null ? null : (await callSteward(target, () => steward.meters.periods(ref, { limit }))).periods;
1148
+ if (values.json) out.out(JSON.stringify(periods === null ? meters : {
1149
+ ...meters,
1150
+ closedPeriods: periods
1151
+ }, null, 2));
1152
+ else for (const line of formatMeters(meters, periods)) out.out(line);
1153
+ return 0;
1154
+ }
1155
+ //#endregion
1156
+ //#region src/commands/credits.ts
1157
+ const CREDITS_USAGE = `Usage: steward credits adjust <ref> <meter> --units=<n> --reason <text> [--json]
1158
+
1159
+ One credit ledger entry for the meter's current usage period of account <ref>
1160
+ (POST /v1/admin/accounts/:ref/credits). Positive units add credit (manual_grant), negative
1161
+ units take it back (adjustment, e.g. events sent by mistake). Write a negative value with
1162
+ "=": --units=-2500. Units: a non-zero decimal with at most 6 places. --reason: 3–500
1163
+ characters, kept on the entry. Entries are never rewritten: a wrong one is corrected by
1164
+ another entry.
1165
+
1166
+ Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
1167
+ const UNITS = /^-?\d{1,16}(\.\d{1,6})?$/;
1168
+ async function creditsCommand(ctx, out, args) {
1169
+ const [sub, ...rest] = args;
1170
+ if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
1171
+ out.out(CREDITS_USAGE);
1172
+ return sub === void 0 ? 2 : 0;
1173
+ }
1174
+ if (sub !== "adjust") throw new UsageError(`unknown subcommand: credits ${sub} (see: steward credits --help)`);
1175
+ const { values, positionals } = parse(rest, {
1176
+ ...HELP_OPTION,
1177
+ units: { type: "string" },
1178
+ reason: { type: "string" },
1179
+ json: { type: "boolean" }
1180
+ }, "credits");
1181
+ if (values.help) {
1182
+ out.out(CREDITS_USAGE);
1183
+ return 0;
1184
+ }
1185
+ expectPositionals(positionals, 2, 2, "credits");
1186
+ const [ref, meter] = positionals;
1187
+ const unitsText = requireOption(values.units, "--units", "credits").trim();
1188
+ if (!UNITS.test(unitsText)) throw new UsageError(`--units: a decimal with at most 6 places, got ${unitsText}`);
1189
+ const input = {
1190
+ meter,
1191
+ units: Number(unitsText),
1192
+ reason: requireOption(values.reason, "--reason", "credits")
1193
+ };
1194
+ const parsed = CreditAdjustmentInputSchema.safeParse(input);
1195
+ 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")}`);
1196
+ const target = requireAdminTarget(await resolveEnv(ctx));
1197
+ out.err(connectionLine(target));
1198
+ const result = await callSteward(target, () => clientFor(ctx, target).admin.credits.adjust(ref, parsed.data));
1199
+ if (values.json) {
1200
+ out.out(JSON.stringify(result, null, 2));
1201
+ return 0;
1202
+ }
1203
+ const { entry } = result;
1204
+ out.out(`${entry.kind} of ${formatUnitsText(entry.units)} ${entry.meter} written → ${originOf(target.url)} (period from ${entry.periodStart})`);
1205
+ const read = result.meters.meters[entry.meter];
1206
+ if (read !== void 0) out.out(` balance ${formatUnitsText(read.balance)} · standing ${read.standing}`);
1207
+ return 0;
1208
+ }
1209
+ //#endregion
1210
+ //#region src/commands/doctor.ts
1211
+ const DOCTOR_USAGE = `Kullanım: steward doctor [--json]
1212
+
1213
+ GET /v1/doctor raporu. Bölümler sırayla: durum, katalog, sağlayıcı, ayarlar,
1214
+ hosted (sayfa hazırlığı), endpoint'ler (teslimat teşhisi), dunning, emails ve
1215
+ sayaçlı üründe metering/events/overage; sonda hatalar, uyarılar ve bilgi
1216
+ listeleri. APP_URL tanımlıysa steward'daki appUrl ve izinli dönüş
1217
+ origin'leriyle karşılaştırılır.
1218
+
1219
+ Bağlantı: STEWARD_URL + STEWARD_API_KEY (ikisi de yoksa STEWARD_ADMIN_URL +
1220
+ STEWARD_ADMIN_API_KEY). Ortamda steward bağlantı değişkenlerinden biri bile
1221
+ varsa bağlantı ve APP_URL yalnızca ortamdan okunur (./.env.local okunmaz);
1222
+ yoksa ./.env.local'den. Kaynak ve hedefin origin'i stderr'e yazılır.
1223
+
1224
+ Çıkış kodu: 0 hazır; 1 rapor ok değil (error önemde uyarı) ya da APP_URL
1225
+ steward'da izinli değil.
1226
+
1227
+ Ölçümleme: kataloğunda sayaç tanımlı üründe "metering" satırı sayaçları ve
1228
+ ölçümlü fiyatları (GET /v1/catalog) ve steward'ın yeteneklerini (GET /v1/me:
1229
+ events, meters, overage) yazar; ardından raporun "events" bölümü (bekleyen olay,
1230
+ rollup gecikmesi, son 7 günün örneği: eşleşmeyen olay adları, geçersiz değerler,
1231
+ olayı olmayan sayaçlar) ve "overage" bölümü (aşım kipi, ölçümlü fiyatlar, kilitli
1232
+ oranı olmayan abonelikler, devreden kayıtlar) gelir. Ölçümleme uyarıları her
1233
+ zamanki gibi alttaki listelerdedir.
1234
+
1235
+ --json raporu JSON yazar (+ cliWarnings: yerel APP_URL karşılaştırması;
1236
+ cliMetering: metering satırının katalog ve yetenek bilgileri)`;
1237
+ /** `APP_URL` (ürünün kendi adresi; checkout `successUrl`'i bundan kurulur) ↔ steward ayarları. */
1238
+ function appUrlWarnings(appUrl, report) {
1239
+ if (appUrl === void 0) return [];
1240
+ let origin;
1241
+ try {
1242
+ origin = new URL(appUrl).origin;
1243
+ } catch {
1244
+ return [{
1245
+ code: "app_url_env_invalid",
734
1246
  severity: "error",
735
1247
  message: "APP_URL geçerli bir adres değil"
736
1248
  }];
@@ -859,6 +1371,13 @@ function formatDoctorReport(report, cliWarnings, metering = null) {
859
1371
  const disabled = emails.disabledTemplates.length > 0 ? ` · disabled: ${emails.disabledTemplates.join(", ")}` : "";
860
1372
  lines.push(`emails ${emails.ready ? "ready ✓" : `not sending ✗${problems.length > 0 ? ` (${problems.join(", ")})` : ""}`}${disabled}`);
861
1373
  }
1374
+ if (report.apiKeys) {
1375
+ lines.push(report.apiKeys.length === 0 ? "api keys none active" : "api keys");
1376
+ for (const key of report.apiKeys) {
1377
+ const expiry = key.expiresAt === null ? "never expires" : `expires ${key.expiresAt}`;
1378
+ lines.push(` ${key.prefix} ${key.scope} ${key.name} · ${key.ageDays} day(s) old · last used ${key.lastUsedAt ?? "never"} · ${expiry}`);
1379
+ }
1380
+ }
862
1381
  lines.push(...formatMetering(report, metering));
863
1382
  for (const severity of SEVERITY_ORDER) {
864
1383
  const items = all.filter((w) => w.severity === severity);
@@ -889,292 +1408,104 @@ async function doctorCommand(ctx, out, args) {
889
1408
  if (appUrl === void 0) out.err(`APP_URL tanımlı değil (${env.source}): steward appUrl karşılaştırması atlandı`);
890
1409
  const steward = clientFor(ctx, target);
891
1410
  const report = await callSteward(target, () => steward.doctor());
892
- const cliWarnings = appUrlWarnings(appUrl, report);
893
- const failed = !report.ok || cliWarnings.some((w) => w.severity === "error");
894
- const metering = await meteringSummary(steward);
895
- if (values.json) out.out(JSON.stringify({
896
- ...report,
897
- cliWarnings,
898
- ...metering !== null ? { cliMetering: metering } : {}
899
- }, null, 2));
900
- else for (const line of formatDoctorReport(report, cliWarnings, metering)) out.out(line);
901
- return failed ? 1 : 0;
902
- }
903
- //#endregion
904
- //#region src/secret-file.ts
905
- async function withSecretFile(cwd, out, secret, options, action) {
906
- const target = resolve(cwd, out);
907
- try {
908
- if ((await lstat(target)).isDirectory()) throw new CliError(`--out bir klasör: ${out}`);
909
- if (!options.force) throw new CliError(`${out} zaten var; üzerine yazmak için --force (istek gönderilmedi)`);
910
- } catch (error) {
911
- if (error instanceof CliError) throw error;
912
- if (errnoCode(error) !== "ENOENT") throw error;
913
- }
914
- const temp = join(dirname(target), `.${basename(target)}.${randomUUID().slice(0, 8)}.tmp`);
915
- try {
916
- await writeFile(temp, secret, {
917
- mode: 384,
918
- flag: "wx"
919
- });
920
- } catch (error) {
921
- const code = errnoCode(error);
922
- if (code === "ENOENT") throw new CliError(`--out klasörü yok: ${relative(cwd, dirname(target)) || "."}`);
923
- throw new CliError(`sır dosyası yazılamadı (${code ?? "hata"}): ${out} (istek gönderilmedi)`);
924
- }
925
- let value;
926
- try {
927
- value = await action();
928
- } catch (error) {
929
- await unlink(temp).catch(() => {});
930
- throw error;
931
- }
932
- try {
933
- if (options.force) await rename(temp, target);
934
- else {
935
- await link(temp, target);
936
- await unlink(temp).catch(() => {});
937
- }
938
- return {
939
- value,
940
- path: out,
941
- fallback: false
942
- };
943
- } catch {
944
- return {
945
- value,
946
- path: relative(cwd, temp),
947
- fallback: true
948
- };
949
- }
950
- }
951
- //#endregion
952
- //#region src/commands/endpoints.ts
953
- const ENDPOINTS_USAGE = `Kullanım:
954
- steward endpoints list [--json]
955
- steward endpoints add --url <url> --out <dosya> [--event-types <a,b>] [--description <metin>] [--force]
956
- steward endpoints rotate <id> --out <dosya> [--force]
957
- steward endpoints deactivate <id>
958
-
959
- Webhook endpoint'leri (/v1/admin/webhook-endpoints). İmza sırrı (whsec_…) bu
960
- makinede üretilir ve YALNIZCA --out dosyasına yazılır (0600, satır sonu yok);
961
- terminale yazılmaz, steward hiçbir yanıtta geri vermez. Dosya varsa --force
962
- olmadan istek gönderilmez. Sırrı ürünün Secret'ına operatör taşır (CLI kubectl
963
- çağırmaz); rotasyonda ürün "yeni,eski" listesiyle geçer. Taşıdıktan sonra dosyayı
964
- silin. --event-types verilmezse yalnızca account.state_changed. deactivate geri
965
- alınmaz (yeni endpoint açılır).
966
-
967
- Bağlantı: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (ortam, yoksa ./.env.local).`;
968
- function schemaProblems(issues) {
969
- return issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(kök)"}: ${issue.message}`).join("\n");
970
- }
971
- const lastDeliveryText = (endpoint) => {
972
- const last = endpoint.lastDelivery;
973
- if (last === null) return "-";
974
- return `${last.status}${last.httpStatus !== null ? ` ${last.httpStatus}` : ""}${last.error !== null ? ` ${last.error}` : ""} (${last.at})`;
975
- };
976
- function table(rows) {
977
- const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
978
- return rows.map((row) => row.map((cell, column) => column === row.length - 1 ? cell : cell.padEnd(widths[column])).join(" "));
1411
+ const cliWarnings = appUrlWarnings(appUrl, report);
1412
+ const failed = !report.ok || cliWarnings.some((w) => w.severity === "error");
1413
+ const metering = await meteringSummary(steward);
1414
+ if (values.json) out.out(JSON.stringify({
1415
+ ...report,
1416
+ cliWarnings,
1417
+ ...metering !== null ? { cliMetering: metering } : {}
1418
+ }, null, 2));
1419
+ else for (const line of formatDoctorReport(report, cliWarnings, metering)) out.out(line);
1420
+ return failed ? 1 : 0;
979
1421
  }
980
- const typesText = (endpoint) => endpoint.eventTypes === null ? "(filtre yok: 0.1 tipleri)" : endpoint.eventTypes.join(",");
981
- async function endpointsCommand(ctx, out, args) {
1422
+ //#endregion
1423
+ //#region src/commands/dunning.ts
1424
+ const DUNNING_USAGE = `Usage:
1425
+ steward dunning get [--json]
1426
+ steward dunning set <policy.json> [--yes]
1427
+
1428
+ The product's dunning policy (/v1/admin/dunning-policy): what steward does after a renewal is
1429
+ not paid, by days since dunning started. Steps run in order:
1430
+ {"steps":[{"afterDays":1,"action":"retry_payment"},{"afterDays":7,"action":"suspend"},
1431
+ {"afterDays":30,"action":"terminate"}],"dryRun":false}
1432
+ retry_payment sends a payment reminder, suspend and terminate change the subscription.
1433
+ With "dryRun": true (the default) steps are only audited. Turning dryRun off needs
1434
+ confirmation (a prompt on a terminal, otherwise --yes): customers will be suspended.
1435
+
1436
+ Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
1437
+ 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"}`];
1438
+ async function dunningCommand(ctx, out, args) {
982
1439
  const [sub, ...rest] = args;
983
1440
  if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
984
- out.out(ENDPOINTS_USAGE);
1441
+ out.out(DUNNING_USAGE);
985
1442
  return sub === void 0 ? 2 : 0;
986
1443
  }
987
- if (sub === "list") {
1444
+ if (sub === "get") {
988
1445
  const { values, positionals } = parse(rest, {
989
1446
  ...HELP_OPTION,
990
1447
  json: { type: "boolean" }
991
- }, "endpoints");
992
- if (values.help) return help(out);
993
- expectPositionals(positionals, 0, 0, "endpoints");
994
- const target = requireAdminTarget(await resolveEnv(ctx));
995
- out.err(connectionLine(target));
996
- const { items } = await callSteward(target, () => clientFor(ctx, target).admin.endpoints.list());
997
- if (values.json) out.out(JSON.stringify(items, null, 2));
998
- else if (items.length === 0) out.out("endpoint yok — steward endpoints add --url <url> --out <dosya>");
999
- else {
1000
- const rows = [[
1001
- "ID",
1002
- "DURUM",
1003
- "OLAYLAR",
1004
- "SON TESLİMAT",
1005
- "URL"
1006
- ]];
1007
- for (const e of items) rows.push([
1008
- e.id,
1009
- e.status,
1010
- typesText(e),
1011
- lastDeliveryText(e),
1012
- e.description !== null ? `${e.url} (${e.description})` : e.url
1013
- ]);
1014
- for (const line of table(rows)) out.out(line);
1015
- }
1016
- return 0;
1017
- }
1018
- if (sub === "add") {
1019
- const { values, positionals } = parse(rest, {
1020
- ...HELP_OPTION,
1021
- url: { type: "string" },
1022
- out: { type: "string" },
1023
- "event-types": { type: "string" },
1024
- description: { type: "string" },
1025
- force: { type: "boolean" }
1026
- }, ENDPOINTS_USAGE);
1027
- if (values.help) return help(out);
1028
- expectPositionals(positionals, 0, 0, "endpoints");
1029
- const url = requireOption(values.url, "--url", "endpoints");
1030
- const file = requireOption(values.out, "--out", "endpoints");
1031
- const secret = generateWebhookSecret();
1032
- const input = {
1033
- url,
1034
- secret,
1035
- ...values["event-types"] !== void 0 ? { eventTypes: parseList(values["event-types"]) } : {},
1036
- ...values.description !== void 0 ? { description: values.description } : {}
1037
- };
1038
- const parsed = WebhookEndpointCreateInputSchema.safeParse(input);
1039
- if (!parsed.success) throw new UsageError(`endpoint geçersiz (istek gönderilmedi)\n${schemaProblems(parsed.error.issues)}`);
1448
+ }, "dunning");
1449
+ if (values.help) return help$1(out);
1450
+ expectPositionals(positionals, 0, 0, "dunning");
1040
1451
  const target = requireAdminTarget(await resolveEnv(ctx));
1041
1452
  out.err(connectionLine(target));
1042
- const steward = clientFor(ctx, target);
1043
- const result = await withSecretFile(ctx.cwd, file, secret, { force: values.force === true }, () => callSteward(target, () => steward.admin.endpoints.create(input)));
1044
- const endpoint = result.value;
1045
- out.out(`endpoint oluşturuldu → ${originOf(target.url)}`);
1046
- out.out(` id ${endpoint.id}`);
1047
- out.out(` url ${endpoint.url}`);
1048
- out.out(` olaylar ${typesText(endpoint)}`);
1049
- secretNotice(out, result.path, result.fallback, "Sırrı ürünün Secret'ına (STEWARD_WEBHOOK_SECRET) taşıyın, sonra dosyayı silin.");
1453
+ const policy = await callSteward(target, () => clientFor(ctx, target).admin.dunning.get());
1454
+ if (values.json) out.out(JSON.stringify(policy, null, 2));
1455
+ else for (const line of policyLines(policy)) out.out(line);
1050
1456
  return 0;
1051
1457
  }
1052
- if (sub === "rotate") {
1458
+ if (sub === "set") {
1053
1459
  const { values, positionals } = parse(rest, {
1054
1460
  ...HELP_OPTION,
1055
- out: { type: "string" },
1056
- force: { type: "boolean" }
1057
- }, "endpoints");
1058
- if (values.help) return help(out);
1059
- expectPositionals(positionals, 1, 1, "endpoints");
1060
- const id = positionals[0];
1061
- const file = requireOption(values.out, "--out", "endpoints");
1062
- const secret = generateWebhookSecret();
1063
- const parsed = WebhookEndpointRotateInputSchema.safeParse({ secret });
1064
- if (!parsed.success) throw new UsageError(`sır geçersiz\n${schemaProblems(parsed.error.issues)}`);
1461
+ yes: {
1462
+ type: "boolean",
1463
+ short: "y"
1464
+ }
1465
+ }, "dunning");
1466
+ if (values.help) return help$1(out);
1467
+ expectPositionals(positionals, 1, 1, "dunning");
1468
+ const file = positionals[0];
1469
+ let json;
1470
+ try {
1471
+ json = JSON.parse(await readFile(resolve(ctx.cwd, file), "utf8"));
1472
+ } catch (error) {
1473
+ throw new CliError(`cannot read ${file}: ${error instanceof Error ? error.message : String(error)}`);
1474
+ }
1475
+ const parsed = DunningPolicySchema.strict().safeParse(json);
1476
+ 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")}`);
1477
+ const policy = parsed.data;
1065
1478
  const target = requireAdminTarget(await resolveEnv(ctx));
1066
1479
  out.err(connectionLine(target));
1067
1480
  const steward = clientFor(ctx, target);
1068
- const result = await withSecretFile(ctx.cwd, file, secret, { force: values.force === true }, () => callSteward(target, () => steward.admin.endpoints.rotate(id, { secret })));
1069
- out.out(`sır döndürüldü → ${originOf(target.url)}`);
1070
- out.out(` id ${result.value.id}`);
1071
- out.out(` url ${result.value.url}`);
1072
- 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.");
1073
- return 0;
1074
- }
1075
- if (sub === "deactivate") {
1076
- const { values, positionals } = parse(rest, { ...HELP_OPTION }, "endpoints");
1077
- if (values.help) return help(out);
1078
- expectPositionals(positionals, 1, 1, "endpoints");
1079
- const target = requireAdminTarget(await resolveEnv(ctx));
1080
- out.err(connectionLine(target));
1081
- const endpoint = await callSteward(target, () => clientFor(ctx, target).admin.endpoints.deactivate(positionals[0]));
1082
- out.out(`endpoint pasifleştirildi → ${originOf(target.url)}: ${endpoint.id} (${endpoint.url}, durum ${endpoint.status})`);
1481
+ const current = await callSteward(target, () => steward.admin.dunning.get());
1482
+ out.out("new policy:");
1483
+ for (const line of policyLines(policy)) out.out(line);
1484
+ if (current.dryRun && !policy.dryRun) {
1485
+ if (!await confirm(ctx, "This turns dry run off: suspend and terminate steps will change subscriptions. Continue?", {
1486
+ yes: values.yes === true,
1487
+ notConfirmed: "the policy was not changed"
1488
+ })) {
1489
+ out.err("not confirmed; the policy was not changed");
1490
+ return 1;
1491
+ }
1492
+ }
1493
+ const stored = await callSteward(target, () => steward.admin.dunning.set(policy));
1494
+ out.out(`policy stored → ${originOf(target.url)} (${stored.steps.length} step${stored.steps.length === 1 ? "" : "s"})`);
1083
1495
  return 0;
1084
1496
  }
1085
- throw new UsageError(`bilinmeyen alt komut: endpoints ${sub} (ayrıntı: steward endpoints --help)`);
1497
+ throw new UsageError(`unknown subcommand: dunning ${sub} (see: steward dunning --help)`);
1086
1498
  }
1087
- function help(out) {
1088
- out.out(ENDPOINTS_USAGE);
1499
+ function help$1(out) {
1500
+ out.out(DUNNING_USAGE);
1089
1501
  return 0;
1090
1502
  }
1091
- function secretNotice(out, path, fallback, next) {
1092
- if (fallback) {
1093
- out.err(`! sır hedef dosyaya taşınamadı (arada oluşturulmuş olabilir); sır ${path} dosyasında (0600)`);
1094
- out.out(` sır ${path} (0600; terminale yazılmadı)`);
1095
- } else out.out(` sır ${path} (0600; terminale yazılmadı)`);
1096
- out.err(next);
1097
- }
1098
- //#endregion
1099
- //#region src/api.ts
1100
- const ATTEMPTS = 3;
1101
- const TIMEOUT_MS = 3e4;
1102
- const MAX_WAIT_MS = 1e4;
1103
- function retryAfterMs(value) {
1104
- if (value === null) return void 0;
1105
- const text = value.trim();
1106
- if (/^\d+$/.test(text)) return Number(text) * 1e3;
1107
- const at = /^[A-Za-z]/.test(text) ? Date.parse(text) : NaN;
1108
- return Number.isNaN(at) ? void 0 : Math.max(0, at - Date.now());
1109
- }
1110
- async function apiError(res) {
1111
- const parsed = ErrorResponseSchema.safeParse(await res.json().catch(() => null));
1112
- const requestId = res.headers.get(HEADER_REQUEST_ID) ?? (parsed.success ? parsed.data.requestId : void 0);
1113
- const wait = res.status === 429 || res.status === 503 ? retryAfterMs(res.headers.get("retry-after")) : void 0;
1114
- return new StewardApiError({
1115
- code: parsed.success ? parsed.data.error : `http_${res.status}`,
1116
- httpStatus: res.status,
1117
- ...parsed.success && parsed.data.message !== void 0 ? { message: parsed.data.message } : {},
1118
- ...parsed.success && parsed.data.category !== void 0 ? { category: parsed.data.category } : {},
1119
- ...parsed.success && parsed.data.retryable !== void 0 ? { retryable: parsed.data.retryable } : {},
1120
- ...requestId !== void 0 && requestId !== null ? { requestId } : {},
1121
- ...wait !== void 0 ? { retryAfterMs: wait } : {}
1122
- });
1123
- }
1124
- async function attempt(ctx, target, request, idempotencyKey) {
1125
- const headers = {
1126
- authorization: `Bearer ${target.apiKey}`,
1127
- accept: "application/json",
1128
- [HEADER_API_VERSION]: API_VERSION
1129
- };
1130
- if (request.method !== "GET") {
1131
- headers[HEADER_IDEMPOTENCY_KEY] = idempotencyKey;
1132
- headers[HEADER_ACTOR_REF] = actorRefOf(ctx.username());
1133
- }
1134
- if (request.body !== void 0) headers["content-type"] = "application/json";
1135
- let res;
1136
- try {
1137
- res = await ctx.fetch(`${target.url.replace(/\/$/, "")}${request.path}`, {
1138
- method: request.method,
1139
- headers,
1140
- ...request.body !== void 0 ? { body: JSON.stringify(request.body) } : {},
1141
- signal: AbortSignal.timeout(TIMEOUT_MS)
1142
- });
1143
- } catch (error) {
1144
- const timeout = error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");
1145
- throw new StewardNetworkError({
1146
- code: timeout ? "timeout" : "network_error",
1147
- cause: error
1148
- });
1149
- }
1150
- if (!res.ok) throw await apiError(res);
1151
- const parsed = request.schema.safeParse(await res.json().catch(() => void 0));
1152
- const requestId = res.headers.get(HEADER_REQUEST_ID);
1153
- if (!parsed.success) throw new StewardContractError({
1154
- httpStatus: res.status,
1155
- ...requestId !== null ? { requestId } : {}
1156
- });
1157
- return {
1158
- status: res.status,
1159
- data: parsed.data,
1160
- etag: res.headers.get("etag")
1161
- };
1162
- }
1163
- /** One steward request (see the header); throws the SDK's `StewardError` subclasses. */
1164
- async function stewardRequest(ctx, target, request) {
1165
- const idempotencyKey = globalThis.crypto.randomUUID();
1166
- for (let n = 1;; n++) try {
1167
- return await attempt(ctx, target, request, idempotencyKey);
1168
- } catch (error) {
1169
- if (!(error instanceof StewardNetworkError || error instanceof StewardApiError && (error.httpStatus === 429 || error.httpStatus >= 500)) || n >= ATTEMPTS) throw error;
1170
- const wait = error instanceof StewardApiError && error.retryAfterMs !== void 0 ? error.retryAfterMs : 250 * 2 ** (n - 1);
1171
- await ctx.sleep(Math.min(wait, MAX_WAIT_MS));
1172
- }
1173
- }
1174
1503
  //#endregion
1175
1504
  //#region src/commands/events.ts
1176
- const EVENTS_USAGE = `Usage: steward events send <ref> <name> [--meta key=value]… [--external-id <id>]
1177
- [--timestamp <iso>] [--json]
1505
+ const EVENTS_USAGE = `Usage:
1506
+ steward events send <ref> <name> [--meta key=value]… [--external-id <id>]
1507
+ [--timestamp <iso>] [--json]
1508
+ steward events redeliver <eventId> [<eventId>…]
1178
1509
 
1179
1510
  Sends one event for account <ref> (POST /v1/events/ingest), e.g. to try a meter locally.
1180
1511
  The event itself has no billing meaning: it counts as usage for the meters whose filter
@@ -1194,7 +1525,12 @@ Metadata must not carry personal data (names, e-mail addresses, phone numbers):
1194
1525
 
1195
1526
  Connection: STEWARD_URL + STEWARD_API_KEY (or, when neither is set, STEWARD_ADMIN_URL +
1196
1527
  STEWARD_ADMIN_API_KEY). Sent with X-Actor-Ref operator:<user>.
1197
- Exit code 1: the event was rejected (unknown or deleted account, timestamp out of range).`;
1528
+ Exit code 1: the event was rejected (unknown or deleted account, timestamp out of range).
1529
+
1530
+ redeliver (admin; STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY): requeues every delivery of a
1531
+ webhook event (evt_…; dead ones included) with attempts reset, after the receiver's problem is
1532
+ fixed. The dispatcher sends it on its next tick; an account's older events go first. When only
1533
+ the current state matters, the product calls POST /v1/accounts/:ref/resync instead.`;
1198
1534
  const SEND_OPTIONS = {
1199
1535
  ...HELP_OPTION,
1200
1536
  meta: {
@@ -1237,6 +1573,7 @@ async function eventsCommand(ctx, out, args) {
1237
1573
  out.out(EVENTS_USAGE);
1238
1574
  return sub === void 0 ? 2 : 0;
1239
1575
  }
1576
+ if (sub === "redeliver") return redeliverCommand(ctx, out, rest);
1240
1577
  if (sub !== "send") throw new UsageError(`unknown subcommand: events ${sub} (see: steward events --help)`);
1241
1578
  const { values, positionals } = parse(rest, SEND_OPTIONS, "events");
1242
1579
  if (values.help) {
@@ -1258,12 +1595,7 @@ async function eventsCommand(ctx, out, args) {
1258
1595
  if (!input.success) throw new UsageError(`invalid event (nothing was sent)\n${input.error.issues.map((issue) => ` - ${issue.path.slice(2).map(String).join(".") || "(event)"}: ${issue.message}`).join("\n")}`);
1259
1596
  const target = requireReadTarget(await resolveEnv(ctx));
1260
1597
  out.err(connectionLine(target));
1261
- const { data: result } = await callSteward(target, () => stewardRequest(ctx, target, {
1262
- method: "POST",
1263
- path: "/v1/events/ingest",
1264
- schema: EventsIngestResultSchema,
1265
- body: input.data
1266
- }));
1598
+ const result = await callSteward(target, () => clientFor(ctx, target).events.ingest(input.data));
1267
1599
  if (values.json) out.out(JSON.stringify({
1268
1600
  externalId,
1269
1601
  ...result
@@ -1279,90 +1611,231 @@ async function eventsCommand(ctx, out, args) {
1279
1611
  }
1280
1612
  return 0;
1281
1613
  }
1614
+ async function redeliverCommand(ctx, out, args) {
1615
+ const { values, positionals } = parse(args, { ...HELP_OPTION }, "events");
1616
+ if (values.help) {
1617
+ out.out(EVENTS_USAGE);
1618
+ return 0;
1619
+ }
1620
+ expectPositionals(positionals, 1, 100, "events");
1621
+ const target = requireAdminTarget(await resolveEnv(ctx));
1622
+ out.err(connectionLine(target));
1623
+ const steward = clientFor(ctx, target);
1624
+ for (const eventId of positionals) {
1625
+ const result = await callSteward(target, () => steward.admin.events.redeliver(eventId));
1626
+ out.out(`${result.eventId} (${result.type}): ${result.deliveries.length} deliver${result.deliveries.length === 1 ? "y" : "ies"} requeued`);
1627
+ }
1628
+ return 0;
1629
+ }
1282
1630
  //#endregion
1283
- //#region src/commands/meters.ts
1284
- const METERS_USAGE = `Usage: steward meters get <ref> [--periods <n>] [--json]
1631
+ //#region src/commands/keys.ts
1632
+ const KEYS_USAGE = `Usage:
1633
+ steward keys list [--json]
1634
+ steward keys create --name <name> --scope product|checkout|admin --out <file>
1635
+ [--expires-days <n> | --no-expiry] [--force]
1636
+ steward keys revoke <prefix>
1285
1637
 
1286
- Reads an account's meters (GET /v1/accounts/:ref/meters): per meter the current usage
1287
- period, units used, the period's credit, the balance, the standing (ok | low | exhausted)
1288
- and, for a billable meter, the estimated overage so far. Nothing is written.
1638
+ The product's API keys (/v1/admin/api-keys). The key (stw_…) is generated on this machine and
1639
+ written ONLY to the --out file (0600, no trailing newline): never to the terminal, and steward
1640
+ never returns it. If the file exists, nothing is sent without --force. Move the key into the
1641
+ product's Secret (the CLI does not call kubectl), then delete the file.
1289
1642
 
1290
- --periods <n> also list the last n closed periods (1–100; GET …/meters/periods)
1291
- --json print the response as JSON
1643
+ --scope product: the product's backend; checkout: its web app (checkout, portal,
1644
+ state only); admin: these management commands
1645
+ --expires-days days until the key stops working (1–3650). Default: admin keys 90 days,
1646
+ other keys never. --no-expiry: never (not allowed for an admin key)
1292
1647
 
1293
- Connection: STEWARD_URL + STEWARD_API_KEY (or, when neither is set, STEWARD_ADMIN_URL +
1294
- STEWARD_ADMIN_API_KEY); environment, otherwise ./.env.local.`;
1295
- const GET_OPTIONS = {
1648
+ revoke takes the 12 hex characters after stw_ (keys list). A key cannot revoke itself: revoke
1649
+ the key you are using with another admin key or the pod CLI.
1650
+
1651
+ Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
1652
+ const SCOPES = [
1653
+ "product",
1654
+ "checkout",
1655
+ "admin"
1656
+ ];
1657
+ const keyStatus = (key, now = Date.now()) => key.revokedAt !== null ? "revoked" : key.expiresAt !== null && Date.parse(key.expiresAt) <= now ? "expired" : "active";
1658
+ async function keysCommand(ctx, out, args) {
1659
+ const [sub, ...rest] = args;
1660
+ if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
1661
+ out.out(KEYS_USAGE);
1662
+ return sub === void 0 ? 2 : 0;
1663
+ }
1664
+ if (sub === "list") {
1665
+ const { values, positionals } = parse(rest, {
1666
+ ...HELP_OPTION,
1667
+ json: { type: "boolean" }
1668
+ }, "keys");
1669
+ if (values.help) return help(out);
1670
+ expectPositionals(positionals, 0, 0, "keys");
1671
+ const target = requireAdminTarget(await resolveEnv(ctx));
1672
+ out.err(connectionLine(target));
1673
+ const { items } = await callSteward(target, () => clientFor(ctx, target).admin.apiKeys.list());
1674
+ if (values.json) {
1675
+ out.out(JSON.stringify(items, null, 2));
1676
+ return 0;
1677
+ }
1678
+ const rows = [[
1679
+ "PREFIX",
1680
+ "SCOPE",
1681
+ "STATUS",
1682
+ "EXPIRES",
1683
+ "LAST USED",
1684
+ "NAME"
1685
+ ]];
1686
+ for (const k of items) rows.push([
1687
+ k.prefix,
1688
+ k.scope,
1689
+ keyStatus(k),
1690
+ k.expiresAt ?? "never",
1691
+ k.lastUsedAt ?? "-",
1692
+ k.name
1693
+ ]);
1694
+ for (const line of table(rows)) out.out(line);
1695
+ return 0;
1696
+ }
1697
+ if (sub === "create") {
1698
+ const { values, positionals } = parse(rest, {
1699
+ ...HELP_OPTION,
1700
+ name: { type: "string" },
1701
+ scope: { type: "string" },
1702
+ out: { type: "string" },
1703
+ "expires-days": { type: "string" },
1704
+ "no-expiry": { type: "boolean" },
1705
+ force: { type: "boolean" }
1706
+ }, "keys");
1707
+ if (values.help) return help(out);
1708
+ expectPositionals(positionals, 0, 0, "keys");
1709
+ const name = requireOption(values.name, "--name", "keys");
1710
+ const scope = requireOption(values.scope, "--scope", "keys");
1711
+ if (!SCOPES.includes(scope)) throw new UsageError(`--scope: one of ${SCOPES.join(", ")}`);
1712
+ const file = requireOption(values.out, "--out", "keys");
1713
+ if (values["expires-days"] !== void 0 && values["no-expiry"]) throw new UsageError("--expires-days and --no-expiry are mutually exclusive");
1714
+ const token = generateApiKeyToken();
1715
+ const input = {
1716
+ token,
1717
+ name,
1718
+ scope,
1719
+ ...values["expires-days"] !== void 0 ? { expiresInDays: parsePositiveInt(values["expires-days"], "--expires-days", { max: 3650 }) } : {},
1720
+ ...values["no-expiry"] ? { expiresInDays: null } : {}
1721
+ };
1722
+ const parsed = ApiKeyCreateInputSchema.safeParse(input);
1723
+ 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")}`);
1724
+ const target = requireAdminTarget(await resolveEnv(ctx));
1725
+ out.err(connectionLine(target));
1726
+ const steward = clientFor(ctx, target);
1727
+ const result = await withSecretFile(ctx.cwd, file, token, { force: values.force === true }, () => callSteward(target, () => steward.admin.apiKeys.create(input)));
1728
+ const key = result.value;
1729
+ out.out(`key created → ${originOf(target.url)}`);
1730
+ out.out(` prefix ${key.prefix}`);
1731
+ out.out(` scope ${key.scope}`);
1732
+ out.out(` expires ${key.expiresAt ?? "never"}`);
1733
+ secretNotice(out, result.path, result.fallback, "Move the key into the product's Secret, then delete the file.");
1734
+ return 0;
1735
+ }
1736
+ if (sub === "revoke") {
1737
+ const { values, positionals } = parse(rest, { ...HELP_OPTION }, "keys");
1738
+ if (values.help) return help(out);
1739
+ expectPositionals(positionals, 1, 1, "keys");
1740
+ const target = requireAdminTarget(await resolveEnv(ctx));
1741
+ out.err(connectionLine(target));
1742
+ const key = await callSteward(target, () => clientFor(ctx, target).admin.apiKeys.revoke(positionals[0]));
1743
+ out.out(`key revoked → ${originOf(target.url)}: ${key.prefix} (${key.scope}, ${key.name})`);
1744
+ return 0;
1745
+ }
1746
+ throw new UsageError(`unknown subcommand: keys ${sub} (see: steward keys --help)`);
1747
+ }
1748
+ function help(out) {
1749
+ out.out(KEYS_USAGE);
1750
+ return 0;
1751
+ }
1752
+ //#endregion
1753
+ //#region src/commands/reprice.ts
1754
+ const REPRICE_USAGE = `Usage: steward reprice --plan <code> --notice-days <n> [--dry-run] [--yes] [--json]
1755
+
1756
+ Moves the live subscriptions of a plan to the plan's current price and metered rates
1757
+ (POST /v1/admin/subscriptions/reprice): each one changes from its first period boundary at
1758
+ least <n> days away (0–3650) and gets one price change notice e-mail. Subscribers otherwise
1759
+ keep the amount they locked at checkout.
1760
+
1761
+ The command always lists first (a dry run: nothing written, no e-mail). Without --dry-run it
1762
+ then asks for confirmation (a prompt on a terminal, otherwise --yes) and runs it for real.
1763
+ Running it again is safe: an already scheduled subscription gets no second notice.
1764
+
1765
+ Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
1766
+ const OPTIONS = {
1296
1767
  ...HELP_OPTION,
1297
- periods: { type: "string" },
1768
+ plan: { type: "string" },
1769
+ "notice-days": { type: "string" },
1770
+ "dry-run": { type: "boolean" },
1771
+ yes: {
1772
+ type: "boolean",
1773
+ short: "y"
1774
+ },
1298
1775
  json: { type: "boolean" }
1299
1776
  };
1300
- /** Units of a meter read (a JSON number with at most 6 decimals) as exact text with grouping: `1,700,000.5`. */
1301
- function formatUnitsText(value) {
1302
- return new Intl.NumberFormat("en", { maximumFractionDigits: 6 }).format(plainDecimalOf(value));
1303
- }
1304
- function meterLines(code, meter, width) {
1305
- const lines = [` ${code.padEnd(width)} ${meter.periodStart} → ${meter.periodEnd}`];
1306
- const indent = " ".repeat(width + 4);
1307
- lines.push(`${indent}used ${formatUnitsText(meter.consumedUnits)} · credit ${formatUnitsText(meter.creditedUnits)} · balance ${formatUnitsText(meter.balance)} · standing ${meter.standing}`);
1308
- const included = meter.includedUnits === null ? "no credit included" : `included ${formatUnitsText(meter.includedUnits)} per period`;
1309
- 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)";
1310
- lines.push(`${indent}${included} · ${billing}`);
1777
+ function summary(result) {
1778
+ const count = (action) => result.items.filter((item) => item.action === action).length;
1779
+ const lines = result.items.map((item) => {
1780
+ const amounts = `${formatMinor(item.oldAmountMinor, item.currency)} → ${formatMinor(item.newAmountMinor, item.currency)}`;
1781
+ const rates = item.meteredRates?.length ? ` (+${item.meteredRates.length} metered rate${item.meteredRates.length === 1 ? "" : "s"})` : "";
1782
+ const when = item.action === "skip" ? `skip: ${item.reason ?? "-"}` : `${item.action} from ${item.effectiveAt}`;
1783
+ return ` ${item.accountRef} ${item.interval} ${amounts}${rates} ${when}`;
1784
+ });
1785
+ lines.push(`${count("schedule")} to schedule, ${count("already_scheduled")} already scheduled, ${count("skip")} skipped; effective not before ${result.effectiveNotBefore}`);
1311
1786
  return lines;
1312
1787
  }
1313
- /** Human-readable meter read (+ closed periods, newest first). */
1314
- function formatMeters(meters, periods) {
1315
- const lines = [`meters of ${meters.ref} · as of ${meters.asOf} · events received before ${meters.rolledUpThrough} are counted`];
1316
- const codes = Object.keys(meters.meters);
1317
- if (codes.length === 0) lines.push(" no meters (the product's catalog defines none)");
1318
- else {
1319
- const width = Math.max(...codes.map((code) => code.length));
1320
- for (const code of codes) lines.push(...meterLines(code, meters.meters[code], width));
1788
+ async function repriceCommand(ctx, out, args) {
1789
+ const { values, positionals } = parse(args, OPTIONS, "reprice");
1790
+ if (values.help) {
1791
+ out.out(REPRICE_USAGE);
1792
+ return 0;
1321
1793
  }
1322
- if (periods !== null) {
1323
- lines.push("");
1324
- if (periods.length === 0) lines.push("closed periods: none");
1325
- else {
1326
- lines.push("closed periods (newest first):");
1327
- const width = Math.max(...periods.map((p) => p.meter.length));
1328
- 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)}`);
1329
- }
1794
+ if (args.length === 0) {
1795
+ out.out(REPRICE_USAGE);
1796
+ return 2;
1330
1797
  }
1331
- return lines;
1332
- }
1333
- async function metersCommand(ctx, out, args) {
1334
- const [sub, ...rest] = args;
1335
- if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
1336
- out.out(METERS_USAGE);
1337
- return sub === void 0 ? 2 : 0;
1798
+ expectPositionals(positionals, 0, 0, "reprice");
1799
+ const input = {
1800
+ planCode: requireOption(values.plan, "--plan", "reprice"),
1801
+ noticeDays: parseNonNegativeInt(requireOption(values["notice-days"], "--notice-days", "reprice"), "--notice-days")
1802
+ };
1803
+ const checked = RepriceInputSchema.safeParse({
1804
+ ...input,
1805
+ dryRun: true
1806
+ });
1807
+ 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")}`);
1808
+ const target = requireAdminTarget(await resolveEnv(ctx));
1809
+ out.err(connectionLine(target));
1810
+ const steward = clientFor(ctx, target);
1811
+ const preview = await callSteward(target, () => steward.admin.subscriptions.reprice({
1812
+ ...input,
1813
+ dryRun: true
1814
+ }));
1815
+ if (values["dry-run"]) {
1816
+ if (values.json) out.out(JSON.stringify(preview, null, 2));
1817
+ else for (const line of ["dry run (nothing written):", ...summary(preview)]) out.out(line);
1818
+ return 0;
1338
1819
  }
1339
- if (sub !== "get") throw new UsageError(`unknown subcommand: meters ${sub} (see: steward meters --help)`);
1340
- const { values, positionals } = parse(rest, GET_OPTIONS, "meters");
1341
- if (values.help) {
1342
- out.out(METERS_USAGE);
1820
+ if (!values.json) for (const line of ["dry run:", ...summary(preview)]) out.out(line);
1821
+ const toSchedule = preview.items.filter((item) => item.action === "schedule").length;
1822
+ if (toSchedule === 0) {
1823
+ out.out("nothing to schedule");
1343
1824
  return 0;
1344
1825
  }
1345
- expectPositionals(positionals, 1, 1, "meters");
1346
- const ref = positionals[0];
1347
- const limit = values.periods === void 0 ? null : parsePositiveInt(values.periods, "--periods", { max: 100 });
1348
- const target = requireReadTarget(await resolveEnv(ctx));
1349
- out.err(connectionLine(target));
1350
- const path = `/v1/accounts/${encodeURIComponent(ref)}/meters`;
1351
- const read = await callSteward(target, () => stewardRequest(ctx, target, {
1352
- method: "GET",
1353
- path,
1354
- schema: AccountMetersSchema
1826
+ if (!await confirm(ctx, `Schedule ${toSchedule} subscription${toSchedule === 1 ? "" : "s"} and send the notice e-mails?`, {
1827
+ yes: values.yes === true,
1828
+ notConfirmed: "nothing was scheduled"
1829
+ })) {
1830
+ out.err("not confirmed; nothing was scheduled");
1831
+ return 1;
1832
+ }
1833
+ const result = await callSteward(target, () => steward.admin.subscriptions.reprice({
1834
+ ...input,
1835
+ dryRun: false
1355
1836
  }));
1356
- const periods = limit === null ? null : (await callSteward(target, () => stewardRequest(ctx, target, {
1357
- method: "GET",
1358
- path: `${path}/periods?limit=${limit}`,
1359
- schema: MeterPeriodListSchema
1360
- }))).data.periods;
1361
- if (values.json) out.out(JSON.stringify(periods === null ? read.data : {
1362
- ...read.data,
1363
- closedPeriods: periods
1364
- }, null, 2));
1365
- else for (const line of formatMeters(read.data, periods)) out.out(line);
1837
+ if (values.json) out.out(JSON.stringify(result, null, 2));
1838
+ else out.out(`scheduled → ${originOf(target.url)}: ${result.scheduled} subscription${result.scheduled === 1 ? "" : "s"} (one notice e-mail each)`);
1366
1839
  return 0;
1367
1840
  }
1368
1841
  //#endregion
@@ -1377,6 +1850,7 @@ const SETTINGS_USAGE = `Kullanım:
1377
1850
  [--billing-allow-multiple-subscriptions true|false]
1378
1851
  [--metering-charge-mode off|dry_run|live]
1379
1852
  [--metering-late-grace-minutes <0-1440>] [--events-retention-days <45-400>]
1853
+ [--provider <id>]
1380
1854
 
1381
1855
  Ürün ayarları (GET/PATCH /v1/admin/settings). Verilmeyen alan değişmez; boş değer
1382
1856
  (--privacy-url "") alanı temizler, --branding null markayı temizler, --branding
@@ -1397,6 +1871,8 @@ it, live adds it to the renewal invoice, off prices nothing — run one full cyc
1397
1871
  dry_run before live. --metering-late-grace-minutes how long a period waits for late
1398
1872
  events before it closes (default 60). --events-retention-days how long raw events are
1399
1873
  kept after receipt, once their period is closed (default 120). "" restores the default.
1874
+ --provider sets the payment provider for NEW checkouts and payment sessions (open ones keep
1875
+ theirs); steward accepts only a provider configured in its deployment (iyzico, fake…).
1400
1876
 
1401
1877
  Bağlantı: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (ortam, yoksa ./.env.local).`;
1402
1878
  const SET_OPTIONS = {
@@ -1415,7 +1891,8 @@ const SET_OPTIONS = {
1415
1891
  "billing-allow-multiple-subscriptions": { type: "string" },
1416
1892
  "metering-charge-mode": { type: "string" },
1417
1893
  "metering-late-grace-minutes": { type: "string" },
1418
- "events-retention-days": { type: "string" }
1894
+ "events-retention-days": { type: "string" },
1895
+ provider: { type: "string" }
1419
1896
  };
1420
1897
  const orNull = (value) => value.trim() === "" ? null : value.trim();
1421
1898
  /** Bayraklardan yama; sözleşme şemasıyla doğrulanır (geçersizse istek gönderilmez). */
@@ -1453,6 +1930,7 @@ function buildSettingsPatch(values) {
1453
1930
  }
1454
1931
  }
1455
1932
  if (values["default-locale"] !== void 0) patch.defaultLocale = values["default-locale"].trim();
1933
+ if (values.provider !== void 0) patch.provider = values.provider.trim();
1456
1934
  if (values["checkout-ttl"] !== void 0) patch.checkoutTtlMinutes = parsePositiveInt(values["checkout-ttl"], "--checkout-ttl");
1457
1935
  if (values["portal-ttl"] !== void 0) patch.portalTtlMinutes = parsePositiveInt(values["portal-ttl"], "--portal-ttl");
1458
1936
  if (values["extra-return-origins"] !== void 0) patch.extraReturnOrigins = parseList(values["extra-return-origins"]);
@@ -1521,7 +1999,7 @@ async function settingsCommand(ctx, out, args) {
1521
1999
  }
1522
2000
  //#endregion
1523
2001
  //#region src/main.ts
1524
- const CLI_VERSION = "0.5.0";
2002
+ const CLI_VERSION = "0.7.0";
1525
2003
  const USAGE = `steward — Steward CLI (@stewardhq/cli ${CLI_VERSION})
1526
2004
 
1527
2005
  Kullanım: steward <komut> [seçenekler]
@@ -1531,8 +2009,13 @@ Komutlar:
1531
2009
  catalog push <dosya> [--yes] katalog senkronu (PUT /v1/admin/catalog)
1532
2010
  settings get | set [bayraklar] ürün ayarları (/v1/admin/settings)
1533
2011
  endpoints list | add | rotate | deactivate webhook endpoint'leri; sır yalnızca --out dosyasına
1534
- meters get <ref> [--periods <n>] [--json] an account's meters (GET /v1/accounts/:ref/meters)
1535
- events send <ref> <name> [--meta k=v]… send one event (POST /v1/events/ingest; local try-out)
2012
+ keys list | create | revoke API keys; the key goes only to the --out file
2013
+ dunning get | set <policy.json> dunning policy (/v1/admin/dunning-policy)
2014
+ reprice --plan <code> --notice-days <n> move a plan's subscribers to its current price
2015
+ bank-transfers list | record bank transfer reconciliation (/v1/admin/bank-transfers)
2016
+ credits adjust <ref> <meter> --units=<n> credit entry, negative = adjustment
2017
+ meters get | recompute | close-periods an account's meters; metering repairs (admin)
2018
+ events send | redeliver send one event; redeliver webhook events (admin)
1536
2019
 
1537
2020
  Bağlantı: yönetim komutları STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY, doctor,
1538
2021
  meters ve events STEWARD_URL + STEWARD_API_KEY (yoksa admin çifti). Ortamda bu dört değişkenden
@@ -1548,7 +2031,12 @@ const COMMANDS = {
1548
2031
  settings: settingsCommand,
1549
2032
  endpoints: endpointsCommand,
1550
2033
  meters: metersCommand,
1551
- events: eventsCommand
2034
+ events: eventsCommand,
2035
+ keys: keysCommand,
2036
+ dunning: dunningCommand,
2037
+ reprice: repriceCommand,
2038
+ "bank-transfers": bankTransfersCommand,
2039
+ credits: creditsCommand
1552
2040
  };
1553
2041
  async function main(argv, ctx) {
1554
2042
  const out = createOutput(ctx.stdout, ctx.stderr);