@tokenoftrust/cli 6.14.2 → 6.14.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/cli",
3
- "version": "6.14.2",
3
+ "version": "6.14.4",
4
4
  "description": "Token of Trust developer CLI — clone a tenant store, run it locally with save→reload, and submit it for preview. Installs the `tot` command.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Token of Trust",
@@ -35,10 +35,12 @@ export const ADMIN_USAGE = `tot app — manage Private App installs on your stor
35
35
  tot app list your store's installs: id, app, version, env, status, scopes (never secrets)
36
36
  tot app replay <deliveryId> re-send a webhook delivery to its install
37
37
  tot app test-order bind <installId>
38
- bind your test install as the preview processor (preview host only)
38
+ bind your test install as the store's preview processor
39
39
  tot app test-order create write one synthetic preview order
40
40
  tot app test-order release <orderId>
41
41
  claim and release one synthetic preview order
42
+ (test orders always act on the store's preview stage, at
43
+ ${DEFAULT_STOREFRONT_ORIGIN}/<tenant>; no --url needed)
42
44
  tot app candidate [--app <dir>] [--jwks-uri <url> | --jwks <file>] [--request-consent] [--webhook-endpoint <url>]
43
45
  stage a production candidate (pending_approval) for owner approval;
44
46
  keys come from --jwks-uri, --jwks, or the manifest's clientAuth
@@ -88,8 +90,11 @@ export function parseAdminArgs(argv) {
88
90
  return a;
89
91
  }
90
92
 
91
- /** The next step for a refused call: the server's `code` first, then the generic admission hint. */
92
- function nextForRefusal(status, body) {
93
+ /**
94
+ * The next step for a refused call: the server's `code` first, then the generic admission hint.
95
+ * @param {number} status @param {any} body @param {{ tenant: string, urlOverridden: boolean }} target
96
+ */
97
+ function nextForRefusal(status, body, target) {
93
98
  const code = typeof body?.code === "string" ? body.code : "";
94
99
  if (code === "owner_required_for_production_app") {
95
100
  return "ask the store owner to install the production app, or install with --env=test";
@@ -98,7 +103,12 @@ function nextForRefusal(status, body) {
98
103
  if (code === "scope_denied") return "remove the refused scopes from tot-app.json, then re-run";
99
104
  if (code === "already_installed") return "run `tot app list` for its installId, then `tot app update <installId>`";
100
105
  if (code === "not_found") return "run `tot app list` to see this store's installs";
101
- if (code === "preview_stage_required") return "point --url at the store's preview host, then re-run";
106
+ if (code === "preview_stage_required") {
107
+ const preview = `${DEFAULT_STOREFRONT_ORIGIN}/${target.tenant}`;
108
+ return target.urlOverridden
109
+ ? `drop --url and TOT_STOREFRONT_URL: test orders run on the store's preview at ${preview}, then re-run`
110
+ : `${preview} has not yet been redeployed with host-free test orders; re-run after its next deploy, or report it with \`tot feedback\``;
111
+ }
102
112
  if (code === "test_install_required") return "bind an install with env test: `tot app list`, then `tot app test-order bind <installId>`";
103
113
  if (code === "invalid_state") return "run `tot app list` to check the install's status";
104
114
  if (status === 403) return refusalHint(status, missingGrantsOf(body));
@@ -236,7 +246,9 @@ export async function runAdmin(argv, ctx, deps = {}) {
236
246
  const reason = typeof data?.error === "string" ? data.error : `the store refused the request (HTTP ${res.status}).`;
237
247
  const denials = Array.isArray(data?.denials) && data.denials.length
238
248
  ? `\n refused scopes: ${data.denials.map((d) => d?.scope ?? d?.id ?? JSON.stringify(d)).join(", ")}` : "";
239
- err(`✗ tot app ${verb}: ${reason}${denials}\n\n → next: ${nextForRefusal(res.status, data)}`);
249
+ const storefrontUrl = String(args.url || env.TOT_STOREFRONT_URL || "").trim().replace(/\/+$/, "");
250
+ const urlOverridden = storefrontUrl !== "" && storefrontUrl !== DEFAULT_STOREFRONT_ORIGIN;
251
+ err(`✗ tot app ${verb}: ${reason}${denials}\n\n → next: ${nextForRefusal(res.status, data, { tenant, urlOverridden })}`);
240
252
  return res.status === 401 || res.status === 403 ? 1 : (res.status >= 500 ? 1 : 2);
241
253
  }
242
254
 
@@ -4,8 +4,9 @@
4
4
  * reading it) has something to render before you migrate real data.
5
5
  *
6
6
  * Catalog content is files in the store's own repo: one `content/catalog/products/<handle>.json`
7
- * per product. This writes those files into the current store checkout — nothing is sent online;
8
- * `tot preview` then pushes them like any other content change. It refuses outside a store
7
+ * per product. This writes those files into the current store checkout and seeds the preview
8
+ * store's stock ledger with the preset's levels; `tot preview` then pushes the files like any other
9
+ * content change. It refuses outside a store
9
10
  * checkout, and refuses to replace a product file that already exists unless `--overwrite`.
10
11
  * Presets are data: `src/catalog-presets/<name>.json`.
11
12
  */
@@ -22,8 +23,9 @@ export const USAGE = `tot catalog — manage your store's catalog content
22
23
 
23
24
  Presets: general, regulated-vape, multi-warehouse
24
25
 
25
- Writes synthetic products to content/catalog/products/<handle>.json in this store checkout.
26
- Run \`tot preview\` afterwards to push them.`;
26
+ Writes synthetic products to content/catalog/products/<handle>.json in this store checkout and
27
+ seeds their stock levels (per location) on your preview store; the live store is never seeded.
28
+ Run \`tot preview\` afterwards to push the products.`;
27
29
 
28
30
  /** Preset names, from the data files. */
29
31
  export function presetNames() {
@@ -101,6 +103,59 @@ export function expandProduct(seed, now) {
101
103
  return { ...product, source_checksum: checksum(product) };
102
104
  }
103
105
 
106
+ /**
107
+ * The stock levels a preset implies: one per (sku, location), `unspecified` for a single-pool
108
+ * product. These are the same numbers `expandProduct` writes into the product files.
109
+ * @param {any} preset
110
+ * @returns {{ sku: string, locationId?: string, onHand: number }[]}
111
+ */
112
+ export function presetStockLevels(preset) {
113
+ const levels = [];
114
+ for (const seed of preset.products) {
115
+ const sku = seed.handle.toUpperCase().replace(/-/g, "_");
116
+ if (seed.locations && typeof seed.locations === "object") {
117
+ for (const [locationId, qty] of Object.entries(seed.locations)) levels.push({ sku, locationId, onHand: Number(qty) });
118
+ } else {
119
+ levels.push({ sku, onHand: Number(seed.quantity ?? 0) });
120
+ }
121
+ }
122
+ return levels;
123
+ }
124
+
125
+ /**
126
+ * Write the preset's levels to the store's stock ledger on the preview stage. The server refuses
127
+ * the live stage and writes one deterministic movement per sku and location, so a repeat adds none.
128
+ * @returns {Promise<{ ok: true } | { ok: false, error: string, hint?: string }>}
129
+ */
130
+ async function seedStock(ctx, preset, now, deps) {
131
+ const env = deps.env || process.env;
132
+ const fetchImpl = deps.fetchImpl || fetch;
133
+ const resolveTransport = deps.resolveViewerTransport || (await import("../viewer-session.mjs")).resolveViewerTransport;
134
+ if (!ctx.tenant) return { ok: false, error: "the checkout names no tenant" };
135
+ const transport = await resolveTransport({ tenant: ctx.tenant, env, fetchImpl, storefrontUrl: env.TOT_STOREFRONT_URL || null });
136
+ if (!transport.ok) return { ok: false, error: transport.message, hint: transport.hint };
137
+ let response;
138
+ try {
139
+ response = await fetchImpl(`${String(transport.base).replace(/\/+$/, "")}/api/admin/inventory/source-on-hand`, {
140
+ method: "POST",
141
+ redirect: "manual",
142
+ headers: { ...transport.authHeaders, "content-type": "application/json" },
143
+ body: JSON.stringify({ runId: `seed.${preset.name}`, asOf: now, seed: true, lines: presetStockLevels(preset) }),
144
+ });
145
+ } catch (e) {
146
+ return { ok: false, error: e?.message || "the stock request failed" };
147
+ }
148
+ if (response.status !== 200) {
149
+ let code = `HTTP ${response.status}`;
150
+ try {
151
+ const body = await response.json();
152
+ if (body && typeof body.error === "string") code = body.error;
153
+ } catch {}
154
+ return { ok: false, error: code };
155
+ }
156
+ return { ok: true };
157
+ }
158
+
104
159
  /** @param {string[]} argv */
105
160
  export function parseCatalogArgs(argv) {
106
161
  /** @type {{ sub: string|null, preset: string|null, overwrite: boolean, help: boolean, unknown: string[] }} */
@@ -120,7 +175,7 @@ export function parseCatalogArgs(argv) {
120
175
 
121
176
  /**
122
177
  * @param {string[]} argv @param {any} ctx
123
- * @param {{ out?: (s: string) => void, err?: (s: string) => void, now?: () => string }} [deps]
178
+ * @param {{ out?: (s: string) => void, err?: (s: string) => void, now?: () => string, env?: NodeJS.ProcessEnv, fetchImpl?: typeof fetch, resolveViewerTransport?: Function }} [deps]
124
179
  */
125
180
  export async function run(argv, ctx, deps = {}) {
126
181
  const out = deps.out || ((s) => process.stdout.write(`${s}\n`));
@@ -164,6 +219,9 @@ export async function run(argv, ctx, deps = {}) {
164
219
  for (const p of products) writeFileSync(join(dir, `${p.handle}.json`), `${JSON.stringify(p, null, 2)}\n`);
165
220
  out(`✓ seeded ${products.length} "${preset.name}" products into content/catalog/products/`);
166
221
  out(` ${preset.description}`);
222
+ const stock = await seedStock(ctx, preset, now, deps);
223
+ if (stock.ok) out("✓ seeded stock levels on your preview store (locations and per-location levels)");
224
+ else err(`! products written, but stock levels were not seeded: ${stock.error}${stock.hint ? ` — ${stock.hint}` : ""}\n → next: re-run \`tot catalog seed --preset=${args.preset} --overwrite\` once the store is reachable`);
167
225
  out(" → next: `tot preview` to push them");
168
226
  return 0;
169
227
  }
@@ -119,8 +119,10 @@ the preview stage without waiting on the store owner:
119
119
  Manage your test install at any time with `tot app update <installId>`,
120
120
  `tot app rotate <installId>`, `tot app list`, and `tot app replay <deliveryId>`.
121
121
  3. **Trigger synthetic preview orders bound to the `test` install:**
122
- Run `tot app test-order bind <installId>`, `tot app test-order create` and
123
- `tot app test-order release <orderId>` (`POST /api/apps/admin/test-orders`) to bind your
122
+ Run `tot app test-order bind <installId> --tenant <tenant>`, `tot app test-order create` and
123
+ `tot app test-order release <orderId>` (`POST /api/apps/admin/test-orders`) with no `--url`:
124
+ test orders always act on the store's preview stage, at
125
+ `https://storefront.tokenoftrust.store/<tenant>`. They bind your
124
126
  `test` install as the preview fulfillment processor and emit synthetic preview orders with
125
127
  RFC-reserved recipient fixtures. Preview tokens and webhooks are isolated by the stage wall
126
128
  (`403 stage_mismatch` if used against live publication hosts).