@tanqory/partner-cli 0.0.0-stage → 0.1.0-alpha.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 (53) hide show
  1. package/LICENSE +21 -0
  2. package/bin/tanqory-partner.mjs +10 -0
  3. package/config/mirror-allowlist.json +17 -0
  4. package/config/theme-licences.json +108 -0
  5. package/config/third-party-toolchains.json +45 -0
  6. package/lib/api.mjs +109 -0
  7. package/lib/auth.mjs +211 -0
  8. package/lib/check.mjs +63 -0
  9. package/lib/cli.mjs +217 -0
  10. package/lib/mcp.mjs +177 -0
  11. package/lib/ops.mjs +179 -0
  12. package/lib/theme.mjs +121 -0
  13. package/lib/vendor/partner-checks.cjs +1617 -0
  14. package/package.json +59 -4
  15. package/starter/LICENSE +18 -0
  16. package/starter/README.md +38 -0
  17. package/starter/config/settings.json +3 -0
  18. package/starter/gitignore +3 -0
  19. package/starter/locales/en.json +22 -0
  20. package/starter/locales/th.json +22 -0
  21. package/starter/package.json +29 -0
  22. package/starter/regions/footer.json +35 -0
  23. package/starter/regions/header.json +13 -0
  24. package/starter/scripts/build.mjs +195 -0
  25. package/starter/scripts/probe.ts +4 -0
  26. package/starter/src/bundle.ts +15 -0
  27. package/starter/src/components/parts.tsx +32 -0
  28. package/starter/src/entry.client.tsx +6 -0
  29. package/starter/src/entry.server.tsx +13 -0
  30. package/starter/src/sections/chrome.tsx +132 -0
  31. package/starter/src/sections/commerce.tsx +242 -0
  32. package/starter/src/sections/content.tsx +111 -0
  33. package/starter/src/sections/editorial.tsx +107 -0
  34. package/starter/src/settings.ts +15 -0
  35. package/starter/src/styles/theme.css +224 -0
  36. package/starter/src/templates.ts +14 -0
  37. package/starter/src/theme.tsx +76 -0
  38. package/starter/templates/404.json +14 -0
  39. package/starter/templates/account.json +14 -0
  40. package/starter/templates/article.json +14 -0
  41. package/starter/templates/blog.json +14 -0
  42. package/starter/templates/cart.json +14 -0
  43. package/starter/templates/collection.json +14 -0
  44. package/starter/templates/index.json +36 -0
  45. package/starter/templates/page.contact.json +18 -0
  46. package/starter/templates/page.json +14 -0
  47. package/starter/templates/product.json +18 -0
  48. package/starter/templates/search.json +14 -0
  49. package/starter/tsconfig.json +17 -0
  50. package/starter/vite.client.config.ts +17 -0
  51. package/starter/vite.probe.config.ts +16 -0
  52. package/starter/vite.server.config.ts +32 -0
  53. package/README.md +0 -3
package/lib/cli.mjs ADDED
@@ -0,0 +1,217 @@
1
+ // tanqory-partner: the command line of the partner toolkit. `<topic> <command>`, as the reference platform's CLI.
2
+ import { watch } from 'node:fs'
3
+ import { resolve } from 'node:path'
4
+ import { parseArgs } from 'node:util'
5
+ import { AuthError, login, logout, rememberOrg, apiBase, signedIn } from './auth.mjs'
6
+ import { ApiError, organizations } from './api.mjs'
7
+ import { formatLines, runConformance, SANDBOX_LINES } from './check.mjs'
8
+ import { ThemeError } from './theme.mjs'
9
+ import * as ops from './ops.mjs'
10
+
11
+ const HELP = `tanqory-partner: build, check and upload Tanqory partner themes.
12
+
13
+ tanqory-partner login [--api <url>] [--no-browser] sign in (a code to allow in the browser)
14
+ tanqory-partner logout
15
+ tanqory-partner orgs [--use <id>] your partner organizations; --use sets the default
16
+
17
+ tanqory-partner theme init <folder> [--author <name>] a new theme from the starter
18
+ tanqory-partner theme check [--dir <d>] [--json] [--conformance]
19
+ build, then the partner checks that need no sandbox
20
+ tanqory-partner theme dev [--dir <d>] rebuild and check on every change
21
+ tanqory-partner theme package [--dir <d>] [--out <d>] the .tgz to upload and its manifest.json
22
+ tanqory-partner theme push [--dir <d>] [--theme <handle|id>] [--name <n>] [--version X.Y.Z] [--notes <t>]
23
+ [--store <id> [--wait]] [--skip-check]
24
+ upload a new version (and install it on a development store)
25
+ tanqory-partner theme install <versionId> [--store <id>] [--wait]
26
+ tanqory-partner theme status <versionId> [--wait] [--json]
27
+ tanqory-partner theme list the organization's themes
28
+ tanqory-partner theme stores the organization's development stores
29
+
30
+ tanqory-partner mcp the MCP server (stdio) with the same operations
31
+
32
+ Options for every command that calls Tanqory: --api <url> (or TANQORY_API_URL: https://api.<root>, <root> being the platform domain you use), --org <id>.
33
+ `
34
+
35
+ const OPTIONS = {
36
+ api: { type: 'string' }, org: { type: 'string' }, dir: { type: 'string' }, out: { type: 'string' }, theme: { type: 'string' },
37
+ name: { type: 'string' }, version: { type: 'string' }, notes: { type: 'string' }, store: { type: 'string' }, author: { type: 'string' },
38
+ use: { type: 'string' }, json: { type: 'boolean' }, wait: { type: 'boolean' }, conformance: { type: 'boolean' },
39
+ 'skip-check': { type: 'boolean' }, 'no-browser': { type: 'boolean' }, help: { type: 'boolean', short: 'h' },
40
+ }
41
+
42
+ const out = (s) => process.stdout.write(`${s}\n`)
43
+ const err = (s) => process.stderr.write(`${s}\n`)
44
+
45
+ async function themeCommand(cmd, args, o) {
46
+ const common = { api: o.api, org: o.org }
47
+ switch (cmd) {
48
+ case 'init': {
49
+ if (!args[0]) throw new ThemeError('Name the new folder: tanqory-partner theme init <folder>')
50
+ const r = ops.initTheme(args[0], { author: o.author })
51
+ out(`Made ${r.dir} (${r.files} files, theme handle ${r.handle}).`)
52
+ out(`Next:\n cd ${args[0]}\n npm install\n tanqory-partner theme check`)
53
+ out('Put your name in LICENSE (or pass --author next time).')
54
+ return 0
55
+ }
56
+ case 'check': {
57
+ const dir = resolve(o.dir ?? '.')
58
+ const r = await ops.check(dir, { quiet: !!o.json })
59
+ if (o.json) out(JSON.stringify(r, null, 2))
60
+ else {
61
+ out(formatLines(r.lines))
62
+ out(`\nThese run when a version is installed on a development store (theme push --store, or theme install):`)
63
+ for (const [k, what] of SANDBOX_LINES) out(` sandbox ${k}: ${what}`)
64
+ }
65
+ let ok = r.ok
66
+ if (o.conformance) {
67
+ const c = runConformance(dir, r.out)
68
+ if (!c) err('ABI conformance: @tanqory/theme-conformance is not installed in this theme (npm install --save-dev @tanqory/theme-conformance@alpha). It runs in the sandbox anyway.')
69
+ else ok = ok && c.ok
70
+ }
71
+ if (!o.json) out(ok ? '\nAll checks that run here passed.' : '\nSome checks failed: fix each line above, then run the check again.')
72
+ return ok ? 0 : 1
73
+ }
74
+ case 'dev': {
75
+ const dir = resolve(o.dir ?? '.')
76
+ out('The theme kit has no local preview server: this rebuilds and checks on every change. See the theme on a development store with theme push --store <id> (each push is a new version), then theme status for its preview link.')
77
+ let timer = null
78
+ let running = false
79
+ const run = async () => {
80
+ if (running) return
81
+ running = true
82
+ try {
83
+ const r = await ops.check(dir, { quiet: true })
84
+ out(`\n[${new Date().toLocaleTimeString()}] ${r.ok ? 'all local checks passed' : 'checks failed'}`)
85
+ if (!r.ok) out(formatLines(r.lines.filter((l) => l.status !== 'passed')))
86
+ } catch (e) {
87
+ out(`\n[${new Date().toLocaleTimeString()}] ${e.message}`)
88
+ } finally {
89
+ running = false
90
+ }
91
+ }
92
+ await run()
93
+ watch(dir, { recursive: true }, (_ev, file) => {
94
+ if (!file || /^(node_modules|dist|\.git)([/\\]|$)/.test(String(file))) return
95
+ clearTimeout(timer)
96
+ timer = setTimeout(run, 400)
97
+ })
98
+ return new Promise(() => {})
99
+ }
100
+ case 'package': {
101
+ const r = await ops.pkg(o.dir, { outDir: o.out })
102
+ out(`${r.tgz}: ${r.files.length} files, ${r.bytes} bytes (no lockfile, no node_modules, no dist)`)
103
+ out(`${r.manifest}: the manifest to send beside it (the partner dashboard's manifest.json field)`)
104
+ return 0
105
+ }
106
+ case 'push': {
107
+ const r = await ops.push(o.dir, { ...common, theme: o.theme, name: o.name, version: o.version, notes: o.notes, skipCheck: o['skip-check'], storeId: o.store, log: err })
108
+ out(`Version ${r.version.version} uploaded: ${r.version.id} (${r.version.status}) of theme ${r.theme.handle} in organization ${r.org}.`)
109
+ if (r.install) out(`Installing on development store ${r.install.storeId}: ${r.install.status}.`)
110
+ if (r.install && o.wait) return waitAndShow(r.version.id, common)
111
+ out(ops.formatVersion(r.version))
112
+ out(r.install ? `Follow it with: tanqory-partner theme status ${r.version.id} --wait` : `Install it on a development store: tanqory-partner theme install ${r.version.id} --store <id>`)
113
+ return 0
114
+ }
115
+ case 'install': {
116
+ if (!args[0]) throw new ThemeError('Name the version: tanqory-partner theme install <versionId> --store <id>')
117
+ const r = await ops.install(args[0], o.store, common)
118
+ out(`Installing version ${args[0]} on development store ${r.storeId}: ${r.install.status}.`)
119
+ if (o.wait) return waitAndShow(args[0], common)
120
+ out(`Follow it with: tanqory-partner theme status ${args[0]} --wait`)
121
+ return 0
122
+ }
123
+ case 'status': {
124
+ if (!args[0]) throw new ThemeError('Name the version: tanqory-partner theme status <versionId>')
125
+ if (o.wait) return waitAndShow(args[0], common, o.json)
126
+ const r = await ops.status(args[0], common)
127
+ out(o.json ? JSON.stringify(r.version, null, 2) : ops.formatVersion(r.version))
128
+ return r.version.checks.some((c) => c.status === 'failed') ? 1 : 0
129
+ }
130
+ case 'list': {
131
+ const r = await ops.listThemes(common)
132
+ for (const t of r.themes) out(`${t.id} ${t.handle.padEnd(28)} ${t.status.padEnd(9)} ${t.latestVersion ? `${t.latestVersion.version} ${t.latestVersion.status}` : '(no version)'} ${t.name}`)
133
+ if (!r.themes.length) out('No themes yet: tanqory-partner theme push makes one.')
134
+ return 0
135
+ }
136
+ case 'stores': {
137
+ const r = await ops.listStores(common)
138
+ for (const s of r.stores) out(`${s.id} ${s.name} (${s.subdomain}) ${s.status}`)
139
+ if (!r.stores.length) out('No development stores: create one on the partner dashboard, Stores.')
140
+ return 0
141
+ }
142
+ default:
143
+ err(HELP)
144
+ return 2
145
+ }
146
+ }
147
+
148
+ async function waitAndShow(versionId, common, json = false) {
149
+ let last = ''
150
+ const r = await ops.waitFor(versionId, {
151
+ ...common,
152
+ onRead: (v) => {
153
+ const line = `${v.status}; ${v.checks.filter((c) => c.status === 'passed').length} of ${v.checks.length} passed; ${v.developmentInstalls.map((i) => i.status).join(', ') || 'not installed'}`
154
+ if (line !== last && !json) err(`[${new Date().toLocaleTimeString()}] ${line}`)
155
+ last = line
156
+ },
157
+ })
158
+ out(json ? JSON.stringify(r.version, null, 2) : ops.formatVersion(r.version))
159
+ if (r.timedOut) err('Still running after 15 minutes: read it again later with tanqory-partner theme status.')
160
+ return r.version.checks.some((c) => c.status === 'failed') || r.version.developmentInstalls.some((i) => i.status === 'FAILED') ? 1 : 0
161
+ }
162
+
163
+ export async function main(argv) {
164
+ let parsed
165
+ try {
166
+ parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true, strict: true })
167
+ } catch (e) {
168
+ err(`${e.message}\n\n${HELP}`)
169
+ return 2
170
+ }
171
+ const { values: o, positionals: [topic, ...rest] } = parsed
172
+ if (o.help || !topic) {
173
+ out(HELP)
174
+ return 0
175
+ }
176
+ try {
177
+ switch (topic) {
178
+ case 'login': {
179
+ const r = await login({ api: o.api, browser: !o['no-browser'] })
180
+ out(`Signed in to ${r.api}.`)
181
+ return 0
182
+ }
183
+ case 'logout':
184
+ out(`Signed out of ${await logout(o.api)}.`)
185
+ return 0
186
+ case 'orgs': {
187
+ const base = apiBase(o.api)
188
+ if (!signedIn(o.api)) throw new AuthError(`Not signed in to ${base}. Run: tanqory-partner login --api ${base}`)
189
+ const list = await organizations(base)
190
+ if (o.use) {
191
+ if (!list.some((x) => x.id === o.use)) throw new ThemeError(`${o.use} is not one of your organizations.`)
192
+ rememberOrg(base, o.use)
193
+ out(`Commands now use organization ${o.use} by default.`)
194
+ }
195
+ for (const x of list) out(`${x.id} ${x.name}`)
196
+ return 0
197
+ }
198
+ case 'theme':
199
+ return await themeCommand(rest[0], rest.slice(1), o)
200
+ case 'mcp': {
201
+ const { serve } = await import('./mcp.mjs')
202
+ await serve({ api: o.api, org: o.org })
203
+ return 0
204
+ }
205
+ default:
206
+ err(HELP)
207
+ return 2
208
+ }
209
+ } catch (e) {
210
+ if (e instanceof ThemeError || e instanceof AuthError || e instanceof ApiError) {
211
+ err(e.message)
212
+ if (e.lines) err(formatLines(e.lines))
213
+ return 1
214
+ }
215
+ throw e
216
+ }
217
+ }
package/lib/mcp.mjs ADDED
@@ -0,0 +1,177 @@
1
+ // The partner theme MCP server (stdio): the CLI's operations as MCP tools, for an AI client on the partner's machine.
2
+ // Transport: MCP stdio, one JSON-RPC 2.0 message per line on stdin and stdout, logs on stderr (specification
3
+ // 2025-06-18, "Transports"). Credential: the partner member's own sign-in (`partner_login` or `tanqory-partner login`,
4
+ // RFC 8628), never a token passed in by the client. No tool calls a model (.claude/rules/ai-standards.md: nothing to meter).
5
+ // Writes to the partner account (push, install) take two calls: the first changes nothing and returns what will happen
6
+ // with a confirmationToken bound to the exact arguments; the client shows it, and only after the person approves calls
7
+ // again with the token (MCP 2025-06-18 Tools: "there SHOULD always be a human in the loop").
8
+ import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto'
9
+ import { readFileSync } from 'node:fs'
10
+ import { createInterface } from 'node:readline'
11
+ import { resolve } from 'node:path'
12
+ import { login, signedIn, apiBase } from './auth.mjs'
13
+ import { SANDBOX_LINES } from './check.mjs'
14
+ import * as ops from './ops.mjs'
15
+ import { readPackage } from './theme.mjs'
16
+
17
+ const PROTOCOL = '2025-06-18'
18
+ const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version
19
+ const KEY = randomBytes(32)
20
+ const CONFIRM_MS = 10 * 60_000
21
+
22
+ export const INSTRUCTIONS = [
23
+ 'Build Tanqory partner themes (code themes sold in the Tanqory Theme Store). Start with partner_theme_init, edit src/, run partner_theme_check until every line passes, then partner_theme_push.',
24
+ 'partner_theme_push and partner_theme_install change the partner account and take two calls: the first changes nothing and returns what will happen and a confirmationToken; show it to the person, and only after they approve call again with the same arguments and the token.',
25
+ 'Tools that call Tanqory need a sign-in once: partner_login returns a code and a link; the person opens the link and allows access, then the tools work. After an install, read partner_theme_status until the install is INSTALLED or FAILED and no check is pending; it gives the preview link.',
26
+ ].join(' ')
27
+
28
+ const dir = { type: 'string', description: 'The theme folder on this machine (the one with package.json), relative to the working directory.' }
29
+ const org = { type: 'string', description: 'The partner organization id. Leave out when the person is in one organization, or a default was set with tanqory-partner orgs --use.' }
30
+ const confirm = { type: 'string', description: 'Leave out on the first call: it changes nothing and returns the change with a confirmationToken. After the person approves that change, call again with the same arguments and this token.' }
31
+ const ann = (readOnly, extra = {}) => ({ readOnlyHint: readOnly, destructiveHint: false, idempotentHint: readOnly, openWorldHint: !readOnly, ...extra })
32
+ const tool = (name, title, description, properties, required, annotations) => ({ name, title, description, inputSchema: { type: 'object', additionalProperties: false, properties, ...(required ? { required } : {}) }, annotations: { title, ...annotations } })
33
+
34
+ export function toolList() {
35
+ return [
36
+ tool('partner_login', 'Sign in to Tanqory Partners', 'Starts a sign-in: gives a short code and a link. The person opens the link, checks the code and allows access.', { api: { type: 'string', description: 'The Tanqory API address, https://api.<root>. Leave out to use the last one.' } }, null, ann(false, { openWorldHint: true })),
37
+ tool('partner_theme_init', 'Start a partner theme', 'Makes a new theme folder from the partner starter, which passes every partner check as it is.', { dir: { ...dir, description: 'The new folder (must not exist or be empty).' }, author: { type: 'string', description: 'The name for LICENSE.' } }, ['dir'], ann(false, { openWorldHint: false })),
38
+ tool('partner_theme_check', 'Check a partner theme', 'Builds the theme and runs the partner checks that need no sandbox, the same code the platform runs on an upload. Changes nothing.', { dir }, ['dir'], ann(true, { openWorldHint: false })),
39
+ tool('partner_theme_package', 'Package a partner theme', 'Builds the theme and writes the .tgz to upload and its manifest.json into dist/partner.', { dir }, ['dir'], ann(false, { openWorldHint: false, idempotentHint: true })),
40
+ tool('partner_theme_push', 'Upload a theme version', 'Checks, packages and uploads the theme as a new version to the partner organization, and can install it on a development store. You approve it first.', {
41
+ dir, org,
42
+ theme: { type: 'string', description: 'The theme id or handle; leave out to use package.json "name" as the handle (made when it does not exist).' },
43
+ name: { type: 'string', description: 'The theme name, when a new theme is made.' },
44
+ version: { type: 'string', description: 'X.Y.Z, greater than every published version; default package.json "version".' },
45
+ notes: { type: 'string', description: 'Release notes.' },
46
+ storeId: { type: 'string', description: 'A development store of the organization to install the new version on (partner_development_stores).' },
47
+ confirmationToken: confirm,
48
+ }, ['dir'], ann(false)),
49
+ tool('partner_theme_install', 'Install a version on a development store', "Builds the version in Tanqory's sandbox, runs every check and installs it as the store's developer draft, never live. You approve it first.", { versionId: { type: 'string' }, storeId: { type: 'string', description: 'Leave out when the organization has one development store.' }, org, confirmationToken: confirm }, ['versionId'], ann(false)),
50
+ tool('partner_theme_status', 'Read a version and its checks', 'Shows a version, each of its 14 check lines and its development installs with the preview link. Each read moves the install and the checks on.', { versionId: { type: 'string' }, org }, ['versionId'], ann(true)),
51
+ tool('partner_theme_list', 'List partner themes', "Lists the organization's themes and each one's latest version.", { org }, null, ann(true)),
52
+ tool('partner_development_stores', 'List development stores', "Lists the organization's development stores, to install a version on.", { org }, null, ann(true)),
53
+ ]
54
+ }
55
+
56
+ const sign = (name, args) => createHmac('sha256', KEY).update(JSON.stringify([name, Object.entries(args).filter(([k]) => k !== 'confirmationToken').sort()])).digest('base64url')
57
+ function confirmation(name, args) {
58
+ const exp = Date.now() + CONFIRM_MS
59
+ return `${exp}.${createHmac('sha256', KEY).update(`${exp}.${sign(name, args)}`).digest('base64url')}`
60
+ }
61
+ function confirmed(name, args) {
62
+ const [exp, mac] = String(args.confirmationToken ?? '').split('.')
63
+ if (!exp || !mac || Number(exp) < Date.now()) return false
64
+ const want = Buffer.from(createHmac('sha256', KEY).update(`${exp}.${sign(name, args)}`).digest('base64url'))
65
+ const got = Buffer.from(mac)
66
+ return want.length === got.length && timingSafeEqual(want, got)
67
+ }
68
+
69
+ const text = (value, isError = false) => ({ content: [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }], ...(isError ? { isError: true } : {}) })
70
+
71
+ let pendingLogin = null
72
+ function needSignIn(api) {
73
+ if (signedIn(api)) return null
74
+ return text(pendingLogin ? `Not signed in yet: the person must open ${pendingLogin.verificationUriComplete} and allow access (code ${pendingLogin.userCode}).` : 'Not signed in to Tanqory. Call partner_login first.', true)
75
+ }
76
+
77
+ export async function callTool(name, args = {}, defaults = {}) {
78
+ const common = { api: args.api ?? defaults.api, org: args.org ?? defaults.org }
79
+ switch (name) {
80
+ case 'partner_login': {
81
+ const code = await new Promise((res, rej) => {
82
+ const p = login({ api: common.api, browser: false, say: () => {}, onCode: (c) => res(c) })
83
+ p.then(() => { pendingLogin = null }, (e) => { pendingLogin = null; rej(e) })
84
+ })
85
+ pendingLogin = code
86
+ return text({ signIn: 'started', open: code.verificationUriComplete, orEnterAt: code.verificationUri, code: code.userCode, expiresInSeconds: code.expiresIn, next: 'Ask the person to open the link, check that the code matches, and choose Allow Access. Then call the tool you need.' })
87
+ }
88
+ case 'partner_theme_init':
89
+ return text(ops.initTheme(args.dir, { author: args.author }))
90
+ case 'partner_theme_check': {
91
+ const r = await ops.check(args.dir, { quiet: true })
92
+ return text({ ok: r.ok, lines: r.lines, runInTheSandbox: SANDBOX_LINES.map(([key, checks]) => ({ key, checks })) }, !r.ok)
93
+ }
94
+ case 'partner_theme_package': {
95
+ const r = await ops.pkg(args.dir, { quiet: true })
96
+ return text({ tgz: r.tgz, manifest: r.manifest, files: r.files.length, bytes: r.bytes })
97
+ }
98
+ case 'partner_theme_push': {
99
+ const blocked = needSignIn(common.api)
100
+ if (blocked) return blocked
101
+ if (!confirmed(name, args)) {
102
+ const p = readPackage(resolve(args.dir))
103
+ return text({ confirmationRequired: true, change: `Upload ${args.dir} as version ${args.version ?? p.version} of theme ${args.theme ?? ops.handleOf(p.name)} to ${apiBase(common.api)}${common.org ? `, organization ${common.org}` : ''}${args.storeId ? `, then install it on development store ${args.storeId}` : ''}.`, confirmationToken: confirmation(name, args) })
104
+ }
105
+ const r = await ops.push(args.dir, { ...common, theme: args.theme, name: args.name, version: args.version, notes: args.notes, storeId: args.storeId })
106
+ return text({ organization: r.org, theme: r.theme, themeCreated: r.themeCreated, version: r.version, install: r.install })
107
+ }
108
+ case 'partner_theme_install': {
109
+ const blocked = needSignIn(common.api)
110
+ if (blocked) return blocked
111
+ if (!confirmed(name, args)) return text({ confirmationRequired: true, change: `Build version ${args.versionId} in the sandbox and install it as the developer draft of development store ${args.storeId ?? '(the only one)'} (never live).`, confirmationToken: confirmation(name, args) })
112
+ const r = await ops.install(args.versionId, args.storeId, common)
113
+ return text({ storeId: r.storeId, install: r.install })
114
+ }
115
+ case 'partner_theme_status': {
116
+ const blocked = needSignIn(common.api)
117
+ if (blocked) return blocked
118
+ const r = await ops.status(args.versionId, common)
119
+ return text({ version: r.version, settled: ops.settled(r.version) })
120
+ }
121
+ case 'partner_theme_list': {
122
+ const blocked = needSignIn(common.api)
123
+ if (blocked) return blocked
124
+ return text((await ops.listThemes(common)).themes)
125
+ }
126
+ case 'partner_development_stores': {
127
+ const blocked = needSignIn(common.api)
128
+ if (blocked) return blocked
129
+ return text((await ops.listStores(common)).stores)
130
+ }
131
+ default:
132
+ return null
133
+ }
134
+ }
135
+
136
+ /** One JSON-RPC message → the answer (or null for a notification). */
137
+ export async function handle(msg, defaults = {}) {
138
+ const reply = (result) => ({ jsonrpc: '2.0', id: msg.id, result })
139
+ const fail = (code, message) => ({ jsonrpc: '2.0', id: msg.id ?? null, error: { code, message } })
140
+ if (msg.id === undefined) return null
141
+ switch (msg.method) {
142
+ case 'initialize':
143
+ return reply({ protocolVersion: PROTOCOL, capabilities: { tools: {} }, serverInfo: { name: 'tanqory-partner', title: 'Tanqory Partner Themes', version: VERSION }, instructions: INSTRUCTIONS })
144
+ case 'ping':
145
+ return reply({})
146
+ case 'tools/list':
147
+ return reply({ tools: toolList() })
148
+ case 'tools/call': {
149
+ const { name, arguments: args } = msg.params ?? {}
150
+ if (!toolList().some((t) => t.name === name)) return fail(-32602, `Unknown tool: ${name}`)
151
+ try {
152
+ return reply(await callTool(name, args ?? {}, defaults))
153
+ } catch (e) {
154
+ return reply(text(`${e.message}${e.lines ? `\n${JSON.stringify(e.lines, null, 2)}` : ''}`, true))
155
+ }
156
+ }
157
+ default:
158
+ return fail(-32601, `Method not found: ${msg.method}`)
159
+ }
160
+ }
161
+
162
+ export function serve(defaults = {}) {
163
+ const rl = createInterface({ input: process.stdin })
164
+ rl.on('line', async (line) => {
165
+ if (!line.trim()) return
166
+ let msg
167
+ try {
168
+ msg = JSON.parse(line)
169
+ } catch {
170
+ process.stdout.write(`${JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } })}\n`)
171
+ return
172
+ }
173
+ const answer = await handle(msg, defaults)
174
+ if (answer) process.stdout.write(`${JSON.stringify(answer)}\n`)
175
+ })
176
+ return new Promise((res) => rl.on('close', res))
177
+ }
package/lib/ops.mjs ADDED
@@ -0,0 +1,179 @@
1
+ // The operations behind both the CLI and the MCP tools: one implementation, two front ends.
2
+ import { existsSync, readFileSync, readdirSync, statSync, writeFileSync, mkdirSync, copyFileSync } from 'node:fs'
3
+ import { basename, dirname, join, resolve } from 'node:path'
4
+ import { fileURLToPath } from 'node:url'
5
+ import * as api from './api.mjs'
6
+ import { apiBase, defaultOrg, rememberOrg } from './auth.mjs'
7
+ import { checkTheme } from './check.mjs'
8
+ import { packSource, packageTheme, readPackage, ThemeError } from './theme.mjs'
9
+
10
+ const STARTER = join(dirname(fileURLToPath(import.meta.url)), '..', 'starter')
11
+ const HANDLE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
12
+ const SEMVER = /^\d+\.\d+\.\d+$/
13
+
14
+ export const handleOf = (name) => String(name).replace(/^@[^/]+\//, '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60)
15
+ const titleOf = (handle) => handle.split('-').filter(Boolean).map((w) => w[0].toUpperCase() + w.slice(1)).join(' ')
16
+
17
+ /** `theme init`: the starter into `dir` (which must not exist or be empty), named after the folder. */
18
+ export function initTheme(dir, { author } = {}) {
19
+ const target = resolve(dir)
20
+ if (existsSync(target) && readdirSync(target).length) throw new ThemeError(`${target} is not empty. Choose a new folder name.`)
21
+ if (!existsSync(STARTER)) throw new ThemeError('This copy of @tanqory/partner-cli has no starter (starter/). Reinstall it from npm.')
22
+ const handle = handleOf(basename(target))
23
+ if (!HANDLE.test(handle)) throw new ThemeError(`${basename(target)} does not make a theme handle. Use letters, digits and dashes, for example my-theme.`)
24
+ if (handle.startsWith('tanqory')) throw new ThemeError('Theme handles starting with "tanqory" are reserved. Choose another folder name.')
25
+ const files = []
26
+ const walk = (rel) => {
27
+ for (const name of readdirSync(join(STARTER, rel)).sort()) {
28
+ const p = rel ? `${rel}/${name}` : name
29
+ if (statSync(join(STARTER, p)).isDirectory()) walk(p)
30
+ else files.push(p)
31
+ }
32
+ }
33
+ walk('')
34
+ for (const f of files) {
35
+ const to = join(target, f === 'gitignore' ? '.gitignore' : f)
36
+ mkdirSync(dirname(to), { recursive: true })
37
+ copyFileSync(join(STARTER, f), to)
38
+ }
39
+ const pkgPath = join(target, 'package.json')
40
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'))
41
+ pkg.name = handle
42
+ pkg.version = '1.0.0'
43
+ writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}\n`)
44
+ const holder = author ?? 'the author of this theme'
45
+ const lic = join(target, 'LICENSE')
46
+ writeFileSync(lic, readFileSync(lic, 'utf8').replace(/^Copyright \(c\) \d{4} the author of this theme$/m, `Copyright (c) ${new Date().getUTCFullYear()} ${holder}`))
47
+ return { dir: target, handle, files: files.length }
48
+ }
49
+
50
+ export async function check(dir, opts) {
51
+ return checkTheme(resolve(dir ?? '.'), opts)
52
+ }
53
+
54
+ export async function pkg(dir, opts) {
55
+ return packageTheme(resolve(dir ?? '.'), opts)
56
+ }
57
+
58
+ /** The organization: --org, else the one remembered, else the only one the member has. */
59
+ export async function resolveOrg(apiFlag, org) {
60
+ const base = apiBase(apiFlag)
61
+ if (org) return { api: base, org }
62
+ const remembered = defaultOrg(base)
63
+ if (remembered) return { api: base, org: remembered }
64
+ const orgs = await api.organizations(base)
65
+ if (orgs.length === 1) {
66
+ rememberOrg(base, orgs[0].id)
67
+ return { api: base, org: orgs[0].id }
68
+ }
69
+ if (!orgs.length) throw new ThemeError('Your account is in no partner organization. Create one on the partner dashboard first.')
70
+ throw new ThemeError(`You are in ${orgs.length} organizations. Pick one with --org <id> (or tanqory-partner orgs --use <id>):\n${orgs.map((o) => ` ${o.id} ${o.name}`).join('\n')}`)
71
+ }
72
+
73
+ /** The theme to push to: --theme (id or handle), else package.json's name as the handle; made when it does not exist. */
74
+ async function resolveTheme(base, org, { theme, name, handle }) {
75
+ const all = await api.themes(base, org)
76
+ if (theme) {
77
+ const t = all.find((x) => x.id === theme || x.handle === theme)
78
+ if (t) return { theme: t, created: false }
79
+ if (!HANDLE.test(theme)) throw new ThemeError(`No theme ${theme} in this organization. Give a theme id or handle (tanqory-partner theme list), or a new handle (lowercase letters, digits and dashes) to create one.`)
80
+ handle = theme
81
+ }
82
+ const t = all.find((x) => x.handle === handle)
83
+ if (t) return { theme: t, created: false }
84
+ return { theme: await api.createTheme(base, org, { name: name ?? titleOf(handle), handle }), created: true }
85
+ }
86
+
87
+ /**
88
+ * `theme push`: check (unless skipped), package, then a new version of the theme through the Partner API. With
89
+ * `storeId`, also installs it on that development store.
90
+ */
91
+ export async function push(dir, { api: apiFlag, org, theme, name, version, notes, skipCheck = false, storeId, log = () => {} } = {}) {
92
+ const root = resolve(dir ?? '.')
93
+ const p = readPackage(root)
94
+ const v = version ?? p.version
95
+ if (!SEMVER.test(String(v))) throw new ThemeError(`Version ${v} is not X.Y.Z. Set "version" in package.json or pass --version.`)
96
+ let checked = null
97
+ if (!skipCheck) {
98
+ log('Checking the theme (build, then the partner checks that need no sandbox)...')
99
+ checked = await checkTheme(root, { quiet: true })
100
+ if (!checked.ok) {
101
+ const err = new ThemeError(`The theme fails ${checked.lines.filter((l) => l.status !== 'passed').map((l) => l.key).join(', ')}. Fix these first (tanqory-partner theme check shows each one).`)
102
+ err.lines = checked.lines
103
+ throw err
104
+ }
105
+ }
106
+ const out = checked?.out ?? join(root, p.tanqory?.out ?? 'dist/abi')
107
+ const manifestPath = join(out, 'manifest.json')
108
+ if (!existsSync(manifestPath)) throw new ThemeError('dist/abi/manifest.json is missing. Run tanqory-partner theme check (it builds the theme) first.')
109
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'))
110
+ const { bytes } = await packSource(root)
111
+ const where = await resolveOrg(apiFlag, org)
112
+ const { theme: t, created } = await resolveTheme(where.api, where.org, { theme, name, handle: handleOf(p.name ?? basename(root)) })
113
+ log(`${created ? 'Created' : 'Using'} theme ${t.name} (${t.handle}, ${t.id}); uploading ${bytes.length} bytes as version ${v}...`)
114
+ const created_ = await api.createVersion(where.api, where.org, t.id, { version: String(v), releaseNotes: notes ?? `Version ${v}`, manifest, tgz: bytes, filename: `${t.handle}-${v}.tgz` })
115
+ let installed = null
116
+ if (storeId) installed = await api.install(where.api, where.org, created_.id, storeId)
117
+ return { ...where, theme: t, themeCreated: created, version: created_, install: installed }
118
+ }
119
+
120
+ export async function status(versionId, { api: apiFlag, org } = {}) {
121
+ const where = await resolveOrg(apiFlag, org)
122
+ return { ...where, version: await api.version(where.api, where.org, versionId) }
123
+ }
124
+
125
+ export async function install(versionId, storeId, { api: apiFlag, org } = {}) {
126
+ const where = await resolveOrg(apiFlag, org)
127
+ if (!storeId) {
128
+ const stores = (await api.developmentStores(where.api, where.org)).filter((s) => s.status !== 'CLOSED')
129
+ if (stores.length !== 1) throw new ThemeError(`Pick a development store with --store <id>:\n${stores.map((s) => ` ${s.id} ${s.name} (${s.subdomain})`).join('\n') || ' (none: create one on the partner dashboard, Stores)'}`)
130
+ storeId = stores[0].id
131
+ }
132
+ return { ...where, storeId, install: await api.install(where.api, where.org, versionId, storeId) }
133
+ }
134
+
135
+ const TERMINAL_INSTALL = new Set(['INSTALLED', 'FAILED'])
136
+ /**
137
+ * Settled: no install still moving, no check line pending, and once a build installed no line still waiting for the
138
+ * sandbox (the extended checks run after the install, PARTNER_THEMES §5.2 "Built 2026-11-14").
139
+ */
140
+ export const settled = (v) =>
141
+ v.developmentInstalls.every((i) => TERMINAL_INSTALL.has(i.status)) &&
142
+ !v.checks.some((c) => c.status === 'pending') &&
143
+ (!v.developmentInstalls.some((i) => i.status === 'INSTALLED') || !v.checks.some((c) => c.status === 'waiting_for_sandbox'))
144
+
145
+ /** Read the version until it settles (each read moves its installs and checks on), at most `timeoutMs`. */
146
+ export async function waitFor(versionId, { api: apiFlag, org, timeoutMs = 15 * 60_000, everyMs = 10_000, onRead = () => {} } = {}) {
147
+ const deadline = Date.now() + timeoutMs
148
+ for (;;) {
149
+ const r = await status(versionId, { api: apiFlag, org })
150
+ onRead(r.version)
151
+ if (settled(r.version) || Date.now() > deadline) return { ...r, timedOut: !settled(r.version) }
152
+ await new Promise((res) => setTimeout(res, everyMs))
153
+ }
154
+ }
155
+
156
+ export async function listThemes({ api: apiFlag, org } = {}) {
157
+ const where = await resolveOrg(apiFlag, org)
158
+ return { ...where, themes: await api.themes(where.api, where.org) }
159
+ }
160
+
161
+ export async function listStores({ api: apiFlag, org } = {}) {
162
+ const where = await resolveOrg(apiFlag, org)
163
+ return { ...where, stores: await api.developmentStores(where.api, where.org) }
164
+ }
165
+
166
+ export function formatVersion(v) {
167
+ const rows = [`version ${v.version} (${v.id}): ${v.status}${v.checksComplete ? ', every check done' : ''}`]
168
+ const passed = v.checks.filter((c) => c.status === 'passed').length
169
+ rows.push(`checks: ${passed} of ${v.checks.length} passed`)
170
+ for (const c of v.checks) {
171
+ rows.push(` ${c.status.padEnd(19)} ${c.key}${c.message ? `: ${c.message}` : ''}`)
172
+ if (c.status === 'failed') for (const e of c.errors.slice(0, 10)) rows.push(` ${e.path} ${e.message}`)
173
+ }
174
+ for (const i of v.developmentInstalls) {
175
+ rows.push(`install on store ${i.storeId}: ${i.status}${i.buildId ? ` (build ${i.buildId})` : ''}${i.errorMessage ? `: ${i.errorMessage}` : ''}`)
176
+ if (i.preview?.url) rows.push(` preview: ${i.preview.url}${i.preview.expiresAt ? ` (until ${i.preview.expiresAt})` : ''} (opens once)`)
177
+ }
178
+ return rows.join('\n')
179
+ }