@shop-on/theme-cli 0.10.0 → 0.11.1

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.
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  import { processIo } from "../audit/command.mjs";
3
+ import { MerchantCallError, merchant } from "../auth/api.mjs";
3
4
  import { defaultConfigDir } from "../auth/credentials.mjs";
4
5
  import { apiFlag, ensureLoggedIn, resolveApiUrl } from "../auth/oauth.mjs";
5
6
  import { openUrl } from "../open-url.mjs";
6
- import { graphql } from "../auth/api.mjs";
7
7
  import { formatCredentialList } from "./credentials.mjs";
8
8
  import { existsSync, readdirSync, rmSync, writeFileSync } from "node:fs";
9
9
  import path from "node:path";
@@ -12,19 +12,14 @@ import { spawn } from "node:child_process";
12
12
  import os from "node:os";
13
13
  import { randomBytes } from "node:crypto";
14
14
  import { packageManagerCommands, scaffoldTheme } from "@shop-on/create-theme";
15
- //#region src/theme/init.ts
16
- const INIT_USAGE = `usage: shop-on theme init <dir> [--api <url>]
15
+ // src/theme/init.ts
16
+ const INIT_USAGE = `usage: shop-on theme init <dir> [--api <url>] [--no-install]
17
17
 
18
18
  Scaffolds a theme in <dir> (new or empty), mints a storefront credential for
19
19
  it on your store, writes its .env and installs its dependencies.
20
20
 
21
- --api <url> the Shop-On api (default: $SHOP_ON_API_URL, else production)`;
22
- const CREATE = `mutation ShopOnDevCredentialCreate($input: StorefrontDevCredentialCreateInput!) {
23
- storefrontDevCredentialCreate(input: $input) {
24
- clientId clientSecret apiUrl shopHandle
25
- userErrors { code field message }
26
- }
27
- }`;
21
+ --api <url> the Shop-On api (default: $SHOP_ON_API_URL, else production)
22
+ --no-install skip installing the dependencies; init prints the command to run`;
28
23
  /** The api caps a credential's name at 100 characters. */
29
24
  const credentialName = (theme) => `${theme} on ${os.hostname()}`.slice(0, 100);
30
25
  const defaultDeps = {
@@ -63,6 +58,10 @@ async function runInit({ argv, cwd = process.cwd(), io = processIo, configDir =
63
58
  allowPositionals: true,
64
59
  options: {
65
60
  api: { type: "string" },
61
+ "no-install": {
62
+ type: "boolean",
63
+ default: false
64
+ },
66
65
  help: {
67
66
  type: "boolean",
68
67
  short: "h",
@@ -94,6 +93,10 @@ async function runInit({ argv, cwd = process.cwd(), io = processIo, configDir =
94
93
  return 1;
95
94
  }
96
95
  io.err(`Scaffolded ${theme.name} in ${theme.dir}`);
96
+ const ctx = {
97
+ apiUrl,
98
+ configDir
99
+ };
97
100
  let created;
98
101
  try {
99
102
  await ensureLoggedIn({
@@ -102,46 +105,44 @@ async function runInit({ argv, cwd = process.cwd(), io = processIo, configDir =
102
105
  io,
103
106
  openUrl: deps.openUrl
104
107
  });
105
- ({storefrontDevCredentialCreate: created} = await graphql({
106
- apiUrl,
107
- configDir
108
- }, CREATE, { input: { name: credentialName(theme.name) } }));
109
- if (created.userErrors.length) {
110
- for (const e of created.userErrors) io.err(e.message);
111
- if (created.userErrors.some((e) => e.code === "CAP_REACHED")) {
112
- io.err(`\nYour store's dev credentials:\n${await formatCredentialList({
113
- apiUrl,
114
- configDir
115
- })}`);
116
- io.err(`\nRevoke one, then run \`shop-on theme init ${target}${apiFlag(apiUrl)}\` again.`);
117
- }
118
- removeScaffold(dir, existed);
119
- return 1;
120
- }
108
+ created = await merchant(ctx, (api) => api.storefrontCredentials.create({ name: credentialName(theme.name) }));
121
109
  } catch (err) {
122
- io.err(err.message);
110
+ if (err instanceof MerchantCallError && err.code === "LIMIT_EXCEEDED") {
111
+ const { limit } = err.data;
112
+ io.err(`Your store already holds ${limit} dev storefront credentials, the most it can.`);
113
+ const list = await formatCredentialList(ctx).catch((listing) => ` (they could not be listed: ${listing.message})`);
114
+ io.err(`\nYour store's dev credentials:\n${list}`);
115
+ io.err(`\nRevoke one, then run \`shop-on theme init ${target}${apiFlag(apiUrl)}\` again.`);
116
+ } else io.err(err.message);
123
117
  removeScaffold(dir, existed);
124
118
  return 1;
125
119
  }
126
120
  writeFileSync(path.join(dir, ".env"), dotenv({
127
121
  STOREFRONT_API_URL: created.apiUrl,
128
- STOREFRONT_CLIENT_ID: created.clientId,
129
- STOREFRONT_CLIENT_SECRET: created.clientSecret,
122
+ STOREFRONT_KEY: created.storefrontKey,
130
123
  STORE_SLUG: created.shopHandle,
131
124
  STOREFRONT_CUSTOMER_SESSION_SECRET: randomBytes(32).toString("hex")
132
125
  }), { mode: 384 });
133
126
  io.err(`Wrote .env for the store ${created.shopHandle}`);
134
- const code = await deps.install(dir).catch((err) => {
135
- io.err(err.message);
136
- return 1;
137
- });
138
- if (code !== 0) {
139
- io.err(`Installing dependencies failed (exit ${code}). Run the install in ${dir} yourself.`);
140
- return 1;
127
+ const skipInstall = parsed.values["no-install"];
128
+ if (!skipInstall) {
129
+ const code = await deps.install(dir).catch((err) => {
130
+ io.err(err.message);
131
+ return 1;
132
+ });
133
+ if (code !== 0) {
134
+ io.err(`Installing dependencies failed (exit ${code}). Run the install in ${dir} yourself.`);
135
+ return 1;
136
+ }
141
137
  }
142
138
  const relative = path.relative(cwd, dir) || ".";
143
- io.out(`\nTheme ready. Next:\n cd ${/\s/.test(relative) ? JSON.stringify(relative) : relative}\n shop-on theme dev`);
139
+ const install = packageManagerCommands(processEnv.npm_config_user_agent).install.join(" ");
140
+ io.out([
141
+ "\nTheme ready. Next:",
142
+ ` cd ${/\s/.test(relative) ? JSON.stringify(relative) : relative}`,
143
+ ...skipInstall ? [` ${install}`] : [],
144
+ " shop-on theme dev"
145
+ ].join("\n"));
144
146
  return 0;
145
147
  }
146
- //#endregion
147
148
  export { INIT_USAGE, runInit };
@@ -1,23 +1,23 @@
1
1
  #!/usr/bin/env node
2
- import { MissingEnvError, loadThemeEnv } from "../audit/env.mjs";
3
- import { mintStorefrontToken, storefrontQuery } from "../audit/store.mjs";
4
2
  import { processIo } from "../audit/command.mjs";
3
+ import { MissingEnvError, loadThemeEnv } from "../audit/env.mjs";
4
+ import { storefrontCall, storefrontClient } from "../audit/store.mjs";
5
+ import { MerchantCallError, merchant } from "../auth/api.mjs";
5
6
  import { defaultConfigDir, readSession } from "../auth/credentials.mjs";
6
7
  import { LoginRequiredError, resolveApiUrl } from "../auth/oauth.mjs";
7
- import { graphql } from "../auth/api.mjs";
8
8
  import { rememberedInstall } from "./dev.mjs";
9
9
  import { existsSync, readFileSync } from "node:fs";
10
10
  import path from "node:path";
11
11
  import { parseArgs } from "node:util";
12
12
  import { PRESET_HANDLE_RE } from "@shop-on/theme-contract/preset-listing";
13
+ import { z } from "zod";
13
14
  import { randomBytes } from "node:crypto";
14
15
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
15
16
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
16
17
  import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
17
18
  import { editorToolListings, isEditorToolName } from "@shop-on/theme-contract/editor-tools";
18
19
  import { OpBatchBodySchema, touchedEntries } from "@shop-on/theme-contract/ops";
19
- import { z } from "zod";
20
- //#region src/theme/mcp.ts
20
+ // src/theme/mcp.ts
21
21
  const DEFAULT_DEV_HOST = "http://localhost:4101";
22
22
  const MCP_USAGE = `usage: shop-on theme mcp [--theme <dir>] [--dev-host <url>] [--api <url>]
23
23
 
@@ -36,37 +36,36 @@ const INSTRUCTIONS = [
36
36
  "Find a product or collection handle with search_products or search_collections before putting it into a setting.",
37
37
  "Nothing reaches src/ until save; the author reviews it with git diff."
38
38
  ].join(" ");
39
- const SESSION = `mutation ShopOnEditorSession($input: EditorSessionCreateInput!) {
40
- editorSessionCreate(input: $input) {
41
- token
42
- expiresAt
43
- sid
44
- shopHandle
45
- userErrors { code field message }
46
- }
47
- }`;
48
39
  const REFRESH_MARGIN_MS = 12e4;
49
40
  /**
50
- * The install's editor JWT: minted on first use, refreshed in place (same
51
- * sid, new exp) once it is within two minutes of expiring. A refused refresh
52
- * (the api caps a session at 8 hours) mints a new session.
41
+ * The dev install's editor token (`themes.editor.session`): minted on first
42
+ * use, renewed in place (same sid, new expiry) once it is within two minutes
43
+ * of expiring. A refused renewal (EDITOR_SESSION_INVALID: the api caps a
44
+ * session at 8 hours) opens a new session. The token is a credential: it goes
45
+ * to the dev host in a header and nowhere else.
53
46
  */
54
- function editorSessions(ctx, installId, now = Date.now) {
47
+ function editorSessions(ctx, handle, now = Date.now) {
55
48
  let current;
56
49
  let pending;
57
50
  async function create(priorToken) {
58
- const { editorSessionCreate: s } = await graphql(ctx, SESSION, { input: {
59
- installId,
60
- ...priorToken ? { priorToken } : {}
61
- } });
62
- if (s.token && s.sid && s.shopHandle && s.expiresAt) return {
63
- token: s.token,
64
- sid: s.sid,
65
- shopHandle: s.shopHandle,
66
- expiresAt: Date.parse(s.expiresAt)
67
- };
68
- if (priorToken) return create();
69
- throw new Error(`no editor session for ${installId}: ${s.userErrors.map((e) => e.message).join("; ")}`);
51
+ try {
52
+ const s = await merchant(ctx, (api) => api.themes.editor.session({
53
+ handle,
54
+ ...priorToken && { priorToken }
55
+ }));
56
+ return {
57
+ token: s.token,
58
+ sid: s.sid,
59
+ shopHandle: s.shopHandle,
60
+ expiresAt: Date.parse(s.expiresAt)
61
+ };
62
+ } catch (err) {
63
+ if (!(err instanceof MerchantCallError)) throw err;
64
+ if (err.code === "EDITOR_SESSION_INVALID" && priorToken) return create();
65
+ if (err.code === "NOT_FOUND") throw new Error(`the dev install ${handle} is gone: run \`shop-on theme dev\` again to make a new one.`);
66
+ if (err.code === "PERMISSION_DENIED") throw new Error(`${handle} is not a dev install, and the theme CLI edits only its own: run \`shop-on theme dev\` again.`);
67
+ throw err;
68
+ }
70
69
  }
71
70
  return () => {
72
71
  if (current && current.expiresAt - REFRESH_MARGIN_MS > now()) return Promise.resolve(current);
@@ -148,12 +147,6 @@ function themeMcpTools() {
148
147
  });
149
148
  })];
150
149
  }
151
- const PRODUCTS = `query ShopOnMcpProducts($query: String!, $first: Int!) {
152
- productSearch(query: $query, first: $first) { nodes { handle title } }
153
- }`;
154
- const COLLECTIONS = `query ShopOnMcpCollections($query: String!, $first: Int!) {
155
- collectionSearch(query: $query, first: $first) { nodes { handle title } }
156
- }`;
157
150
  const answer = (result) => ({
158
151
  content: [{
159
152
  type: "text",
@@ -190,7 +183,7 @@ function readJson(file) {
190
183
  function createThemeMcpServer({ api, devHost, installId, themeDir, env, now = Date.now, fetchImpl = fetch }) {
191
184
  const session = editorSessions(api, installId, now);
192
185
  const base = devHost.replace(/\/+$/, "");
193
- let storefront;
186
+ const storefront = storefrontClient(env, (request) => fetchImpl(request));
194
187
  async function devHostCall(method, route, body) {
195
188
  const s = await session();
196
189
  const res = await fetchImpl(`${base}/api/stores/${encodeURIComponent(s.shopHandle)}/${encodeURIComponent(installId)}${route}`, {
@@ -208,10 +201,6 @@ function createThemeMcpServer({ api, devHost, installId, themeDir, env, now = Da
208
201
  body: await res.json().catch(() => null)
209
202
  };
210
203
  }
211
- async function storefrontSearch(query, variables) {
212
- if (!storefront || storefront.expiresAt - 6e4 <= now()) storefront = await mintStorefrontToken(env, fetchImpl);
213
- return storefrontQuery(env, storefront.token, query, variables, fetchImpl);
214
- }
215
204
  const sourceName = (preset, rel) => (readJson(path.join(themeDir, "src", "listings", preset, rel)) ?? readJson(path.join(themeDir, "src", rel)))?.name;
216
205
  /** The entries the draft's op log touched since its last reset, or null
217
206
  * when the log no longer reaches back that far. */
@@ -307,18 +296,24 @@ function createThemeMcpServer({ api, devHost, installId, themeDir, env, now = Da
307
296
  return answer({ url: `${base}${args.path ?? "/"}?preview=${sid}` });
308
297
  }
309
298
  case "search_products": {
310
- const data = await storefrontSearch(PRODUCTS, {
299
+ const { items } = await storefrontCall(env, storefront.search.products({
311
300
  query: args.query,
312
- first: args.first ?? 10
313
- });
314
- return answer({ data: data.productSearch.nodes });
301
+ limit: args.first ?? 10
302
+ }));
303
+ return answer({ data: items.map(({ handle, title }) => ({
304
+ handle,
305
+ title
306
+ })) });
315
307
  }
316
308
  case "search_collections": {
317
- const data = await storefrontSearch(COLLECTIONS, {
309
+ const { items } = await storefrontCall(env, storefront.search.collections({
318
310
  query: args.query,
319
- first: args.first ?? 10
320
- });
321
- return answer({ data: data.collectionSearch?.nodes ?? [] });
311
+ limit: args.first ?? 10
312
+ }));
313
+ return answer({ data: items.map(({ handle, title }) => ({
314
+ handle,
315
+ title
316
+ })) });
322
317
  }
323
318
  }
324
319
  }
@@ -416,5 +411,4 @@ async function runMcp({ argv, cwd = process.cwd(), io = processIo, configDir = d
416
411
  await server.connect(transport);
417
412
  return closed;
418
413
  }
419
- //#endregion
420
414
  export { MCP_USAGE, createThemeMcpServer, editorSessions, runMcp, themeMcpTools };
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import { runThemeBuild } from "./build.mjs";
3
2
  import { processIo } from "../audit/command.mjs";
4
3
  import { noHardLinks } from "./tar.mjs";
4
+ import { runThemeBuild } from "./build.mjs";
5
5
  import { existsSync, readFileSync, readdirSync, renameSync, rmSync, statSync } from "node:fs";
6
6
  import path from "node:path";
7
7
  import { parseArgs } from "node:util";
8
8
  import { create } from "tar";
9
- //#region src/theme/pack.ts
9
+ // src/theme/pack.ts
10
10
  const USAGE = `usage: shop-on theme pack [--theme <dir>] [--out <path>] [--build]
11
11
 
12
12
  --theme <dir> the theme to pack (default: the current directory)
@@ -122,5 +122,4 @@ function isFile(p) {
122
122
  function isDirectory(p) {
123
123
  return existsSync(p) && statSync(p).isDirectory();
124
124
  }
125
- //#endregion
126
125
  export { REQUIRED_FILES, USAGE, isDirectory, isFile, runPack, themeHandle };
@@ -6,7 +6,7 @@ import { readFileSync, readdirSync, renameSync, rmSync, statSync } from "node:fs
6
6
  import path from "node:path";
7
7
  import { parseArgs } from "node:util";
8
8
  import { create } from "tar";
9
- //#region src/theme/source.ts
9
+ // src/theme/source.ts
10
10
  const USAGE = `usage: shop-on theme source [--theme <dir>] [--out <path>]
11
11
 
12
12
  --theme <dir> the theme to pack (default: the current directory)
@@ -170,5 +170,4 @@ async function runSource({ argv, cwd = process.cwd(), io = processIo }) {
170
170
  function mb(n) {
171
171
  return (n / 1024 / 1024).toFixed(1);
172
172
  }
173
- //#endregion
174
173
  export { LIMITS, REQUIRED_FILES, USAGE, pathRefusal, runSource, skipReason };
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- //#region src/theme/tar.ts
2
+ // src/theme/tar.ts
3
3
  /**
4
4
  * A `linkCache` for `tar.create` that never remembers a file. node-tar writes
5
5
  * the second path of a hard-linked pair as a Link entry pointing at the first,
@@ -14,5 +14,4 @@ function noHardLinks() {
14
14
  }
15
15
  }();
16
16
  }
17
- //#endregion
18
17
  export { noHardLinks };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shop-on/theme-cli",
3
- "version": "0.10.0",
3
+ "version": "0.11.1",
4
4
  "description": "The Shop-On theme developer CLI: `shop-on login`, `shop-on theme init`, `shop-on theme dev`, `shop-on theme mcp`, `shop-on theme audit`, `shop-on theme pack` and `shop-on theme source`.",
5
5
  "license": "SEE LICENSE IN dist/LICENSE.md",
6
6
  "bin": {
@@ -12,20 +12,23 @@
12
12
  "type": "module",
13
13
  "dependencies": {
14
14
  "@modelcontextprotocol/sdk": "^1.32.2",
15
- "chrome-launcher": "^1.2.2",
16
- "lighthouse": "^13.5.0",
17
- "tar": "^7.5.22",
18
- "wrangler": "4.151.0",
19
- "zod": "4.6.7",
20
- "@shop-on/theme-dev-host": "0.10.0",
21
- "@shop-on/theme-contract": "0.10.0",
22
- "@shop-on/create-theme": "0.10.0"
15
+ "@orpc/client": "1.16.2",
16
+ "@shop-on/create-theme": "0.11.1",
17
+ "@shop-on/theme-contract": "0.11.1",
18
+ "@shop-on/theme-dev-host": "0.11.1",
19
+ "chrome-launcher": "^1.2.3",
20
+ "lighthouse": "^13.6.0",
21
+ "tar": "^7.5.23",
22
+ "wrangler": "4.162.0",
23
+ "zod": "4.6.7"
23
24
  },
24
25
  "devDependencies": {
25
- "@types/node": "26.6.5",
26
+ "@shop-on/api-contract": "0.0.0",
27
+ "@shop-on/contract-kit": "0.0.0",
28
+ "@types/node": "26.6.6",
26
29
  "tsx": "^4.23.15",
27
30
  "typescript": "7.0.2",
28
- "vitest": "5.0.5"
31
+ "vitest": "5.1.0"
29
32
  },
30
33
  "engines": {
31
34
  "node": "^20.19.0 || >=22.12.0"