@sbuilder/cli 0.8.0 → 0.9.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.
package/dist/bin/sb.js CHANGED
@@ -10,7 +10,7 @@ import { lstat } from 'node:fs/promises';
10
10
  import { realpathSync } from 'node:fs';
11
11
  import { homedir, userInfo } from 'node:os';
12
12
  import { resolve } from 'node:path';
13
- import { init, nextSteps, InitError } from '../src/init.js';
13
+ import { init, nextSteps, normalizeName, InitError } from '../src/init.js';
14
14
  import { readConfig, watchAndUpload, DevError } from '../src/dev.js';
15
15
  import { deploy, submit, DeployStopped } from '../src/deploy.js';
16
16
  import { readPair, storedAuth } from '../src/auth.js';
@@ -19,11 +19,13 @@ import { pull, push, ROOT_LINKED } from '../src/code.js';
19
19
  import { agent } from '../src/agent.js';
20
20
  import { servicePlan, install, uninstall, status } from '../src/service.js';
21
21
  import { newSite } from '../src/new.js';
22
- import { exportNext, ExportError } from '../src/export.js';
23
22
  import { pull as sitePull, push as sitePush, publish as sitePublish, blocks as siteBlocks, } from '../src/site.js';
24
- import { initSite, nextSteps as siteNextSteps, buildPrompt } from '../src/siteinit.js';
23
+ import { APP_SKILL_PATH } from '../src/agentdocs.js';
24
+ import { agents, initSite, nextSteps as siteNextSteps, buildPrompt } from '../src/siteinit.js';
25
25
  import { mcp, siteEnv } from '../src/repo.js';
26
26
  import { initNext } from '../src/next.js';
27
+ import { route, SUBCOMMANDS } from '../src/route.js';
28
+ import { createApp, createdSteps } from '../src/appcreate.js';
27
29
  import { VERSION } from '../src/login.js';
28
30
  import { spawnSync } from 'node:child_process';
29
31
  import { createInterface } from 'node:readline/promises';
@@ -34,7 +36,21 @@ Start
34
36
  repo for one of your sites, or an app (same as
35
37
  npm create sbuilder-app)
36
38
 
39
+ Account
40
+ sb login sign in through the browser: opens <editor>/device,
41
+ where you type the code it prints; stores a
42
+ credential that renews itself
43
+ sb logout sign this machine out and forget the credential
44
+ sb whoami which account (and platform) this CLI acts as
45
+
37
46
  Sites
47
+ sb site new "<description>" [--dir <path>] [--github] [--editor]
48
+ make a site from one sentence: creates it and a repo
49
+ for it, then offers to start Claude Code there with
50
+ your description. --github also creates the private
51
+ repo (gh). --editor builds it in the editor instead:
52
+ opens it and the assistant starts building, on this
53
+ machine's Claude Code login when it can.
38
54
  sb site init [dir] [--site <id>] [--github]
39
55
  a repo holding one site's pages: picks the site,
40
56
  pulls it, adds a GitHub workflow that syncs both
@@ -50,21 +66,34 @@ Sites
50
66
  with the line to paste into a page file
51
67
  sb site next make the repo a Next.js app serving its pages, rendered
52
68
  by the platform's own renderer (npm run dev to preview)
53
- sb code pull [--site <id>] [--dir <path>] [--force]
69
+ sb site code pull [--site <id>] [--dir <path>] [--force]
54
70
  mirror a site's Code Dock files into ./code
55
- sb code push [--site <id>] [--dir <path>] [--force] [--dry-run] [--delete]
71
+ sb site code push [--site <id>] [--dir <path>] [--force] [--dry-run] [--delete]
56
72
  send local edits back; refuses a file changed
57
73
  in the Code Dock since your pull unless --force
58
- sb new "<what to build>" make a site from one sentence: opens the editor
59
- and the assistant starts building, on this
60
- machine's Claude Code login when it can. Signs
61
- you in first if needed.
62
- sb export next <site-url> [--dir <path>]
63
- turn a published site into a Next.js repo: each
64
- page as published, cart/checkout served by the
65
- live site. Writes into ./<host> by default.
74
+ sb site agents write the AI-agent files (AGENTS.md, MCP configs, the
75
+ page skill) into a repo; never overwrites
76
+ sb site mcp the Store Builder MCP server, with this repo's key
77
+ from .env — what the repo's .mcp.json starts
78
+
79
+ Apps (for developers building on the platform)
80
+ sb app init [name] [--port 3000] [--with-block]
81
+ scaffold an app that runs, registers, and opens
82
+ inside a merchant's admin. --with-block adds a
83
+ block and its island a merchant can drag onto a page.
84
+ sb app create "<name>" [--site <id>] [--org <id>] [--yes]
85
+ create the app in your organization, a draft version
86
+ pointing at localhost, and a sandbox install on one
87
+ of your stores; writes .env and sb.json
88
+ sb app dev upload an island's code to your DRAFT version
89
+ every time you save it (not hot reload — you
90
+ refresh). Reads sb.json; needs sb login or SB_TOKEN.
91
+ sb app deploy [--submit] push the version's payload in dependency order.
92
+ Not one write: if it stops it says where, and
93
+ running it again is safe. --submit then sends
94
+ it for review.
66
95
 
67
- AI assistant
96
+ AI
68
97
  sb agent [--codex] run the editor's AI assistant on THIS machine's
69
98
  Claude Code login — no API key (--codex also
70
99
  lets Codex run, which can READ your files). Pick
@@ -75,26 +104,6 @@ AI assistant
75
104
  at login, restarts if it stops (launchd / systemd).
76
105
  Needs a global install (npm i -g @sbuilder/cli).
77
106
  sb agent uninstall | status remove it, or say whether it is running
78
- sb mcp the Store Builder MCP server, with this repo's key
79
- from .env — what the repo's .mcp.json starts
80
-
81
- Apps (for developers building on the platform)
82
- sb init [name] [--port 3000] scaffold an app that runs, registers, and opens
83
- inside a merchant's admin
84
- sb dev upload an island's code to your DRAFT version
85
- every time you save it (not hot reload — you
86
- refresh). Reads sb.json; needs sb login or SB_TOKEN.
87
- sb deploy [--submit] push the version's payload in dependency order.
88
- Not one write: if it stops it says where, and
89
- running it again is safe. --submit then sends
90
- it for review.
91
-
92
- Account
93
- sb login sign in through the browser: opens <editor>/device,
94
- where you type the code it prints; stores a
95
- credential that renews itself
96
- sb whoami which account (and platform) this CLI acts as
97
- sb logout sign this machine out and forget the credential
98
107
 
99
108
  Docs: /cli-docs (this tool) · /app-docs (building an app) · /block-docs (contributing
100
109
  to the editor)`;
@@ -132,6 +141,18 @@ function parse(argv) {
132
141
  else if (a === '--all') {
133
142
  args.all = true;
134
143
  }
144
+ else if (a === '--editor') {
145
+ args.editor = true;
146
+ }
147
+ else if (a === '--with-block') {
148
+ args.withBlock = true;
149
+ }
150
+ else if (a === '--yes') {
151
+ args.yes = true;
152
+ }
153
+ else if (a === '--org') {
154
+ args.org = argv[++i];
155
+ }
135
156
  else if (a === '-h' || a === '--help') {
136
157
  args.help = true;
137
158
  }
@@ -161,18 +182,22 @@ async function ask(question) {
161
182
  rl.close();
162
183
  }
163
184
  }
164
- async function pickSite(sites) {
185
+ async function pickFrom(what, items, flag) {
165
186
  if (!process.stdin.isTTY) {
166
- throw new DevError('Which site? Pass --site <id>:\n' + sites.map((s) => ` ${s.id} ${s.name}`).join('\n'));
187
+ throw new DevError(`Which ${what}? Pass ${flag} <id>:\n` + items.map((s) => ` ${s.id} ${s.name}`).join('\n'));
167
188
  }
168
- console.log('Your sites:');
169
- sites.forEach((s, i) => console.log(` ${i + 1}) ${s.name}${s.publicUrl ? ` ${s.publicUrl}` : ''}`));
189
+ console.log(`Your ${what}s:`);
190
+ items.forEach((s, i) => {
191
+ const url = s.publicUrl;
192
+ console.log(` ${i + 1}) ${s.name}${url ? ` ${url}` : ''}`);
193
+ });
170
194
  for (;;) {
171
- const n = Number(await ask(`Choose 1-${sites.length}: `));
172
- if (Number.isInteger(n) && n >= 1 && n <= sites.length)
173
- return sites[n - 1];
195
+ const n = Number(await ask(`Choose 1-${items.length}: `));
196
+ if (Number.isInteger(n) && n >= 1 && n <= items.length)
197
+ return items[n - 1];
174
198
  }
175
199
  }
200
+ const pickSite = (sites) => pickFrom('site', sites, '--site');
176
201
  /** A folder name from a site name: lower case, no diacritics, dashes. */
177
202
  function slug(name) {
178
203
  return (name
@@ -229,368 +254,404 @@ async function startSiteRepo(o) {
229
254
  console.log(' (Cursor / VS Code work too — the Store Builder tools are set up in the folder.)');
230
255
  return res.code;
231
256
  }
232
- async function main(argv) {
233
- const args = parse(argv);
234
- const cmd = args._[0];
235
- if (args.help || !cmd) {
236
- console.log(USAGE);
237
- return 0;
257
+ /** A site name from its description: the first words, cut at a word boundary. */
258
+ function siteName(description) {
259
+ const words = description.trim().replace(/\s+/g, ' ');
260
+ if (words.length <= 40)
261
+ return words;
262
+ const cut = words.slice(0, 40);
263
+ return cut.slice(0, Math.max(cut.lastIndexOf(' '), 1)).replace(/[\s,.;:-]+$/, '');
264
+ }
265
+ /**
266
+ * `sb site new "<description>"` and menu choice 1: create the site and its repo,
267
+ * then offer Claude Code with the description.
268
+ */
269
+ function siteNew(o) {
270
+ const name = o.name || siteName(o.description);
271
+ return startSiteRepo({
272
+ dir: o.dir ?? slug(name),
273
+ create: name,
274
+ github: o.github,
275
+ description: o.description,
276
+ });
277
+ }
278
+ /** `sb site new --editor` (the old `sb new`): the editor opens and the assistant builds. */
279
+ async function siteNewEditor(prompt) {
280
+ const api = apiBase();
281
+ if (!prompt.trim()) {
282
+ console.error('Say what to build: sb site new --editor "a shop selling handmade candles"');
283
+ return 1;
238
284
  }
239
- if (cmd === 'dev') {
240
- try {
241
- const cfg = await readConfig();
242
- const api = apiBase();
243
- const token = await credential(api);
244
- if (!token) {
245
- console.error(NOT_SIGNED_IN);
246
- return 1;
247
- }
248
- const w = watchAndUpload({ ...cfg, api, token });
249
- console.log(`watching ${cfg.entry} — save it and this uploads to version ${cfg.versionId}.`);
250
- console.log('This is not hot reload: after each upload, refresh the page.');
251
- await w.send(); // upload once now rather than waiting for the first save
252
- // Runs until interrupted. No resolve: the watcher IS the program.
253
- await new Promise(() => { });
254
- return 0;
255
- }
256
- catch (err) {
257
- if (err instanceof DevError) {
258
- console.error(err.message);
259
- return 1;
260
- }
261
- throw err;
262
- }
285
+ if (!(await credential(api)))
286
+ await login({ api });
287
+ const token = await credential(api);
288
+ if (!token) {
289
+ console.error(NOT_SIGNED_IN);
290
+ return 1;
263
291
  }
264
- if (cmd === 'deploy') {
265
- try {
266
- const cfg = await readConfig();
267
- const api = apiBase();
268
- const token = await credential(api);
269
- if (!token) {
270
- console.error(NOT_SIGNED_IN);
271
- return 1;
272
- }
273
- console.log(`deploying to version ${cfg.versionId}:`);
274
- await deploy({ api, token, cfg, log: (l) => console.log(l) });
275
- console.log('done.');
276
- if (args.submit) {
277
- await submit({ api, token, cfg });
278
- console.log('submitted for review.');
279
- }
280
- return 0;
281
- }
282
- catch (err) {
283
- if (err instanceof DeployStopped || err instanceof DevError) {
284
- console.error(err.message);
285
- return 1;
286
- }
287
- throw err;
288
- }
292
+ // After login, whose wait a Ctrl-C has to be able to end.
293
+ const stop = new AbortController();
294
+ process.once('SIGINT', () => stop.abort());
295
+ await newSite({ api, token, prompt, log: (l) => console.log(l), signal: stop.signal });
296
+ return 0;
297
+ }
298
+ /** `sb app create` and the menu's offer after the scaffold: sign in if needed, then create. */
299
+ async function appCreate(o) {
300
+ // Before sign-in: a missing name should not cost a browser round trip.
301
+ if (!o.name.trim()) {
302
+ console.error('Name the app: sb app create "My app"');
303
+ return 1;
289
304
  }
290
- if (cmd === 'code') {
291
- const sub = args._[1];
292
- if (sub !== 'pull' && sub !== 'push') {
293
- console.error('usage: sb code pull|push [--site <id>] [--dir <path>] [--force] [--dry-run] [--delete]');
294
- return 1;
295
- }
296
- // A committed `code` link would re-root the sync; typing --dir is the deliberate act.
297
- // lstat checks only the final component, and an absent ./code (a first pull) is not a link.
298
- if (args.dir === undefined &&
299
- (await lstat(resolve('code')).catch(() => undefined))?.isSymbolicLink()) {
300
- console.error(ROOT_LINKED);
301
- return 1;
302
- }
303
- // Inside a site repo its .env (the repo's own key) fills what the shell leaves unset.
304
- const env = siteEnv();
305
- const api = env.SB_API || apiBase();
306
- try {
307
- return await (sub === 'pull' ? pull : push)({
308
- api,
309
- token: env.SB_TOKEN || (await credential(api)),
310
- dir: resolve(args.dir ?? 'code'),
311
- site: args.site,
312
- force: args.force,
313
- dryRun: args.dryRun,
314
- delete: args.delete,
315
- log: (l) => console.log(l),
316
- warn: (l) => console.error(l),
317
- });
318
- }
319
- catch (err) {
320
- if (err instanceof DevError) {
321
- console.error(err.message);
322
- return 1;
323
- }
324
- throw err;
325
- }
305
+ const api = apiBase();
306
+ let token = await credential(api);
307
+ if (!token) {
308
+ await login({ api });
309
+ token = await credential(api);
326
310
  }
327
- if (cmd === 'mcp') {
328
- return mcp(args.dir);
311
+ if (!token) {
312
+ console.error(NOT_SIGNED_IN);
313
+ return 1;
329
314
  }
330
- if (cmd === 'site') {
331
- const sub = args._[1];
332
- if (sub !== 'pull' &&
333
- sub !== 'push' &&
334
- sub !== 'init' &&
335
- sub !== 'publish' &&
336
- sub !== 'next' &&
337
- sub !== 'blocks') {
338
- console.error('usage: sb site init|pull|push|publish|next|blocks [--site <id>] [--dir <path>] [--force] [--dry-run] [--all]');
339
- return 1;
340
- }
341
- try {
342
- if (sub === 'init') {
343
- return await startSiteRepo({
344
- dir: args.dir ?? args._[2] ?? 'my-site',
345
- site: args.site,
346
- github: args.github,
347
- });
348
- }
349
- if (sub === 'next') {
350
- const minor = VERSION.split('.').slice(0, 2).join('.');
351
- await initNext({
352
- dir: resolve(args.dir ?? '.'),
353
- cliRange: `^${minor}.0`,
354
- renderRange: '^0.1.0',
355
- });
356
- return 0;
357
- }
358
- // Inside a site repo its .env (the repo's own key) fills what the shell leaves unset.
359
- const dir = resolve(args.dir ?? '.');
360
- const env = siteEnv(dir);
361
- const api = env.SB_API || apiBase();
362
- const opts = {
363
- api,
364
- token: env.SB_TOKEN || (await credential(api)),
365
- dir,
366
- site: args.site,
367
- force: args.force,
368
- dryRun: args.dryRun,
369
- log: (l) => console.log(l),
370
- warn: (l) => console.error(l),
371
- };
372
- if (sub === 'blocks')
373
- return await siteBlocks(opts);
374
- if (sub === 'publish')
375
- return await sitePublish({ ...opts, files: args._.slice(2), all: args.all });
376
- return await (sub === 'pull' ? sitePull : sitePush)(opts);
377
- }
378
- catch (err) {
379
- if (err instanceof DevError) {
380
- console.error(err.message);
381
- return 1;
315
+ const tty = !!process.stdin.isTTY;
316
+ const r = await createApp({
317
+ api,
318
+ token,
319
+ name: o.name,
320
+ dir: resolve(o.dir),
321
+ port: o.port,
322
+ site: o.site,
323
+ org: o.org,
324
+ yes: o.yes,
325
+ confirm: tty
326
+ ? async () => {
327
+ return /^y/i.test(await ask('Create the app and install it with these? [y/N]: '));
382
328
  }
383
- throw err;
384
- }
329
+ : undefined,
330
+ pickOrg: tty ? (orgs) => pickFrom('organization', orgs, '--org') : undefined,
331
+ pickSite: tty ? (sites) => pickFrom('store', sites, '--site') : undefined,
332
+ log: (l) => console.log(l),
333
+ });
334
+ for (const l of createdSteps(r))
335
+ console.log(l);
336
+ return 0;
337
+ }
338
+ async function appInit(o) {
339
+ if (!Number.isFinite(o.port) || o.port <= 0) {
340
+ console.error('--port must be a number');
341
+ return 1;
342
+ }
343
+ try {
344
+ const res = await init({ name: o.name, port: o.port, withBlock: o.withBlock });
345
+ console.log(nextSteps({ name: res.name, port: o.port, withBlock: o.withBlock }));
346
+ for (const f of res.kept)
347
+ console.log(`Kept your existing ${f}.` +
348
+ (f === 'AGENTS.md' ? ` Add a line telling agents to read ${APP_SKILL_PATH}.` : ''));
349
+ return 0;
385
350
  }
386
- if (cmd === 'export') {
387
- const url = args._[2];
388
- if (args._[1] !== 'next' || !url) {
389
- console.error('Usage: sb export next <site-url> [--dir <path>]');
351
+ catch (err) {
352
+ // An InitError is a refusal the developer can act on — print it plainly.
353
+ // Anything else is a bug in this tool and gets its stack, because a
354
+ // scaffolder that swallows its own failures is one nobody can report.
355
+ if (err instanceof InitError) {
356
+ console.error(err.message);
390
357
  return 1;
391
358
  }
392
- try {
393
- const dir = resolve(args.dir ?? (URL.canParse(url) ? new URL(url).hostname : 'site'));
394
- console.log(`Exporting ${url} into ${dir}`);
395
- const r = await exportNext(url, dir);
396
- for (const s of r.skipped)
397
- console.error(` skipped ${s.path}: ${s.reason}`);
398
- console.log(`${r.written.length} page(s) written. Next: cd ${dir} && npm install && npm run dev`);
399
- return 0;
400
- }
401
- catch (err) {
402
- if (err instanceof ExportError || err instanceof TypeError) {
403
- console.error(err instanceof TypeError
404
- ? `could not reach ${url}: ${err.cause?.code ?? err.message}`
405
- : err.message);
406
- return 1;
407
- }
408
- throw err;
409
- }
359
+ throw err;
410
360
  }
411
- if (cmd === 'new') {
412
- const api = apiBase();
413
- try {
414
- const prompt = args._.slice(1).join(' ');
415
- if (!prompt.trim()) {
416
- console.error('Say what to build: sb new "a shop selling handmade candles"');
417
- return 1;
418
- }
419
- if (!(await credential(api)))
420
- await login({ api });
421
- const token = await credential(api);
422
- if (!token) {
423
- console.error(NOT_SIGNED_IN);
424
- return 1;
425
- }
426
- // After login, whose wait a Ctrl-C has to be able to end.
427
- const stop = new AbortController();
428
- process.once('SIGINT', () => stop.abort());
429
- await newSite({ api, token, prompt, log: (l) => console.log(l), signal: stop.signal });
430
- return 0;
431
- }
432
- catch (err) {
433
- if (err instanceof DevError) {
434
- console.error(err.message);
435
- return 1;
436
- }
437
- throw err;
438
- }
361
+ }
362
+ /** The menu: `sb init` with no arguments on a terminal. */
363
+ async function menu(args) {
364
+ const choice = await ask('What do you want to start?\n' +
365
+ ' 1) A new website, built by AI — describe it, an AI agent builds it\n' +
366
+ ' 2) A repo for one of your sites — edit it with AI, synced with GitHub\n' +
367
+ " 3) An app — runs inside a merchant's admin\n" +
368
+ 'Choose 1-3 [1]: ');
369
+ if (choice === '' || choice === '1') {
370
+ let description = '';
371
+ while (!description)
372
+ description = await ask('Describe the website (any language): ');
373
+ const name = (await ask('Site name [My shop]: ')) || 'My shop';
374
+ const dir = (await ask(`Folder [${slug(name)}]: `)) || slug(name);
375
+ const github = /^y/i.test(await ask('Also create a private GitHub repo with gh? [y/N]: '));
376
+ return siteNew({ description, name, dir, github });
439
377
  }
440
- if (cmd === 'agent') {
441
- const api = apiBase();
442
- const sub = args._[1];
443
- if (sub === 'install' || sub === 'uninstall' || sub === 'status') {
444
- try {
445
- // A service cannot answer a browser sign-in: it must start signed in.
446
- if (sub === 'install' && !(await credential(api))) {
447
- console.error(NOT_SIGNED_IN);
448
- return 1;
449
- }
450
- const plan = servicePlan({
451
- platform: process.platform,
452
- home: homedir(),
453
- uid: userInfo().uid,
454
- node: process.execPath,
455
- script: realpathSync(process.argv[1]),
456
- codex: args.codex === true,
457
- env: { PATH: process.env.PATH, SB_API: process.env.SB_API },
458
- });
459
- const say = sub === 'install' ? install : sub === 'uninstall' ? uninstall : status;
460
- for (const l of say(plan))
461
- console.log(l);
462
- return 0;
463
- }
464
- catch (err) {
465
- if (err instanceof DevError) {
466
- console.error(err.message);
467
- return 1;
468
- }
469
- throw err;
470
- }
471
- }
472
- if (sub !== undefined) {
473
- console.error(`unknown: sb agent ${sub} (install, uninstall or status)`);
474
- return 1;
475
- }
476
- const token = await credential(api);
477
- if (!token) {
478
- console.error(NOT_SIGNED_IN);
479
- return 1;
480
- }
481
- console.log('sb agent: Claude Code runs here with its tools off.');
482
- if (args.codex) {
483
- console.log('--codex: Codex may run too. It can READ files on this machine through read-only');
484
- console.log('shell commands, steered by page content other editors of the site wrote.');
485
- }
486
- else {
487
- console.log('Codex jobs are refused (a co-editor could pick Codex for a site); add --codex to allow.');
488
- }
489
- const stop = new AbortController();
490
- process.once('SIGINT', () => stop.abort());
491
- try {
492
- await agent({
493
- api,
494
- token,
495
- log: (l) => console.log(l),
496
- signal: stop.signal,
497
- allowCodex: args.codex === true,
498
- });
499
- return 0;
500
- }
501
- catch (err) {
502
- if (err instanceof DevError) {
503
- console.error(err.message);
504
- return 1;
505
- }
506
- throw err;
507
- }
378
+ if (choice === '2') {
379
+ const dir = (await ask('Folder [my-site]: ')) || 'my-site';
380
+ const github = /^y/i.test(await ask('Also create a private GitHub repo with gh? [y/N]: '));
381
+ return startSiteRepo({ dir, github });
508
382
  }
509
- if (cmd === 'whoami') {
510
- const api = apiBase();
511
- const cred = await credential(api);
512
- const where = new URL(api).origin;
513
- if (!cred) {
514
- console.log(`Not signed in to ${where}. Run sb login.`);
383
+ const name = (await ask('App name [my-app]: ')) || 'my-app';
384
+ const withBlock = /^y/i.test(await ask('Include an example block and island? [y/N]: '));
385
+ const code = await appInit({ name, port: args.port, withBlock });
386
+ if (code !== 0)
387
+ return code;
388
+ const create = await ask('Create the app on the platform now (a draft version and a sandbox install on one of your stores)? [Y/n]: ');
389
+ if (/^n/i.test(create))
390
+ return 0;
391
+ return appCreate({ name, dir: normalizeName(name), port: args.port });
392
+ }
393
+ async function appDev() {
394
+ const cfg = await readConfig();
395
+ const api = apiBase();
396
+ const token = await credential(api);
397
+ if (!token) {
398
+ console.error(NOT_SIGNED_IN);
399
+ return 1;
400
+ }
401
+ const w = watchAndUpload({ ...cfg, api, token });
402
+ console.log(`watching ${cfg.entry} — save it and this uploads to version ${cfg.versionId}.`);
403
+ console.log('This is not hot reload: after each upload, refresh the page.');
404
+ await w.send(); // upload once now rather than waiting for the first save
405
+ // Runs until interrupted. No resolve: the watcher IS the program.
406
+ await new Promise(() => { });
407
+ return 0;
408
+ }
409
+ async function appDeploy(args) {
410
+ const cfg = await readConfig();
411
+ const api = apiBase();
412
+ const token = await credential(api);
413
+ if (!token) {
414
+ console.error(NOT_SIGNED_IN);
415
+ return 1;
416
+ }
417
+ console.log(`deploying to version ${cfg.versionId}:`);
418
+ await deploy({ api, token, cfg, log: (l) => console.log(l) });
419
+ console.log('done.');
420
+ if (args.submit) {
421
+ await submit({ api, token, cfg });
422
+ console.log('submitted for review.');
423
+ }
424
+ return 0;
425
+ }
426
+ /** `sb app …` */
427
+ async function appCommand(args) {
428
+ const sub = args._[1];
429
+ if (sub === 'init') {
430
+ return appInit({ name: args._[2], port: args.port, withBlock: args.withBlock });
431
+ }
432
+ if (sub === 'create') {
433
+ return appCreate({
434
+ name: args._.slice(2).join(' '),
435
+ dir: args.dir ?? '.',
436
+ port: args.port,
437
+ site: args.site,
438
+ org: args.org,
439
+ yes: args.yes,
440
+ });
441
+ }
442
+ if (sub === 'dev')
443
+ return appDev();
444
+ if (sub === 'deploy')
445
+ return appDeploy(args);
446
+ console.error(`usage: sb app ${SUBCOMMANDS.app.join('|')}`);
447
+ return 1;
448
+ }
449
+ /** `sb site code pull|push` (the old `sb code`). */
450
+ async function siteCode(args) {
451
+ const sub = args._[2];
452
+ if (!sub || !SUBCOMMANDS['site code'].includes(sub)) {
453
+ console.error('usage: sb site code pull|push [--site <id>] [--dir <path>] [--force] [--dry-run] [--delete]');
454
+ return 1;
455
+ }
456
+ // A committed `code` link would re-root the sync; typing --dir is the deliberate act.
457
+ // lstat checks only the final component, and an absent ./code (a first pull) is not a link.
458
+ if (args.dir === undefined &&
459
+ (await lstat(resolve('code')).catch(() => undefined))?.isSymbolicLink()) {
460
+ console.error(ROOT_LINKED);
461
+ return 1;
462
+ }
463
+ // Inside a site repo its .env (the repo's own key) fills what the shell leaves unset.
464
+ const env = siteEnv();
465
+ const api = env.SB_API || apiBase();
466
+ return (sub === 'pull' ? pull : push)({
467
+ api,
468
+ token: env.SB_TOKEN || (await credential(api)),
469
+ dir: resolve(args.dir ?? 'code'),
470
+ site: args.site,
471
+ force: args.force,
472
+ dryRun: args.dryRun,
473
+ delete: args.delete,
474
+ log: (l) => console.log(l),
475
+ warn: (l) => console.error(l),
476
+ });
477
+ }
478
+ /** `sb site …` */
479
+ async function siteCommand(args) {
480
+ const sub = args._[1];
481
+ if (sub === 'new') {
482
+ const description = args._.slice(2).join(' ').trim();
483
+ if (args.editor)
484
+ return siteNewEditor(description);
485
+ if (!description) {
486
+ console.error('Say what to build: sb site new "a shop selling handmade candles"');
515
487
  return 1;
516
488
  }
517
- if (typeof cred === 'string' && /^(wbk|sbdk)_/.test(cred)) {
518
- console.log(`Using the ${cred.startsWith('wbk_') ? 'API key' : 'deploy key'} in SB_TOKEN, on ${where}.`);
519
- return 0;
520
- }
521
- const email = await whoIs(api, cred);
522
- if (!email) {
523
- console.log(`Signed in to ${where}, but the server would not say as whom — run sb login again.`);
489
+ return siteNew({ description, dir: args.dir, github: args.github });
490
+ }
491
+ if (sub === 'code')
492
+ return siteCode(args);
493
+ if (sub === 'mcp')
494
+ return mcp(args.dir);
495
+ if (sub === 'agents')
496
+ return agents({ dir: resolve(args.dir ?? '.') });
497
+ if (!sub || !SUBCOMMANDS.site.includes(sub)) {
498
+ console.error('usage: sb site new|init|pull|push|publish|next|blocks|agents|code|mcp [--site <id>] [--dir <path>] [--force] [--dry-run] [--all]');
499
+ return 1;
500
+ }
501
+ if (sub === 'init') {
502
+ return startSiteRepo({
503
+ dir: args.dir ?? args._[2] ?? 'my-site',
504
+ site: args.site,
505
+ github: args.github,
506
+ });
507
+ }
508
+ if (sub === 'next') {
509
+ const minor = VERSION.split('.').slice(0, 2).join('.');
510
+ await initNext({
511
+ dir: resolve(args.dir ?? '.'),
512
+ cliRange: `^${minor}.0`,
513
+ renderRange: '^0.1.0',
514
+ });
515
+ return 0;
516
+ }
517
+ // Inside a site repo its .env (the repo's own key) fills what the shell leaves unset.
518
+ const dir = resolve(args.dir ?? '.');
519
+ const env = siteEnv(dir);
520
+ const api = env.SB_API || apiBase();
521
+ const opts = {
522
+ api,
523
+ token: env.SB_TOKEN || (await credential(api)),
524
+ dir,
525
+ site: args.site,
526
+ force: args.force,
527
+ dryRun: args.dryRun,
528
+ log: (l) => console.log(l),
529
+ warn: (l) => console.error(l),
530
+ };
531
+ if (sub === 'blocks')
532
+ return siteBlocks(opts);
533
+ if (sub === 'publish')
534
+ return sitePublish({ ...opts, files: args._.slice(2), all: args.all });
535
+ return (sub === 'pull' ? sitePull : sitePush)(opts);
536
+ }
537
+ /** `sb agent …` */
538
+ async function agentCommand(args) {
539
+ const api = apiBase();
540
+ const sub = args._[1];
541
+ if (sub && SUBCOMMANDS.agent.includes(sub)) {
542
+ // A service cannot answer a browser sign-in: it must start signed in.
543
+ if (sub === 'install' && !(await credential(api))) {
544
+ console.error(NOT_SIGNED_IN);
524
545
  return 1;
525
546
  }
526
- console.log(`${email} on ${where}`);
547
+ const plan = servicePlan({
548
+ platform: process.platform,
549
+ home: homedir(),
550
+ uid: userInfo().uid,
551
+ node: process.execPath,
552
+ script: realpathSync(process.argv[1]),
553
+ codex: args.codex === true,
554
+ env: { PATH: process.env.PATH, SB_API: process.env.SB_API },
555
+ });
556
+ const say = sub === 'install' ? install : sub === 'uninstall' ? uninstall : status;
557
+ for (const l of say(plan))
558
+ console.log(l);
527
559
  return 0;
528
560
  }
529
- if (cmd === 'login' || cmd === 'logout') {
530
- const api = apiBase();
531
- try {
532
- await (cmd === 'login' ? login({ api }) : logout({ api }));
533
- return 0;
534
- }
535
- catch (err) {
536
- if (err instanceof DevError) {
537
- console.error(err.message);
538
- return 1;
539
- }
540
- throw err;
541
- }
561
+ if (sub !== undefined) {
562
+ console.error(`unknown: sb agent ${sub} (${SUBCOMMANDS.agent.join(', ')})`);
563
+ return 1;
542
564
  }
543
- if (cmd !== 'init') {
544
- console.error(`unknown command: ${cmd}\n`);
545
- console.error(USAGE);
565
+ const token = await credential(api);
566
+ if (!token) {
567
+ console.error(NOT_SIGNED_IN);
546
568
  return 1;
547
569
  }
548
- if (!Number.isFinite(args.port) || args.port <= 0) {
549
- console.error('--port must be a number');
570
+ console.log('sb agent: Claude Code runs here with its tools off.');
571
+ if (args.codex) {
572
+ console.log('--codex: Codex may run too. It can READ files on this machine through read-only');
573
+ console.log('shell commands, steered by page content other editors of the site wrote.');
574
+ }
575
+ else {
576
+ console.log('Codex jobs are refused (a co-editor could pick Codex for a site); add --codex to allow.');
577
+ }
578
+ const stop = new AbortController();
579
+ process.once('SIGINT', () => stop.abort());
580
+ await agent({
581
+ api,
582
+ token,
583
+ log: (l) => console.log(l),
584
+ signal: stop.signal,
585
+ allowCodex: args.codex === true,
586
+ });
587
+ return 0;
588
+ }
589
+ async function whoami() {
590
+ const api = apiBase();
591
+ const cred = await credential(api);
592
+ const where = new URL(api).origin;
593
+ if (!cred) {
594
+ console.log(`Not signed in to ${where}. Run sb login.`);
550
595
  return 1;
551
596
  }
552
- if (args._.length === 1 && process.stdin.isTTY && process.stdout.isTTY) {
553
- const choice = await ask('What do you want to start?\n' +
554
- ' 1) A new website, built by AI — describe it, an AI agent builds it\n' +
555
- ' 2) A repo for one of your sites — edit it with AI, synced with GitHub\n' +
556
- " 3) An app — runs inside a merchant's admin\n" +
557
- 'Choose 1-3 [1]: ');
558
- try {
559
- if (choice === '' || choice === '1') {
560
- let description = '';
561
- while (!description)
562
- description = await ask('Describe the website (any language): ');
563
- const name = (await ask('Site name [My shop]: ')) || 'My shop';
564
- const dir = (await ask(`Folder [${slug(name)}]: `)) || slug(name);
565
- const github = /^y/i.test(await ask('Also create a private GitHub repo with gh? [y/N]: '));
566
- return await startSiteRepo({ dir, create: name, github, description });
567
- }
568
- if (choice === '2') {
569
- const dir = (await ask('Folder [my-site]: ')) || 'my-site';
570
- const github = /^y/i.test(await ask('Also create a private GitHub repo with gh? [y/N]: '));
571
- return await startSiteRepo({ dir, github });
597
+ if (typeof cred === 'string' && /^(wbk|sbdk)_/.test(cred)) {
598
+ console.log(`Using the ${cred.startsWith('wbk_') ? 'API key' : 'deploy key'} in SB_TOKEN, on ${where}.`);
599
+ return 0;
600
+ }
601
+ const email = await whoIs(api, cred);
602
+ if (!email) {
603
+ console.log(`Signed in to ${where}, but the server would not say as whom — run sb login again.`);
604
+ return 1;
605
+ }
606
+ console.log(`${email} on ${where}`);
607
+ return 0;
608
+ }
609
+ /**
610
+ * Dispatch. Old names are rewritten first (route.ts) and their one-line note goes
611
+ * to STDERR — stdout is untouched, because `sb mcp` is an MCP stream.
612
+ */
613
+ async function main(rawArgv) {
614
+ const { argv, note } = route(rawArgv);
615
+ if (note)
616
+ console.error(note);
617
+ const args = parse(argv);
618
+ const cmd = args._[0];
619
+ if (args.help || !cmd) {
620
+ console.log(USAGE);
621
+ return 0;
622
+ }
623
+ try {
624
+ switch (cmd) {
625
+ case 'site':
626
+ return await siteCommand(args);
627
+ case 'app':
628
+ return await appCommand(args);
629
+ case 'agent':
630
+ return await agentCommand(args);
631
+ case 'whoami':
632
+ return await whoami();
633
+ case 'login':
634
+ case 'logout': {
635
+ const api = apiBase();
636
+ await (cmd === 'login' ? login({ api }) : logout({ api }));
637
+ return 0;
572
638
  }
573
- }
574
- catch (err) {
575
- if (err instanceof DevError) {
576
- console.error(err.message);
639
+ case 'export':
640
+ console.error("`sb export next` was removed in 0.9 — use `sb site next` (a Next.js app rendered by the platform's own renderer).");
641
+ return 1;
642
+ case 'init':
643
+ if (args._.length === 1 && process.stdin.isTTY && process.stdout.isTTY)
644
+ return await menu(args);
645
+ // A bare `sb init` off a terminal is what it always was: the app scaffold, `my-app`.
646
+ return await appInit({ port: args.port, withBlock: args.withBlock });
647
+ default:
648
+ console.error(`unknown command: ${cmd}\n`);
649
+ console.error(USAGE);
577
650
  return 1;
578
- }
579
- throw err;
580
651
  }
581
- const name = (await ask('App name [my-app]: ')) || 'my-app';
582
- args._.push(name);
583
- }
584
- try {
585
- const res = await init({ name: args._[1], port: args.port });
586
- console.log(nextSteps({ name: res.name, port: args.port }));
587
- return 0;
588
652
  }
589
653
  catch (err) {
590
- // An InitError is a refusal the developer can act on — print it plainly.
591
- // Anything else is a bug in this tool and gets its stack, because a
592
- // scaffolder that swallows its own failures is one nobody can report.
593
- if (err instanceof InitError) {
654
+ if (err instanceof DevError || err instanceof DeployStopped) {
594
655
  console.error(err.message);
595
656
  return 1;
596
657
  }