@buffcore/cli 0.8.41 → 0.8.42

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 (164) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/dist/commands/agents-file.d.ts +5 -0
  3. package/dist/commands/agents-file.js +30 -7
  4. package/dist/commands/change.d.ts +4 -0
  5. package/dist/commands/change.js +12 -5
  6. package/dist/commands/create-block.d.ts +2 -1
  7. package/dist/commands/create-block.js +7 -5
  8. package/dist/commands/create.d.ts +3 -2
  9. package/dist/commands/create.en.js +1 -1
  10. package/dist/commands/create.es.js +1 -1
  11. package/dist/commands/create.js +8 -6
  12. package/dist/commands/design/check.d.ts +2 -0
  13. package/dist/commands/design/check.js +6 -0
  14. package/dist/commands/design/journey-roles.d.ts +6 -0
  15. package/dist/commands/design/journey-roles.js +60 -0
  16. package/dist/commands/design/references.d.ts +3 -0
  17. package/dist/commands/design/references.js +25 -0
  18. package/dist/commands/design/tells-text.js +2 -2
  19. package/dist/commands/design/tells.d.ts +3 -1
  20. package/dist/commands/design/tells.en.d.ts +2 -0
  21. package/dist/commands/design/tells.en.js +2 -0
  22. package/dist/commands/design/tells.es.js +2 -0
  23. package/dist/commands/design/tells.js +10 -7
  24. package/dist/commands/dev.js +3 -0
  25. package/dist/commands/port-claims.d.ts +23 -0
  26. package/dist/commands/port-claims.js +95 -0
  27. package/dist/commands/prototype/browser.d.ts +9 -4
  28. package/dist/commands/prototype/browser.js +26 -18
  29. package/dist/commands/prototype/export-base.d.ts +27 -0
  30. package/dist/commands/prototype/export-base.js +80 -0
  31. package/dist/commands/prototype/export.d.ts +3 -2
  32. package/dist/commands/prototype/export.js +13 -6
  33. package/dist/commands/prototype/index.js +1 -0
  34. package/dist/commands/prototype/media-ready.d.ts +8 -0
  35. package/dist/commands/prototype/media-ready.js +36 -0
  36. package/dist/commands/prototype/messages.en.d.ts +6 -0
  37. package/dist/commands/prototype/messages.en.js +6 -0
  38. package/dist/commands/prototype/messages.js +6 -0
  39. package/dist/commands/prototype/scene.d.ts +3 -1
  40. package/dist/commands/prototype/scene.js +22 -6
  41. package/dist/commands/prototype/snapshot-inputs.js +35 -7
  42. package/dist/commands/prototype/snapshot-setup.d.ts +1 -1
  43. package/dist/commands/prototype/snapshot-setup.js +2 -1
  44. package/dist/commands/prototype/snapshot.d.ts +2 -0
  45. package/dist/commands/prototype/snapshot.js +2 -1
  46. package/dist/commands/ui/chat/allow-folder.js +23 -77
  47. package/dist/commands/ui/chat/claude-permissions.d.ts +21 -0
  48. package/dist/commands/ui/chat/claude-permissions.js +69 -0
  49. package/dist/commands/ui/chat/codex-idle.d.ts +1 -0
  50. package/dist/commands/ui/chat/codex-overrides.js +2 -1
  51. package/dist/commands/ui/chat/codex-permissions.d.ts +12 -0
  52. package/dist/commands/ui/chat/codex-permissions.js +97 -0
  53. package/dist/commands/ui/chat/command-parts.d.ts +33 -0
  54. package/dist/commands/ui/chat/command-parts.js +219 -0
  55. package/dist/commands/ui/chat/command-wrappers.d.ts +21 -0
  56. package/dist/commands/ui/chat/command-wrappers.js +100 -0
  57. package/dist/commands/ui/chat/design-deletes.d.ts +1 -0
  58. package/dist/commands/ui/chat/design-deletes.js +39 -0
  59. package/dist/commands/ui/chat/launch-input.d.ts +4 -2
  60. package/dist/commands/ui/chat/launch-input.js +16 -3
  61. package/dist/commands/ui/chat/limit-mentions.d.ts +5 -0
  62. package/dist/commands/ui/chat/limit-mentions.js +74 -0
  63. package/dist/commands/ui/chat/limit-patterns.d.ts +15 -0
  64. package/dist/commands/ui/chat/limit-patterns.js +182 -0
  65. package/dist/commands/ui/chat/limits-hook.d.ts +1 -0
  66. package/dist/commands/ui/chat/limits-hook.js +30 -0
  67. package/dist/commands/ui/chat/limits.d.ts +37 -0
  68. package/dist/commands/ui/chat/limits.en.d.ts +18 -0
  69. package/dist/commands/ui/chat/limits.en.js +18 -0
  70. package/dist/commands/ui/chat/limits.es.d.ts +2 -0
  71. package/dist/commands/ui/chat/limits.es.js +17 -0
  72. package/dist/commands/ui/chat/limits.js +224 -0
  73. package/dist/commands/ui/chat/local-settings.d.ts +17 -0
  74. package/dist/commands/ui/chat/local-settings.js +73 -0
  75. package/dist/commands/ui/chat/opencode-config.d.ts +22 -0
  76. package/dist/commands/ui/chat/opencode-config.js +83 -0
  77. package/dist/commands/ui/chat/parse-claude.js +18 -2
  78. package/dist/commands/ui/chat/permission-ask.d.ts +44 -0
  79. package/dist/commands/ui/chat/permission-ask.js +142 -0
  80. package/dist/commands/ui/chat/permission-channel.d.ts +18 -0
  81. package/dist/commands/ui/chat/permission-channel.js +67 -0
  82. package/dist/commands/ui/chat/permission-route.d.ts +10 -0
  83. package/dist/commands/ui/chat/permission-route.js +47 -0
  84. package/dist/commands/ui/chat/permission-tool.d.ts +1 -0
  85. package/dist/commands/ui/chat/permission-tool.js +86 -0
  86. package/dist/commands/ui/chat/permissions.d.ts +11 -12
  87. package/dist/commands/ui/chat/permissions.js +20 -102
  88. package/dist/commands/ui/chat/planning-limits.d.ts +12 -0
  89. package/dist/commands/ui/chat/planning-limits.js +31 -0
  90. package/dist/commands/ui/chat/process.js +4 -1
  91. package/dist/commands/ui/chat/prompt.d.ts +8 -1
  92. package/dist/commands/ui/chat/prompt.en.d.ts +4 -0
  93. package/dist/commands/ui/chat/prompt.en.js +4 -0
  94. package/dist/commands/ui/chat/prompt.es.d.ts +4 -0
  95. package/dist/commands/ui/chat/prompt.es.js +4 -0
  96. package/dist/commands/ui/chat/prompt.js +18 -50
  97. package/dist/commands/ui/chat/recorded-turn.js +3 -0
  98. package/dist/commands/ui/chat/routes.js +2 -0
  99. package/dist/commands/ui/chat/secret-folders.d.ts +16 -0
  100. package/dist/commands/ui/chat/secret-folders.js +35 -0
  101. package/dist/commands/ui/chat/stdin-shells.d.ts +8 -0
  102. package/dist/commands/ui/chat/stdin-shells.js +102 -0
  103. package/dist/commands/ui/chat/step-rules.d.ts +13 -0
  104. package/dist/commands/ui/chat/step-rules.js +47 -0
  105. package/dist/commands/ui/chat/store.js +11 -2
  106. package/dist/commands/ui/chat/stream.en.d.ts +6 -0
  107. package/dist/commands/ui/chat/stream.en.js +6 -0
  108. package/dist/commands/ui/chat/stream.es.d.ts +6 -0
  109. package/dist/commands/ui/chat/stream.es.js +6 -0
  110. package/dist/commands/ui/chat/stream.js +4 -1
  111. package/dist/commands/ui/chat/turn-guard.d.ts +25 -0
  112. package/dist/commands/ui/chat/turn-guard.js +74 -0
  113. package/dist/commands/ui/chat/turn-input.d.ts +3 -2
  114. package/dist/commands/ui/chat/turn-input.js +3 -1
  115. package/dist/commands/ui/chat/turn-scenes.d.ts +19 -0
  116. package/dist/commands/ui/chat/turn-scenes.js +44 -0
  117. package/dist/commands/ui/chat/turn-state.d.ts +6 -0
  118. package/dist/commands/ui/chat/turn.js +8 -3
  119. package/dist/commands/ui/level-route.js +8 -3
  120. package/dist/commands/ui/page.d.ts +19 -1
  121. package/dist/commands/ui/page.js +9 -6
  122. package/dist/commands/ui/plan-structure.d.ts +9 -2
  123. package/dist/commands/ui/plan-structure.en.d.ts +1 -0
  124. package/dist/commands/ui/plan-structure.en.js +1 -0
  125. package/dist/commands/ui/plan-structure.es.d.ts +1 -0
  126. package/dist/commands/ui/plan-structure.es.js +1 -0
  127. package/dist/commands/ui/plan-structure.js +36 -10
  128. package/dist/commands/ui/prototype-main.d.ts +1 -0
  129. package/dist/commands/ui/prototype-scenes-child.js +3 -1
  130. package/dist/commands/ui/prototype-scenes-read.d.ts +1 -0
  131. package/dist/commands/ui/prototype-scenes-route.js +7 -1
  132. package/dist/commands/ui/save-commit.js +6 -2
  133. package/dist/commands/ui/server-options.js +2 -0
  134. package/dist/commands/ui/server.d.ts +5 -22
  135. package/dist/commands/ui/server.js +3 -45
  136. package/dist/commands/ui/snapshot-runners.d.ts +22 -0
  137. package/dist/commands/ui/snapshot-runners.js +45 -0
  138. package/dist/commands/ui/studio-routes.d.ts +1 -0
  139. package/dist/commands/ui/studio-routes.js +1 -0
  140. package/dist/commands/ui/studio-state.d.ts +3 -0
  141. package/dist/commands/ui/studio-state.js +1 -0
  142. package/dist/commands/ui/studio.en.d.ts +13 -0
  143. package/dist/commands/ui/studio.en.js +13 -0
  144. package/dist/commands/ui/studio.es.d.ts +13 -0
  145. package/dist/commands/ui/studio.es.js +13 -0
  146. package/dist/commands/ui/theme-option.d.ts +8 -0
  147. package/dist/commands/ui/theme-option.js +40 -0
  148. package/dist/commands/ui/theme-values.d.ts +5 -0
  149. package/dist/commands/ui/theme-values.js +113 -0
  150. package/dist/ui/page.js +93 -93
  151. package/docs/PROTOTYPE.md +4 -1
  152. package/docs/WORKBENCH.md +76 -22
  153. package/package.json +11 -11
  154. package/skills/ape-critique/SKILL.md +8 -4
  155. package/skills/ape-design-system/SKILL.md +3 -3
  156. package/skills/ape-plan-change/SKILL.md +7 -3
  157. package/skills/ape-prototype/SKILL.md +8 -1
  158. package/templates/example/apps/app/src/i18n/en.ts +2 -0
  159. package/templates/example/apps/app/src/i18n/es.json +2 -0
  160. package/templates/product/apps/admin/src/fonts.ts +2 -1
  161. package/templates/product/apps/app/src/fonts.ts +5 -1
  162. package/templates/product/apps/app/src/i18n/en.ts +2 -0
  163. package/templates/product/apps/app/src/i18n/es.json +2 -0
  164. package/templates/product/prototype/journeys.ts +3 -0
@@ -0,0 +1,95 @@
1
+ import { existsSync, lstatSync, readdirSync, readFileSync } from 'node:fs';
2
+ import { mkdir, rename, rm, writeFile } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import { dirname, join, resolve } from 'node:path';
5
+ const FILE = 'ports.json';
6
+ const SIBLINGS = 500;
7
+ /** The user's BuffCore config folder: `APE_CONFIG_HOME`, else the platform's own. */
8
+ export function configHome(env = process.env) {
9
+ if (env.APE_CONFIG_HOME)
10
+ return env.APE_CONFIG_HOME;
11
+ if (process.platform === 'win32' && env.APPDATA)
12
+ return join(env.APPDATA, 'buffcore');
13
+ return join(env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'buffcore');
14
+ }
15
+ /** One spelling per folder: Windows paths compare without case. */
16
+ const folderKey = (path) => process.platform === 'win32' ? resolve(path).toLowerCase() : resolve(path);
17
+ /** Folder → block, as `ports.json` lists them; a missing or malformed file lists none. */
18
+ export function readClaims(home) {
19
+ try {
20
+ const blocks = JSON.parse(readFileSync(join(home ?? configHome(), FILE), 'utf8'))?.blocks;
21
+ if (!blocks || typeof blocks !== 'object')
22
+ return {};
23
+ return Object.fromEntries(Object.entries(blocks).filter((entry) => Number.isInteger(entry[1]) && entry[1] >= 10 && entry[1] <= 64));
24
+ }
25
+ catch {
26
+ return {};
27
+ }
28
+ }
29
+ /** A product folder's block, from the API port its `.env` or `.env.example` names (not a link). */
30
+ export function folderBlock(folder) {
31
+ for (const name of ['.env', '.env.example']) {
32
+ try {
33
+ const path = join(folder, name);
34
+ if (lstatSync(path).isSymbolicLink())
35
+ continue;
36
+ const text = readFileSync(path, 'utf8');
37
+ const port = /^APE_API_PORT=(\d{4})\s*$/m.exec(text)?.[1];
38
+ if (port)
39
+ return String(Math.floor(Number(port) / 100));
40
+ }
41
+ catch {
42
+ // No such file, or unreadable: the next source, or no claim.
43
+ }
44
+ }
45
+ return undefined;
46
+ }
47
+ /** Every block claimed by a product other than the one at `target`. */
48
+ export function claimedBlocks(target, home) {
49
+ const own = folderKey(target);
50
+ const blocks = new Set();
51
+ for (const [path, block] of Object.entries(readClaims(home)))
52
+ if (folderKey(path) !== own && existsSync(path))
53
+ blocks.add(String(block));
54
+ try {
55
+ const parent = dirname(resolve(target));
56
+ const entries = readdirSync(parent, { withFileTypes: true }).slice(0, SIBLINGS);
57
+ for (const entry of entries) {
58
+ const folder = join(parent, entry.name);
59
+ if (!entry.isDirectory() || folderKey(folder) === own)
60
+ continue;
61
+ if (!existsSync(join(folder, 'buffcore.config.ts')))
62
+ continue;
63
+ const block = folderBlock(folder);
64
+ if (block)
65
+ blocks.add(block);
66
+ }
67
+ }
68
+ catch {
69
+ // The parent folder can't be listed: the list's claims only.
70
+ }
71
+ return blocks;
72
+ }
73
+ /** Records a product's block; folders that are gone drop out. Never fails the command. */
74
+ export async function claimBlock(folder, block, home) {
75
+ let temporary;
76
+ try {
77
+ const dir = home ?? configHome();
78
+ const kept = Object.fromEntries(Object.entries(readClaims(dir)).filter(([path]) => folderKey(path) !== folderKey(folder) && existsSync(path)));
79
+ kept[resolve(folder)] = Number(block);
80
+ await mkdir(dir, { recursive: true });
81
+ temporary = join(dir, `${FILE}.${process.pid}.tmp`);
82
+ await writeFile(temporary, `${JSON.stringify({ blocks: kept }, null, 2)}\n`);
83
+ await rename(temporary, join(dir, FILE));
84
+ }
85
+ catch {
86
+ // A list that can't be written changes nothing today; a half-written copy goes.
87
+ if (temporary)
88
+ await rm(temporary, { force: true }).catch(() => undefined);
89
+ }
90
+ }
91
+ /** This computer's claims, in the user's config folder. */
92
+ export const machineClaims = {
93
+ claimed: (target) => claimedBlocks(target),
94
+ claim: (folder, block) => claimBlock(folder, block),
95
+ };
@@ -43,14 +43,19 @@ export declare function sceneFrames(page: Page, locale: string): Promise<{
43
43
  index: number;
44
44
  locale: string;
45
45
  }[]>;
46
- /** Wait for the current scene and its framed scenes to finish drawing. */
47
- export declare function waitForScene(page: Page, locale: string, { live, animationWait, }?: {
46
+ /**
47
+ * Wait for the current scene and its framed scenes to finish drawing. True when a font or picture
48
+ * was still loading as its allowance ran out: the page is shot as it is.
49
+ */
50
+ export declare function waitForScene(page: Page, locale: string, { live, animationWait, mediaWait, }?: {
48
51
  live?: () => boolean;
49
52
  animationWait?: number;
50
- }): Promise<void>;
53
+ mediaWait?: number;
54
+ }): Promise<boolean>;
51
55
  /**
52
56
  * Show a scene page and wait until it has drawn. A scene that frames a scene page (a console
53
57
  * scene with the app's `/_scene` inside, e.g. a `DeviceFrame`) waits for that page too. A page
54
58
  * whose module fails to load (a busy dev server drops requests under load) is loaded again once.
59
+ * True when a font or picture was still loading after `mediaWait` (`MEDIA_WAIT` unset).
55
60
  */
56
- export declare function openScene(page: Page, url: string, locale: string): Promise<void>;
61
+ export declare function openScene(page: Page, url: string, locale: string, mediaWait?: number): Promise<boolean>;
@@ -5,6 +5,7 @@
5
5
  import { createRequire } from 'node:module';
6
6
  import { chromium, } from 'playwright-core';
7
7
  import { accessDenied } from './access-denied.js';
8
+ import { MEDIA_WAIT, mediaReady } from './media-ready.js';
8
9
  import { SnapshotAccessRefused } from './snapshot-refused.js';
9
10
  /**
10
11
  * The one command that installs the browser, anywhere (a product has no playwright-core of its
@@ -124,20 +125,20 @@ export async function animationsDone(timeout) {
124
125
  const ANIMATION_WAIT = 2_000;
125
126
  /**
126
127
  * Wait until a scene page in this frame has drawn: the view rendered in the asked language, the
127
- * fonts loaded, two frames painted, and animations finished within their allowance. The focused element is blurred
128
- * first, so a field that autofocuses shows no focus ring.
128
+ * fonts and pictures loaded (`mediaReady`), two frames painted, and animations finished within
129
+ * their allowance. The focused element is blurred first, so a field that autofocuses shows no
130
+ * focus ring. True when fonts or pictures were still loading as their allowance ran out.
129
131
  */
130
- async function drawn(frame, locale, live, animationWait) {
132
+ async function drawn(frame, locale, live, { animationWait, mediaWait }) {
131
133
  await frame.waitForFunction((lang) => document.documentElement.lang === lang &&
132
134
  (document.getElementById('root')?.childElementCount ?? 0) > 0, locale);
133
135
  // An attempt that lost its page (a module failed, the page loaded again) does nothing more.
134
136
  if (!live())
135
- return;
136
- await frame.evaluate(async () => {
137
- document.activeElement?.blur();
138
- await document.fonts.ready;
139
- });
137
+ return false;
138
+ await frame.evaluate(() => document.activeElement?.blur());
139
+ const ready = await frame.evaluate(mediaReady, mediaWait);
140
140
  await frame.evaluate(animationsDone, animationWait);
141
+ return !ready;
141
142
  }
142
143
  /** A script or module of the page failed to load: a busy dev server dropping a request. */
143
144
  class ModuleLost extends Error {
@@ -154,17 +155,23 @@ export async function sceneFrames(page, locale) {
154
155
  }));
155
156
  return frames.filter((entry) => entry !== undefined);
156
157
  }
157
- /** Wait for the current scene and its framed scenes to finish drawing. */
158
- export async function waitForScene(page, locale, { live = () => true, animationWait = ANIMATION_WAIT, } = {}) {
159
- await drawn(page.mainFrame(), locale, live, animationWait);
158
+ /**
159
+ * Wait for the current scene and its framed scenes to finish drawing. True when a font or picture
160
+ * was still loading as its allowance ran out: the page is shot as it is.
161
+ */
162
+ export async function waitForScene(page, locale, { live = () => true, animationWait = ANIMATION_WAIT, mediaWait = MEDIA_WAIT, } = {}) {
163
+ const waits = { animationWait, mediaWait };
164
+ let late = await drawn(page.mainFrame(), locale, live, waits);
160
165
  for (const entry of await sceneFrames(page, locale))
161
- await drawn(entry.frame, entry.locale, live, animationWait);
166
+ if (await drawn(entry.frame, entry.locale, live, waits))
167
+ late = true;
168
+ return late;
162
169
  }
163
170
  /**
164
171
  * Open the page (or load it again) and wait until it has drawn. A page whose script or module
165
172
  * fails to load never draws, so that ends the wait at once, not at the timeout.
166
173
  */
167
- async function show(page, url, locale, again) {
174
+ async function show(page, url, locale, again, mediaWait) {
168
175
  let lose = (_) => { };
169
176
  const lost = new Promise((_, reject) => {
170
177
  lose = reject;
@@ -192,13 +199,13 @@ async function show(page, url, locale, again) {
192
199
  throw new ConnectionRefused(url);
193
200
  throw error;
194
201
  }
195
- await waitForScene(page, locale, { live });
202
+ return waitForScene(page, locale, { live, ...(mediaWait === undefined ? {} : { mediaWait }) });
196
203
  })();
197
204
  // Whichever loses the race must not end the run as an unhandled rejection.
198
205
  drawing.catch(() => { });
199
206
  lost.catch(() => { });
200
207
  try {
201
- await Promise.race([drawing, lost]);
208
+ return await Promise.race([drawing, lost]);
202
209
  }
203
210
  finally {
204
211
  over = true;
@@ -209,16 +216,17 @@ async function show(page, url, locale, again) {
209
216
  * Show a scene page and wait until it has drawn. A scene that frames a scene page (a console
210
217
  * scene with the app's `/_scene` inside, e.g. a `DeviceFrame`) waits for that page too. A page
211
218
  * whose module fails to load (a busy dev server drops requests under load) is loaded again once.
219
+ * True when a font or picture was still loading after `mediaWait` (`MEDIA_WAIT` unset).
212
220
  */
213
- export async function openScene(page, url, locale) {
221
+ export async function openScene(page, url, locale, mediaWait) {
214
222
  try {
215
223
  try {
216
- await show(page, url, locale, false);
224
+ return await show(page, url, locale, false, mediaWait);
217
225
  }
218
226
  catch (error) {
219
227
  if (!(error instanceof ModuleLost))
220
228
  throw error;
221
- await show(page, url, locale, true);
229
+ return await show(page, url, locale, true, mediaWait);
222
230
  }
223
231
  }
224
232
  catch (error) {
@@ -0,0 +1,27 @@
1
+ export declare const ROOT_BASE = "/";
2
+ /**
3
+ * The base, checked and ending in `/`: `./` (or `.`), or a plain absolute path. Anything else is
4
+ * refused (a scheme, `..`, quotes or shell characters), since the base reaches a build command.
5
+ */
6
+ export declare function exportBase(text: string | undefined): string;
7
+ /** The viewer's own base for Vite: under `prototype/` of the site's root. */
8
+ export declare const viewerBase: (base: string) => string;
9
+ /** A page of the export: the viewer, the admin's scene page, or the app's scene page. */
10
+ export type ExportPage = 'viewer' | 'admin' | 'app';
11
+ /**
12
+ * Set before anything loads on an export's page: the export's root path (`__APE_EXPORT__` for the
13
+ * viewer's pages), a `<base>` its files resolve from, and for the app's scene page the root to its
14
+ * asset URLs (`__APE_SITE__`) and the path its router knows (`/_scene/`, a rewrite of the address
15
+ * only: Expo's router follows a base path in production builds alone, and the export's are
16
+ * development builds). Under a plain path the root is the one built in; only `./` finds it from
17
+ * the address, with leading slashes collapsed, and only when it resolves on the page's own origin,
18
+ * so an address such as `//other.example/..%2Fs/abc/_scene/` never sends the page elsewhere.
19
+ */
20
+ export declare function pageScript(page: ExportPage, base: string): string;
21
+ /**
22
+ * The app bundle's own files (its assets' `uri:"/assets/…"` or `exports="/assets/…"`, its chunks'
23
+ * `"paths"`), from the site's path rather than the server's root: each value becomes an expression.
24
+ */
25
+ export declare const siteAssets: (code: string) => string;
26
+ /** Make an export with a base other than `/` play from wherever its root is served. */
27
+ export declare function relocate(out: string, app: boolean, base: string): Promise<void>;
@@ -0,0 +1,80 @@
1
+ // Where a prototype export is served from (`ape prototype export --base <path>`): the site's root
2
+ // path, `/` by default (the viewer under `/prototype/`, as before), any other plain path such as
3
+ // `/s/abc/`, or `./` for paths relative to the page. Any base but `/` makes the scene pages find
4
+ // their files from where they are opened, so one export plays under any path, framed or not.
5
+ import { readdir, readFile, writeFile } from 'node:fs/promises';
6
+ import { join } from 'node:path';
7
+ import { t } from './messages.js';
8
+ export const ROOT_BASE = '/';
9
+ /** A plain path's segments: letters, digits, `-`, `_`, `~` and dots, never starting with a dot. */
10
+ const PLAIN = /^\/(?:[A-Za-z0-9_~-][A-Za-z0-9._~-]*\/)*$/;
11
+ /**
12
+ * The base, checked and ending in `/`: `./` (or `.`), or a plain absolute path. Anything else is
13
+ * refused (a scheme, `..`, quotes or shell characters), since the base reaches a build command.
14
+ */
15
+ export function exportBase(text) {
16
+ if (text === undefined)
17
+ return ROOT_BASE;
18
+ if (text === '.' || text === './')
19
+ return './';
20
+ const base = text.endsWith('/') ? text : `${text}/`;
21
+ if (!text || !PLAIN.test(base))
22
+ throw new Error(t('prototype.baseInvalid', { base: text }));
23
+ return base;
24
+ }
25
+ /** The viewer's own base for Vite: under `prototype/` of the site's root. */
26
+ export const viewerBase = (base) => (base === './' ? './' : `${base}prototype/`);
27
+ /** Where each page is under the export's root, found at the end of its path (regex source). */
28
+ const PAGE_AT = {
29
+ viewer: String.raw `\/prototype\/?$`,
30
+ admin: String.raw `\/prototype\/_scene\/?$`,
31
+ app: String.raw `\/_scene\/?$`,
32
+ };
33
+ /**
34
+ * Set before anything loads on an export's page: the export's root path (`__APE_EXPORT__` for the
35
+ * viewer's pages), a `<base>` its files resolve from, and for the app's scene page the root to its
36
+ * asset URLs (`__APE_SITE__`) and the path its router knows (`/_scene/`, a rewrite of the address
37
+ * only: Expo's router follows a base path in production builds alone, and the export's are
38
+ * development builds). Under a plain path the root is the one built in; only `./` finds it from
39
+ * the address, with leading slashes collapsed, and only when it resolves on the page's own origin,
40
+ * so an address such as `//other.example/..%2Fs/abc/_scene/` never sends the page elsewhere.
41
+ */
42
+ export function pageScript(page, base) {
43
+ const built = base === './' ? 'null' : JSON.stringify(base);
44
+ const set = page === 'app'
45
+ ? 'b.href=r;g.__APE_SITE__=r.slice(0,-1);' +
46
+ 'if(m)history.replaceState(history.state,"",p.slice(m.index)+location.search+location.hash);'
47
+ : `g.__APE_EXPORT__=r;${page === 'admin' ? 'b.href=r+"prototype/";' : ''}`;
48
+ const find = String.raw `p=location.pathname.replace(/^[\/\\]+/,"/"),m=/${PAGE_AT[page]}/.exec(p);`;
49
+ return (`<script>(function(){var g=globalThis,r=${built},${find}` +
50
+ 'if(r===null){if(!m)return;r=p.slice(0,m.index+1);' +
51
+ 'try{if(new URL(r,location.origin).origin!==location.origin)return}catch(e){return}}' +
52
+ `${page === 'viewer' ? '' : 'var b=document.createElement("base");document.head.prepend(b);'}` +
53
+ `${set}})()</script>`);
54
+ }
55
+ /**
56
+ * Root-relative `src` and `href` in a page moved under the base: absolute under a plain path (so
57
+ * the browser's early fetches find them too), or relative for `./`, resolved from its `<base>`.
58
+ */
59
+ const movedLinks = (html, base) => html.replace(/\b(src|href)="\/(?!\/)/g, `$1="${base === './' ? '' : base}`);
60
+ async function rewrite(file, change) {
61
+ await writeFile(file, change(await readFile(file, 'utf8')));
62
+ }
63
+ /**
64
+ * The app bundle's own files (its assets' `uri:"/assets/…"` or `exports="/assets/…"`, its chunks'
65
+ * `"paths"`), from the site's path rather than the server's root: each value becomes an expression.
66
+ */
67
+ export const siteAssets = (code) => code.replace(/(?<=[:(,[?]|(?<![=!<>])=)"\/(assets|_expo)\//g, '(globalThis.__APE_SITE__||"")+"/$1/');
68
+ /** Make an export with a base other than `/` play from wherever its root is served. */
69
+ export async function relocate(out, app, base) {
70
+ const head = (page) => (html) => html.replace(/<head[^>]*>/i, `$&${pageScript(page, base)}`);
71
+ await rewrite(join(out, 'prototype', 'index.html'), head('viewer'));
72
+ await rewrite(join(out, 'prototype', '_scene', 'index.html'), head('admin'));
73
+ if (!app)
74
+ return;
75
+ await rewrite(join(out, '_scene', 'index.html'), (html) => head('app')(movedLinks(html, base)));
76
+ const bundles = join(out, '_expo', 'static', 'js', 'web');
77
+ const files = await readdir(bundles).catch(() => []);
78
+ for (const file of files.filter((f) => f.endsWith('.js')))
79
+ await rewrite(join(bundles, file), siteAssets);
80
+ }
@@ -21,8 +21,9 @@ export declare function commitToExport(root: string, commit?: string): string;
21
21
  * and name the commit in its `export.json`. Development builds: production ones leave the scenes
22
22
  * and the sample data out.
23
23
  */
24
- export declare function buildSite(root: string, out: string, exported: ExportedCommit): Promise<void>;
25
- /** `ape prototype export [<commit>] [--out <dir>]` */
24
+ export declare function buildSite(root: string, out: string, exported: ExportedCommit, given?: string): Promise<void>;
25
+ /** `ape prototype export [<commit>] [--out <dir>] [--base <path>]` */
26
26
  export declare function exportCommit(text: string | undefined, options: {
27
27
  out?: string;
28
+ base?: string;
28
29
  }): Promise<void>;
@@ -2,12 +2,14 @@
2
2
  // file server, with no API, database or development server. A scene needs no backend (its view
3
3
  // gets everything as props, sample data included), so the export is two development builds of the
4
4
  // commit checked out: the app's scene pages (Expo's web export) at the root, and the viewer with
5
- // the admin's scene pages (Vite, under `prototype/`).
5
+ // the admin's scene pages (Vite, under `prototype/`). `--base` serves it under another path.
6
6
  import { spawnSync } from 'node:child_process';
7
7
  import { existsSync } from 'node:fs';
8
8
  import { cp, mkdir, readdir, rm, writeFile } from 'node:fs/promises';
9
9
  import { join, relative, resolve } from 'node:path';
10
10
  import { findRoot } from '../../project.js';
11
+ import { exportBase, ROOT_BASE, relocate, viewerBase } from './export-base.js';
12
+ import { t } from './messages.js';
11
13
  import { checkedOut, git, requireCommitted } from './report.js';
12
14
  /** The root page: the export opens on the viewer. */
13
15
  const OPEN_VIEWER = `<!doctype html>
@@ -72,7 +74,8 @@ async function requireExportFolder(out) {
72
74
  * and name the commit in its `export.json`. Development builds: production ones leave the scenes
73
75
  * and the sample data out.
74
76
  */
75
- export async function buildSite(root, out, exported) {
77
+ export async function buildSite(root, out, exported, given = ROOT_BASE) {
78
+ const base = exportBase(given);
76
79
  const admin = surfaceDir(root, 'admin');
77
80
  if (!admin)
78
81
  throw new Error('No admin console here: the viewer is part of it.');
@@ -81,21 +84,25 @@ export async function buildSite(root, out, exported) {
81
84
  await rm(out, { recursive: true, force: true });
82
85
  if (app)
83
86
  build(app, `pnpm exec expo export --platform web --dev --output-dir "${out}"`);
84
- build(admin, `pnpm exec vite build --base /prototype/ --outDir "${out}/prototype" --emptyOutDir`, {
87
+ build(admin, `pnpm exec vite build --base ${viewerBase(base)} --outDir "${out}/prototype" --emptyOutDir`, {
85
88
  NODE_ENV: 'development',
86
89
  // The app's scene pages are on the same site, at its root.
87
90
  VITE_APP_URL: '',
88
91
  });
89
92
  await arrange(out, exported, Boolean(app));
93
+ if (base !== ROOT_BASE)
94
+ await relocate(out, Boolean(app), base);
90
95
  }
91
- /** `ape prototype export [<commit>] [--out <dir>]` */
96
+ /** `ape prototype export [<commit>] [--out <dir>] [--base <path>]` */
92
97
  export async function exportCommit(text, options) {
98
+ const base = exportBase(options.base);
93
99
  const root = findRoot();
94
100
  const commit = commitToExport(root, text);
95
101
  const out = resolve(options.out ?? join(root, 'dist', `prototype-${commit}`));
96
102
  const started = performance.now();
97
- await buildSite(root, out, { commit, exportedAt: new Date().toISOString() });
103
+ await buildSite(root, out, { commit, exportedAt: new Date().toISOString() }, base);
98
104
  const seconds = Math.round((performance.now() - started) / 1000);
99
105
  console.log(`\nThe prototype of commit ${commit} is in ${relative(process.cwd(), out) || '.'}, in ${seconds} s.`);
100
- console.log('Serve that folder at the root of any static file server (e.g. python -m http.server) and open it: no API, database or development server.');
106
+ const serve = base === ROOT_BASE ? 'exportServe' : base === './' ? 'exportServeRelative' : 'exportServeBase';
107
+ console.log(t(`prototype.${serve}`, { base }));
101
108
  }
@@ -23,6 +23,7 @@ export function addPrototypeCommand(program) {
23
23
  .command('export [commit]')
24
24
  .description('A commit (the one checked out, unchanged) as static files that run from a plain file server')
25
25
  .option('--out <dir>', 'where to write it (default dist/prototype-<commit>)')
26
+ .option('--base <path>', t('prototype.baseHelp'))
26
27
  .action(exportCommit);
27
28
  prototype
28
29
  .command('data')
@@ -0,0 +1,8 @@
1
+ /** The longest a scene page waits for its fonts and pictures; then it is shot anyway, with a hint. */
2
+ export declare const MEDIA_WAIT = 10000;
3
+ /**
4
+ * Runs in the page: wait until its fonts are ready and every picture has finished, loaded or
5
+ * failed (a lazy picture loads now: the shot is of the whole page). False when `timeout` ran out
6
+ * first. Self-contained, since Playwright sends it to the page as text.
7
+ */
8
+ export declare function mediaReady(timeout: number): Promise<boolean>;
@@ -0,0 +1,36 @@
1
+ /// <reference lib="dom" />
2
+ // Fonts and pictures a scene page is still loading: the snapshot waits for them before a picture.
3
+ /** The longest a scene page waits for its fonts and pictures; then it is shot anyway, with a hint. */
4
+ export const MEDIA_WAIT = 10_000;
5
+ /**
6
+ * Runs in the page: wait until its fonts are ready and every picture has finished, loaded or
7
+ * failed (a lazy picture loads now: the shot is of the whole page). False when `timeout` ran out
8
+ * first. Self-contained, since Playwright sends it to the page as text.
9
+ */
10
+ export async function mediaReady(timeout) {
11
+ // Layout first, so the fonts the text needs have started loading before `fonts.ready` is read.
12
+ document.body?.getBoundingClientRect();
13
+ const pictures = [...document.images].flatMap((image) => {
14
+ if (image.loading === 'lazy')
15
+ image.loading = 'eager';
16
+ if (image.complete)
17
+ return [];
18
+ return [
19
+ new Promise((done) => {
20
+ image.addEventListener('load', () => done(), { once: true });
21
+ image.addEventListener('error', () => done(), { once: true });
22
+ }),
23
+ ];
24
+ });
25
+ let timer;
26
+ const late = new Promise((done) => {
27
+ timer = setTimeout(() => done(false), timeout);
28
+ });
29
+ const ready = Promise.all([document.fonts.ready, ...pictures]).then(() => true);
30
+ try {
31
+ return await Promise.race([ready, late]);
32
+ }
33
+ finally {
34
+ clearTimeout(timer);
35
+ }
36
+ }
@@ -25,6 +25,7 @@ export declare const en: {
25
25
  'prototype.renderFailed': string;
26
26
  'prototype.devOverlay': string;
27
27
  'prototype.fontMismatch': string;
28
+ 'prototype.mediaLate': string;
28
29
  'prototype.identicalMore': string;
29
30
  'prototype.identical': string;
30
31
  'prototype.sceneStart': string;
@@ -164,4 +165,9 @@ export declare const en: {
164
165
  'prototype.lowMemory': string;
165
166
  'prototype.noRender': string;
166
167
  'prototype.drift': string;
168
+ 'prototype.baseHelp': string;
169
+ 'prototype.baseInvalid': string;
170
+ 'prototype.exportServe': string;
171
+ 'prototype.exportServeBase': string;
172
+ 'prototype.exportServeRelative': string;
167
173
  };
@@ -26,6 +26,7 @@ export const en = {
26
26
  'prototype.renderFailed': 'Scene rendering failed.',
27
27
  'prototype.devOverlay': 'A development error overlay was showing.',
28
28
  'prototype.fontMismatch': 'Hint to review: scene "{scene}" renders "{text}" in "{rendered}" instead of "{expected}".',
29
+ 'prototype.mediaLate': 'Hint to review: scene "{scene}" was still loading a font or picture after {seconds} seconds; its pictures show it as it was.',
29
30
  'prototype.identicalMore': '{scenes}, and {count} more',
30
31
  'prototype.identical': 'These scenes look exactly alike: {scenes}. Make them differ, or remove one.',
31
32
  'prototype.sceneStart': ' Snapshotting scene "{scene}"…',
@@ -165,4 +166,9 @@ export const en = {
165
166
  'prototype.lowMemory': 'This computer has {free} MB of free memory and a snapshot needs at least {need} MB. Close some programs and take the snapshot again, or set APE_SNAPSHOT_MIN_FREE_MB to change this.',
166
167
  'prototype.noRender': "No scene was drawn: the theme checks failed. Fix the theme, then snapshot again to see each scene's findings.",
167
168
  'prototype.drift': 'This change has sample data edits beyond its approved version.',
169
+ 'prototype.baseHelp': 'the path its root is served from (default /), e.g. /s/abc/, or ./ for paths relative to the page',
170
+ 'prototype.baseInvalid': '--base "{base}" is not a plain path. Use ./ or a path like /s/abc/: letters, digits, - _ ~ and dots, no .. and no address.',
171
+ 'prototype.exportServe': 'Serve that folder at the root of any static file server (e.g. python -m http.server) and open it: no API, database or development server.',
172
+ 'prototype.exportServeBase': 'Serve that folder at {base} of any static file server and open it there: no API, database or development server.',
173
+ 'prototype.exportServeRelative': 'Serve that folder under any path of any static file server and open it there: no API, database or development server.',
168
174
  };
@@ -27,6 +27,7 @@ const es = {
27
27
  'prototype.renderFailed': 'El renderizado de la escena falló.',
28
28
  'prototype.devOverlay': 'Se estaba mostrando una superposición de error de desarrollo.',
29
29
  'prototype.fontMismatch': 'Sugerencia para revisar: la escena "{scene}" muestra "{text}" con "{rendered}" en vez de "{expected}".',
30
+ 'prototype.mediaLate': 'Sugerencia para revisar: la escena "{scene}" seguía cargando una fuente o una imagen después de {seconds} segundos; sus capturas la muestran como estaba.',
30
31
  'prototype.identicalMore': '{scenes}, y {count} más',
31
32
  'prototype.identical': 'Estas escenas se ven exactamente iguales: {scenes}. Haz que se diferencien, o quita una.',
32
33
  'prototype.sceneStart': ' Capturando la escena "{scene}"…',
@@ -166,6 +167,11 @@ const es = {
166
167
  'prototype.lowMemory': 'Este equipo tiene {free} MB de memoria libre y una captura necesita al menos {need} MB. Cierra algunos programas y toma la captura de nuevo, o define APE_SNAPSHOT_MIN_FREE_MB para cambiarlo.',
167
168
  'prototype.noRender': 'No se dibujó ninguna escena: fallaron las comprobaciones del tema. Corrige el tema y toma la captura de nuevo para ver los hallazgos de cada escena.',
168
169
  'prototype.drift': 'Este cambio tiene ediciones en los datos de ejemplo posteriores a su versión aprobada.',
170
+ 'prototype.baseHelp': 'la ruta desde la que se sirve su raíz (/ por defecto), p. ej. /s/abc/, o ./ para rutas relativas a la página',
171
+ 'prototype.baseInvalid': '--base "{base}" no es una ruta simple. Usa ./ o una ruta como /s/abc/: letras, dígitos, - _ ~ y puntos, sin .. y sin dirección.',
172
+ 'prototype.exportServe': 'Sirve esa carpeta en la raíz de cualquier servidor de archivos estáticos (p. ej. python -m http.server) y ábrela: sin API, base de datos ni servidor de desarrollo.',
173
+ 'prototype.exportServeBase': 'Sirve esa carpeta en {base} de cualquier servidor de archivos estáticos y ábrela ahí: sin API, base de datos ni servidor de desarrollo.',
174
+ 'prototype.exportServeRelative': 'Sirve esa carpeta bajo cualquier ruta de cualquier servidor de archivos estáticos y ábrela ahí: sin API, base de datos ni servidor de desarrollo.',
169
175
  };
170
176
  /** The locale the prototype's words are shown in (also for the lists inside them). */
171
177
  export const locale = () => /^es(?:[-_.]|$)/i.test(process.env.LC_ALL || process.env.LANG || '') ? 'es' : 'en';
@@ -1,4 +1,4 @@
1
- import { type Scene, type Surface } from '@buffcore/config';
1
+ import { type Frame, type FrameSize, type Scene, type Surface } from '@buffcore/config';
2
2
  import { type Theme } from '@buffcore/tokens';
3
3
  import type { Browser } from 'playwright-core';
4
4
  import { type browserSession } from './browser.ts';
@@ -14,6 +14,8 @@ export interface Run {
14
14
  sceneTimeout?: number | undefined;
15
15
  checkCheckout?: (() => void) | undefined;
16
16
  looks: readonly Theme[];
17
+ /** Each frame's size: the presets, with the product's own desktop frame (`frameSizes`). */
18
+ frames: Record<Frame, FrameSize>;
17
19
  /** The theme also photographed in dark mode: the product's. */
18
20
  product: string;
19
21
  /** The declared theme. Implicit starter looks carry no font requirement. */
@@ -1,22 +1,26 @@
1
1
  // One scene of a snapshot: opened in every theme, mode and language, checked in each, and
2
2
  // screenshotted in the looks a person reviews.
3
3
  import { join } from 'node:path';
4
- import { FRAME_SIZES, sceneUrl } from '@buffcore/config';
4
+ import { sceneUrl } from '@buffcore/config';
5
5
  import { setAsideWords } from '@buffcore/tokens';
6
6
  import { openScene, PageLoadError, pageGone } from './browser.js';
7
7
  import { clippedEdges, dataWords, pageProblems } from './checks.js';
8
8
  import { watchFonts } from './fonts.js';
9
9
  import { fullShot } from './full-shot.js';
10
10
  import { measure } from './measure.js';
11
+ import { MEDIA_WAIT } from './media-ready.js';
12
+ import { t } from './messages.js';
11
13
  import { describe, readText } from './readable.js';
12
14
  import { renderScene, requireNoErrorOverlay } from './scene-render.js';
13
15
  import { sceneRequests } from './snapshot-requests.js';
14
16
  import { shotName } from './snapshot-shots.js';
15
17
  import { lookKey, photographed } from './snapshot-themes.js';
16
18
  export { lookKey, photographed };
19
+ /** How long a scene's later looks wait for fonts and pictures once one look ran out of time. */
20
+ const LATE_WAIT = 1_000;
17
21
  /** Open the first look so the surface can finish its cold build. */
18
22
  export async function warmSurface(browser, scene, run, signal) {
19
- await renderScene(browser, FRAME_SIZES[scene.frame], scene.key, run.sceneTimeout, async (page) => {
23
+ await renderScene(browser, run.frames[scene.frame], scene.key, run.sceneTimeout, async (page) => {
20
24
  if (run.requests)
21
25
  sceneRequests(page, run, scene);
22
26
  const look = { theme: run.product, mode: 'light', locale: run.first };
@@ -25,7 +29,7 @@ export async function warmSurface(browser, scene, run, signal) {
25
29
  }
26
30
  /** One scene in every theme, mode and language: its screenshots and its problems. */
27
31
  export async function snapScene(browser, scene, run, signal) {
28
- return renderScene(browser, FRAME_SIZES[scene.frame], scene.key, run.sceneTimeout, async (page, advise) => {
32
+ return renderScene(browser, run.frames[scene.frame], scene.key, run.sceneTimeout, async (page, advise) => {
29
33
  const requests = sceneRequests(page, run, scene);
30
34
  const found = {
31
35
  scene,
@@ -36,6 +40,8 @@ export async function snapScene(browser, scene, run, signal) {
36
40
  hints: [],
37
41
  pairs: new Set(),
38
42
  };
43
+ // A font or picture still loading is noted once; the scene's other looks wait a second.
44
+ const late = [];
39
45
  const declared = run.photosOnly
40
46
  ? undefined
41
47
  : run.looks.find((theme) => theme.key === run.fontTheme);
@@ -46,7 +52,17 @@ export async function snapScene(browser, scene, run, signal) {
46
52
  if (run.photosOnly &&
47
53
  !(locale === run.first && photographed(theme.key, mode, run.product)))
48
54
  continue;
49
- await openScene(page, sceneUrl(run.urls[scene.surface], scene.key, look), locale);
55
+ const url = sceneUrl(run.urls[scene.surface], scene.key, look);
56
+ if (await openScene(page, url, locale, late.length ? LATE_WAIT : undefined))
57
+ if (!late.length)
58
+ late.push({
59
+ scene: scene.key,
60
+ ...look,
61
+ detail: t('prototype.mediaLate', {
62
+ scene: scene.key,
63
+ seconds: MEDIA_WAIT / 1000,
64
+ }),
65
+ });
50
66
  await checkLook(page, look, run, found).catch((error) => {
51
67
  throw pageGone(error) ? new PageLoadError(String(error), { cause: error }) : error;
52
68
  });
@@ -62,8 +78,8 @@ export async function snapScene(browser, scene, run, signal) {
62
78
  }
63
79
  }
64
80
  }
65
- const { screenshots, cut, problems, hints } = found;
66
- return { screenshots, cut, problems, hints, ...requests };
81
+ const { screenshots, cut, problems } = found;
82
+ return { screenshots, cut, problems, hints: [...found.hints, ...late], ...requests };
67
83
  }, signal, run);
68
84
  }
69
85
  /** The scene page as it shows one look: photographed when it is reviewed, and checked. */