@tokenoftrust/cli 6.11.2 → 6.12.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.
- package/bin/tot.mjs +16 -1
- package/package.json +1 -1
- package/src/catalog-presets/general.json +14 -0
- package/src/catalog-presets/multi-warehouse.json +15 -0
- package/src/catalog-presets/regulated-vape.json +29 -0
- package/src/commands/app/admin.mjs +276 -0
- package/src/commands/app/index.mjs +16 -4
- package/src/commands/catalog.mjs +169 -0
package/bin/tot.mjs
CHANGED
|
@@ -76,6 +76,12 @@ const COMMANDS = [
|
|
|
76
76
|
{ invocation: 'feedback "<msg>"', blurb: "send feedback to Token of Trust (attaches recent activity)" },
|
|
77
77
|
{ invocation: "app scaffold <name>", blurb: "scaffold a Storefront Private App" },
|
|
78
78
|
{ invocation: "app dev ...", blurb: "local, offline Private App webhook/manifest/JWT harness" },
|
|
79
|
+
{ invocation: "app install", blurb: "install your Private App on your store (env defaults to test); prints the client secret once" },
|
|
80
|
+
{ invocation: "app update <installId>", blurb: "push your app's current version, scopes and manifest to an install" },
|
|
81
|
+
{ invocation: "app rotate <installId>", blurb: "issue a new client secret for an install (printed once)" },
|
|
82
|
+
{ invocation: "app list", blurb: "your store's app installs — id, app, version, env, status, scopes" },
|
|
83
|
+
{ invocation: "app replay <deliveryId>", blurb: "re-send a webhook delivery to its install" },
|
|
84
|
+
{ invocation: "catalog seed --preset=<name>", blurb: "seed your store checkout with synthetic products (general, regulated-vape, multi-warehouse)" },
|
|
79
85
|
{ invocation: "help", blurb: "show this help" },
|
|
80
86
|
{ invocation: "--version", blurb: "print the CLI version" },
|
|
81
87
|
];
|
|
@@ -319,6 +325,11 @@ async function dispatch(cmd, rest, ctx) {
|
|
|
319
325
|
return run(rest, ctx);
|
|
320
326
|
}
|
|
321
327
|
|
|
328
|
+
if (cmd === "catalog") {
|
|
329
|
+
const { run } = await import("../src/commands/catalog.mjs");
|
|
330
|
+
return run(rest, ctx);
|
|
331
|
+
}
|
|
332
|
+
|
|
322
333
|
// `checkout` was deliberately freed up: it's no longer a tot verb precisely so it
|
|
323
334
|
// can mean what it means in git. Point both ways rather than a bare "unknown".
|
|
324
335
|
if (cmd === "checkout") {
|
|
@@ -355,7 +366,11 @@ async function dispatch(cmd, rest, ctx) {
|
|
|
355
366
|
function safeSubcommand(cmd, rest) {
|
|
356
367
|
if (cmd === "app") {
|
|
357
368
|
const sub = rest.find((t) => t && !t.startsWith("-"));
|
|
358
|
-
if (sub === "scaffold" || sub === "dev") return sub;
|
|
369
|
+
if (sub === "scaffold" || sub === "dev" || sub === "install" || sub === "update" || sub === "rotate" || sub === "list" || sub === "replay") return sub;
|
|
370
|
+
}
|
|
371
|
+
if (cmd === "catalog") {
|
|
372
|
+
const sub = rest.find((t) => t && !t.startsWith("-"));
|
|
373
|
+
if (sub === "seed") return sub;
|
|
359
374
|
}
|
|
360
375
|
if (cmd === "image") {
|
|
361
376
|
const sub = rest.find((t) => t && !t.startsWith("-"));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tokenoftrust/cli",
|
|
3
|
-
"version": "6.
|
|
3
|
+
"version": "6.12.0",
|
|
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",
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "general",
|
|
3
|
+
"description": "Four ordinary products, one stock pool.",
|
|
4
|
+
"products": [
|
|
5
|
+
{ "handle": "seed-canvas-tote", "title": "Seed Canvas Tote", "vendor": "Seed Goods", "product_type": "Bag",
|
|
6
|
+
"tags": ["seed", "bags"], "price": 24.0, "quantity": 40 },
|
|
7
|
+
{ "handle": "seed-ceramic-mug", "title": "Seed Ceramic Mug", "vendor": "Seed Goods", "product_type": "Mug",
|
|
8
|
+
"tags": ["seed", "kitchen"], "price": 14.5, "quantity": 120 },
|
|
9
|
+
{ "handle": "seed-notebook", "title": "Seed Notebook", "vendor": "Seed Goods", "product_type": "Stationery",
|
|
10
|
+
"tags": ["seed", "stationery"], "price": 9.0, "quantity": 200 },
|
|
11
|
+
{ "handle": "seed-enamel-pin", "title": "Seed Enamel Pin", "vendor": "Seed Goods", "product_type": "Accessory",
|
|
12
|
+
"tags": ["seed", "accessories"], "price": 6.0, "quantity": 500 }
|
|
13
|
+
]
|
|
14
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "multi-warehouse",
|
|
3
|
+
"description": "Products stocked across three locations. The product shape has no location field, so each variant's inventory.quantity is the total and the per-location split is in an \"inventory\" metafield per location (inventory.<location>).",
|
|
4
|
+
"products": [
|
|
5
|
+
{ "handle": "seed-warehouse-widget", "title": "Seed Warehouse Widget", "vendor": "Seed Logistics", "product_type": "Widget",
|
|
6
|
+
"tags": ["seed", "multi-location"], "price": 12.0,
|
|
7
|
+
"locations": { "east-dc": 80, "west-dc": 35, "central-dc": 0 } },
|
|
8
|
+
{ "handle": "seed-warehouse-gadget", "title": "Seed Warehouse Gadget", "vendor": "Seed Logistics", "product_type": "Gadget",
|
|
9
|
+
"tags": ["seed", "multi-location"], "price": 27.5,
|
|
10
|
+
"locations": { "east-dc": 0, "west-dc": 0, "central-dc": 14 } },
|
|
11
|
+
{ "handle": "seed-warehouse-gizmo", "title": "Seed Warehouse Gizmo", "vendor": "Seed Logistics", "product_type": "Gizmo",
|
|
12
|
+
"tags": ["seed", "multi-location"], "price": 8.75,
|
|
13
|
+
"locations": { "east-dc": 220, "west-dc": 180, "central-dc": 95 } }
|
|
14
|
+
]
|
|
15
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "regulated-vape",
|
|
3
|
+
"description": "Age-restricted products. The product shape has no age field, so each carries tags \"age-restricted\" and \"age-21\" and compliance metafields (age_restricted, minimum_age, regulated_category).",
|
|
4
|
+
"products": [
|
|
5
|
+
{ "handle": "seed-regulated-pod-mint", "title": "Seed Regulated Pod, Mint", "vendor": "Seed Regulated Co", "product_type": "Pod",
|
|
6
|
+
"tags": ["seed", "age-restricted", "age-21"], "price": 18.25, "quantity": 60,
|
|
7
|
+
"metafields": [
|
|
8
|
+
{ "namespace": "compliance", "key": "age_restricted", "value": "true", "type": "boolean" },
|
|
9
|
+
{ "namespace": "compliance", "key": "minimum_age", "value": "21", "type": "number_integer" },
|
|
10
|
+
{ "namespace": "compliance", "key": "regulated_category", "value": "vapor", "type": "single_line_text_field" }
|
|
11
|
+
] },
|
|
12
|
+
{ "handle": "seed-regulated-pod-berry", "title": "Seed Regulated Pod, Berry", "vendor": "Seed Regulated Co", "product_type": "Pod",
|
|
13
|
+
"tags": ["seed", "age-restricted", "age-21"], "price": 18.25, "quantity": 45,
|
|
14
|
+
"metafields": [
|
|
15
|
+
{ "namespace": "compliance", "key": "age_restricted", "value": "true", "type": "boolean" },
|
|
16
|
+
{ "namespace": "compliance", "key": "minimum_age", "value": "21", "type": "number_integer" },
|
|
17
|
+
{ "namespace": "compliance", "key": "regulated_category", "value": "vapor", "type": "single_line_text_field" }
|
|
18
|
+
] },
|
|
19
|
+
{ "handle": "seed-regulated-device-kit", "title": "Seed Regulated Device Kit", "vendor": "Seed Regulated Co", "product_type": "Device",
|
|
20
|
+
"tags": ["seed", "age-restricted", "age-21"], "price": 39.0, "quantity": 25,
|
|
21
|
+
"metafields": [
|
|
22
|
+
{ "namespace": "compliance", "key": "age_restricted", "value": "true", "type": "boolean" },
|
|
23
|
+
{ "namespace": "compliance", "key": "minimum_age", "value": "21", "type": "number_integer" },
|
|
24
|
+
{ "namespace": "compliance", "key": "regulated_category", "value": "vapor", "type": "single_line_text_field" }
|
|
25
|
+
] },
|
|
26
|
+
{ "handle": "seed-unrestricted-sticker", "title": "Seed Brand Sticker", "vendor": "Seed Regulated Co", "product_type": "Accessory",
|
|
27
|
+
"tags": ["seed"], "price": 3.0, "quantity": 300 }
|
|
28
|
+
]
|
|
29
|
+
}
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `tot app install | update | rotate | list | replay` — the ONLINE Private App commands.
|
|
3
|
+
*
|
|
4
|
+
* They call the store's own `/api/apps/admin/*` routes with your `tot login` identity
|
|
5
|
+
* (`resolveViewerTransport`: a viewer session minted from your MCP token). The server's
|
|
6
|
+
* admission rule decides who may install what; the CLI decides nothing.
|
|
7
|
+
*
|
|
8
|
+
* tot app install POST /api/apps/admin/install
|
|
9
|
+
* tot app update POST /api/apps/admin/update
|
|
10
|
+
* tot app rotate POST /api/apps/admin/credentials/rotate
|
|
11
|
+
* tot app list GET /api/apps/admin/list
|
|
12
|
+
* tot app replay POST /api/apps/admin/webhooks/deliveries/<deliveryId>/replay
|
|
13
|
+
*
|
|
14
|
+
* A client secret is printed once, by `install` or `rotate`, and nowhere else: `list` never
|
|
15
|
+
* carries one and nothing here writes it to a file or the activity log.
|
|
16
|
+
*/
|
|
17
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
18
|
+
import { join, resolve } from "node:path";
|
|
19
|
+
import { resolveViewerTransport } from "../../viewer-session.mjs";
|
|
20
|
+
import { missingGrantsOf, refusalHint } from "../../admission-hint.mjs";
|
|
21
|
+
import { validateManifest } from "../../vendor/private-apps-devkit.mjs";
|
|
22
|
+
|
|
23
|
+
export const DEFAULT_APP_ENV = "test";
|
|
24
|
+
const OPTION_VERBS = new Set(["install", "update", "rotate", "list", "replay"]);
|
|
25
|
+
|
|
26
|
+
export const ADMIN_USAGE = `tot app — manage Private App installs on your store
|
|
27
|
+
|
|
28
|
+
tot app install [--app <dir>] [--env test|production] [--webhook-endpoint <url>]
|
|
29
|
+
install the app in <dir> (reads its tot-app.json); prints the client secret ONCE
|
|
30
|
+
tot app update <installId> [--app <dir>] [--webhook-endpoint <url|none>]
|
|
31
|
+
push the app's current version, scopes, manifest and widgets to an install
|
|
32
|
+
tot app rotate <installId> issue a new client secret (printed ONCE); the old one stops working
|
|
33
|
+
tot app list your store's installs: id, app, version, env, status, scopes (never secrets)
|
|
34
|
+
tot app replay <deliveryId> re-send a webhook delivery to its install
|
|
35
|
+
|
|
36
|
+
Options (all online commands):
|
|
37
|
+
--tenant <appDomain> the store (default: the current checkout's store)
|
|
38
|
+
--url <origin> storefront origin (default: $TOT_STOREFRONT_URL or the hosted storefront)
|
|
39
|
+
--json machine-readable output
|
|
40
|
+
|
|
41
|
+
--env defaults to test. A production install needs --env=production, and the store owner.`;
|
|
42
|
+
|
|
43
|
+
/** Parse the online `tot app` argv. Pure — unit-tested. @param {string[]} argv */
|
|
44
|
+
export function parseAdminArgs(argv) {
|
|
45
|
+
/** @type {{ verb: string|null, positional: string[], app: string|null, env: string|null, tenant: string|null,
|
|
46
|
+
* url: string|null, webhookEndpoint: string|null|undefined, json: boolean, help: boolean, unknown: string[] }} */
|
|
47
|
+
const a = { verb: null, positional: [], app: null, env: null, tenant: null, url: null,
|
|
48
|
+
webhookEndpoint: undefined, json: false, help: false, unknown: [] };
|
|
49
|
+
const valueOf = (i, t) => {
|
|
50
|
+
const eq = t.indexOf("=");
|
|
51
|
+
return eq >= 0 ? { value: t.slice(eq + 1), next: i } : { value: argv[i + 1], next: i + 1 };
|
|
52
|
+
};
|
|
53
|
+
for (let i = 0; i < argv.length; i++) {
|
|
54
|
+
const t = argv[i];
|
|
55
|
+
const flag = t.startsWith("--") ? t.slice(0, t.includes("=") ? t.indexOf("=") : undefined) : null;
|
|
56
|
+
if (t === "--json") a.json = true;
|
|
57
|
+
else if (t === "--help" || t === "-h") a.help = true;
|
|
58
|
+
else if (flag === "--app" || flag === "--env" || flag === "--tenant" || flag === "--url" || flag === "--webhook-endpoint") {
|
|
59
|
+
const { value, next } = valueOf(i, t);
|
|
60
|
+
i = next;
|
|
61
|
+
const v = value === undefined || value.startsWith("--") ? "" : value;
|
|
62
|
+
if (flag === "--app") a.app = v;
|
|
63
|
+
else if (flag === "--env") a.env = v;
|
|
64
|
+
else if (flag === "--tenant") a.tenant = v;
|
|
65
|
+
else if (flag === "--url") a.url = v;
|
|
66
|
+
else a.webhookEndpoint = v === "none" ? null : v;
|
|
67
|
+
} else if (t.startsWith("--")) a.unknown.push(t);
|
|
68
|
+
else if (a.verb === null) a.verb = t;
|
|
69
|
+
else a.positional.push(t);
|
|
70
|
+
}
|
|
71
|
+
return a;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** The next step for a refused call: the server's `code` first, then the generic admission hint. */
|
|
75
|
+
function nextForRefusal(status, body) {
|
|
76
|
+
const code = typeof body?.code === "string" ? body.code : "";
|
|
77
|
+
if (code === "owner_required_for_production_app") {
|
|
78
|
+
return "ask the store owner to install the production app, or install with --env=test";
|
|
79
|
+
}
|
|
80
|
+
if (status === 401) return "run `tot login`, then re-run";
|
|
81
|
+
if (code === "scope_denied") return "remove the refused scopes from tot-app.json, then re-run";
|
|
82
|
+
if (code === "already_installed") return "run `tot app list` for its installId, then `tot app update <installId>`";
|
|
83
|
+
if (code === "not_found") return "run `tot app list` to see this store's installs";
|
|
84
|
+
if (code === "invalid_state") return "run `tot app list` to check the install's status";
|
|
85
|
+
if (status === 403) return refusalHint(status, missingGrantsOf(body));
|
|
86
|
+
if (status === 429) return "wait a minute, then re-run";
|
|
87
|
+
if (status >= 500) return "retry shortly; if it persists, report it with `tot feedback`";
|
|
88
|
+
return "fix the input named above, then re-run";
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** @param {string[]} argv @param {any} ctx @param {Record<string, any>} [deps] */
|
|
92
|
+
export async function runAdmin(argv, ctx, deps = {}) {
|
|
93
|
+
const out = deps.out || ((s) => process.stdout.write(`${s}\n`));
|
|
94
|
+
const err = deps.err || ((s) => process.stderr.write(`${s}\n`));
|
|
95
|
+
const env = deps.env || process.env;
|
|
96
|
+
const fetchImpl = deps.fetchImpl || fetch;
|
|
97
|
+
const resolveViewer = deps.resolveViewerTransport || resolveViewerTransport;
|
|
98
|
+
const fail = (what, next) => { err(`✗ ${what}${next ? `\n\n → next: ${next}` : ""}`); return 2; };
|
|
99
|
+
|
|
100
|
+
const args = parseAdminArgs(argv);
|
|
101
|
+
if (args.help || !args.verb || !OPTION_VERBS.has(args.verb)) {
|
|
102
|
+
(args.help ? out : err)(ADMIN_USAGE);
|
|
103
|
+
return args.help ? 0 : 2;
|
|
104
|
+
}
|
|
105
|
+
if (args.unknown.length) return fail(`unknown option ${args.unknown[0]}`, "tot app --help");
|
|
106
|
+
const verb = args.verb;
|
|
107
|
+
|
|
108
|
+
// ── build the request from local files and arguments, before any network call ──
|
|
109
|
+
/** @type {{ method: string, path: string, body?: unknown }} */
|
|
110
|
+
let request;
|
|
111
|
+
if (verb === "install") {
|
|
112
|
+
const appEnv = args.env === null ? DEFAULT_APP_ENV : args.env;
|
|
113
|
+
if (appEnv !== "test" && appEnv !== "production") {
|
|
114
|
+
return fail(`--env must be test or production (got "${appEnv}")`, "re-run with --env=test, or --env=production for the owner's live app");
|
|
115
|
+
}
|
|
116
|
+
const loaded = loadManifest(args.app, ctx);
|
|
117
|
+
if (!loaded.ok) return fail(loaded.message, loaded.next);
|
|
118
|
+
const m = loaded.manifest;
|
|
119
|
+
const webhookEndpoint = args.webhookEndpoint === undefined ? m.webhooks?.endpoint : args.webhookEndpoint;
|
|
120
|
+
request = {
|
|
121
|
+
method: "POST", path: "/api/apps/admin/install",
|
|
122
|
+
body: {
|
|
123
|
+
appId: m.id, appVersion: m.version, env: appEnv, scopes: m.scopes || [], manifest: m,
|
|
124
|
+
...(webhookEndpoint ? { webhookEndpoint } : {}),
|
|
125
|
+
...(Array.isArray(m.widgets) && m.widgets.length ? { widgetPlacements: m.widgets } : {}),
|
|
126
|
+
},
|
|
127
|
+
};
|
|
128
|
+
} else if (verb === "update") {
|
|
129
|
+
const installId = args.positional[0];
|
|
130
|
+
if (!installId) return fail("no install to update", "tot app update <installId> (find it with `tot app list`)");
|
|
131
|
+
const loaded = loadManifest(args.app, ctx);
|
|
132
|
+
if (!loaded.ok) return fail(loaded.message, loaded.next);
|
|
133
|
+
const m = loaded.manifest;
|
|
134
|
+
request = {
|
|
135
|
+
method: "POST", path: "/api/apps/admin/update",
|
|
136
|
+
body: {
|
|
137
|
+
installId, appVersion: m.version, scopes: m.scopes || [], manifest: m,
|
|
138
|
+
...(args.webhookEndpoint === undefined
|
|
139
|
+
? (m.webhooks?.endpoint ? { webhookEndpoint: m.webhooks.endpoint } : {})
|
|
140
|
+
: { webhookEndpoint: args.webhookEndpoint }),
|
|
141
|
+
...(Array.isArray(m.widgets) ? { widgetPlacements: m.widgets } : {}),
|
|
142
|
+
},
|
|
143
|
+
};
|
|
144
|
+
} else if (verb === "rotate") {
|
|
145
|
+
const installId = args.positional[0];
|
|
146
|
+
if (!installId) return fail("no install to rotate", "tot app rotate <installId> (find it with `tot app list`)");
|
|
147
|
+
request = { method: "POST", path: "/api/apps/admin/credentials/rotate", body: { installId } };
|
|
148
|
+
} else if (verb === "list") {
|
|
149
|
+
request = { method: "GET", path: "/api/apps/admin/list" };
|
|
150
|
+
} else {
|
|
151
|
+
const deliveryId = args.positional[0];
|
|
152
|
+
if (!deliveryId) return fail("no delivery to replay", "tot app replay <deliveryId>");
|
|
153
|
+
request = { method: "POST", path: `/api/apps/admin/webhooks/deliveries/${encodeURIComponent(deliveryId)}/replay`, body: {} };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const tenant = String(args.tenant || ctx?.tenant || "").trim().toLowerCase();
|
|
157
|
+
if (!tenant) return fail("no store to act on", "pass --tenant <appDomain>, or run inside a store checkout");
|
|
158
|
+
|
|
159
|
+
const transport = await resolveViewer({ tenant, env, fetchImpl, storefrontUrl: args.url || env.TOT_STOREFRONT_URL || null });
|
|
160
|
+
if (!transport.ok) {
|
|
161
|
+
err(`✗ ${transport.message}\n\n → next: ${transport.hint}`);
|
|
162
|
+
return 1;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
let res;
|
|
166
|
+
try {
|
|
167
|
+
// Every admin route admits a console session only for the store named by `?tenant=`.
|
|
168
|
+
res = await fetchImpl(`${transport.base}${request.path}?tenant=${encodeURIComponent(tenant)}`, {
|
|
169
|
+
method: request.method,
|
|
170
|
+
headers: {
|
|
171
|
+
...transport.authHeaders,
|
|
172
|
+
accept: "application/json",
|
|
173
|
+
...(request.body === undefined ? {} : { "content-type": "application/json" }),
|
|
174
|
+
},
|
|
175
|
+
...(request.body === undefined ? {} : { body: JSON.stringify(request.body) }),
|
|
176
|
+
});
|
|
177
|
+
} catch (e) {
|
|
178
|
+
err(`✗ could not reach the store: ${e?.message || e}\n\n → next: check --url / your network, then re-run`);
|
|
179
|
+
return 1;
|
|
180
|
+
}
|
|
181
|
+
const data = parseJsonBody(await res.text());
|
|
182
|
+
if (!res.ok) {
|
|
183
|
+
const reason = typeof data?.error === "string" ? data.error : `the store refused the request (HTTP ${res.status}).`;
|
|
184
|
+
const denials = Array.isArray(data?.denials) && data.denials.length
|
|
185
|
+
? `\n refused scopes: ${data.denials.map((d) => d?.scope ?? d?.id ?? JSON.stringify(d)).join(", ")}` : "";
|
|
186
|
+
err(`✗ tot app ${verb}: ${reason}${denials}\n\n → next: ${nextForRefusal(res.status, data)}`);
|
|
187
|
+
return res.status === 401 || res.status === 403 ? 1 : (res.status >= 500 ? 1 : 2);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
if (verb === "list") return renderList(data, args.json, out);
|
|
191
|
+
if (verb === "install" || verb === "rotate") return renderCredential(verb, data, args.json, out, err);
|
|
192
|
+
if (verb === "update") {
|
|
193
|
+
if (args.json) out(JSON.stringify(data));
|
|
194
|
+
else out(`✓ updated ${data?.install?.installId ?? "the install"} (${data?.install?.appId ?? "app"} ${data?.install?.appVersion ?? ""}, ${data?.install?.env ?? ""})`.replace(/ ,/g, ","));
|
|
195
|
+
return 0;
|
|
196
|
+
}
|
|
197
|
+
if (args.json) out(JSON.stringify(data));
|
|
198
|
+
else out(`✓ replay queued for delivery ${data?.delivery?.deliveryId ?? args.positional[0]}`);
|
|
199
|
+
return 0;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* A response body as JSON, or null when the store answered with something that is not JSON (an
|
|
204
|
+
* HTML error page from a proxy, an empty 204). Only a parse failure maps to null.
|
|
205
|
+
* @param {string} text
|
|
206
|
+
*/
|
|
207
|
+
function parseJsonBody(text) {
|
|
208
|
+
try {
|
|
209
|
+
return JSON.parse(text);
|
|
210
|
+
} catch (e) {
|
|
211
|
+
if (e instanceof SyntaxError) return null;
|
|
212
|
+
throw e;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** @param {string|null} appDir @param {any} ctx */
|
|
217
|
+
function loadManifest(appDir, ctx) {
|
|
218
|
+
const dir = resolve(appDir || ctx?.cwd || process.cwd());
|
|
219
|
+
const path = join(dir, "tot-app.json");
|
|
220
|
+
if (!existsSync(path)) {
|
|
221
|
+
return { ok: false, message: `no tot-app.json at ${path}`, next: "run inside your app's directory, pass --app <dir>, or `tot app scaffold <name>`" };
|
|
222
|
+
}
|
|
223
|
+
let parsed;
|
|
224
|
+
try { parsed = JSON.parse(readFileSync(path, "utf8")); }
|
|
225
|
+
catch (e) { return { ok: false, message: `${path} is not valid JSON: ${e.message}`, next: "fix the file, then re-run" }; }
|
|
226
|
+
const result = validateManifest(parsed);
|
|
227
|
+
if (!result.ok) {
|
|
228
|
+
return { ok: false, message: `${path} is not a valid manifest:\n${(result.errors || []).map((e) => ` - ${e}`).join("\n")}`, next: "tot app dev validate" };
|
|
229
|
+
}
|
|
230
|
+
return { ok: true, manifest: parsed };
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function renderCredential(verb, data, json, out, err) {
|
|
234
|
+
const secret = data?.credential?.secret;
|
|
235
|
+
if (json) {
|
|
236
|
+
out(JSON.stringify(data));
|
|
237
|
+
} else {
|
|
238
|
+
const install = data?.install;
|
|
239
|
+
if (install) out(`✓ installed ${install.appId} ${install.appVersion} (${install.env}) as ${install.installId}`);
|
|
240
|
+
else out(`✓ rotated the client secret`);
|
|
241
|
+
out(` client id: ${data?.credential?.clientId ?? ""}`);
|
|
242
|
+
out(` client secret: ${secret ?? ""}`);
|
|
243
|
+
}
|
|
244
|
+
if (typeof secret === "string" && secret) {
|
|
245
|
+
err(" Store this secret now — it is never shown again. If you lose it, run `tot app rotate <installId>`.");
|
|
246
|
+
}
|
|
247
|
+
return 0;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function renderList(data, json, out) {
|
|
251
|
+
const installs = Array.isArray(data?.installs) ? data.installs : [];
|
|
252
|
+
if (json) {
|
|
253
|
+
out(JSON.stringify(installs.map(installRow)));
|
|
254
|
+
return 0;
|
|
255
|
+
}
|
|
256
|
+
if (!installs.length) {
|
|
257
|
+
out("No app installs on this store yet. Install one with `tot app install`.");
|
|
258
|
+
return 0;
|
|
259
|
+
}
|
|
260
|
+
const rows = installs.map(installRow);
|
|
261
|
+
const cols = ["installId", "appId", "appVersion", "env", "status", "scopes"];
|
|
262
|
+
const cell = (r, c) => (c === "scopes" ? r.scopes.join(",") : String(r[c] ?? ""));
|
|
263
|
+
const widths = cols.map((c) => Math.max(c.length, ...rows.map((r) => cell(r, c).length)));
|
|
264
|
+
const line = (vals) => vals.map((v, i) => v.padEnd(widths[i])).join(" ").trimEnd();
|
|
265
|
+
out(line(["INSTALL ID", "APP", "VERSION", "ENV", "STATUS", "SCOPES"]));
|
|
266
|
+
for (const r of rows) out(line(cols.map((c) => cell(r, c))));
|
|
267
|
+
return 0;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Only these fields ever leave a list response — a secret or hash can never ride along. */
|
|
271
|
+
function installRow(i) {
|
|
272
|
+
return {
|
|
273
|
+
installId: i?.installId, appId: i?.appId, appVersion: i?.appVersion, env: i?.env, status: i?.status,
|
|
274
|
+
scopes: Array.isArray(i?.scopes) ? i.scopes : [],
|
|
275
|
+
};
|
|
276
|
+
}
|
|
@@ -1,17 +1,25 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* `tot app` — the Storefront Private App developer subcommand group
|
|
3
|
-
* (PrivateApps epic): scaffold a new app,
|
|
4
|
-
*
|
|
3
|
+
* (PrivateApps epic): scaffold a new app, exercise its webhook/manifest/widget-launch
|
|
4
|
+
* loop offline, then install and operate it on a store.
|
|
5
5
|
*
|
|
6
6
|
* tot app scaffold <name> materialize a runnable Private App skeleton
|
|
7
7
|
* tot app dev ... local, offline webhook/manifest/JWT harness
|
|
8
|
+
* tot app install|update|rotate|list|replay online install management (admin.mjs)
|
|
8
9
|
*/
|
|
9
10
|
import { fail } from "../../errors.mjs";
|
|
10
11
|
|
|
11
|
-
const USAGE = `tot app — build a Storefront Private App
|
|
12
|
+
const USAGE = `tot app — build and install a Storefront Private App
|
|
12
13
|
|
|
13
14
|
tot app scaffold <name> scaffold a runnable Private App skeleton
|
|
14
|
-
tot app dev ... local, offline webhook/manifest/JWT harness (see \`tot app dev --help\`)
|
|
15
|
+
tot app dev ... local, offline webhook/manifest/JWT harness (see \`tot app dev --help\`)
|
|
16
|
+
tot app install install your app on your store (env defaults to test); prints the client secret once
|
|
17
|
+
tot app update <installId> push your app's current version, scopes and manifest to an install
|
|
18
|
+
tot app rotate <installId> issue a new client secret (printed once)
|
|
19
|
+
tot app list your store's installs (never secrets)
|
|
20
|
+
tot app replay <deliveryId> re-send a webhook delivery
|
|
21
|
+
|
|
22
|
+
Run \`tot app <command> --help\` for options. Online commands use your \`tot login\` session.`;
|
|
15
23
|
|
|
16
24
|
/** @param {string[]} argv @param {any} ctx */
|
|
17
25
|
export async function run(argv, ctx) {
|
|
@@ -29,6 +37,10 @@ export async function run(argv, ctx) {
|
|
|
29
37
|
const { run: runDev } = await import("./dev.mjs");
|
|
30
38
|
return /** @type {any} */ (runDev)(rest, ctx);
|
|
31
39
|
}
|
|
40
|
+
if (sub === "install" || sub === "update" || sub === "rotate" || sub === "list" || sub === "replay") {
|
|
41
|
+
const { runAdmin } = await import("./admin.mjs");
|
|
42
|
+
return runAdmin(argv, ctx);
|
|
43
|
+
}
|
|
32
44
|
|
|
33
45
|
console.error(fail(`unknown \`tot app\` subcommand: ${sub}`, "tot app --help"));
|
|
34
46
|
return 2;
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `tot catalog seed --preset=<general|regulated-vape|multi-warehouse>` — fill your store's
|
|
3
|
+
* catalog with a canned set of obviously synthetic products, so a storefront (and an app
|
|
4
|
+
* reading it) has something to render before you migrate real data.
|
|
5
|
+
*
|
|
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
|
|
9
|
+
* checkout, and refuses to replace a product file that already exists unless `--overwrite`.
|
|
10
|
+
* Presets are data: `src/catalog-presets/<name>.json`.
|
|
11
|
+
*/
|
|
12
|
+
import { createHash } from "node:crypto";
|
|
13
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
|
|
14
|
+
import { join } from "node:path";
|
|
15
|
+
import { fileURLToPath } from "node:url";
|
|
16
|
+
|
|
17
|
+
const PRESET_DIR = fileURLToPath(new URL("../catalog-presets/", import.meta.url));
|
|
18
|
+
|
|
19
|
+
export const USAGE = `tot catalog — manage your store's catalog content
|
|
20
|
+
|
|
21
|
+
tot catalog seed --preset=<name> [--overwrite]
|
|
22
|
+
|
|
23
|
+
Presets: general, regulated-vape, multi-warehouse
|
|
24
|
+
|
|
25
|
+
Writes synthetic products to content/catalog/products/<handle>.json in this store checkout.
|
|
26
|
+
Run \`tot preview\` afterwards to push them.`;
|
|
27
|
+
|
|
28
|
+
/** Preset names, from the data files. */
|
|
29
|
+
export function presetNames() {
|
|
30
|
+
return readdirSync(PRESET_DIR).filter((f) => f.endsWith(".json")).map((f) => f.slice(0, -5)).sort();
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** @param {string} name */
|
|
34
|
+
export function loadPreset(name) {
|
|
35
|
+
if (!/^[a-z0-9-]+$/.test(name) || !presetNames().includes(name)) return null;
|
|
36
|
+
return JSON.parse(readFileSync(join(PRESET_DIR, `${name}.json`), "utf8"));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function canonicalize(value) {
|
|
40
|
+
if (Array.isArray(value)) return value.map(canonicalize);
|
|
41
|
+
if (value && typeof value === "object") {
|
|
42
|
+
const sorted = {};
|
|
43
|
+
for (const key of Object.keys(value).sort()) sorted[key] = canonicalize(value[key]);
|
|
44
|
+
return sorted;
|
|
45
|
+
}
|
|
46
|
+
return value;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Same checksum scope the catalog importer writes (`computeChecksum`). */
|
|
50
|
+
function checksum(record) {
|
|
51
|
+
const { migrated_at: _m, source_checksum: _s, ...rest } = record;
|
|
52
|
+
return createHash("sha256").update(JSON.stringify(canonicalize(rest)), "utf8").digest("hex");
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Expand one compact preset entry into a catalog product record.
|
|
57
|
+
* @param {any} seed @param {string} now ISO timestamp
|
|
58
|
+
*/
|
|
59
|
+
export function expandProduct(seed, now) {
|
|
60
|
+
const locations = seed.locations && typeof seed.locations === "object" ? seed.locations : null;
|
|
61
|
+
const quantity = locations ? Object.values(locations).reduce((a, b) => a + Number(b), 0) : Number(seed.quantity ?? 0);
|
|
62
|
+
const metafields = [
|
|
63
|
+
...(seed.metafields || []),
|
|
64
|
+
...(locations
|
|
65
|
+
? Object.entries(locations).map(([loc, qty]) => ({ namespace: "inventory", key: loc, value: String(qty), type: "number_integer" }))
|
|
66
|
+
: []),
|
|
67
|
+
];
|
|
68
|
+
const description = `${seed.title} — synthetic seed product.`;
|
|
69
|
+
const product = {
|
|
70
|
+
id: `prod_${seed.handle}`,
|
|
71
|
+
source: { platform: "manual", source_id: seed.handle },
|
|
72
|
+
handle: seed.handle,
|
|
73
|
+
title: seed.title,
|
|
74
|
+
description_html: `<p>${description}</p>`,
|
|
75
|
+
description_text: description,
|
|
76
|
+
vendor: seed.vendor,
|
|
77
|
+
product_type: seed.product_type,
|
|
78
|
+
tags: seed.tags || [],
|
|
79
|
+
status: "active",
|
|
80
|
+
seo: { title: seed.title, description: description },
|
|
81
|
+
options: [],
|
|
82
|
+
images: [],
|
|
83
|
+
variants: [{
|
|
84
|
+
id: `var_${seed.handle}`,
|
|
85
|
+
source: { platform: "manual", source_id: `var_${seed.handle}` },
|
|
86
|
+
sku: seed.handle.toUpperCase().replace(/-/g, "_"),
|
|
87
|
+
title: "Default",
|
|
88
|
+
price: seed.price,
|
|
89
|
+
currency: "USD",
|
|
90
|
+
option_values: {},
|
|
91
|
+
inventory: { quantity, available: quantity > 0 },
|
|
92
|
+
position: 1,
|
|
93
|
+
}],
|
|
94
|
+
price_range: { min: seed.price, max: seed.price, currency: "USD" },
|
|
95
|
+
collections: [],
|
|
96
|
+
metafields,
|
|
97
|
+
created_at: now,
|
|
98
|
+
updated_at: now,
|
|
99
|
+
migrated_at: now,
|
|
100
|
+
};
|
|
101
|
+
return { ...product, source_checksum: checksum(product) };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** @param {string[]} argv */
|
|
105
|
+
export function parseCatalogArgs(argv) {
|
|
106
|
+
/** @type {{ sub: string|null, preset: string|null, overwrite: boolean, help: boolean, unknown: string[] }} */
|
|
107
|
+
const a = { sub: null, preset: null, overwrite: false, help: false, unknown: [] };
|
|
108
|
+
for (let i = 0; i < argv.length; i++) {
|
|
109
|
+
const t = argv[i];
|
|
110
|
+
if (t === "--help" || t === "-h") a.help = true;
|
|
111
|
+
else if (t === "--overwrite") a.overwrite = true;
|
|
112
|
+
else if (t === "--preset") a.preset = argv[++i] ?? "";
|
|
113
|
+
else if (t.startsWith("--preset=")) a.preset = t.slice("--preset=".length);
|
|
114
|
+
else if (t.startsWith("--")) a.unknown.push(t);
|
|
115
|
+
else if (a.sub === null) a.sub = t;
|
|
116
|
+
else a.unknown.push(t);
|
|
117
|
+
}
|
|
118
|
+
return a;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* @param {string[]} argv @param {any} ctx
|
|
123
|
+
* @param {{ out?: (s: string) => void, err?: (s: string) => void, now?: () => string }} [deps]
|
|
124
|
+
*/
|
|
125
|
+
export async function run(argv, ctx, deps = {}) {
|
|
126
|
+
const out = deps.out || ((s) => process.stdout.write(`${s}\n`));
|
|
127
|
+
const err = deps.err || ((s) => process.stderr.write(`${s}\n`));
|
|
128
|
+
const args = parseCatalogArgs(argv);
|
|
129
|
+
if (args.help || !args.sub) {
|
|
130
|
+
(args.help ? out : err)(USAGE);
|
|
131
|
+
return args.help ? 0 : 2;
|
|
132
|
+
}
|
|
133
|
+
if (args.sub !== "seed") {
|
|
134
|
+
err(`✗ unknown \`tot catalog\` command: ${args.sub}\n\n → next: tot catalog seed --preset=<${presetNames().join("|")}>`);
|
|
135
|
+
return 2;
|
|
136
|
+
}
|
|
137
|
+
if (args.unknown.length) {
|
|
138
|
+
err(`✗ unknown argument ${args.unknown[0]}\n\n → next: tot catalog --help`);
|
|
139
|
+
return 2;
|
|
140
|
+
}
|
|
141
|
+
if (!args.preset) {
|
|
142
|
+
err(`✗ no preset chosen. Presets: ${presetNames().join(", ")}\n\n → next: tot catalog seed --preset=general`);
|
|
143
|
+
return 2;
|
|
144
|
+
}
|
|
145
|
+
const preset = loadPreset(args.preset);
|
|
146
|
+
if (!preset) {
|
|
147
|
+
err(`✗ unknown preset "${args.preset}". Presets: ${presetNames().join(", ")}\n\n → next: tot catalog seed --preset=${presetNames()[0]}`);
|
|
148
|
+
return 2;
|
|
149
|
+
}
|
|
150
|
+
if (ctx?.mode !== "checkout" || !ctx.workspacePath) {
|
|
151
|
+
err("✗ not inside a store checkout — `tot catalog seed` writes into your store's own repo.\n\n → next: `tot clone <tenant>`, cd into it, then re-run");
|
|
152
|
+
return 2;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const dir = join(ctx.workspacePath, "content", "catalog", "products");
|
|
156
|
+
const now = (deps.now || (() => new Date().toISOString()))();
|
|
157
|
+
const products = preset.products.map((p) => expandProduct(p, now));
|
|
158
|
+
const existing = products.filter((p) => existsSync(join(dir, `${p.handle}.json`)));
|
|
159
|
+
if (existing.length && !args.overwrite) {
|
|
160
|
+
err(`✗ ${existing.length} product file(s) already exist (${existing.map((p) => p.handle).join(", ")}); nothing written.\n\n → next: re-run with --overwrite to replace them`);
|
|
161
|
+
return 2;
|
|
162
|
+
}
|
|
163
|
+
mkdirSync(dir, { recursive: true });
|
|
164
|
+
for (const p of products) writeFileSync(join(dir, `${p.handle}.json`), `${JSON.stringify(p, null, 2)}\n`);
|
|
165
|
+
out(`✓ seeded ${products.length} "${preset.name}" products into content/catalog/products/`);
|
|
166
|
+
out(` ${preset.description}`);
|
|
167
|
+
out(" → next: `tot preview` to push them");
|
|
168
|
+
return 0;
|
|
169
|
+
}
|