@sbuilder/cli 0.9.1 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +302 -6
  2. package/README.vi.md +296 -7
  3. package/dist/bin/sb.js +190 -6
  4. package/dist/bin/sb.js.map +1 -1
  5. package/dist/src/agentdocs.js +12 -3
  6. package/dist/src/agentdocs.js.map +1 -1
  7. package/dist/src/components.js +574 -0
  8. package/dist/src/components.js.map +1 -0
  9. package/dist/src/doctor.js +520 -0
  10. package/dist/src/doctor.js.map +1 -0
  11. package/dist/src/envtypes.gen.js +1761 -0
  12. package/dist/src/envtypes.gen.js.map +1 -0
  13. package/dist/src/host.js +414 -22
  14. package/dist/src/host.js.map +1 -1
  15. package/dist/src/hostlink.js +161 -0
  16. package/dist/src/hostlink.js.map +1 -0
  17. package/dist/src/login.js +1 -1
  18. package/dist/src/login.js.map +1 -1
  19. package/dist/src/next.js +82 -6
  20. package/dist/src/next.js.map +1 -1
  21. package/dist/src/repo.js +24 -2
  22. package/dist/src/repo.js.map +1 -1
  23. package/dist/src/roottsconfig.js +154 -0
  24. package/dist/src/roottsconfig.js.map +1 -0
  25. package/dist/src/route.js +18 -1
  26. package/dist/src/route.js.map +1 -1
  27. package/dist/src/site.js +621 -71
  28. package/dist/src/site.js.map +1 -1
  29. package/dist/src/sitedev.js +99 -0
  30. package/dist/src/sitedev.js.map +1 -0
  31. package/dist/src/siteinit.js +76 -0
  32. package/dist/src/siteinit.js.map +1 -1
  33. package/dist/src/sitekinds.js +1048 -0
  34. package/dist/src/sitekinds.js.map +1 -0
  35. package/dist/src/sitepaths.js +12 -0
  36. package/dist/src/sitepaths.js.map +1 -0
  37. package/dist/src/sitestatus.js +104 -0
  38. package/dist/src/sitestatus.js.map +1 -0
  39. package/dist/src/source/meta.js +118 -0
  40. package/dist/src/source/meta.js.map +1 -0
  41. package/dist/src/source/parse.js +21 -2
  42. package/dist/src/source/parse.js.map +1 -1
  43. package/dist/src/starter.js +61 -0
  44. package/dist/src/starter.js.map +1 -0
  45. package/dist/src/vercel.js +379 -0
  46. package/dist/src/vercel.js.map +1 -0
  47. package/package.json +9 -1
  48. package/dist/src/export.js +0 -167
  49. package/dist/src/export.js.map +0 -1
package/dist/src/site.js CHANGED
@@ -1,12 +1,19 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { lstat, mkdir, readdir, readFile, rename, writeFile } from 'node:fs/promises';
2
+ import { lstat, mkdir, readdir, readFile, rename, stat, writeFile } from 'node:fs/promises';
3
3
  import { dirname, join } from 'node:path';
4
4
  import { authedFetch, SB_TOKEN_REFUSED } from './auth.js';
5
5
  import { sbJsonSite } from './code.js';
6
6
  import { APP_BLOCK_EDITED, appBlockSeals, editedAppBlocks } from './appblocks.js';
7
7
  import { DevError, messageOf } from './dev.js';
8
- import { parsePage, SourceError } from './source/parse.js';
9
- import { literal, printPage, tagFor } from './source/print.js';
8
+ import { pushComponents } from './components.js';
9
+ import { parseFile, printFile } from './source/meta.js';
10
+ import { pullKinds, pushKinds } from './sitekinds.js';
11
+ import { staleTranslations } from './sitestatus.js';
12
+ import { SAFE_FILE, SAFE_KIND_FILE } from './sitepaths.js';
13
+ export { SAFE_FILE, SAFE_KIND_FILE };
14
+ import { SourceError } from './source/parse.js';
15
+ import { tagFor } from './source/print.js';
16
+ import { isDeepStrictEqual } from 'node:util';
10
17
  /**
11
18
  * `sb site pull` / `sb site push` — a site's page DRAFTS as `.page.tsx` files in a repo.
12
19
  *
@@ -22,9 +29,15 @@ import { literal, printPage, tagFor } from './source/print.js';
22
29
  * a page someone edited in the editor since. Neither side is ever overwritten
23
30
  * silently — a clash is named, and `--force` is the deliberate way past it.
24
31
  *
25
- * Pages are never created or deleted from here: a file with no manifest entry is
26
- * reported, and a page deleted on the platform keeps its file. Deleting something
27
- * a merchant still depends on is a decision, not a sync side effect.
32
+ * `export const page = { name, slug, type, isHomepage, settings }` in a page file is
33
+ * AUTHORITATIVE: a file with one and no manifest entry creates the page, and a changed
34
+ * field renames or re-types it. Deletion never happens by itself: a tracked file that is
35
+ * gone is reported, and only `--prune` (plus `--yes` off a terminal) deletes the page.
36
+ * A page deleted on the platform keeps its file. Deleting something a merchant still
37
+ * depends on is a decision, not a sync side effect.
38
+ *
39
+ * After a save the file is rewritten to what the platform stored (ids it minted, the
40
+ * facts it settled on), so the next pull has nothing to change.
28
41
  */
29
42
  export const SITE_MANIFEST = '.sb-site.json';
30
43
  export const PAGES_DIR = 'design/pages';
@@ -33,20 +46,32 @@ export class SiteRefused extends DevError {
33
46
  export const SITE_UNAUTHORIZED = 'Not signed in, or the token was refused (expired or revoked). Run `sb login`, or set SB_TOKEN ' +
34
47
  'to an API key (wbk_…) with pages.read / pages.write from Settings -> API keys.';
35
48
  export const SITE_NO_SITE = 'Which site? Pass --site <id>, or add "siteId" to sb.json. (An API key (wbk_…) in SB_TOKEN implies its site.)';
36
- const sha256 = (s) => createHash('sha256').update(s, 'utf8').digest('hex');
49
+ const factsOf = (p) => ({
50
+ name: p.name,
51
+ slug: p.slug ?? '',
52
+ type: p.type,
53
+ isHomepage: p.isHomepage === true,
54
+ defaultTemplate: p.isDefaultTemplate === true,
55
+ settings: p.settings && typeof p.settings === 'object' ? p.settings : {},
56
+ });
57
+ /** The text of `export const page`: empty settings and a false default are left out. */
58
+ const metaOf = (id, path, f) => ({
59
+ id,
60
+ path,
61
+ name: f.name,
62
+ slug: f.slug,
63
+ type: f.type,
64
+ isHomepage: f.isHomepage,
65
+ ...(f.defaultTemplate ? { defaultTemplate: true } : {}),
66
+ ...(Object.keys(f.settings).length ? { settings: f.settings } : {}),
67
+ });
68
+ export const sha256 = (s) => createHash('sha256').update(s, 'utf8').digest('hex');
37
69
  /**
38
70
  * A page file: the document as `.page.tsx` (cli/src/source, SKILL sbuilder-site-source),
39
- * plus the page's own facts for the reader. `page` is information only — renaming or
40
- * moving a page happens in the editor; the parser ignores this export.
71
+ * plus the page's own facts, which push reads back (`export const page`).
41
72
  */
42
- const fileText = (p, d) => printPage(d.document) +
43
- `\n// Information only: rename or move the page in the editor.\nexport const page = ${literal({
44
- id: p.id,
45
- name: p.name,
46
- path: p.path,
47
- type: p.type,
48
- })};\n`;
49
- async function readText(path) {
73
+ const fileText = (id, path, f, doc) => printFile('page', doc, metaOf(id, path, f));
74
+ export async function readText(path) {
50
75
  try {
51
76
  return await readFile(path, 'utf8');
52
77
  }
@@ -56,7 +81,7 @@ async function readText(path) {
56
81
  throw err;
57
82
  }
58
83
  }
59
- async function put(path, text) {
84
+ export async function put(path, text) {
60
85
  await mkdir(dirname(path), { recursive: true });
61
86
  const tmp = `${path}.${process.pid}.tmp`;
62
87
  await writeFile(tmp, text, 'utf8');
@@ -80,7 +105,27 @@ export async function readManifest(dir) {
80
105
  throw new SiteRefused(`${SITE_MANIFEST} names ${JSON.stringify(e?.file)}, which is not a file in ${PAGES_DIR}/ — nothing was read or sent.`);
81
106
  }
82
107
  }
83
- return { siteId: m.siteId ?? null, pages: m.pages ?? {} };
108
+ const named = [
109
+ ['globals', SAFE_KIND_FILE.globals, 'design/globals/'],
110
+ ['overlays', SAFE_KIND_FILE.overlays, 'design/overlays/'],
111
+ ['translations', SAFE_KIND_FILE.translations, 'design/translations/<locale>.json'],
112
+ ];
113
+ for (const [k, re, where] of named) {
114
+ for (const e of Object.values(m[k] ?? {})) {
115
+ if (!re.test(String(e?.file)))
116
+ throw new SiteRefused(`${SITE_MANIFEST} names ${JSON.stringify(e?.file)}, which is not a file in ${where} — nothing was read or sent.`);
117
+ }
118
+ }
119
+ if (m.theme && !SAFE_KIND_FILE.theme.test(String(m.theme.file)))
120
+ throw new SiteRefused(`${SITE_MANIFEST} names ${JSON.stringify(m.theme.file)}, which is not design/theme.json — nothing was read or sent.`);
121
+ return {
122
+ siteId: m.siteId ?? null,
123
+ pages: m.pages ?? {},
124
+ ...(m.globals ? { globals: m.globals } : {}),
125
+ ...(m.overlays ? { overlays: m.overlays } : {}),
126
+ ...(m.theme ? { theme: m.theme } : {}),
127
+ ...(m.translations ? { translations: m.translations } : {}),
128
+ };
84
129
  }
85
130
  /**
86
131
  * A symbolic link anywhere on a page file's path, or undefined. The name check
@@ -96,10 +141,8 @@ export async function linkOn(dir, file) {
96
141
  }
97
142
  return undefined;
98
143
  }
99
- /** A page file this command may touch: one name, directly in design/pages, no dot first. */
100
- const SAFE_FILE = /^design\/pages\/[A-Za-z0-9_-][A-Za-z0-9._-]*\.page\.tsx$/;
101
- const saveManifest = (ctx) => put(join(ctx.dir, SITE_MANIFEST), JSON.stringify(ctx.manifest, null, 2) + '\n');
102
- async function open(o) {
144
+ export const saveManifest = (ctx) => put(join(ctx.dir, SITE_MANIFEST), JSON.stringify(ctx.manifest, null, 2) + '\n');
145
+ export async function open(o) {
103
146
  const cred = o.token;
104
147
  if (!cred)
105
148
  throw new SiteRefused(SITE_UNAUTHORIZED);
@@ -128,14 +171,19 @@ async function open(o) {
128
171
  manifest,
129
172
  log,
130
173
  warn: o.warn ?? log,
174
+ o,
131
175
  };
132
176
  }
133
- async function send(ctx, url, method, body) {
177
+ export async function send(ctx, url, method, body, headers) {
134
178
  let res;
135
179
  try {
136
180
  res = await authedFetch(url, body === undefined
137
- ? { method }
138
- : { method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }, ctx.cred);
181
+ ? { method, ...(headers ? { headers } : {}) }
182
+ : {
183
+ method,
184
+ headers: { 'Content-Type': 'application/json', ...headers },
185
+ body: JSON.stringify(body),
186
+ }, ctx.cred);
139
187
  }
140
188
  catch (err) {
141
189
  if (err instanceof DevError)
@@ -146,7 +194,7 @@ async function send(ctx, url, method, body) {
146
194
  throw new SiteRefused(SITE_UNAUTHORIZED);
147
195
  return res;
148
196
  }
149
- async function errorOf(res) {
197
+ export async function errorOf(res) {
150
198
  try {
151
199
  return (await res.json());
152
200
  }
@@ -210,7 +258,10 @@ export async function pull(o) {
210
258
  if (!draft)
211
259
  continue; // a page with no draft yet has nothing to hold
212
260
  const entry = ctx.manifest.pages[p.id];
213
- if (entry && entry.rev === draft.rev) {
261
+ const facts = factsOf(p);
262
+ // A page synced before facts were recorded has no base for them: it is NOT "unchanged" — the
263
+ // file is rewritten from the platform (or kept and named if you edited it), which records them.
264
+ if (entry && entry.rev === draft.rev && entry.page && isDeepStrictEqual(entry.page, facts)) {
214
265
  // The draft has not moved, but the page may have been re-pathed in the editor.
215
266
  if (entry.path !== p.path && !o.dryRun) {
216
267
  entry.path = p.path;
@@ -231,12 +282,15 @@ export async function pull(o) {
231
282
  clashes++;
232
283
  continue;
233
284
  }
234
- if (!entry && local !== undefined && local !== fileText(p, draft) && !o.force) {
285
+ if (!entry &&
286
+ local !== undefined &&
287
+ local !== fileText(p.id, p.path, facts, draft.document) &&
288
+ !o.force) {
235
289
  ctx.warn(` ! ${file}: already exists and is not tracked — kept it. Move it aside, or --force.`);
236
290
  clashes++;
237
291
  continue;
238
292
  }
239
- const text = fileText(p, draft);
293
+ const text = fileText(p.id, p.path, facts, draft.document);
240
294
  if (!o.dryRun) {
241
295
  await put(join(ctx.dir, file), text);
242
296
  ctx.manifest.pages[p.id] = {
@@ -245,6 +299,7 @@ export async function pull(o) {
245
299
  sha256: sha256(text),
246
300
  schemaVersion: draft.schemaVersion,
247
301
  path: p.path,
302
+ page: facts,
248
303
  appBlocks: appBlockSeals(draft.document),
249
304
  };
250
305
  await saveManifest(ctx);
@@ -263,76 +318,340 @@ export async function pull(o) {
263
318
  if (!o.dryRun)
264
319
  await saveManifest(ctx);
265
320
  ctx.log(`${wrote} page(s) ${o.dryRun ? 'would be ' : ''}pulled${clashes ? `, ${clashes} kept` : ''}.`);
266
- return clashes ? 1 : 0;
321
+ const more = await pullKinds(ctx);
322
+ for (const line of await staleTranslations(ctx.dir))
323
+ ctx.warn(` ~ STALE ${line}`);
324
+ if (more.wrote || more.clashes)
325
+ ctx.log(`${more.wrote} other file(s) ${o.dryRun ? 'would be ' : ''}pulled${more.clashes ? `, ${more.clashes} kept` : ''}.`);
326
+ return clashes || more.clashes ? 1 : 0;
267
327
  }
268
- export async function push(o) {
269
- const ctx = await open(o);
270
- const tracked = new Set(Object.values(ctx.manifest.pages).map((e) => e.file));
271
- let failed = 0;
272
- let sent = 0;
273
- for (const [id, entry] of Object.entries(ctx.manifest.pages)) {
274
- const link = await linkOn(ctx.dir, entry.file);
275
- if (link) {
276
- ctx.warn(` ! ${entry.file}: ${link} is a symbolic link — not followed, nothing sent.`);
277
- failed++;
278
- continue;
328
+ /** The platform's answer to a page write: `{ page: {…} }` on both surfaces. */
329
+ const pageOf = async (res) => (await res.json()).page;
330
+ export const refusal = (err) => `${err.code ? `${err.code}: ` : ''}${err.error}`;
331
+ const ABSENT = Symbol('absent');
332
+ const isPlain = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
333
+ const sameV = (a, b) => a === ABSENT || b === ABSENT ? a === b : isDeepStrictEqual(a, b);
334
+ const at = (o, k) => (k in o ? o[k] : ABSENT);
335
+ /**
336
+ * The three-way merge of the page's `settings` (its SEO blob), PER KEY, recursively over plain
337
+ * objects — arrays and scalars are leaves, and a key added or removed is a change of that key.
338
+ * A SEO title edited in the editor and a description edited in the file therefore both survive.
339
+ *
340
+ * merged what to send: ours where only ours changed, theirs where only theirs changed
341
+ * held what the FILE will hold afterwards: the same, but a key only the editor changed keeps its
342
+ * base value (it reaches the file only through the rewrite — see the base-advance rule)
343
+ * conflicts `settings.seo.title`-style paths changed to different values on both sides
344
+ */
345
+ export function mergeSettings(base, ours, theirs, force) {
346
+ const conflicts = [];
347
+ const three = (b, o, t, path) => {
348
+ if (sameV(o, b))
349
+ return [t, b]; // ours did not change it: the platform's value stands
350
+ if (sameV(t, b) || sameV(o, t))
351
+ return [o, o]; // only ours changed, or both made the same change
352
+ if (isPlain(o) && isPlain(t) && (isPlain(b) || b === ABSENT)) {
353
+ const bb = isPlain(b) ? b : {};
354
+ const m = {};
355
+ const h = {};
356
+ for (const k of new Set([...Object.keys(bb), ...Object.keys(o), ...Object.keys(t)])) {
357
+ const [mv, hv] = three(at(bb, k), at(o, k), at(t, k), `${path}.${k}`);
358
+ if (mv !== ABSENT)
359
+ m[k] = mv;
360
+ if (hv !== ABSENT)
361
+ h[k] = hv;
362
+ }
363
+ return [m, h];
279
364
  }
280
- const text = await readText(join(ctx.dir, entry.file));
281
- if (text === undefined) {
282
- ctx.warn(` ! ${entry.file}: missing — pages are not deleted from here; delete the page in the editor.`);
283
- failed++;
365
+ if (!force)
366
+ conflicts.push(path);
367
+ return force ? [o, o] : [t, b];
368
+ };
369
+ const [merged, held] = three(base, ours, theirs, 'settings');
370
+ return { merged, held, conflicts };
371
+ }
372
+ const FACT_KEYS = ['name', 'slug', 'type', 'isHomepage', 'settings', 'defaultTemplate'];
373
+ /**
374
+ * Three-way, per fact, like the document: `base` is what was last synced, `meta` is the file
375
+ * (ours), `theirs` is the platform now. Only ours changed → send it; only theirs changed → leave
376
+ * it (it is recorded and the file takes it); both changed to the same value → nothing; both
377
+ * changed differently → a conflict, unless `force` picks the file.
378
+ *
379
+ * A key the file does not state is not a change (printing omits an empty `settings` and a false
380
+ * `defaultTemplate`); a default template can be set but not unset — make another page it.
381
+ */
382
+ export function mergeFacts(meta, base, theirs, force, warn) {
383
+ const send = {};
384
+ const conflicts = [];
385
+ const held = {};
386
+ if (!meta)
387
+ return { send, conflicts, held };
388
+ if (meta.defaultTemplate === false && base.defaultTemplate)
389
+ warn(' ! defaultTemplate cannot be switched off — make another page of this type the default.');
390
+ for (const k of FACT_KEYS) {
391
+ if (k === 'settings') {
392
+ // One fact per KEY inside it, not one fact for the whole blob.
393
+ if (!('settings' in meta) || !isPlain(meta.settings))
394
+ continue;
395
+ const m = mergeSettings(base.settings, meta.settings, theirs.settings, force);
396
+ conflicts.push(...m.conflicts);
397
+ held.settings = m.held;
398
+ if (!isDeepStrictEqual(m.merged, theirs.settings))
399
+ send.settings = m.merged;
284
400
  continue;
285
401
  }
286
- const sha = sha256(text);
287
- if (sha === entry.sha256)
402
+ const ours = meta[k];
403
+ const changed = k === 'defaultTemplate'
404
+ ? ours === true && !base[k]
405
+ : k in meta && !isDeepStrictEqual(ours, base[k]);
406
+ if (!changed || isDeepStrictEqual(ours, theirs[k]))
288
407
  continue;
289
- let document;
290
- try {
291
- document = parsePage(text);
292
- }
293
- catch (err) {
294
- // file:line:col — clickable in a terminal and in an editor's problem matcher.
295
- ctx.warn(err instanceof SourceError
296
- ? ` ! ${entry.file}:${err.message} — nothing sent.`
297
- : ` ! ${entry.file}: ${messageOf(err)} — nothing sent.`);
298
- failed++;
408
+ if (force || isDeepStrictEqual(theirs[k], base[k]))
409
+ send[k] = ours;
410
+ else
411
+ conflicts.push(k);
412
+ }
413
+ return { send, conflicts, held };
414
+ }
415
+ /**
416
+ * The file's facts when nothing records the last sync: any fact it states differently from the
417
+ * platform is a conflict (--force sends it). Equal facts are fine; absent ones are left alone.
418
+ */
419
+ export function unrecordedFacts(meta, now, force) {
420
+ const send = {};
421
+ const conflicts = [];
422
+ for (const k of FACT_KEYS) {
423
+ if (!meta || !(k in meta))
424
+ continue;
425
+ if (k === 'defaultTemplate' ? meta[k] !== true || now[k] : isDeepStrictEqual(meta[k], now[k]))
299
426
  continue;
427
+ if (force)
428
+ send[k] = meta[k];
429
+ else
430
+ conflicts.push(k);
431
+ }
432
+ return { send, conflicts };
433
+ }
434
+ /**
435
+ * Rewrites `file` to `back` only if it still holds `seen` — the text this push read. A save made
436
+ * while the push was in flight (routine under `sb site dev`) is never overwritten; it is said, and
437
+ * it goes up on the next push. True when the file holds `back` now.
438
+ */
439
+ export async function writeBack(ctx, file, seen, back) {
440
+ if (back === seen)
441
+ return true;
442
+ if ((await readText(join(ctx.dir, file))) !== seen) {
443
+ ctx.warn(` ! ${file}: changed while it was being pushed — not rewritten; the newer save goes up on the next push (elements in it without an id get new ids then).`);
444
+ return false;
445
+ }
446
+ await put(join(ctx.dir, file), back);
447
+ return true;
448
+ }
449
+ /** What the platform settled on is not always what was asked (a slug is de-duplicated): say so. */
450
+ function verifyFacts(ctx, file, asked, got) {
451
+ const now = factsOf(got);
452
+ for (const [k, want] of Object.entries(asked))
453
+ if (!isDeepStrictEqual(now[k], want))
454
+ ctx.warn(` ! ${file}: asked ${k} ${JSON.stringify(want)}, the platform has ${JSON.stringify(now[k])}.`);
455
+ }
456
+ /** PATCH the changed facts (and the default template, which the session surface sets by PUT). */
457
+ async function sendFacts(ctx, id, file, changes,
458
+ /** The platform's facts as the three-way read them: sent as `base` (v1 only). */
459
+ seen,
460
+ /** On a --force retry: what to send against the page as it is NOW (the three-way, redone). */
461
+ refresh) {
462
+ const url = `${ctx.base}/pages/${encodeURIComponent(id)}`;
463
+ /**
464
+ * The v1 PATCH is fenced: `base` carries the value of each field being changed as this push read
465
+ * it, and the platform refuses (409 source_stale, naming the field) if it moved since — so an
466
+ * editor save landing between the read and the write is never overwritten. The session surface
467
+ * has no such fence.
468
+ */
469
+ const patchOf = (ch, b) => {
470
+ const { defaultTemplate, ...patch } = ch;
471
+ const body = ctx.v1 && defaultTemplate ? { ...patch, defaultTemplate } : patch;
472
+ return ctx.v1 && b
473
+ ? {
474
+ ...body,
475
+ base: Object.fromEntries(['name', 'slug', 'type', 'isHomepage', 'settings']
476
+ .filter((f) => f in patch)
477
+ .map((f) => [f, b[f]])),
478
+ }
479
+ : body;
480
+ };
481
+ let sent = changes;
482
+ const { defaultTemplate } = changes;
483
+ const calls = [];
484
+ if (Object.keys(patchOf(changes)).length)
485
+ calls.push(['PATCH', url, patchOf(changes, seen)]);
486
+ // Only the session surface sets the default by its own route; v1 takes it in the PATCH.
487
+ if (!ctx.v1 && defaultTemplate)
488
+ calls.push(['PUT', `${url}/default-template`, undefined]);
489
+ let got;
490
+ for (const [method, to, payload] of calls) {
491
+ let res = await send(ctx, to, method, payload);
492
+ if (res.status === 409 && method === 'PATCH' && ctx.v1 && seen && ctx.o.force) {
493
+ // --force: re-read, REDO the merge against the page as it is now (so an editor save to a key
494
+ // the file did not touch survives), and send once more.
495
+ const fresh = await send(ctx, url, 'GET');
496
+ if (fresh.ok) {
497
+ const page = await pageOf(fresh);
498
+ sent = refresh ? refresh(factsOf(page)) : changes;
499
+ const body = patchOf(sent, factsOf(page));
500
+ if (Object.keys(body).length)
501
+ res = await send(ctx, to, method, body);
502
+ else
503
+ res = fresh; // nothing of the file's is left to send
504
+ }
300
505
  }
506
+ if (!res.ok) {
507
+ const err = await errorOf(res);
508
+ ctx.warn(err.code === 'source_stale' && err.details?.field
509
+ ? ` ! ${file}: ${err.details.field} changed in the editor while pushing — nothing sent. Pull to take the editor's, or sb site push --force to overwrite it.`
510
+ : ` ! ${file}: the page's facts were refused (${refusal(err)}) — nothing sent.`);
511
+ return undefined;
512
+ }
513
+ got = await pageOf(res);
514
+ }
515
+ if (got)
516
+ verifyFacts(ctx, file, sent, got);
517
+ return got;
518
+ }
519
+ export async function push(o) {
520
+ const ctx = await open(o);
521
+ const tracked = new Set(Object.values(ctx.manifest.pages).map((e) => e.file));
522
+ let failed = 0;
523
+ let sent = 0;
524
+ // Components go up BEFORE any page, so a page's pin always names a version that exists. A refused
525
+ // component fails the run but never stops the pages: they pin versions that were uploaded earlier.
526
+ // `sb site dev` sends named files only and never builds.
527
+ if (!o.only)
528
+ failed += (await pushComponents(ctx, o)).failed;
529
+ let listed;
530
+ const server = async () => (listed ??= await listPages(ctx));
531
+ /** Saves one page: its facts first (a refusal stops the file), then its document. */
532
+ async function savePage(id, entry, text, document, meta, created) {
301
533
  const edited = editedAppBlocks(document, entry.appBlocks);
302
534
  if (edited.length) {
303
535
  // Refused here, not on the server: the platform would save the page and quietly
304
536
  // drop the edit, which reads as success. --force does not change that outcome.
305
537
  ctx.warn(APP_BLOCK_EDITED(entry.file, edited));
306
538
  failed++;
307
- continue;
539
+ return;
540
+ }
541
+ // A page this push created or adopted (rev < 0) takes the platform's revision ONCE, now, and
542
+ // keeps it: a retry after a failed save then 409s if the editor moved meanwhile, instead of
543
+ // re-reading the current rev and overwriting the editor's edit.
544
+ if (!o.dryRun && entry.rev < 0) {
545
+ const draft = await getDraft(ctx, id);
546
+ entry.rev = draft?.rev ?? 0;
547
+ entry.schemaVersion = draft?.schemaVersion;
548
+ await saveManifest(ctx);
549
+ }
550
+ // Three-way per fact (mergeFacts): an edit made in the editor is neither undone by a file that
551
+ // never mentioned it nor overwritten by one that changed the same fact differently.
552
+ let theirs;
553
+ let settled;
554
+ let patched = false;
555
+ if (!created) {
556
+ const res = await send(ctx, `${ctx.base}/pages/${encodeURIComponent(id)}`, 'GET');
557
+ if (!res.ok && res.status !== 404) {
558
+ ctx.warn(` ! ${entry.file}: reading the page failed (${refusal(await errorOf(res))}) — nothing sent.`);
559
+ failed++;
560
+ return;
561
+ }
562
+ theirs = res.ok ? await pageOf(res) : undefined;
563
+ }
564
+ let changes = {};
565
+ let held = {};
566
+ if (theirs) {
567
+ const now = factsOf(theirs);
568
+ let conflicts;
569
+ if (entry.page)
570
+ ({ send: changes, conflicts, held } = mergeFacts(meta, entry.page, now, o.force, ctx.warn));
571
+ else {
572
+ // No record of the last sync (a manifest from before facts were kept): there is no base, so
573
+ // a fact the file states differently from the platform cannot be told from an editor edit
574
+ // the file never saw. Name it; never guess.
575
+ ({ send: changes, conflicts } = unrecordedFacts(meta, now, o.force));
576
+ for (const k of conflicts)
577
+ ctx.warn(` ! ${entry.file}: ${k} differs from the platform and this repo has no record of the last sync — ` +
578
+ 'sb site pull to take the platform’s, or sb site push --force to send the file’s. Nothing sent for this page.');
579
+ }
580
+ if (entry.page)
581
+ for (const k of conflicts)
582
+ ctx.warn(` ! ${entry.file}: ${k} changed here AND in the editor — kept both; ` +
583
+ "pull to take the editor's, or sb site push --force. Nothing sent for this page.");
584
+ if (conflicts.length) {
585
+ failed++;
586
+ o.report?.(entry.file, 'refused');
587
+ return;
588
+ }
308
589
  }
309
590
  if (o.dryRun) {
310
591
  ctx.log(` ↑ ${entry.file} (dry run)`);
311
592
  sent++;
312
- continue;
593
+ return;
594
+ }
595
+ if (theirs) {
596
+ const now = factsOf(theirs);
597
+ patched = Object.keys(changes).length > 0;
598
+ const got = patched
599
+ ? await sendFacts(ctx, id, entry.file, changes, now, (fresh) => mergeFacts(meta, entry.page ?? now, fresh, true, () => { }).send)
600
+ : theirs;
601
+ if (!got) {
602
+ failed++;
603
+ return;
604
+ }
605
+ // A fact's recorded base may only move to a value the FILE holds: it is what the next push
606
+ // compares the file with, so one that ran ahead of the file would revert the editor's change
607
+ // if the document save below failed. Sent facts hold the file's value; a fact the file
608
+ // already states as the platform has it is the same. The rest wait for the rewrite.
609
+ const base = { ...(entry.page ?? now) };
610
+ for (const k of FACT_KEYS) {
611
+ if (k in changes)
612
+ base[k] = changes[k];
613
+ else if (meta && k in meta && isDeepStrictEqual(meta[k], now[k]))
614
+ base[k] = now[k];
615
+ }
616
+ // `settings` is held key by key: what the file holds, not the merged blob (which carries
617
+ // the editor's keys the file has not seen yet).
618
+ if (held.settings !== undefined)
619
+ base.settings = held.settings;
620
+ entry.page = base;
621
+ await saveManifest(ctx);
622
+ settled = got;
313
623
  }
314
624
  const body = (baseRev) => ({
315
625
  document,
316
626
  schemaVersion: entry.schemaVersion ?? document.schema_version,
317
627
  baseRev,
318
628
  });
319
- let res = await send(ctx, docURL(ctx, id), 'PUT', body(entry.rev));
629
+ const url = docURL(ctx, id);
630
+ let res = await send(ctx, url, 'PUT', body(entry.rev));
320
631
  if (res.status === 409 && o.force) {
321
632
  const err = await errorOf(res);
322
633
  const cur = Number(err.details?.rev);
323
634
  if (err.code === 'source_stale' && cur > 0)
324
- res = await send(ctx, docURL(ctx, id), 'PUT', body(cur));
635
+ res = await send(ctx, url, 'PUT', body(cur));
325
636
  }
326
637
  if (!res.ok) {
327
638
  const err = await errorOf(res);
639
+ const saved = patched ? "the page's facts were saved, the document was not: " : '';
328
640
  ctx.warn(err.code === 'source_stale'
329
- ? ` ! ${entry.file}: edited in the editor since your last pull — nothing sent. ` +
641
+ ? ` ! ${entry.file}: ${saved}` +
642
+ (patched
643
+ ? 'edited in the editor since your last pull — the document was not sent. '
644
+ : 'edited in the editor since your last pull — nothing sent. ') +
330
645
  'Pull and merge, or sb site push --force to overwrite the editor’s draft.'
331
- : ` ! ${entry.file}: refused (${err.code ? `${err.code}: ` : ''}${err.error})`);
646
+ : ` ! ${entry.file}: ${saved}refused (${refusal(err)})`);
332
647
  failed++;
333
- continue;
648
+ o.report?.(entry.file, err.code === 'source_stale' ? 'stale' : 'refused');
649
+ return;
334
650
  }
335
651
  const draft = await draftOf(res, ctx.v1);
652
+ // `path` is derived from the slug, information only: it may follow the platform at once.
653
+ if (settled)
654
+ entry.path = settled.path;
336
655
  for (const w of draft.warnings ?? []) {
337
656
  const subject = Object.entries(w)
338
657
  .filter(([k, v]) => k !== 'code' && typeof v === 'string' && v)
@@ -340,27 +659,258 @@ export async function push(o) {
340
659
  .join(', ');
341
660
  ctx.warn(` ! ${entry.file}: the platform says ${w.code}${subject ? ` (${subject})` : ''}`);
342
661
  }
662
+ // The file becomes what the platform STORED — minted ids, the facts it settled on — so the
663
+ // next pull finds nothing to change. (A file the platform stored as sent prints as itself.)
664
+ const saved = draft.document ?? document;
665
+ const facts = settled ? factsOf(settled) : entry.page;
666
+ const out = facts
667
+ ? fileText(id, entry.path ?? '', facts, saved)
668
+ : printFile('page', saved, undefined);
669
+ const wrote = await writeBack(ctx, entry.file, text, out);
670
+ // The recorded facts are what the FILE holds. The platform's facts reach the file only through
671
+ // the rewrite: when it was declined (a newer save landed meanwhile) the base keeps just what
672
+ // this push sent and what the file already stated, so an editor-only change is not mistaken
673
+ // for the file's own on the next push and reverted.
674
+ if (wrote && settled)
675
+ entry.page = facts;
343
676
  ctx.manifest.pages[id] = {
344
677
  ...entry,
345
- appBlocks: appBlockSeals(draft.document),
678
+ appBlocks: appBlockSeals(saved),
346
679
  rev: draft.rev,
347
- sha256: sha,
680
+ // What the file holds: the rewrite, or — when it was saved over meanwhile — the text we sent,
681
+ // so the newer save differs from it and goes up next.
682
+ sha256: sha256(wrote ? out : text),
348
683
  schemaVersion: draft.schemaVersion,
349
684
  };
350
685
  await saveManifest(ctx);
351
686
  ctx.log(` ↑ ${entry.file}`);
352
687
  sent++;
688
+ o.report?.(entry.file, 'sent');
689
+ }
690
+ const missing = [];
691
+ for (const [id, entry] of Object.entries(ctx.manifest.pages)) {
692
+ if (o.only && !o.only.has(entry.file))
693
+ continue;
694
+ const link = await linkOn(ctx.dir, entry.file);
695
+ if (link) {
696
+ ctx.warn(` ! ${entry.file}: ${link} is a symbolic link — not followed, nothing sent.`);
697
+ failed++;
698
+ continue;
699
+ }
700
+ const text = await readText(join(ctx.dir, entry.file));
701
+ if (text === undefined) {
702
+ missing.push([id, entry]);
703
+ continue;
704
+ }
705
+ if (sha256(text) === entry.sha256)
706
+ continue;
707
+ let parsed;
708
+ try {
709
+ parsed = parseFile(text, 'page');
710
+ }
711
+ catch (err) {
712
+ // file:line:col — clickable in a terminal and in an editor's problem matcher.
713
+ ctx.warn(err instanceof SourceError
714
+ ? ` ! ${entry.file}:${err.message} — nothing sent.`
715
+ : ` ! ${entry.file}: ${messageOf(err)} — nothing sent.`);
716
+ failed++;
717
+ o.report?.(entry.file, 'refused');
718
+ continue;
719
+ }
720
+ await savePage(id, entry, text, parsed.document, parsed.meta, false);
353
721
  }
354
722
  const local = await readdir(join(ctx.dir, PAGES_DIR)).catch(() => []);
355
- for (const f of local) {
723
+ for (const f of local.sort()) {
356
724
  const file = `${PAGES_DIR}/${f}`;
357
- if (f.endsWith('.page.tsx') && !tracked.has(file)) {
358
- ctx.warn(` ? ${file}: not a tracked page — create the page in the editor, then sb site pull.`);
725
+ if (!f.endsWith('.page.tsx') || tracked.has(file) || (o.only && !o.only.has(file)))
726
+ continue;
727
+ // Untracked: a file with `export const page` is a NEW page; one without is only reported.
728
+ const link = SAFE_FILE.test(file) ? await linkOn(ctx.dir, file) : file;
729
+ if (link) {
730
+ ctx.warn(` ! ${file}: ${link} is not a plain page file — not read, nothing sent.`);
731
+ failed++;
732
+ continue;
733
+ }
734
+ const text = (await readText(join(ctx.dir, file)));
735
+ let parsed;
736
+ try {
737
+ parsed = parseFile(text, 'page');
738
+ }
739
+ catch (err) {
740
+ ctx.warn(err instanceof SourceError
741
+ ? ` ! ${file}:${err.message} — nothing sent.`
742
+ : ` ! ${file}: ${messageOf(err)} — nothing sent.`);
743
+ failed++;
744
+ continue;
745
+ }
746
+ const meta = parsed.meta;
747
+ if (!meta) {
748
+ ctx.warn(` ? ${file}: not a tracked page — create the page in the editor, then sb site pull ` +
749
+ '(or add `export const page = { name: "…" }` to create it from this file).');
750
+ continue;
751
+ }
752
+ if (typeof meta.name !== 'string' || !meta.name.trim()) {
753
+ ctx.warn(` ! ${file}: \`export const page\` needs a name to create the page — nothing sent.`);
754
+ failed++;
755
+ continue;
756
+ }
757
+ const known = typeof meta.id === 'string' ? (await server()).find((p) => p.id === meta.id) : undefined;
758
+ if (typeof meta.id === 'string' && !known) {
759
+ // An id the platform does not have: a page deleted there, or a file copied from another site.
760
+ // Creating "a new one" would silently break the identity the file claims.
761
+ ctx.warn(` ! ${file}: names page ${JSON.stringify(meta.id)}, which this site does not have — ` +
762
+ 'remove `id` from `export const page` to create a new page. Nothing sent.');
763
+ failed++;
764
+ continue;
765
+ }
766
+ if (known) {
767
+ // Its id names a page that exists but is not tracked here (a lost manifest, a copied file):
768
+ // sending would overwrite that page's draft with no fence, so only --force does.
769
+ if (!o.force || ctx.manifest.pages[known.id]) {
770
+ ctx.warn(` ! ${file}: names page ${known.id}, which exists but is not tracked from this file — ` +
771
+ 'sb site pull to take it, or --force to overwrite its draft. Nothing sent.');
772
+ failed++;
773
+ continue;
774
+ }
775
+ const entry = {
776
+ file,
777
+ rev: -1,
778
+ sha256: '',
779
+ path: known.path,
780
+ page: factsOf(known),
781
+ };
782
+ if (!o.dryRun)
783
+ ctx.manifest.pages[known.id] = entry;
784
+ await savePage(known.id, entry, text, parsed.document, meta, false);
785
+ continue;
786
+ }
787
+ if (o.dryRun) {
788
+ ctx.log(` + ${file} (dry run: would create page ${JSON.stringify(meta.name)})`);
789
+ sent++;
790
+ continue;
791
+ }
792
+ const asked = { name: meta.name };
793
+ for (const k of ['slug', 'type'])
794
+ if (typeof meta[k] === 'string')
795
+ asked[k] = meta[k];
796
+ if (meta.isHomepage === true)
797
+ asked.isHomepage = true;
798
+ if (meta.settings && Object.keys(meta.settings).length)
799
+ asked.settings = meta.settings;
800
+ const res = await send(ctx, `${ctx.base}/pages`, 'POST', asked);
801
+ if (!res.ok) {
802
+ ctx.warn(` ! ${file}: the page was refused (${refusal(await errorOf(res))}) — nothing created.`);
803
+ failed++;
804
+ continue;
805
+ }
806
+ const made = await pageOf(res);
807
+ // Recorded BEFORE the document goes up: if that fails the page exists, and the next push
808
+ // must retry this file rather than create a second page.
809
+ const entry = {
810
+ file,
811
+ rev: -1,
812
+ sha256: '',
813
+ path: made.path,
814
+ page: factsOf(made),
815
+ };
816
+ ctx.manifest.pages[made.id] = entry;
817
+ await saveManifest(ctx);
818
+ verifyFacts(ctx, file, asked, made);
819
+ if (meta.defaultTemplate === true) {
820
+ const got = await sendFacts(ctx, made.id, file, { defaultTemplate: true });
821
+ if (got)
822
+ entry.page = factsOf(got);
823
+ }
824
+ ctx.log(` + ${file} (page ${made.id} created)`);
825
+ await savePage(made.id, entry, text, parsed.document, meta, true);
826
+ }
827
+ if (missing.length && o.only)
828
+ for (const [, e] of missing)
829
+ ctx.warn(` ! ${e.file}: missing — not deleted (sb site dev never prunes).`);
830
+ if (missing.length && !o.only) {
831
+ if (!o.prune) {
832
+ for (const [id, e] of missing) {
833
+ ctx.warn(` ! ${e.file}: missing — the page ${JSON.stringify(e.page?.name ?? id)} is kept on the platform; ` +
834
+ 'sb site push --prune deletes it.');
835
+ failed++;
836
+ }
359
837
  }
838
+ else if (!(await prune(ctx, o, missing)))
839
+ failed++;
360
840
  }
361
841
  ctx.log(`${sent} page draft(s) ${o.dryRun ? 'would be ' : ''}saved. Publish with sb site publish when ready.`);
362
- return failed ? 1 : 0;
842
+ const more = await pushKinds(ctx, gatePrune(ctx, o));
843
+ if (more.sent)
844
+ ctx.log(`${more.sent} other file(s) ${o.dryRun ? 'would be ' : ''}saved.`);
845
+ return failed || more.failed ? 1 : 0;
846
+ }
847
+ /**
848
+ * `push --prune`: delete the pages whose tracked file is gone. The list is printed first; off a
849
+ * terminal `--yes` is required, on one the answer is asked. False when something was refused.
850
+ */
851
+ async function prune(ctx, o, missing) {
852
+ const go = await gatePrune(ctx, o)(PAGES_DIR, `${missing.length} page(s)`, missing.map(([id, e]) => ` - ${e.file} (${JSON.stringify(e.page?.name ?? id)}, ${id})`));
853
+ if (go !== 'delete')
854
+ return go === 'stop';
855
+ let ok = true;
856
+ for (const [id, e] of missing) {
857
+ // The platform's draft must still be the one this file stood for: a page edited in the editor
858
+ // since the last sync is not deleted on the strength of a file that never saw the edit.
859
+ if (e.rev < 0) {
860
+ ctx.warn(` ! ${e.file}: this page was created from the file but never saved from it — not deleted (the draft is the platform's). Push it first, or delete the page in the editor.`);
861
+ ok = false;
862
+ continue;
863
+ }
864
+ const draft = await getDraft(ctx, id);
865
+ if (draft && draft.rev !== e.rev) {
866
+ ctx.warn(` ! ${e.file}: the page was edited in the editor since your last pull — not deleted. Pull, then decide.`);
867
+ ok = false;
868
+ continue;
869
+ }
870
+ const res = await send(ctx, `${ctx.base}/pages/${encodeURIComponent(id)}`, 'DELETE', undefined, { 'If-Match': String(e.rev) });
871
+ if (res.ok || res.status === 404) {
872
+ delete ctx.manifest.pages[id];
873
+ await saveManifest(ctx);
874
+ ctx.log(` ✗ ${e.file} (page deleted)`);
875
+ }
876
+ else {
877
+ const err = await errorOf(res);
878
+ ctx.warn(err.code === 'source_stale'
879
+ ? ` ! ${e.file}: the page was edited in the editor since your last pull — not deleted. Pull, then decide.`
880
+ : ` ! ${e.file}: the page was not deleted (${refusal(err)})`);
881
+ ok = false;
882
+ }
883
+ }
884
+ return ok;
363
885
  }
886
+ /**
887
+ * The ONE gate every `--prune` passes, whatever it deletes: the directory must exist (a checkout
888
+ * with none makes everything look deleted), the list is printed BEFORE any DELETE, and off a
889
+ * terminal `--yes` is required. 'stop' = declined or a dry run (not a failure), 'fail' = refused.
890
+ */
891
+ export const gatePrune = (ctx, o) => async (dir, what, lines) => {
892
+ const there = await stat(join(ctx.dir, dir)).then((s) => s.isDirectory(), () => false);
893
+ if (!there) {
894
+ ctx.warn(` ! ${dir}/ is not here, so everything in it would look deleted — nothing deleted.`);
895
+ return 'fail';
896
+ }
897
+ ctx.log(`--prune ${o.dryRun ? 'would delete' : 'deletes'} ${what} from the platform:`);
898
+ for (const l of lines)
899
+ ctx.log(l);
900
+ if (o.dryRun)
901
+ return 'stop';
902
+ if (!o.yes) {
903
+ if (!o.confirm) {
904
+ ctx.warn(' ! off a terminal --prune also needs --yes; nothing deleted.');
905
+ return 'fail';
906
+ }
907
+ if (!(await o.confirm(`Delete ${what} from the platform? [y/N] `))) {
908
+ ctx.log('Nothing deleted.');
909
+ return 'stop';
910
+ }
911
+ }
912
+ return 'delete';
913
+ };
364
914
  export const PUBLISH_WHAT = 'Which pages? Name their files (sb site publish design/pages/index.page.tsx) or pass --all. ' +
365
915
  'Publishing makes them live; nothing is published by default.';
366
916
  /**