@buffcore/cli 0.8.46 → 0.8.47

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 (187) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/dist/commands/change-merge-remove.d.ts +9 -2
  3. package/dist/commands/change-merge-remove.js +27 -15
  4. package/dist/commands/design/check.d.ts +1 -1
  5. package/dist/commands/design/check.js +2 -1
  6. package/dist/commands/design/contract-size.d.ts +7 -0
  7. package/dist/commands/design/contract-size.js +47 -0
  8. package/dist/commands/design/tells.en.d.ts +2 -0
  9. package/dist/commands/design/tells.en.js +2 -0
  10. package/dist/commands/design/tells.es.js +2 -0
  11. package/dist/commands/extension/places-approval.d.ts +4 -0
  12. package/dist/commands/process-paths.d.ts +14 -0
  13. package/dist/commands/process-paths.js +90 -0
  14. package/dist/commands/prototype/ai-approval.d.ts +27 -0
  15. package/dist/commands/prototype/ai-approval.js +60 -0
  16. package/dist/commands/prototype/approver.d.ts +71 -0
  17. package/dist/commands/prototype/approver.js +168 -0
  18. package/dist/commands/prototype/critique-gate.d.ts +14 -0
  19. package/dist/commands/prototype/critique-gate.js +48 -0
  20. package/dist/commands/prototype/fence.d.ts +1 -0
  21. package/dist/commands/prototype/fence.js +12 -0
  22. package/dist/commands/prototype/final-approval-grant.js +18 -0
  23. package/dist/commands/prototype/final-approval.js +4 -1
  24. package/dist/commands/prototype/index.js +3 -0
  25. package/dist/commands/prototype/layout-hints.d.ts +34 -0
  26. package/dist/commands/prototype/layout-hints.js +194 -0
  27. package/dist/commands/prototype/layout-measure.d.ts +39 -0
  28. package/dist/commands/prototype/layout-measure.js +97 -0
  29. package/dist/commands/prototype/layout-words.d.ts +2 -0
  30. package/dist/commands/prototype/layout-words.js +11 -0
  31. package/dist/commands/prototype/layout.en.d.ts +6 -0
  32. package/dist/commands/prototype/layout.en.js +7 -0
  33. package/dist/commands/prototype/load-location.js +2 -3
  34. package/dist/commands/prototype/messages.en.d.ts +14 -0
  35. package/dist/commands/prototype/messages.en.js +15 -1
  36. package/dist/commands/prototype/messages.js +15 -1
  37. package/dist/commands/prototype/milestone-versions.d.ts +4 -0
  38. package/dist/commands/prototype/prune-command.d.ts +5 -0
  39. package/dist/commands/prototype/prune-command.js +25 -0
  40. package/dist/commands/prototype/prune-words.d.ts +1 -0
  41. package/dist/commands/prototype/prune-words.js +7 -0
  42. package/dist/commands/prototype/prune.d.ts +16 -0
  43. package/dist/commands/prototype/prune.en.d.ts +9 -0
  44. package/dist/commands/prototype/prune.en.js +9 -0
  45. package/dist/commands/prototype/prune.es.d.ts +2 -0
  46. package/dist/commands/prototype/prune.es.js +9 -0
  47. package/dist/commands/prototype/prune.js +140 -0
  48. package/dist/commands/prototype/reopen-messages.d.ts +9 -0
  49. package/dist/commands/prototype/reopen-messages.js +19 -0
  50. package/dist/commands/prototype/report.d.ts +14 -0
  51. package/dist/commands/prototype/report.js +5 -1
  52. package/dist/commands/prototype/scene-layout.d.ts +17 -0
  53. package/dist/commands/prototype/scene-layout.js +57 -0
  54. package/dist/commands/prototype/scene-ready.js +8 -2
  55. package/dist/commands/prototype/scene.d.ts +15 -2
  56. package/dist/commands/prototype/scene.js +54 -42
  57. package/dist/commands/prototype/selector-answer.d.ts +43 -0
  58. package/dist/commands/prototype/selector-answer.js +73 -0
  59. package/dist/commands/prototype/selector-misses.d.ts +19 -0
  60. package/dist/commands/prototype/selector-misses.js +78 -0
  61. package/dist/commands/prototype/selector-prompt.d.ts +23 -0
  62. package/dist/commands/prototype/selector-prompt.js +32 -0
  63. package/dist/commands/prototype/selector-run.d.ts +13 -0
  64. package/dist/commands/prototype/selector-run.js +113 -0
  65. package/dist/commands/prototype/selector.d.ts +54 -0
  66. package/dist/commands/prototype/selector.js +96 -0
  67. package/dist/commands/prototype/snapshot-ancestor.js +2 -0
  68. package/dist/commands/prototype/snapshot-bundle.d.ts +17 -3
  69. package/dist/commands/prototype/snapshot-bundle.js +69 -7
  70. package/dist/commands/prototype/snapshot-check-files.d.ts +2 -0
  71. package/dist/commands/prototype/snapshot-check-files.js +41 -0
  72. package/dist/commands/prototype/snapshot-command.d.ts +2 -0
  73. package/dist/commands/prototype/snapshot-command.js +3 -0
  74. package/dist/commands/prototype/snapshot-completion.d.ts +4 -0
  75. package/dist/commands/prototype/snapshot-completion.js +30 -2
  76. package/dist/commands/prototype/snapshot-dependencies.d.ts +23 -2
  77. package/dist/commands/prototype/snapshot-dependencies.js +120 -14
  78. package/dist/commands/prototype/snapshot-hashes.d.ts +7 -0
  79. package/dist/commands/prototype/snapshot-hashes.js +28 -0
  80. package/dist/commands/prototype/snapshot-inputs.d.ts +15 -6
  81. package/dist/commands/prototype/snapshot-inputs.js +140 -197
  82. package/dist/commands/prototype/snapshot-matrix.d.ts +58 -0
  83. package/dist/commands/prototype/snapshot-matrix.js +95 -0
  84. package/dist/commands/prototype/snapshot-metro-inputs.d.ts +8 -0
  85. package/dist/commands/prototype/snapshot-metro-inputs.js +81 -0
  86. package/dist/commands/prototype/snapshot-owners.d.ts +6 -2
  87. package/dist/commands/prototype/snapshot-owners.js +12 -3
  88. package/dist/commands/prototype/snapshot-progress-entry.d.ts +14 -0
  89. package/dist/commands/prototype/snapshot-progress-entry.js +85 -0
  90. package/dist/commands/prototype/snapshot-progress.d.ts +19 -2
  91. package/dist/commands/prototype/snapshot-progress.js +54 -102
  92. package/dist/commands/prototype/snapshot-registry.d.ts +14 -0
  93. package/dist/commands/prototype/snapshot-registry.js +121 -0
  94. package/dist/commands/prototype/snapshot-report.d.ts +4 -0
  95. package/dist/commands/prototype/snapshot-report.js +77 -12
  96. package/dist/commands/prototype/snapshot-requests.d.ts +13 -3
  97. package/dist/commands/prototype/snapshot-requests.js +68 -30
  98. package/dist/commands/prototype/snapshot-reuse.d.ts +6 -1
  99. package/dist/commands/prototype/snapshot-reuse.js +17 -7
  100. package/dist/commands/prototype/snapshot-scene-inputs.d.ts +30 -0
  101. package/dist/commands/prototype/snapshot-scene-inputs.js +210 -0
  102. package/dist/commands/prototype/snapshot-served-inputs.d.ts +3 -0
  103. package/dist/commands/prototype/snapshot-served-inputs.js +12 -0
  104. package/dist/commands/prototype/snapshot-server-record.d.ts +26 -0
  105. package/dist/commands/prototype/snapshot-server-record.js +135 -0
  106. package/dist/commands/prototype/snapshot-servers.d.ts +3 -1
  107. package/dist/commands/prototype/snapshot-servers.js +50 -2
  108. package/dist/commands/prototype/snapshot-setup.d.ts +3 -1
  109. package/dist/commands/prototype/snapshot-setup.js +2 -1
  110. package/dist/commands/prototype/snapshot-surface-inputs.d.ts +23 -0
  111. package/dist/commands/prototype/snapshot-surface-inputs.js +161 -0
  112. package/dist/commands/prototype/snapshot-vite-inputs.d.ts +22 -0
  113. package/dist/commands/prototype/snapshot-vite-inputs.js +209 -0
  114. package/dist/commands/prototype/snapshot.d.ts +5 -0
  115. package/dist/commands/prototype/snapshot.js +72 -10
  116. package/dist/commands/prototype/version-commands.d.ts +4 -0
  117. package/dist/commands/prototype/version-commands.js +36 -8
  118. package/dist/commands/prototype/versions.d.ts +28 -2
  119. package/dist/commands/prototype/versions.js +25 -1
  120. package/dist/commands/prototype/vite-fs-path.d.ts +4 -0
  121. package/dist/commands/prototype/vite-fs-path.js +15 -0
  122. package/dist/commands/remove-links.d.ts +6 -0
  123. package/dist/commands/remove-links.js +17 -0
  124. package/dist/commands/size-docs.d.ts +9 -0
  125. package/dist/commands/size-docs.en.d.ts +6 -0
  126. package/dist/commands/size-docs.en.js +6 -0
  127. package/dist/commands/size-docs.es.d.ts +2 -0
  128. package/dist/commands/size-docs.es.js +6 -0
  129. package/dist/commands/size-docs.js +28 -0
  130. package/dist/commands/size.d.ts +5 -2
  131. package/dist/commands/size.js +27 -9
  132. package/dist/commands/ui/approval-authority.d.ts +10 -2
  133. package/dist/commands/ui/approval-authority.js +1 -0
  134. package/dist/commands/ui/autopilot-ai-approve.d.ts +18 -0
  135. package/dist/commands/ui/autopilot-ai-approve.js +68 -0
  136. package/dist/commands/ui/autopilot-loop.js +5 -6
  137. package/dist/commands/ui/autopilot-merge.js +3 -0
  138. package/dist/commands/ui/autopilot.en.d.ts +23 -0
  139. package/dist/commands/ui/autopilot.en.js +23 -0
  140. package/dist/commands/ui/autopilot.es.d.ts +23 -0
  141. package/dist/commands/ui/autopilot.es.js +23 -0
  142. package/dist/commands/ui/chat/find.d.ts +2 -0
  143. package/dist/commands/ui/chat/find.js +13 -0
  144. package/dist/commands/ui/chat/fresh-codex.d.ts +39 -0
  145. package/dist/commands/ui/chat/fresh-codex.js +175 -0
  146. package/dist/commands/ui/chat/fresh-critique.js +13 -5
  147. package/dist/commands/ui/chat/fresh-launch.d.ts +19 -0
  148. package/dist/commands/ui/chat/fresh-launch.js +67 -11
  149. package/dist/commands/ui/chat/fresh-prompts.d.ts +2 -0
  150. package/dist/commands/ui/chat/fresh-prompts.js +2 -0
  151. package/dist/commands/ui/chat/fresh-secrets.d.ts +6 -0
  152. package/dist/commands/ui/chat/fresh-secrets.js +172 -0
  153. package/dist/commands/ui/chat/fresh.en.d.ts +1 -0
  154. package/dist/commands/ui/chat/fresh.en.js +2 -1
  155. package/dist/commands/ui/chat/fresh.es.d.ts +1 -0
  156. package/dist/commands/ui/chat/fresh.es.js +2 -1
  157. package/dist/commands/ui/chat/worktree.js +25 -5
  158. package/dist/commands/ui/index.js +3 -0
  159. package/dist/commands/ui/loop-approve.d.ts +30 -1
  160. package/dist/commands/ui/loop-approve.js +2 -2
  161. package/dist/commands/ui/merge-route.js +3 -0
  162. package/dist/commands/ui/places-change.d.ts +4 -0
  163. package/dist/commands/ui/prototype-main.d.ts +4 -0
  164. package/dist/commands/ui/reopen-route.d.ts +117 -0
  165. package/dist/commands/ui/reopen-route.js +97 -0
  166. package/dist/commands/ui/save-route.d.ts +2 -0
  167. package/dist/commands/ui/save-route.js +4 -0
  168. package/dist/commands/ui/studio-routes.js +2 -0
  169. package/dist/commands/ui/studio-state.d.ts +33 -0
  170. package/dist/commands/ui/studio-versions.d.ts +24 -0
  171. package/dist/commands/ui/worktrees.d.ts +1 -1
  172. package/dist/commands/ui/worktrees.js +19 -3
  173. package/dist/commands/worktree-sweep.d.ts +45 -0
  174. package/dist/commands/worktree-sweep.js +188 -0
  175. package/dist/commands/worktrees-command.d.ts +32 -0
  176. package/dist/commands/worktrees-command.en.d.ts +25 -0
  177. package/dist/commands/worktrees-command.en.js +55 -0
  178. package/dist/commands/worktrees-command.js +96 -0
  179. package/dist/main.js +2 -0
  180. package/dist/ui/page.js +82 -82
  181. package/docs/PROTOTYPE.md +6 -3
  182. package/docs/WORKBENCH.md +11 -6
  183. package/package.json +11 -11
  184. package/skills/ape-critique/SKILL.md +41 -6
  185. package/skills/ape-design-system/SKILL.md +3 -0
  186. package/skills/ape-plan-change/SKILL.md +6 -0
  187. package/skills/ape-prototype/SKILL.md +8 -4
@@ -1,92 +1,22 @@
1
- import { createHash } from 'node:crypto';
2
1
  import { rmSync } from 'node:fs';
3
- import { copyFile, link, lstat, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
4
- import { basename, join } from 'node:path';
5
- import { PrototypeProblem } from '@buffcore/contracts/prototype';
6
- import { z } from 'zod';
2
+ import { mkdir, readdir, rm } from 'node:fs/promises';
3
+ import { join } from 'node:path';
7
4
  import { commandT } from '../ui/commands.js';
8
5
  import { locale, number, t } from './messages.js';
9
- import { plainData, sha256 } from './snapshot-hashes.js';
6
+ import { SnapshotCheckoutChanged } from './snapshot-checkout.js';
7
+ import { plainData, sceneData, sha256 } from './snapshot-hashes.js';
8
+ import { atomicWrite, fingerprint, readIfPresent, readScene, sceneBinding, shotNames, stageShot, tracked, } from './snapshot-progress-entry.js';
10
9
  import { takeProgressSlot } from './snapshot-storage.js';
11
- const resultShape = z.object({
12
- screenshots: z.record(z.string(), z.string()),
13
- cut: z.array(z.string()),
14
- apiCalls: z.boolean().optional(),
15
- untrackedRequests: z.boolean().optional(),
16
- retried: z.literal(true).optional(),
17
- retryError: z.string().optional(),
18
- problems: z.array(PrototypeProblem),
19
- hints: z.array(z.object({
20
- scene: z.string(),
21
- theme: z.string(),
22
- mode: z.string(),
23
- locale: z.string(),
24
- detail: z.string(),
25
- })),
26
- });
27
- async function atomicWrite(path, text) {
28
- const temp = `${path}.tmp`;
29
- await writeFile(temp, text);
30
- await rename(temp, path);
31
- }
32
- async function readIfPresent(path) {
33
- try {
34
- return await readFile(path, 'utf8');
35
- }
36
- catch (error) {
37
- if (error.code !== 'ENOENT')
38
- throw error;
39
- }
40
- }
41
- function shotNames(result, commit) {
42
- return Object.values(result.screenshots).map((path) => {
43
- const file = basename(path);
44
- if (path !== `${commit}/${file}` || !/^[^/\\:]+\.png$/.test(file))
45
- throw new Error();
46
- return file;
47
- });
48
- }
49
- async function stageShot(from, to) {
50
- try {
51
- await link(from, to);
52
- }
53
- catch (error) {
54
- // A worktree can be on a different disk. Unlink a name collision before copying.
55
- if (error.code === 'EEXIST')
56
- await rm(to);
57
- await copyFile(from, to);
58
- }
59
- }
60
- const sceneBinding = (identity, index, key) => JSON.stringify([identity, index, key]);
61
- async function fingerprint(binding, result, commit, folder) {
62
- const sum = createHash('sha256').update(binding).update(JSON.stringify(result));
63
- for (const file of shotNames(result, commit)) {
64
- const path = join(folder, file);
65
- if (!(await lstat(path)).isFile())
66
- throw new Error();
67
- sum.update(sha256(await readFile(path)));
68
- }
69
- return sum.digest('hex');
70
- }
71
- async function readScene(dir, commit, binding) {
72
- const saved = await readIfPresent(join(dir, 'result.json'));
73
- if (saved === undefined)
74
- return;
75
- const { checksum, result } = JSON.parse(saved);
76
- if (!resultShape.safeParse(result).success)
77
- throw new Error();
78
- if (checksum !== (await fingerprint(binding, result, commit, dir)))
79
- throw new Error();
80
- return result;
81
- }
82
10
  /** Only marked scenes count. A corrupt marked scene invalidates the run as a whole. */
83
- async function readScenes(dir, identity, scenes, commit) {
11
+ async function readScenes(dir, identity, scenes, commit, runtime) {
84
12
  const saved = new Map();
13
+ const index = new Map(scenes.all.map((scene, i) => [scene.key, i]));
85
14
  try {
86
15
  if ((await readIfPresent(join(dir, 'progress.json'))) !== identity)
87
16
  return;
88
- for (const [i, scene] of scenes.entries()) {
89
- const result = await readScene(join(dir, String(i)), commit, sceneBinding(identity, i, scene.key));
17
+ for (const scene of scenes.picked) {
18
+ const i = index.get(scene.key);
19
+ const result = await readScene(join(dir, String(i)), commit, sceneBinding(identity, i, scene.key, scenes.inputs?.get(scene.key), runtime));
90
20
  if (result)
91
21
  saved.set(scene.key, result);
92
22
  }
@@ -96,17 +26,18 @@ async function readScenes(dir, identity, scenes, commit) {
96
26
  return undefined;
97
27
  }
98
28
  }
99
- async function journal(source, identity, scenes, commit) {
29
+ async function journal(source, identity, scenes, commit, runtime) {
100
30
  const { dir } = source;
101
31
  const identityPath = join(dir, 'progress.json');
102
- const old = await readScenes(dir, identity, scenes, commit);
32
+ const boundRuntime = runtime();
33
+ const old = await readScenes(dir, identity, scenes, commit, boundRuntime);
103
34
  const saved = old ?? new Map();
104
35
  if (!old) {
105
36
  await rm(dir, { recursive: true, force: true, maxRetries: 3 });
106
37
  await mkdir(dir);
107
38
  await atomicWrite(identityPath, identity);
108
39
  }
109
- const indices = new Map(scenes.map((scene, i) => [scene.key, i]));
40
+ const indices = new Map(scenes.all.map((scene, i) => [scene.key, i]));
110
41
  const sceneDir = (key) => join(dir, String(indices.get(key)));
111
42
  const resumed = saved.size > 0;
112
43
  let valid = true;
@@ -118,6 +49,8 @@ async function journal(source, identity, scenes, commit) {
118
49
  if (!resumed)
119
50
  return;
120
51
  try {
52
+ if (runtime() !== boundRuntime)
53
+ throw new SnapshotCheckoutChanged(commit, commit);
121
54
  source.check();
122
55
  }
123
56
  catch (error) {
@@ -128,15 +61,17 @@ async function journal(source, identity, scenes, commit) {
128
61
  return {
129
62
  check,
130
63
  valid: () => valid,
131
- remaining: scenes.filter((scene) => !saved.has(scene.key)),
64
+ remaining: scenes.picked.filter((scene) => !saved.has(scene.key)),
132
65
  async draw(scene, run, draw) {
133
66
  const index = indices.get(scene.key);
134
67
  const out = sceneDir(scene.key);
135
68
  await rm(out, { recursive: true, force: true });
136
69
  await mkdir(out);
137
70
  const result = await draw({ ...run, out });
138
- if (valid && !result.problems.some((problem) => problem.check === 'render')) {
139
- const checksum = await fingerprint(sceneBinding(identity, index, scene.key), result, run.commit, out);
71
+ if (valid &&
72
+ tracked(result) &&
73
+ !result.problems.some((problem) => problem.check === 'render')) {
74
+ const checksum = await fingerprint(sceneBinding(identity, index, scene.key, scenes.inputs?.get(scene.key), runtime()), result, run.commit, out);
140
75
  if (resumed)
141
76
  check();
142
77
  else if (!source.same())
@@ -159,56 +94,73 @@ async function journal(source, identity, scenes, commit) {
159
94
  }
160
95
  return results;
161
96
  },
97
+ /** Every picked scene was drawn: drop their entries, and the journal when none is left. */
98
+ async finish() {
99
+ for (const scene of scenes.picked)
100
+ await rm(sceneDir(scene.key), { recursive: true, force: true });
101
+ const left = (await readdir(dir)).filter((name) => /^\d+$/.test(name));
102
+ if (!left.length)
103
+ await rm(dir, { recursive: true, force: true, maxRetries: 3 });
104
+ },
162
105
  };
163
106
  }
164
107
  function comparableScenes(scenes) {
165
108
  try {
166
- return scenes.every((scene) => plainData(scene.props));
109
+ return scenes.every((scene) => plainData(sceneData(scene.props)));
167
110
  }
168
111
  catch {
169
112
  return false;
170
113
  }
171
114
  }
172
- /** The one saved run lives in Git's validation storage, outside publication and child cleanup. */
173
- export async function withSnapshotProgress(source, inputs, scenes, commit, write) {
115
+ /**
116
+ * The one saved run lives in Git's validation storage, outside publication and child cleanup. A run
117
+ * that stops, crashes or has a scene that failed to draw keeps its finished scenes; a run that drew
118
+ * every scene it picked (findings or not) drops their entries.
119
+ */
120
+ export async function withSnapshotProgress(source, inputs, { all, picked, inputs: own }, commit, write, runtime = () => undefined) {
174
121
  const release = await takeProgressSlot(source.dir);
175
122
  if (!release)
176
- return write(scenes);
123
+ return write(picked);
177
124
  try {
178
- if (!source.identity || !comparableScenes(scenes)) {
125
+ if (!source.identity || !comparableScenes(picked)) {
179
126
  await rm(source.dir, { recursive: true, force: true, maxRetries: 3 });
180
- return await write(scenes);
127
+ return await write(picked);
181
128
  }
182
129
  const identity = JSON.stringify({
183
- version: 2,
130
+ version: 4,
184
131
  hash: sha256(JSON.stringify([source.identity, await inputs()])),
185
132
  });
186
- const progress = await journal(source, identity, scenes, commit);
187
- let complete = false;
133
+ const progress = await journal(source, identity, { all, picked, inputs: own }, commit, runtime);
134
+ let drawn = false;
188
135
  try {
189
136
  progress.check();
190
- const finished = scenes.length - progress.remaining.length;
137
+ const finished = picked.length - progress.remaining.length;
191
138
  if (finished) {
192
139
  const first = progress.remaining[0];
193
- const next = first === undefined ? scenes.length : scenes.indexOf(first) + 1;
140
+ const next = first === undefined ? picked.length : picked.indexOf(first) + 1;
194
141
  process.stderr.write(`${t('prototype.continuing', {
195
142
  next: number(next),
196
- total: number(scenes.length),
143
+ total: number(picked.length),
197
144
  count: finished,
198
- })}\n`);
145
+ })}
146
+ `);
199
147
  const digits = new Intl.NumberFormat(locale(), { useGrouping: false });
200
148
  console.log(commandT('ui.snapshot.progress.total', {
201
149
  done: digits.format(finished),
202
- total: digits.format(scenes.length),
150
+ total: digits.format(picked.length),
203
151
  }));
204
152
  }
205
153
  const report = await write(progress.remaining, progress);
206
- complete = true;
154
+ // Only this run's scenes count: a kept scene's old render failure is not this run's.
155
+ const mine = new Set(picked.map((scene) => scene.key));
156
+ drawn = !report.problems.some((problem) => problem.check === 'render' && mine.has(problem.scene ?? ''));
207
157
  return report;
208
158
  }
209
159
  finally {
210
- if (complete || !progress.valid())
160
+ if (!progress.valid())
211
161
  await rm(source.dir, { recursive: true, force: true, maxRetries: 3 }).catch(() => { });
162
+ else if (drawn)
163
+ await progress.finish().catch(() => { });
212
164
  }
213
165
  }
214
166
  finally {
@@ -0,0 +1,14 @@
1
+ import { type Imports, type SourceFiles, type SurfaceEntry } from './snapshot-bundle.ts';
2
+ export declare function registry(file: string, edges: Imports, deps: SourceFiles, eager: boolean): Promise<{
3
+ named: Map<string, string>;
4
+ lazy: Set<string>;
5
+ setup: {
6
+ path: string;
7
+ kind: import("esbuild").ImportKind;
8
+ external?: boolean;
9
+ original?: string;
10
+ with?: Record<string, string>;
11
+ }[];
12
+ } | undefined>;
13
+ export declare function registryConsumer(entry: SurfaceEntry, consumer: string, imports: Imports, deps: SourceFiles): Promise<boolean>;
14
+ export declare function knownDeferred(entry: SurfaceEntry, file: string, edges: Imports, locales: readonly string[], deps: SourceFiles): Promise<boolean>;
@@ -0,0 +1,121 @@
1
+ import { dirname, resolve } from 'node:path';
2
+ import { PSEUDO_LOCALES } from '@buffcore/i18n';
3
+ import { generatedIntlLoaders } from '../intl-locales.js';
4
+ import { codeReferences } from './milestone-references.js';
5
+ import { inProse, tokenize } from './milestone-tokens.js';
6
+ import { code, reexports, } from './snapshot-bundle.js';
7
+ function lazyViews(source, edges) {
8
+ const tokens = tokenize(source, true);
9
+ const views = new Map();
10
+ const imports = new Set();
11
+ if (!tokens || !/^import \{[\w\s,]*\blazy\b[\w\s,]*} from "react";$/m.test(source))
12
+ return { views, imports };
13
+ const declaration = /^export const (\w+) = lazy\(\s*\(\) => import\("(\.\/[^"?\\]+)"\)\.then\(\(m\) => \(\{ default: m\.\1 }\)\)\s*\);$/gm;
14
+ for (const { 1: name, 2: spec, index } of source.matchAll(declaration)) {
15
+ if (!name || !spec || inProse(tokens.prose, index))
16
+ continue;
17
+ const targets = edges.filter((edge) => edge.original === spec);
18
+ const [target] = targets;
19
+ if (!target || targets.length !== 1 || target.external || target.kind !== 'dynamic-import')
20
+ continue;
21
+ views.set(name, target.path);
22
+ imports.add(spec);
23
+ }
24
+ return { views, imports };
25
+ }
26
+ export async function registry(file, edges, deps, eager) {
27
+ const source = await code(file, deps);
28
+ const exports = reexports(source);
29
+ if (!exports)
30
+ return;
31
+ const lazy = lazyViews(source, edges);
32
+ const named = lazy.views;
33
+ const imported = new Set();
34
+ for (const match of exports) {
35
+ const [, bindings, specifier] = match;
36
+ if (!bindings || !specifier)
37
+ return;
38
+ const spec = JSON.parse(specifier);
39
+ const targets = edges.filter((edge) => edge.original === spec);
40
+ const target = targets[0]?.path;
41
+ if (!target || targets.some((edge) => edge.path !== target))
42
+ return;
43
+ if (bindings !== '*') {
44
+ for (const binding of bindings.slice(1, -1).split(',')) {
45
+ const [, original, alias] = /^\s*([\w$]+)(?:\s+as\s+([\w$]+))?\s*$/.exec(binding) ?? [];
46
+ if (!original)
47
+ return;
48
+ named.set(alias ?? original, target);
49
+ }
50
+ }
51
+ imported.add(spec);
52
+ }
53
+ const body = source.split('');
54
+ for (const { index, 0: statement } of exports)
55
+ body.fill(' ', index, index + statement.length);
56
+ const refs = codeReferences(body.join(''), true);
57
+ if (typeof refs === 'string')
58
+ return;
59
+ const used = new Set(refs.map(([, spec]) => spec));
60
+ return {
61
+ named,
62
+ lazy: lazy.imports,
63
+ setup: edges.filter(({ original }) => !original ||
64
+ !(eager ? lazy.imports.has(original) : imported.has(original) && !used.has(original))),
65
+ };
66
+ }
67
+ export async function registryConsumer(entry, consumer, imports, deps) {
68
+ const app = entry.surface === 'app';
69
+ if (consumer !== resolve(dirname(entry.registry), app ? 'scene.tsx' : 'index.tsx'))
70
+ return false;
71
+ const source = await code(consumer, deps);
72
+ const tokens = tokenize(source, true);
73
+ if (!tokens)
74
+ return false;
75
+ const { code: body, prose } = tokens;
76
+ const factory = app ? 'createScene' : 'createPrototype';
77
+ const shell = app ? 'app' : 'admin';
78
+ const module = `@buffcore/${shell}-shell/prototype`;
79
+ const resolved = imports.find(({ original }) => original === module)?.path;
80
+ if (!resolved ||
81
+ !new RegExp(`(?:^|/)(?:packages/|node_modules/@buffcore/)${shell}-shell/`).test(resolved))
82
+ return false;
83
+ const matches = (pattern) => [...body.matchAll(pattern)].filter(({ index }) => !inProse(prose, index));
84
+ const input = matches(/^import \* as views from "\.\/views(?:\.ts)?";$/gm)[0];
85
+ const factoryImport = matches(/^import \{ (\w+) } from "(@buffcore\/[\w/-]+)";$/gm);
86
+ const [call] = matches(new RegExp(`\\b${factory}\\(\\{`, 'g'));
87
+ const views = matches(/\bviews\b/g);
88
+ const property = views[1]?.index;
89
+ if (!input ||
90
+ !call ||
91
+ property === undefined ||
92
+ views.length !== 2 ||
93
+ !factoryImport.some(([, name, spec]) => name === factory && spec === module) ||
94
+ matches(new RegExp(`\\b${factory}\\b`, 'g')).length !== 2 ||
95
+ !/^[{,]\s*$/.test(body.slice(0, property).trimEnd().slice(-1)) ||
96
+ !/^\s*[,}]/.test(body.slice(property + 'views'.length)))
97
+ return false;
98
+ const start = call.index + call[0].length;
99
+ if (property < start)
100
+ return false;
101
+ let depth = 1;
102
+ for (let i = start; i < property; i++) {
103
+ if (inProse(prose, i))
104
+ continue;
105
+ if ('({['.includes(body.charAt(i)))
106
+ depth++;
107
+ if (')}]'.includes(body.charAt(i)) && --depth < 1)
108
+ return false;
109
+ }
110
+ return depth === 1;
111
+ }
112
+ export async function knownDeferred(entry, file, edges, locales, deps) {
113
+ if (entry.surface === 'admin')
114
+ return (file === resolve(entry.dir, 'src/main.tsx') &&
115
+ edges.every(({ original }) => original === './prototype/index.tsx'));
116
+ if (file !== resolve(entry.dir, 'src/i18n/intl-locales.gen.ts'))
117
+ return false;
118
+ const product = locales.filter((locale) => !PSEUDO_LOCALES.some((pseudo) => pseudo === locale));
119
+ return ((await deps.read(file)).toString('utf8').replaceAll('\r\n', '\n') ===
120
+ generatedIntlLoaders(entry.dir, product));
121
+ }
@@ -5,4 +5,8 @@ import type { SnapshotOptions } from './snapshot.ts';
5
5
  import { type PreviousSnapshot } from './snapshot-completion.ts';
6
6
  import type { SnapshotInputs } from './snapshot-inputs.ts';
7
7
  import type { SnapshotProgress } from './snapshot-progress.ts';
8
+ export declare function snapshotFiles(folder: string): Promise<string[]>;
9
+ /** Expo Router discovers these modules even though nobody imports them by name. */
10
+ export declare function expoRoutes(dir: string): Promise<string[]>;
11
+ export declare function appBootstrap(dir: string, read: (file: string) => Promise<Buffer>): Promise<string | undefined>;
8
12
  export declare function writeSnapshot(options: SnapshotOptions, run: Run, picked: readonly Scene[], remaining: readonly Scene[], progress?: SnapshotProgress, inputs?: SnapshotInputs, previous?: PreviousSnapshot): Promise<SnapshotReport>;
@@ -1,16 +1,52 @@
1
- import { writeFile } from 'node:fs/promises';
2
- import { join } from 'node:path';
1
+ import { existsSync } from 'node:fs';
2
+ import { lstat, readdir, writeFile } from 'node:fs/promises';
3
+ import { join, resolve } from 'node:path';
3
4
  import { checkTheme } from '@buffcore/tokens';
4
5
  import { HOST_GIT_MAX_BUFFER } from '../safe-git.js';
5
6
  import { t } from './messages.js';
7
+ import { withoutComments } from './milestone-tokens.js';
6
8
  import { ownFirst } from './own-scenes.js';
7
9
  import { sceneSelection } from './scene-selection.js';
8
10
  import { SnapshotCheckoutChanged } from './snapshot-checkout.js';
9
- import { inputsFingerprint, keptScenes, partialReason, stagePreviousFiles, } from './snapshot-completion.js';
11
+ import { inputsFingerprint, keptScenes, partialReason, reuseFingerprint, runtimeHash, stagePreviousFiles, } from './snapshot-completion.js';
10
12
  import { identicalProblems } from './snapshot-identical.js';
11
13
  import { reuseScenes, sceneFacts } from './snapshot-reuse.js';
12
14
  import { snapAll } from './snapshot-runner.js';
13
15
  import { hashShots } from './snapshot-shots.js';
16
+ export async function snapshotFiles(folder) {
17
+ if (!existsSync(folder))
18
+ return [];
19
+ if (!(await lstat(folder)).isDirectory())
20
+ throw new Error();
21
+ const paths = [];
22
+ for (const file of await readdir(folder, { recursive: true, withFileTypes: true })) {
23
+ if (file.isDirectory())
24
+ continue;
25
+ if (!file.isFile())
26
+ throw new Error();
27
+ paths.push(join(file.parentPath, file.name));
28
+ }
29
+ return paths.sort();
30
+ }
31
+ /** Expo Router discovers these modules even though nobody imports them by name. */
32
+ export async function expoRoutes(dir) {
33
+ const paths = await Promise.all(['app', 'src/app'].map((folder) => snapshotFiles(join(dir, folder))));
34
+ return paths.flat().filter((file) => /\.[jt]sx?$/.test(file) && !/\+api\.[jt]sx?$/.test(file));
35
+ }
36
+ export async function appBootstrap(dir, read) {
37
+ const manifest = await read(resolve(dir, 'package.json'));
38
+ const { main } = JSON.parse(manifest.toString('utf8'));
39
+ if (main === undefined || main === 'expo-router/entry')
40
+ return;
41
+ if (main !== 'index.ts' && main !== './index.ts')
42
+ throw new Error();
43
+ const boot = resolve(dir, main);
44
+ const source = withoutComments((await read(boot)).toString('utf8'), false)?.trim();
45
+ const stock = /^import ['"]\.\/src\/themes\.ts['"];?\s*import ['"]expo-router\/entry['"];?$/;
46
+ if (!source || !stock.test(source))
47
+ throw new Error();
48
+ return boot;
49
+ }
14
50
  export async function writeSnapshot(options, run, picked, remaining, progress, inputs, previous) {
15
51
  // Everything that needs no page runs first: a run that will fail on it fails before a server
16
52
  // starts. The problems are listed where they always were, after the scenes'.
@@ -25,7 +61,10 @@ export async function writeSnapshot(options, run, picked, remaining, progress, i
25
61
  const kept = keptScenes(previous?.report, selected);
26
62
  await stagePreviousFiles(previous, run, selected);
27
63
  const draw = await drawResults(options, run, picked, remaining, themeProblems.length > 0, progress, inputs);
28
- const { scenes, problems, hints } = await collectScenes(run, picked, draw, kept, inputs?.fingerprints);
64
+ const runtime = runtimeHash(inputs, run);
65
+ if (runtime !== draw.runtime && (draw.reuse?.scenes.size || remaining.length < picked.length))
66
+ throw new SnapshotCheckoutChanged(run.commit, run.commit);
67
+ const { scenes, problems, hints } = await collectScenes(run, picked, draw, kept, inputs);
29
68
  problems.push(...themeProblems);
30
69
  const all = options.scenes.scenes;
31
70
  const dirty = options.dirty?.() !== false;
@@ -35,6 +74,13 @@ export async function writeSnapshot(options, run, picked, remaining, progress, i
35
74
  ? undefined
36
75
  : await partialReason(previous?.report, run, selected, all, { dirty, design: options.design, inputsFingerprint: fingerprint }, inputs);
37
76
  if (selection !== undefined && reason === undefined) {
77
+ // Local completion can retain pictures for the terminal report. Only a full run can
78
+ // supply new reuse evidence, so keep the broad binding on its locally retained entries.
79
+ for (const scene of scenes) {
80
+ const broad = inputs?.fingerprints.get(scene.key);
81
+ if (!scene.reusedFrom && scene.fingerprint && broad)
82
+ scene.fingerprint = broad;
83
+ }
38
84
  const order = new Map(all.map(({ key }, index) => [key, index]));
39
85
  scenes.sort((a, b) => (order.get(a.key) ?? 0) - (order.get(b.key) ?? 0));
40
86
  }
@@ -52,6 +98,10 @@ export async function writeSnapshot(options, run, picked, remaining, progress, i
52
98
  dirty: dirty || (!!kept?.scenes.length && previous?.report?.dirty !== false),
53
99
  themes: run.looks.map((t) => t.key),
54
100
  locales: run.locales,
101
+ matrix: run.matrix ?? 'full',
102
+ ...(run.matrixReason ? { matrixReason: run.matrixReason } : {}),
103
+ ...(run.fullInputs ? { fullInputs: run.fullInputs } : {}),
104
+ ...(run.selector ? { selector: run.selector } : {}),
55
105
  scenes,
56
106
  problems,
57
107
  ...(hints.length ? { hints } : {}),
@@ -59,17 +109,21 @@ export async function writeSnapshot(options, run, picked, remaining, progress, i
59
109
  const reuseReport = draw.reuse?.ancestor?.ref ?? previous?.report?.reuseReport;
60
110
  if (reuseReport && scenes.some((scene) => scene.reusedFrom))
61
111
  report.reuseReport = reuseReport;
62
- if (inputs?.fingerprints.size && !(await inputs.same()))
63
- throw new SnapshotCheckoutChanged(run.commit, run.commit);
64
112
  await options.beforeReport?.();
65
113
  await writeReport(run.out, report, run.checkCheckout);
66
114
  for (const [name, value] of Object.entries(options.artifacts ?? {}))
67
115
  await writeFile(join(run.out, name), `${JSON.stringify(value, null, 2)}\n`);
116
+ if (inputs && (!(await inputs.same()) || runtime !== runtimeHash(inputs, run)))
117
+ throw new SnapshotCheckoutChanged(run.commit, run.commit);
68
118
  return report;
69
119
  }
70
120
  async function drawResults(options, run, picked, remaining, themeFailed, progress, inputs) {
71
- const reuse = options.scene === undefined && inputs?.fingerprints.size && options.root
72
- ? await reuseScenes(options.root, run, picked, remaining, inputs.fingerprints)
121
+ const runtime = runtimeHash(inputs, run);
122
+ const reuse = options.scene === undefined && inputs?.reuse.size && options.root
123
+ ? await reuseScenes(options.root, run, picked, remaining, new Map(picked.flatMap((scene) => {
124
+ const fingerprint = reuseFingerprint(inputs, scene);
125
+ return fingerprint ? [[scene.key, fingerprint]] : [];
126
+ })))
73
127
  : undefined;
74
128
  // The change's own scenes are drawn first when the run names them; the report keeps its order.
75
129
  const own = options.ownScenes;
@@ -81,16 +135,21 @@ async function drawResults(options, run, picked, remaining, themeFailed, progres
81
135
  const warmScenes = new Set(firstOnSurface.values());
82
136
  if (themeFailed) {
83
137
  console.log(t('prototype.noRender'));
84
- return { reuse, results: new Map() };
138
+ return { reuse, runtime, results: new Map(), fresh: new Set() };
85
139
  }
86
140
  await options.prepare?.(drawing);
87
141
  const drawn = await snapAll(drawing, options.scene === undefined ? { ...run, warmScenes } : run, undefined, { pages: options.pages });
88
142
  const order = progress ? uncopied : drawing;
89
143
  const snapped = progress ? await progress.collect(order, run) : drawn;
90
144
  // Each result belongs to the scene it was drawn for, whatever order the scenes were drawn in.
91
- return { reuse, results: new Map(order.map(({ key }, i) => [key, snapped[i]])) };
145
+ return {
146
+ reuse,
147
+ runtime,
148
+ results: new Map(order.map(({ key }, i) => [key, snapped[i]])),
149
+ fresh: new Set(options.scene === undefined ? drawing.map(({ key }) => key) : []),
150
+ };
92
151
  }
93
- async function collectScenes(run, picked, { reuse, results }, kept, fingerprints) {
152
+ async function collectScenes(run, picked, { reuse, results, fresh }, kept, inputs) {
94
153
  const hints = [...(kept?.hints ?? [])];
95
154
  const problems = [...(kept?.problems ?? [])];
96
155
  const scenes = [...(kept?.scenes ?? [])];
@@ -115,6 +174,11 @@ async function collectScenes(run, picked, { reuse, results }, kept, fingerprints
115
174
  };
116
175
  if (result.cut?.length)
117
176
  scene.cut = result.cut;
177
+ if (run.matrix === 'floor')
178
+ scene.matrix = 'floor';
179
+ const extra = run.matrix === 'floor' ? run.extraLooks?.get(key) : undefined;
180
+ if (extra?.size)
181
+ scene.extraLooks = [...extra];
118
182
  if (typeof result.apiCalls === 'boolean')
119
183
  scene.apiCalls = result.apiCalls;
120
184
  if (result.retried)
@@ -128,7 +192,8 @@ async function collectScenes(run, picked, { reuse, results }, kept, fingerprints
128
192
  const hashes = await hashShots(run.out, run.commit, scene);
129
193
  if (hashes)
130
194
  scene.screenshotHashes = hashes;
131
- const fingerprint = fingerprints?.get(key);
195
+ const candidate = fresh.has(key) && reuseFingerprint(inputs, scene);
196
+ const fingerprint = candidate || inputs?.fingerprints.get(key);
132
197
  if (hashes && fingerprint && result.untrackedRequests === false)
133
198
  scene.fingerprint = fingerprint;
134
199
  scenes.push(scene);
@@ -1,9 +1,19 @@
1
1
  import type { Scene } from '@buffcore/config';
2
- import type { Page } from 'playwright-core';
2
+ import type { Page, Response } from 'playwright-core';
3
3
  import type { Run } from './scene.ts';
4
4
  export interface SceneRequestFacts {
5
5
  apiCalls: boolean;
6
6
  untrackedRequests: boolean;
7
7
  }
8
- /** Context requests include iframes, workers and requests that fail before receiving a response. */
9
- export declare function sceneRequests(page: Page, { urls, hasAsset, requests: found, }: Pick<Run, 'urls' | 'hasAsset' | 'requests'>, scene: Scene): SceneRequestFacts;
8
+ export type RequestCoverage = (scene: Scene, url: URL, kind: string, response?: Response) => boolean | Promise<boolean>;
9
+ /** Wait for the coverage of every load that added to these facts, failed loads included. */
10
+ export declare function settleRequests(facts: SceneRequestFacts): Promise<void>;
11
+ /**
12
+ * Context requests include iframes, workers and requests that fail before receiving a response.
13
+ * `look()` starts a look: more than one navigation of the page within a look is not tracked.
14
+ */
15
+ export declare function sceneRequests(page: Page, { urls, coversRequest, requests: found, }: Pick<Run, 'urls' | 'coversRequest' | 'requests'>, scene: Scene): {
16
+ facts: SceneRequestFacts;
17
+ finish: () => Promise<void>;
18
+ look: () => void;
19
+ };