@sbuilder/cli 0.12.0 → 0.14.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 (42) hide show
  1. package/README.md +116 -13
  2. package/README.vi.md +115 -13
  3. package/dist/bin/sb.js +221 -41
  4. package/dist/bin/sb.js.map +1 -1
  5. package/dist/src/agentdocs.js +250 -8
  6. package/dist/src/agentdocs.js.map +1 -1
  7. package/dist/src/appblocks.js +5 -1
  8. package/dist/src/appblocks.js.map +1 -1
  9. package/dist/src/components.js +400 -24
  10. package/dist/src/components.js.map +1 -1
  11. package/dist/src/doctor.js +37 -3
  12. package/dist/src/doctor.js.map +1 -1
  13. package/dist/src/envtypes.gen.js +2929 -271
  14. package/dist/src/envtypes.gen.js.map +1 -1
  15. package/dist/src/host.js +31 -0
  16. package/dist/src/host.js.map +1 -1
  17. package/dist/src/login.js +1 -1
  18. package/dist/src/preview.js +114 -0
  19. package/dist/src/preview.js.map +1 -0
  20. package/dist/src/route.js +4 -2
  21. package/dist/src/route.js.map +1 -1
  22. package/dist/src/site.js +164 -22
  23. package/dist/src/site.js.map +1 -1
  24. package/dist/src/siteinit.js +381 -74
  25. package/dist/src/siteinit.js.map +1 -1
  26. package/dist/src/sitekinds.js +56 -13
  27. package/dist/src/sitekinds.js.map +1 -1
  28. package/dist/src/source/derived.js +96 -0
  29. package/dist/src/source/derived.js.map +1 -0
  30. package/dist/src/source/meta.js +3 -3
  31. package/dist/src/source/meta.js.map +1 -1
  32. package/dist/src/source/parse.js +6 -2
  33. package/dist/src/source/parse.js.map +1 -1
  34. package/dist/src/source/print.js +8 -1
  35. package/dist/src/source/print.js.map +1 -1
  36. package/dist/src/structure.js +114 -0
  37. package/dist/src/structure.js.map +1 -0
  38. package/dist/src/templates.js +93 -0
  39. package/dist/src/templates.js.map +1 -0
  40. package/dist/src/themediff.js +49 -0
  41. package/dist/src/themediff.js.map +1 -0
  42. package/package.json +1 -1
@@ -1,15 +1,16 @@
1
- import { execFileSync } from 'node:child_process';
1
+ import { execFileSync, spawnSync } from 'node:child_process';
2
2
  import { appendFile, mkdir, readdir, readFile, writeFile } from 'node:fs/promises';
3
3
  import { existsSync } from 'node:fs';
4
4
  import { basename, dirname, join } from 'node:path';
5
- import { CLI_RANGE, PAGE_SKILL, PAGE_SKILL_PATH } from './agentdocs.js';
5
+ import { CLI_RANGE, COMPONENTS_SKILL, COMPONENTS_SKILL_PATH, PAGE_SKILL, PAGE_SKILL_PATH, } from './agentdocs.js';
6
+ import { editorOrigin } from './appcreate.js';
6
7
  import { authedFetch } from './auth.js';
7
8
  import { pull as codePull } from './code.js';
8
9
  import { ENV_DTS } from './envtypes.gen.js';
9
10
  import { DEFAULT_API } from './login.js';
10
11
  import { parseEnv } from './repo.js';
11
12
  import { describeRoot, excludeDesign } from './roottsconfig.js';
12
- import { linkOn, pull, SiteRefused, SITE_MANIFEST, SITE_UNAUTHORIZED } from './site.js';
13
+ import { linkOn, pull, put, putIfStill, readManifest, readText, recordAgentFiles, sha256, SiteRefused, SITE_MANIFEST, SITE_UNAUTHORIZED, } from './site.js';
13
14
  export { CLI_RANGE };
14
15
  const CLI = `@sbuilder/cli@${CLI_RANGE}`;
15
16
  /** Scopes a key never carries: each means "this human's account", and the gateway refuses them on a key. */
@@ -87,11 +88,15 @@ export const CODEX_TOML = `[mcp_servers.sbuilder]\ncommand = ${JSON.stringify(MC
87
88
  `args = ${JSON.stringify(MCP_SERVER.args)}\n`;
88
89
  /** The one line that sends every agent to the skill — also what a kept AGENTS.md is told to add. */
89
90
  export const SKILL_POINTER = `**Before editing a page file or building a section, read \`${PAGE_SKILL_PATH}\`**`;
91
+ /** The same for code components: when one is right, and how it is written, pushed and pinned. */
92
+ export const COMPONENTS_POINTER = `**Before writing a code component (components/*.tsx), read \`${COMPONENTS_SKILL_PATH}\`.**`;
90
93
  export function agentsMd(site) {
91
94
  return `# Working on ${site.name}
92
95
 
93
96
  This repo is the Store Builder site **${site.name}**${site.publicUrl ? ` (${site.publicUrl})` : ''}.
94
- You build it through the \`sbuilder\` MCP tools, which edit the site's DRAFTS on the platform.
97
+ You build it through the \`sbuilder\` MCP tools when they are connected, which edit the site's
98
+ DRAFTS on the platform — or, without them, by editing the page files and pushing them (the page
99
+ skill's "Without the MCP tools": the element catalog, the structure check, the draft preview).
95
100
  Nothing you do here is live until the owner publishes.
96
101
 
97
102
  Setup: approve the \`sbuilder\` MCP server the first time. Codex: trust this folder once, or it
@@ -99,6 +104,7 @@ will not read \`.codex/config.toml\`.
99
104
 
100
105
  ${SKILL_POINTER} — the page
101
106
  syntax, the build loop with the tools, app-block rules, and what pull / push / publish do.
107
+ ${COMPONENTS_POINTER}
102
108
 
103
109
  ## Rules
104
110
 
@@ -134,6 +140,7 @@ export function agentFiles(site) {
134
140
  'GEMINI.md': '@AGENTS.md\n',
135
141
  '.codex/config.toml': CODEX_TOML,
136
142
  [PAGE_SKILL_PATH]: PAGE_SKILL,
143
+ [COMPONENTS_SKILL_PATH]: COMPONENTS_SKILL,
137
144
  ...MCP_FILES,
138
145
  };
139
146
  }
@@ -152,7 +159,7 @@ function missingHint(f) {
152
159
  if (f === TYPES_TSCONFIG_PATH)
153
160
  return `make sure it has "jsx": "preserve" and includes "sbuilder-env.d.ts" and "**/*.tsx"`;
154
161
  if (f === 'AGENTS.md')
155
- return `add this line near the top:\n${SKILL_POINTER}`;
162
+ return `add these lines near the top:\n${SKILL_POINTER}\n${COMPONENTS_POINTER}`;
156
163
  if (f === 'CLAUDE.md' || f === 'GEMINI.md')
157
164
  return 'add the line: @AGENTS.md';
158
165
  return 'delete it and run sb site agents to get the current text';
@@ -255,75 +262,306 @@ export async function types(o) {
255
262
  /** Writes every agent file with the keep-existing rule; returns how many were kept or refused. */
256
263
  export async function writeAgentFiles(dir, site, warn) {
257
264
  let kept = 0;
265
+ const wrote = {};
258
266
  for (const [f, text] of Object.entries(agentFiles(site))) {
259
267
  const note = await writeKept(dir, f, text);
260
268
  if (note) {
261
269
  warn(` ! ${note}`);
262
270
  kept++;
263
271
  }
272
+ else
273
+ wrote[f] = { sha256: sha256(text) };
264
274
  }
275
+ await recordAgentFiles(dir, wrote);
265
276
  return kept;
266
277
  }
278
+ /** The CI workflow sb site init writes: it pins the CLI too, so a refresh must reach it. */
279
+ export const WORKFLOW_PATH = '.github/workflows/sbuilder.yml';
267
280
  /**
268
- * `sb site agents` — the agent files for a repo made by an older sb (or one that lost them).
269
- * Never overwrites; a file that is there is kept with what it lacks.
281
+ * What `--refresh` and doctor's `agents` check look after: the agent files, plus the workflow —
282
+ * which, unlike them, is never re-created when absent (a repo may have dropped CI on purpose).
270
283
  */
271
- export async function agents(o) {
272
- const log = o.log ?? console.log;
273
- const warn = o.warn ?? console.error;
274
- let id;
284
+ const refreshSet = (site) => ({
285
+ ...agentFiles(site),
286
+ [WORKFLOW_PATH]: WORKFLOW,
287
+ });
288
+ const escapeRe = (t) => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
289
+ /** Whether `have` is a file the owner kept against exactly today's text (see AgentRecord.kept). */
290
+ const keptAgainst = (rec, have, text) => !!rec?.kept && rec.kept.sha256 === sha256(have) && rec.kept.text === sha256(text);
291
+ /**
292
+ * Where today's text goes beside an edited file: `<file>.new`, unless that holds something that is
293
+ * neither today's text nor sb's own earlier offer — then `<file>.new.2`, `.3`, … A path through a
294
+ * link is never chosen.
295
+ */
296
+ async function offerPath(dir, f, text, rec) {
297
+ for (let n = 1; n < 100; n++) {
298
+ const p = n === 1 ? `${f}.new` : `${f}.new.${n}`;
299
+ if (await linkOn(dir, p))
300
+ return undefined;
301
+ const there = await readText(join(dir, p));
302
+ if (there === undefined ||
303
+ there === text ||
304
+ (rec?.offered?.file === p && sha256(there) === rec.offered.sha256))
305
+ return p;
306
+ }
307
+ return undefined;
308
+ }
309
+ /**
310
+ * `sb site agents --refresh`: brings the agent files (and the CI workflow) to THIS CLI's text
311
+ * without clobbering an edit. The rule pull uses: a file is rewritten only while it still has the
312
+ * sha recorded when sb wrote it (re-checked at the rename, putIfStill). One edited since — or one
313
+ * sb never recorded (an older repo, the owner's own AGENTS.md) — is kept, and today's text is
314
+ * OFFERED beside it as `<file>.new`, named. Once the owner deletes that offer and keeps their file,
315
+ * the next refresh records it as KEPT and stops asking — until sb's own text changes again.
316
+ * Returns how many offers are open.
317
+ */
318
+ export async function refreshAgentFiles(dir, site, log, warn) {
319
+ const base = (await readManifest(dir)).agentFiles ?? {};
320
+ const recs = {};
321
+ let left = 0;
322
+ for (const [f, text] of Object.entries(refreshSet(site))) {
323
+ const rec = base[f];
324
+ const link = await linkOn(dir, f);
325
+ if (link) {
326
+ warn(` ! ${f}: ${link} is a symbolic link — not followed, nothing written.`);
327
+ left++;
328
+ continue;
329
+ }
330
+ const have = await readText(join(dir, f));
331
+ if (have === undefined && f === WORKFLOW_PATH)
332
+ continue; // CI dropped on purpose stays dropped
333
+ if (have === text) {
334
+ if (rec?.sha256 !== sha256(text) || rec.offered || rec.kept)
335
+ recs[f] = { sha256: sha256(text) };
336
+ continue;
337
+ }
338
+ if (have !== undefined && keptAgainst(rec, have, text))
339
+ continue;
340
+ const ours = have === undefined || (rec?.sha256 !== undefined && sha256(have) === rec.sha256);
341
+ if (ours && (await putIfStill(join(dir, f), have, text))) {
342
+ recs[f] = { sha256: sha256(text) };
343
+ log(have === undefined ? ` + ${f} (was missing)` : ` ↻ ${f}`);
344
+ continue;
345
+ }
346
+ const mine = have ?? '';
347
+ // `offered.file` comes from a committed file: only ever one of THIS file's own offer names.
348
+ const offer = rec?.offered;
349
+ const ownOffer = !!offer &&
350
+ typeof offer.file === 'string' &&
351
+ (offer.file === `${f}.new` ||
352
+ new RegExp(`^${escapeRe(f)}\\.new\\.\\d{1,2}$`).test(offer.file));
353
+ if (offer &&
354
+ ownOffer &&
355
+ offer.sha256 === sha256(text) &&
356
+ !(await linkOn(dir, offer.file)) &&
357
+ (await readText(join(dir, offer.file))) === undefined) {
358
+ // The owner read today's text, deleted the offer and kept theirs: that is the answer.
359
+ recs[f] = { ...rec, offered: undefined, kept: { sha256: sha256(mine), text: sha256(text) } };
360
+ log(` = ${f}: kept as yours (you removed ${offer.file}) — sb stops asking until its own text for it changes.`);
361
+ continue;
362
+ }
363
+ const at = await offerPath(dir, f, text, rec);
364
+ if (!at) {
365
+ warn(` ! ${f}: kept yours; no free ${f}.new name to put today's text in — nothing written.`);
366
+ left++;
367
+ continue;
368
+ }
369
+ if ((await readText(join(dir, at))) !== text)
370
+ await put(join(dir, at), text);
371
+ recs[f] = { ...rec, offered: { file: at, sha256: sha256(text) } };
372
+ warn(` ! ${f}: ${ours ? 'changed while refreshing' : rec?.sha256 ? 'edited since sb wrote it' : 'not written by this sb (no record of it)'} — kept yours; today's text is in ${at}. Merge it and delete ${at}; or delete ${at} to keep yours as it is.`);
373
+ left++;
374
+ }
375
+ await recordAgentFiles(dir, recs);
376
+ return left;
377
+ }
378
+ /** The repo's site as the agent files name it — from sb.json and .env — or undefined outside a site repo. */
379
+ export async function repoSite(dir) {
380
+ let id = '';
275
381
  try {
276
382
  id =
277
- JSON.parse(await readFile(join(o.dir, 'sb.json'), 'utf8')).siteId ??
383
+ JSON.parse(await readFile(join(dir, 'sb.json'), 'utf8')).siteId ??
278
384
  '';
279
385
  }
280
386
  catch {
281
387
  id = '';
282
388
  }
283
389
  if (!id)
284
- throw new SiteRefused(`${o.dir} is not a site repo (no sb.json with a siteId) — run sb site init.`);
285
- const env = parseEnv(await readFile(join(o.dir, '.env'), 'utf8').catch(() => ''));
286
- const kept = await writeAgentFiles(o.dir, {
390
+ return undefined;
391
+ const env = parseEnv(await readFile(join(dir, '.env'), 'utf8').catch(() => ''));
392
+ return {
287
393
  id,
288
- name: env.SB_SITE_NAME || basename(o.dir),
394
+ name: env.SB_SITE_NAME || basename(dir),
289
395
  slug: '',
290
396
  publicUrl: env.SB_STOREFRONT || undefined,
291
- }, warn);
292
- log(kept ? `Agent files written; ${kept} kept as they were.` : 'Agent files are up to date.');
397
+ };
398
+ }
399
+ /**
400
+ * Agent files (and the CI workflow) that differ from what this CLI writes (`stale`) or are not
401
+ * there (`missing`). A file the owner KEPT against today's text is neither; an absent workflow is
402
+ * not missing (CI may be off on purpose).
403
+ */
404
+ export async function agentDrift(dir) {
405
+ const site = await repoSite(dir);
406
+ if (!site)
407
+ return undefined;
408
+ const base = (await readManifest(dir).catch(() => undefined))?.agentFiles ?? {};
409
+ const out = { stale: [], missing: [] };
410
+ for (const [f, text] of Object.entries(refreshSet(site))) {
411
+ if (await linkOn(dir, f))
412
+ continue;
413
+ const have = await readText(join(dir, f));
414
+ if (have === undefined) {
415
+ if (f !== WORKFLOW_PATH)
416
+ out.missing.push(f);
417
+ }
418
+ else if (have !== text && !keptAgainst(base[f], have, text))
419
+ out.stale.push(f);
420
+ }
421
+ return out;
422
+ }
423
+ /**
424
+ * `sb site agents` — the agent files for a repo made by an older sb (or one that lost them).
425
+ * Without `--refresh` it never overwrites: a file that is there is kept with what it lacks.
426
+ */
427
+ export async function agents(o) {
428
+ const log = o.log ?? console.log;
429
+ const warn = o.warn ?? console.error;
430
+ const site = await repoSite(o.dir);
431
+ if (!site)
432
+ throw new SiteRefused(`${o.dir} is not a site repo (no sb.json with a siteId) — run sb site init.`);
433
+ if (o.refresh) {
434
+ const left = await refreshAgentFiles(o.dir, site, log, warn);
435
+ log(left
436
+ ? `Agent files refreshed; ${left} left beside yours as <file>.new to merge.`
437
+ : 'Agent files are up to date.');
438
+ return left ? 1 : 0;
439
+ }
440
+ const kept = await writeAgentFiles(o.dir, site, warn);
441
+ log(kept
442
+ ? `Agent files written; ${kept} kept as they were (sb site agents --refresh updates the ones sb wrote).`
443
+ : 'Agent files are up to date.');
293
444
  return 0;
294
445
  }
295
- function readme(site) {
446
+ /** Where the docs live; the CLI's own reference is served by the platform at /cli-docs. */
447
+ export const DOCS_URL = 'https://docs.sbuilder.io.vn';
448
+ /**
449
+ * The site repo's README: what a developer (or a teammate who cloned it) reads first. Every `sb …`
450
+ * it names is held to the dispatcher by tests/site-readme.test.ts.
451
+ */
452
+ export function readme(site, o) {
453
+ const editor = `${editorOrigin(o.api)}/editor/${encodeURIComponent(site.id)}`;
454
+ const links = [
455
+ ...(site.publicUrl ? [`[Live site](${site.publicUrl})`] : []),
456
+ `[Open in the editor](${editor})`,
457
+ `[Docs](${DOCS_URL})`,
458
+ `[CLI reference](${o.api}/cli-docs)`,
459
+ ].join(' · ');
460
+ const line = o.description?.trim().replace(/\s+/g, ' ') ||
461
+ 'A Store Builder site, kept as source: build it with an AI agent, review it as a git diff.';
296
462
  return `# ${site.name}
297
463
 
298
- The Store Builder site **${site.name}**${site.publicUrl ? ` (${site.publicUrl})` : ''}, as a repo.
464
+ ${line}
299
465
 
300
- ## Build it with an AI agent
466
+ ${links}
467
+ ${o.template ? `\nStarted from the **${o.template}** template.\n` : ''}
468
+ ## Quick start
301
469
 
302
- Open this folder in **Claude Code**, **Codex**, **Cursor**, **Gemini CLI** or **VS Code** and ask for what you want:
470
+ 1. **Install the CLI** — \`npm i -g @sbuilder/cli\` (or write \`npx @sbuilder/cli\` wherever this
471
+ README says \`sb\`).${o.keyed === false ? '' : " This repo's API key is already in `.env`."}
472
+ 2. **Open the folder in an AI agent** — Claude Code, Codex, Cursor, Gemini CLI or VS Code — and
473
+ approve the \`sbuilder\` tools the first time:
303
474
 
304
- claude "Làm trang chủ bán trà: ảnh lớn, bảng giá, form đặt hàng"
475
+ \`\`\`sh
476
+ claude "${EXAMPLE_PROMPT}"
477
+ \`\`\`
305
478
 
306
- The agent uses the Store Builder tools (approve the \`sbuilder\` server the first time), builds on
307
- the site's drafts, looks at what it built, and pulls the result into this repo. Nothing goes live
308
- until you publish.
479
+ 3. **Review and publish** — the agent pulls what it built into \`design/\`; read it with
480
+ \`git diff\`, then \`sb site publish --all\` when it should go live.
309
481
 
310
- ## Commands
482
+ A fresh clone has no \`.env\` (it is never committed): create a key in Settings → API keys and put
483
+ \`SB_TOKEN=wbk_…\` in \`.env\`.
311
484
 
312
- npx @sbuilder/cli site pull # take what was edited in the editor
313
- npx @sbuilder/cli site push # save your edits as drafts
314
- npx @sbuilder/cli site publish --all # make every page live
315
- npx @sbuilder/cli site code pull --dir code # Code Dock files (code push to send them back)
485
+ ## Build with an AI agent
316
486
 
317
- A page edited on both sides is never overwritten silently: the command names it and stops;
318
- \`--force\` picks a side. New pages are created in the editor (or by the agent), then pulled.
487
+ The agent edits the site's **drafts** through the Store Builder tools, looks at each section on
488
+ desktop and mobile, and pulls the result here. \`AGENTS.md\` holds its rules. Things to ask for:
319
489
 
320
- | Path | What it is |
490
+ - "${EXAMPLE_PROMPT}."
491
+ — *Add an FAQ to the homepage: five questions about shipping and returns.*
492
+ - "Làm một section bảng giá ba gói, gói giữa nổi bật nhất."
493
+ — *Make a pricing section with three plans, the middle one highlighted.*
494
+ - "Viết code component đếm ngược đến ngày khai trương và đặt nó dưới hero của trang chủ."
495
+ — *Write a countdown code component to our opening day and place it under the homepage hero.*
496
+ - "Xem trang chủ trên điện thoại và sửa những chỗ bị vỡ."
497
+ — *Check the homepage on a phone and fix whatever breaks.*
498
+
499
+ ## Project structure
500
+
501
+ \`\`\`
502
+ .
503
+ ├── design/
504
+ │ ├── pages/*.page.tsx one page's draft, as source: edit it, push it
505
+ │ ├── globals/ shared sections every page uses (header, footer…)
506
+ │ ├── overlays/ what renders over pages (the cart drawer, pop-ups)
507
+ │ ├── translations/ one <locale>.json per language
508
+ │ ├── theme.json colours and fonts (sent only with sb site push --theme)
509
+ │ └── sbuilder-env.d.ts types, so your editor completes and checks page files
510
+ ├── code/ Code Dock files: CSS and JS injected into pages
511
+ ├── components/ code components (sb site components init adds two examples)
512
+ ├── .claude/skills/ the page and components skills every agent reads
513
+ ├── AGENTS.md how an AI agent works here (CLAUDE.md and GEMINI.md import it)
514
+ ├── .mcp.json the Store Builder tools (also .cursor/, .vscode/, .gemini/, .codex/)
515
+ ├── .github/workflows/ the GitHub half of the two-way sync
516
+ ├── ${SITE_MANIFEST} what was last synced: commit it
517
+ ├── sb.json which site this repo is
518
+ └── .env this repo's API key: never committed
519
+ \`\`\`
520
+
521
+ Folders the site has nothing in yet appear on the first pull that brings something.
522
+
523
+ ## Commands
524
+
525
+ | Command | What it does |
321
526
  | --- | --- |
322
- | \`design/pages/*.page.tsx\` | One page's draft as source — edit it, push it |
323
- | \`code/\` | Code Dock files (CSS/JS injected into pages) |
324
- | \`${SITE_MANIFEST}\` | What was last synced — commit it |
325
- | \`.env\` | This repo's API key — never committed |
326
- | \`AGENTS.md\` | How an AI agent should work here (the page syntax is in \`.claude/skills/sbuilder-page/\`) |
527
+ | \`sb site pull\` | Take what was edited in the editor into \`design/\` |
528
+ | \`sb site push\` | Save your edited files as **drafts** (code components are uploaded first) |
529
+ | \`sb site status\` | What differs from the last sync (offline) |
530
+ | \`sb site dev\` | Watch \`design/\` and \`code/\`, push each save as a draft |
531
+ | \`sb site preview <file>\` | A link to the page's draft, rendered as a visitor sees it — nothing published |
532
+ | \`sb site publish <file>\` · \`--all\` | Make pages **live** |
533
+ | \`sb doctor\` | Check this machine and repo — including that every element sits where it may; every problem names its fix |
534
+ | \`sb site components init\` | Set the repo up for code components, with two examples |
535
+ | \`sb site components preview <Name>\` | Build one here and have the platform render it once |
536
+ | \`sb site code pull --dir code\` | Mirror the Code Dock files (\`sb site code push --dir code\` sends them back) |
537
+ | \`sb site agents --refresh\` | Bring the agent files to the CLI's current text; an edited one is kept |
538
+
539
+ ## How sync works
540
+
541
+ - **Drafts only.** \`sb site push\` and the agent change drafts; nothing is live until \`sb site publish\`.
542
+ - **Conflicts are never silent.** A page edited in the editor since your last pull is refused by
543
+ name, and pull keeps a page you both changed; \`--force\` picks a side, on purpose.
544
+ - **Derived fields are the platform's.** A code component's rendered HTML is made on every save;
545
+ one written into a page file is ignored, and push says so.
546
+ - **\`${SITE_MANIFEST}\` is the memory.** It records what was last synced, so edits on both sides
547
+ can be told apart. Commit it.
548
+
549
+ ## Deploy / publish
550
+
551
+ - **Publish:** \`sb site publish design/pages/index.page.tsx\` (named files) or \`sb site publish --all\`.
552
+ - **GitHub:** \`.github/workflows/sbuilder.yml\` saves every push to \`main\` as drafts, and every
553
+ 30 minutes runs \`npx @sbuilder/cli site pull\` and \`npx @sbuilder/cli site code pull --dir code\`
554
+ and commits what changed. *Run workflow* with **publish** ticked makes every page live. It needs
555
+ one secret:
556
+
557
+ \`\`\`sh
558
+ git init -b main && git add -A && git commit -m "From Store Builder" # if it is not a repo yet
559
+ gh repo create --private --source . --push
560
+ gh secret set SB_TOKEN # paste the SB_TOKEN value from .env
561
+ \`\`\`
562
+
563
+ - **Your own host:** \`sb site next\` makes this repo a Next.js app serving these pages with the
564
+ platform's renderer; \`sb site deploy --vercel\` puts it on Vercel.
327
565
  `;
328
566
  }
329
567
  async function getJSON(o, url, init = {}) {
@@ -379,29 +617,39 @@ async function mintKey(o, siteId) {
379
617
  const envLine = (k, v) => `${k}=${/[\s#"']/.test(v) ? JSON.stringify(v) : v}`;
380
618
  /** The non-agent files init writes; a link under any of them is refused before the key is minted. */
381
619
  const INIT_FILES = ['.env', '.gitignore', 'README.md', 'sb.json', '.github/workflows/sbuilder.yml'];
382
- export async function initSite(o) {
383
- const log = o.log ?? console.log;
384
- const warn = o.warn ?? log;
385
- if (!o.token)
386
- throw new SiteRefused(SITE_UNAUTHORIZED);
387
- const isKey = typeof o.token === 'string' && o.token.startsWith('wbk_');
388
- if (isKey && !o.site) {
389
- throw new SiteRefused('An API key does not list sites; pass --site <id> (the key’s own site).');
390
- }
391
- const existing = await readdir(o.dir).catch(() => []);
620
+ /**
621
+ * What `sb site init` refuses before it creates anything: a folder that is already a site repo, a
622
+ * symbolic link where init writes, an existing `.env`. Exported so a caller that creates a site
623
+ * FIRST (a template copy) runs it before, and never leaves a site behind for a folder init refuses.
624
+ */
625
+ export async function checkInitFolder(dir) {
626
+ const existing = await readdir(dir).catch(() => []);
392
627
  const clash = ['sb.json', SITE_MANIFEST, 'design'].filter((f) => existing.includes(f));
393
628
  if (clash.length) {
394
- throw new SiteRefused(`${o.dir} already has ${clash.join(', ')} — run sb site pull there instead.`);
629
+ throw new SiteRefused(`${dir} already has ${clash.join(', ')} — run sb site pull there instead.`);
395
630
  }
396
631
  // Refused BEFORE a key is minted: a link in the way (.env -> docs/key.txt, .github -> elsewhere)
397
632
  // would carry the key, or this repo's files, out of the folder and into git.
398
633
  for (const f of INIT_FILES) {
399
- const link = await linkOn(o.dir, f);
634
+ const link = await linkOn(dir, f);
400
635
  if (link)
401
- throw new SiteRefused(`${o.dir}/${link} is a symbolic link — refusing to write ${f} through it. Remove the link and run again; nothing was created.`);
636
+ throw new SiteRefused(`${dir}/${link} is a symbolic link — refusing to write ${f} through it. Remove the link and run again; nothing was created.`);
402
637
  }
403
638
  if (existing.includes('.env'))
404
- throw new SiteRefused(`${o.dir} already has a .env — move it aside; init writes this repo's key there.`);
639
+ throw new SiteRefused(`${dir} already has a .env — move it aside; init writes this repo's key there.`);
640
+ // Whether init will be the only author of what is here: gitStart commits only then.
641
+ return { empty: existing.length === 0 };
642
+ }
643
+ export async function initSite(o) {
644
+ const log = o.log ?? console.log;
645
+ const warn = o.warn ?? log;
646
+ if (!o.token)
647
+ throw new SiteRefused(SITE_UNAUTHORIZED);
648
+ const isKey = typeof o.token === 'string' && o.token.startsWith('wbk_');
649
+ if (isKey && !o.site) {
650
+ throw new SiteRefused('An API key does not list sites; pass --site <id> (the key’s own site).');
651
+ }
652
+ await checkInitFolder(o.dir);
405
653
  const site = isKey
406
654
  ? { id: o.site, name: basename(o.dir), slug: '' }
407
655
  : await chooseSite(o);
@@ -432,8 +680,13 @@ export async function initSite(o) {
432
680
  'sb.json': JSON.stringify({ siteId: site.id }, null, 2) + '\n',
433
681
  '.gitignore': 'node_modules\n.env\n',
434
682
  '.env': env + '\n',
435
- 'README.md': readme(site),
436
- '.github/workflows/sbuilder.yml': WORKFLOW,
683
+ 'README.md': readme(site, {
684
+ api: o.api,
685
+ description: o.description,
686
+ template: o.template,
687
+ keyed: !!key,
688
+ }),
689
+ [WORKFLOW_PATH]: WORKFLOW,
437
690
  };
438
691
  // A cloned folder's own .gitignore and README are the owner's: replacing the ignore file
439
692
  // would un-hide whatever it hid (.env.local, credentials…) right before `git add -A`.
@@ -460,13 +713,20 @@ export async function initSite(o) {
460
713
  });
461
714
  }
462
715
  await writeAgentFiles(o.dir, site, warn);
716
+ // The workflow pins the CLI: recorded, so `sb site agents --refresh` may move it later.
717
+ if (files[WORKFLOW_PATH] !== undefined)
718
+ await recordAgentFiles(o.dir, { [WORKFLOW_PATH]: { sha256: sha256(WORKFLOW) } });
463
719
  await writeTypeFiles(o.dir, warn, log);
464
720
  log(`Pulling ${site.name} into ${o.dir}`);
465
- const code = await pull({ api: o.api, token: o.token, dir: o.dir, site: site.id, log, warn });
721
+ // With the repo's own key when one was minted: a browser session reaches only the pages, so the
722
+ // shared sections, overlays, theme and translations would wait for the first `sb site pull` —
723
+ // which then rewrote `.sb-site.json` in a repo nobody had touched.
724
+ const token = key || o.token;
725
+ const code = await pull({ api: o.api, token, dir: o.dir, site: site.id, log, warn });
466
726
  try {
467
727
  await codePull({
468
728
  api: o.api,
469
- token: o.token,
729
+ token,
470
730
  dir: join(o.dir, 'code'),
471
731
  site: site.id,
472
732
  cwd: o.dir,
@@ -499,24 +759,71 @@ export async function initSite(o) {
499
759
  }
500
760
  return { code, site, keyed: !!key };
501
761
  }
502
- /** The words after init: how to start building, on whatever this machine has. */
503
- export function nextSteps(dir, github) {
504
- const out = ['', 'Next:', ` cd ${dir}`];
505
- out.push(' claude "Làm trang chủ bán trà: ảnh lớn, bảng giá, form đặt hàng"');
506
- out.push(' (or open the folder in Codex / Cursor / Gemini CLI / VS Code — the Store Builder tools are set up)');
507
- out.push(' Codex: trust the folder once, so it reads .codex/config.toml');
508
- if (!github) {
509
- out.push('', 'To keep it on GitHub, synced both ways:');
510
- out.push(' git init -b main && git add -A && git commit -m "From Store Builder"');
511
- out.push(' gh repo create --private --source . --push');
512
- out.push(' gh secret set SB_TOKEN # paste the SB_TOKEN value from .env');
513
- out.push(' (next time, sb site init <dir> --github does all of this)');
514
- }
515
- return out;
762
+ const realGit = (args, cwd) => {
763
+ const r = spawnSync('git', args, { cwd, encoding: 'utf8' });
764
+ return {
765
+ status: r.status,
766
+ stderr: r.stderr ?? '',
767
+ missing: r.error?.code === 'ENOENT',
768
+ };
769
+ };
770
+ /**
771
+ * Makes a fresh site repo a git repo with a first commit — so "review it as a git diff" is true from
772
+ * the first agent edit. Only where the folder is not inside a git repo already, and only when git is
773
+ * installed; a commit git refuses (no user.name yet) leaves the repo initialised and says why.
774
+ * Returns the line to print. `.env` is git-ignored before this runs (init writes .gitignore first).
775
+ */
776
+ export function gitStart(dir, name, o, git = realGit) {
777
+ const inside = git(['rev-parse', '--is-inside-work-tree'], dir);
778
+ if (inside.missing)
779
+ return 'git is not installed: install it and run git init here, so every change can be reviewed as a diff.';
780
+ if (inside.status === 0)
781
+ return 'This folder is already in a git repo: review what init wrote with git status.';
782
+ const init = git(['init', '-b', 'main'], dir);
783
+ if (init.status !== 0)
784
+ return `git init failed (${init.stderr.trim()}) — run it yourself to review changes as diffs.`;
785
+ // A folder that held files before init is the owner's: commit nothing of it (a credentials file,
786
+ // a draft) on their behalf. Only a folder init filled from empty gets the first commit.
787
+ if (!o.empty)
788
+ return 'Started a git repo here. The folder already had files, so nothing was committed: check git status, then commit what belongs in the repo.';
789
+ git(['add', '-A'], dir);
790
+ const commit = git(['commit', '-q', '-m', `${name}, from Store Builder`], dir);
791
+ if (commit.status !== 0)
792
+ return `Started a git repo here; the first commit failed (${commit.stderr.trim().split('\n')[0]}) — set git config user.name and user.email, then git commit.`;
793
+ return 'Started a git repo here with a first commit: every later pull or agent edit shows as a git diff.';
794
+ }
795
+ /** The example prompt the README and the words after init both start with. */
796
+ export const EXAMPLE_PROMPT = 'Thêm mục Câu hỏi thường gặp vào trang chủ: 5 câu về giao hàng và đổi trả';
797
+ /**
798
+ * The words after init, short like create-next-app's: where it is, then cd, npm install when the
799
+ * folder has a package.json, one agent prompt, the docs. Everything else is in the repo's README.
800
+ */
801
+ export function nextSteps(o) {
802
+ const quoted = `'${(o.prompt ?? EXAMPLE_PROMPT).replace(/'/g, `'\\''`)}'`;
803
+ return [
804
+ '',
805
+ o.ok === false
806
+ ? `${o.name} is in ${o.dir}, but not everything came across — fix what is named above, then run sb site pull there.`
807
+ : `Success! ${o.name} is in ${o.dir}${o.github ? ', synced with its GitHub repo' : ''}.`,
808
+ '',
809
+ 'Next:',
810
+ ` cd ${o.dir}`,
811
+ ...(o.npm ? [' npm install'] : []),
812
+ ` claude ${quoted}`,
813
+ '',
814
+ 'Any agent works: Codex, Cursor, Gemini CLI and VS Code see the Store Builder tools too',
815
+ '(approve "sbuilder" once; Codex: trust the folder once). Nothing goes live until you publish.',
816
+ ...(o.github ? [] : ['To sync it with GitHub: README.md, "Deploy / publish".']),
817
+ `Docs: ${DOCS_URL}`,
818
+ ];
516
819
  }
517
- /** The prompt an agent starts with when the site was described in the menu. */
518
- export function buildPrompt(description) {
519
- return (`Build this website on Store Builder: "${description}". ` +
820
+ /** The prompt an agent starts with when the site was described (and maybe copied from a template). */
821
+ export function buildPrompt(description, template) {
822
+ const what = template
823
+ ? `This Store Builder site was copied from the "${template}" template. Adapt it to: "${description}" — ` +
824
+ "keep the design, replace the template's copy, images and sections that do not fit. "
825
+ : `Build this website on Store Builder: "${description}". `;
826
+ return (what +
520
827
  'Follow AGENTS.md — build each section with the sbuilder tools, look at it on desktop and ' +
521
828
  'mobile, fix what you see, then pull the result into this repo. Ask me for any real facts ' +
522
829
  '(phone, address, prices) you need. Do not publish.');