@buffcore/cli 0.8.44 → 0.8.46

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 (48) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/commands/prototype/browser.d.ts +4 -24
  3. package/dist/commands/prototype/browser.js +13 -76
  4. package/dist/commands/prototype/loaded-garbage.d.ts +10 -0
  5. package/dist/commands/prototype/loaded-garbage.js +20 -0
  6. package/dist/commands/prototype/mark-shot.d.ts +31 -0
  7. package/dist/commands/prototype/mark-shot.js +149 -0
  8. package/dist/commands/prototype/media-ready.d.ts +9 -3
  9. package/dist/commands/prototype/media-ready.js +9 -4
  10. package/dist/commands/prototype/messages.en.d.ts +1 -0
  11. package/dist/commands/prototype/messages.en.js +1 -0
  12. package/dist/commands/prototype/messages.js +1 -0
  13. package/dist/commands/prototype/scene-check.d.ts +37 -0
  14. package/dist/commands/prototype/scene-check.js +68 -0
  15. package/dist/commands/prototype/scene-look.d.ts +14 -0
  16. package/dist/commands/prototype/scene-look.js +89 -0
  17. package/dist/commands/prototype/scene-ready.d.ts +46 -0
  18. package/dist/commands/prototype/scene-ready.js +116 -0
  19. package/dist/commands/prototype/scene.d.ts +22 -1
  20. package/dist/commands/prototype/scene.js +60 -5
  21. package/dist/commands/prototype/snapshot-command.js +20 -10
  22. package/dist/commands/prototype/snapshot-inputs.js +7 -0
  23. package/dist/commands/prototype/snapshot-requests.d.ts +1 -1
  24. package/dist/commands/prototype/snapshot-requests.js +1 -1
  25. package/dist/commands/prototype/snapshot-servers.js +4 -2
  26. package/dist/commands/prototype/snapshot.d.ts +1 -0
  27. package/dist/commands/prototype/snapshot.js +1 -0
  28. package/dist/commands/ui/commands.en.d.ts +3 -0
  29. package/dist/commands/ui/commands.en.js +3 -0
  30. package/dist/commands/ui/commands.es.d.ts +3 -0
  31. package/dist/commands/ui/commands.es.js +3 -0
  32. package/dist/commands/ui/plan-brief.d.ts +13 -0
  33. package/dist/commands/ui/plan-brief.js +91 -0
  34. package/dist/commands/ui/plan-files.d.ts +1 -11
  35. package/dist/commands/ui/plan-files.js +2 -48
  36. package/dist/commands/ui/prototype-main.d.ts +5 -0
  37. package/dist/commands/ui/prototype-shot-route.d.ts +16 -0
  38. package/dist/commands/ui/prototype-shot-route.js +98 -0
  39. package/dist/commands/ui/server-core.js +2 -0
  40. package/dist/commands/ui/server.js +13 -1
  41. package/dist/commands/ui/studio-state.d.ts +5 -0
  42. package/dist/ui/page.js +109 -99
  43. package/docs/PROTOTYPE.md +3 -2
  44. package/docs/WORKBENCH.md +1 -1
  45. package/package.json +11 -11
  46. package/skills/ape-plan-change/SKILL.md +8 -0
  47. package/templates/product/apps/app/app.json +3 -0
  48. package/templates/product/plan/brief.md +29 -0
@@ -0,0 +1,89 @@
1
+ /// <reference lib="dom" />
2
+ import { SCENE_LOOK_ATTR, SCENE_LOOK_CHANGE, SCENE_LOOK_REUSABLE, } from '@buffcore/contracts/prototype';
3
+ import { openScene, sceneFrames, waitForScene } from './browser.js';
4
+ import { MEDIA_WAIT } from './media-ready.js';
5
+ import { SCENE_FOCUS_KEPT } from './scene-ready.js';
6
+ const LOOK_WAIT = 5_000;
7
+ /** The attempt may have had side effects. Discard its context before replaying the scene. */
8
+ export class LookMoveFailed extends Error {
9
+ }
10
+ /**
11
+ * The head's stylesheets, by element: one added or removed by a look would stay on the kept page.
12
+ * A sheet's text may change, since a styling library (Unistyles) rewrites its one sheet for the
13
+ * look on screen; the proof's equal pictures cover that.
14
+ */
15
+ function headStyles() {
16
+ return [...document.head.querySelectorAll('style, link[rel="stylesheet"]')]
17
+ .map((node) => node.cloneNode(false).outerHTML)
18
+ .join('\n');
19
+ }
20
+ /** False means the current document was left untouched. */
21
+ async function moveLook(page, url, locale, mediaWait, onMove) {
22
+ try {
23
+ if ((await sceneFrames(page, locale)).length)
24
+ return false;
25
+ const eligible = await page.evaluate(({ url, attr, reusable, kept }) => {
26
+ const html = document.documentElement;
27
+ const current = new URL(location.href);
28
+ const next = new URL(url);
29
+ return (current.origin === next.origin &&
30
+ current.pathname === next.pathname &&
31
+ current.searchParams.get('key') === next.searchParams.get('key') &&
32
+ html.getAttribute(attr) === location.search &&
33
+ html.hasAttribute(reusable) &&
34
+ (document.activeElement === document.body ||
35
+ document.activeElement === html ||
36
+ html.hasAttribute(kept)));
37
+ }, { url, attr: SCENE_LOOK_ATTR, reusable: SCENE_LOOK_REUSABLE, kept: SCENE_FOCUS_KEPT });
38
+ if (!eligible)
39
+ return false;
40
+ const styles = await page.evaluate(headStyles);
41
+ onMove?.();
42
+ await page.evaluate(({ url, event, attr }) => {
43
+ document.documentElement.removeAttribute(attr);
44
+ history.replaceState(history.state, '', url);
45
+ window.dispatchEvent(new Event(event));
46
+ }, { url, event: SCENE_LOOK_CHANGE, attr: SCENE_LOOK_ATTR });
47
+ await page.waitForFunction(({ attr, search }) => location.search === search && document.documentElement.getAttribute(attr) === search, { attr: SCENE_LOOK_ATTR, search: new URL(url).search }, { timeout: LOOK_WAIT });
48
+ const late = await waitForScene(page, locale, {
49
+ unframed: true,
50
+ readyWait: LOOK_WAIT,
51
+ ...(mediaWait === undefined ? {} : { mediaWait }),
52
+ });
53
+ if (late)
54
+ throw new LookMoveFailed('Media was late after the move');
55
+ if (styles !== (await page.evaluate(headStyles)))
56
+ throw new LookMoveFailed('The move added or removed a stylesheet');
57
+ return true;
58
+ }
59
+ catch (cause) {
60
+ throw new LookMoveFailed(undefined, { cause });
61
+ }
62
+ }
63
+ /**
64
+ * A fresh navigation starts the scene; its later looks move in place. A picture is shot only once
65
+ * `mediaReady` says all is ready, so warm media draws the same picture; only a media finding could
66
+ * differ. So a later look loads fresh when the first look got one (late or failed), or when its
67
+ * wait used more than half the later look's allowance (a cold load near the limit). A cold load
68
+ * well within the allowance means a warm one is too, so the findings are equal.
69
+ */
70
+ export function sceneLookLoader(page, onFallback, inPlace = true, onMove) {
71
+ let opened = false;
72
+ let found = false;
73
+ let elapsed = 0;
74
+ const observe = (media) => {
75
+ found ||= !media.ready || media.failed;
76
+ elapsed = Math.max(elapsed, media.elapsed);
77
+ };
78
+ return async (url, locale, mediaWait) => {
79
+ if (opened) {
80
+ const warmSafe = !found && elapsed <= (mediaWait ?? MEDIA_WAIT) / 2;
81
+ if (inPlace && warmSafe && (await moveLook(page, url, locale, mediaWait, onMove)))
82
+ return false;
83
+ onFallback?.('look');
84
+ }
85
+ const late = await openScene(page, url, locale, mediaWait, inPlace ? observe : undefined);
86
+ opened = true;
87
+ return late;
88
+ };
89
+ }
@@ -0,0 +1,46 @@
1
+ import type { Frame, Page } from 'playwright-core';
2
+ import { type MediaState } from './media-ready.ts';
3
+ /**
4
+ * Runs inside the page (Playwright sends its source): paints two frames, then resolves when the
5
+ * animations have finished, so a sheet fading in is not caught half way, or after `timeout` ms.
6
+ * An animation that never ends (a spinner) is not waited for. Chromium paints no frame in a framed
7
+ * page from another origin while it is off screen, so the wait for a paint ends after a second.
8
+ */
9
+ export declare function animationsDone(timeout: number): Promise<void>;
10
+ /** Set on `<html>` when the view took the focus back on purpose (`unfocused`). */
11
+ export declare const SCENE_FOCUS_KEPT = "data-scene-focus-kept";
12
+ /**
13
+ * Runs inside the page, after `animationsDone` has painted two frames (so the view's mount effects
14
+ * and autofocus have had their chance): blur whatever has focus, and again after each frame until
15
+ * nothing does, for up to `timeout` ms. A field that autofocuses late (Expo's router can commit the
16
+ * root before the view) then shows no focus ring on any path. An element that takes the focus back
17
+ * after its blur does so on purpose (a sheet that focuses its field): it keeps the focus, as a plain
18
+ * load shows it, and `<html>` is marked with `data-scene-focus-kept`. True when nothing has focus.
19
+ */
20
+ export declare function unfocused(timeout: number): Promise<boolean>;
21
+ /** How long a scene page waits: for its animations, and for its fonts and pictures. */
22
+ type Waits = {
23
+ animationWait: number;
24
+ mediaWait: number;
25
+ readyWait?: number | undefined;
26
+ onMedia?: ((media: MediaState) => void) | undefined;
27
+ };
28
+ /** The console can show an app scene in an iframe of its own. */
29
+ export declare function sceneFrames(page: Page, locale: string): Promise<{
30
+ frame: Frame;
31
+ index: number;
32
+ locale: string;
33
+ }[]>;
34
+ /**
35
+ * Wait for the current scene and its framed scenes to finish drawing. True when a font or picture
36
+ * was still loading as its allowance ran out: the page is shot as it is.
37
+ */
38
+ export declare function waitForScene(page: Page, locale: string, { live, animationWait, mediaWait, readyWait, unframed, onMedia, }?: {
39
+ live?: () => boolean;
40
+ animationWait?: number;
41
+ mediaWait?: number;
42
+ readyWait?: number;
43
+ unframed?: boolean;
44
+ onMedia?: Waits['onMedia'];
45
+ }): Promise<boolean>;
46
+ export {};
@@ -0,0 +1,116 @@
1
+ import { MEDIA_WAIT, mediaReady } from './media-ready.js';
2
+ /**
3
+ * Runs inside the page (Playwright sends its source): paints two frames, then resolves when the
4
+ * animations have finished, so a sheet fading in is not caught half way, or after `timeout` ms.
5
+ * An animation that never ends (a spinner) is not waited for. Chromium paints no frame in a framed
6
+ * page from another origin while it is off screen, so the wait for a paint ends after a second.
7
+ */
8
+ export async function animationsDone(timeout) {
9
+ const frames = () => new Promise((done) => {
10
+ requestAnimationFrame(() => requestAnimationFrame(done));
11
+ setTimeout(done, 1_000);
12
+ });
13
+ const end = performance.now() + timeout;
14
+ await frames();
15
+ while (performance.now() < end) {
16
+ const running = document
17
+ .getAnimations()
18
+ .filter((a) => a.playState === 'running' && a.effect?.getComputedTiming().endTime !== Infinity);
19
+ if (running.length === 0)
20
+ return;
21
+ const wait = Math.max(end - performance.now(), 0);
22
+ await Promise.race([
23
+ Promise.allSettled(running.map((a) => a.finished)),
24
+ new Promise((done) => setTimeout(done, wait)),
25
+ ]);
26
+ await frames();
27
+ }
28
+ }
29
+ /** Set on `<html>` when the view took the focus back on purpose (`unfocused`). */
30
+ export const SCENE_FOCUS_KEPT = 'data-scene-focus-kept';
31
+ /**
32
+ * Runs inside the page, after `animationsDone` has painted two frames (so the view's mount effects
33
+ * and autofocus have had their chance): blur whatever has focus, and again after each frame until
34
+ * nothing does, for up to `timeout` ms. A field that autofocuses late (Expo's router can commit the
35
+ * root before the view) then shows no focus ring on any path. An element that takes the focus back
36
+ * after its blur does so on purpose (a sheet that focuses its field): it keeps the focus, as a plain
37
+ * load shows it, and `<html>` is marked with `data-scene-focus-kept`. True when nothing has focus.
38
+ */
39
+ export async function unfocused(timeout) {
40
+ const frames = () => new Promise((done) => {
41
+ requestAnimationFrame(() => requestAnimationFrame(done));
42
+ setTimeout(done, 1_000);
43
+ });
44
+ const end = performance.now() + timeout;
45
+ const focused = () => {
46
+ const active = document.activeElement;
47
+ return active && active !== document.body && active !== document.documentElement
48
+ ? active
49
+ : undefined;
50
+ };
51
+ // The same name as SCENE_FOCUS_KEPT: Playwright sends this function as text.
52
+ document.documentElement.removeAttribute('data-scene-focus-kept');
53
+ let blurred;
54
+ for (let active = focused(); active; active = focused()) {
55
+ if (active === blurred) {
56
+ document.documentElement.setAttribute('data-scene-focus-kept', '');
57
+ return false;
58
+ }
59
+ if (performance.now() > end)
60
+ return false;
61
+ active.blur();
62
+ blurred = active;
63
+ await frames();
64
+ }
65
+ return true;
66
+ }
67
+ /** How long `unfocused` keeps blurring a field that takes the focus back. */
68
+ const FOCUS_WAIT = 1_000;
69
+ /** The longest `openScene` waits for animations to finish. */
70
+ const ANIMATION_WAIT = 2_000;
71
+ /**
72
+ * Wait until a scene page in this frame has drawn: the view rendered in the asked language, the
73
+ * fonts and pictures loaded (`mediaReady`), two frames painted, and animations finished within
74
+ * their allowance, and then nothing focused (`unfocused`), so a field that autofocuses shows no
75
+ * focus ring. True when fonts or pictures were still loading as their allowance ran out.
76
+ */
77
+ async function drawn(frame, locale, live, { animationWait, mediaWait, readyWait, onMedia }) {
78
+ await frame.waitForFunction((lang) => document.documentElement.lang === lang &&
79
+ (document.getElementById('root')?.childElementCount ?? 0) > 0, locale, readyWait === undefined ? undefined : { timeout: readyWait });
80
+ // An attempt that lost its page (a module failed, the page loaded again) does nothing more.
81
+ if (!live())
82
+ return false;
83
+ await frame.evaluate(() => document.activeElement?.blur());
84
+ const media = await frame.evaluate(mediaReady, mediaWait);
85
+ onMedia?.(media);
86
+ await frame.evaluate(animationsDone, animationWait);
87
+ await frame.evaluate(unfocused, FOCUS_WAIT);
88
+ return !media.ready;
89
+ }
90
+ /** The console can show an app scene in an iframe of its own. */
91
+ export async function sceneFrames(page, locale) {
92
+ const frames = await Promise.all((await page.$$('iframe')).map(async (iframe, index) => {
93
+ const src = new URL((await iframe.getAttribute('src')) ?? '', page.url());
94
+ if (src.pathname !== '/_scene')
95
+ return;
96
+ const frame = await iframe.contentFrame();
97
+ if (frame)
98
+ return { frame, index, locale: src.searchParams.get('locale') ?? locale };
99
+ }));
100
+ return frames.filter((entry) => entry !== undefined);
101
+ }
102
+ /**
103
+ * Wait for the current scene and its framed scenes to finish drawing. True when a font or picture
104
+ * was still loading as its allowance ran out: the page is shot as it is.
105
+ */
106
+ export async function waitForScene(page, locale, { live = () => true, animationWait = ANIMATION_WAIT, mediaWait = MEDIA_WAIT, readyWait, unframed = false, onMedia, } = {}) {
107
+ const waits = { animationWait, mediaWait, readyWait, onMedia };
108
+ let late = await drawn(page.mainFrame(), locale, live, waits);
109
+ const children = await sceneFrames(page, locale);
110
+ if (unframed && children.length)
111
+ throw new Error('Framed scene appeared while settling a look');
112
+ for (const entry of children)
113
+ if (await drawn(entry.frame, entry.locale, live, waits))
114
+ late = true;
115
+ return late;
116
+ }
@@ -1,9 +1,11 @@
1
1
  import { type Frame, type FrameSize, type Scene, type Surface } from '@buffcore/config';
2
+ import type { PrototypeProblem } from '@buffcore/contracts/prototype';
2
3
  import { type Theme } from '@buffcore/tokens';
3
- import type { Browser } from 'playwright-core';
4
+ import type { Browser, Page } from 'playwright-core';
4
5
  import { type browserSession } from './browser.ts';
5
6
  import type { SnapshotHint } from './report.ts';
6
7
  import type { LoadFailure } from './scene-errors.ts';
8
+ import { type FallbackCounter } from './scene-look.ts';
7
9
  import type { SnapshotProgress } from './snapshot-progress.ts';
8
10
  import { type SceneRequestFacts } from './snapshot-requests.ts';
9
11
  import { lookKey, photographed } from './snapshot-themes.ts';
@@ -30,6 +32,7 @@ export interface Run {
30
32
  out: string;
31
33
  session?: ReturnType<typeof browserSession> | undefined;
32
34
  requests?: SceneRequestFacts;
35
+ onFallback?: FallbackCounter | undefined;
33
36
  hasAsset?: ((scene: Scene, url: URL) => boolean) | undefined;
34
37
  saveScene?: SnapshotProgress['draw'] | undefined;
35
38
  /** The first full-run scene on each surface, even when that scene has already finished. */
@@ -51,6 +54,18 @@ export type SceneResult = Awaited<ReturnType<typeof snapScene>> & {
51
54
  /** A page exception's source and first line; it is not evidence of a load failure. */
52
55
  scriptError?: LoadFailure;
53
56
  };
57
+ /** What one scene gathers as it goes. */
58
+ interface Found {
59
+ scene: Scene;
60
+ data: Set<string>;
61
+ screenshots: Record<string, string>;
62
+ /** The looks whose shot was cut at the height cap. */
63
+ cut: string[];
64
+ problems: PrototypeProblem[];
65
+ hints: SnapshotHint[];
66
+ /** The color pairs already reported, by theme and mode. */
67
+ pairs: Set<string>;
68
+ }
54
69
  /** Open the first look so the surface can finish its cold build. */
55
70
  export declare function warmSurface(browser: Browser, scene: Scene, run: Run, signal: AbortSignal): Promise<void>;
56
71
  /** One scene in every theme, mode and language: its screenshots and its problems. */
@@ -69,3 +84,9 @@ export declare function snapScene(browser: Browser, scene: Scene, run: Run, sign
69
84
  }[];
70
85
  hints: SnapshotHint[];
71
86
  }>;
87
+ /** The scene page as it shows one look: photographed when it is reviewed, and checked. */
88
+ export declare function checkLook(page: Page, look: {
89
+ theme: string;
90
+ mode: string;
91
+ locale: string;
92
+ }, run: Run, found: Found): Promise<void>;
@@ -11,7 +11,9 @@ import { measure } from './measure.js';
11
11
  import { MEDIA_WAIT } from './media-ready.js';
12
12
  import { t } from './messages.js';
13
13
  import { describe, readText } from './readable.js';
14
- import { renderScene, requireNoErrorOverlay } from './scene-render.js';
14
+ import { freshLoadsAgree, lookEvidence } from './scene-check.js';
15
+ import { LookMoveFailed, sceneLookLoader } from './scene-look.js';
16
+ import { renderScene, requireNoErrorOverlay, SceneTimeoutError } from './scene-render.js';
15
17
  import { sceneRequests } from './snapshot-requests.js';
16
18
  import { shotName } from './snapshot-shots.js';
17
19
  import { lookKey, photographed } from './snapshot-themes.js';
@@ -29,8 +31,46 @@ export async function warmSurface(browser, scene, run, signal) {
29
31
  }
30
32
  /** One scene in every theme, mode and language: its screenshots and its problems. */
31
33
  export async function snapScene(browser, scene, run, signal) {
34
+ const requests = run.requests ?? { apiCalls: false, untrackedRequests: false };
35
+ const attempt = { ...run, requests };
36
+ let moved = false;
37
+ let started = performance.now();
38
+ let result;
39
+ try {
40
+ result = await drawScene(browser, scene, attempt, signal, () => {
41
+ moved = true;
42
+ });
43
+ }
44
+ catch (error) {
45
+ signal.throwIfAborted();
46
+ if (!(error instanceof LookMoveFailed) && (!moved || error instanceof SceneTimeoutError))
47
+ throw error;
48
+ // The failed document may have changed storage or cookies. Replay the scene in a new
49
+ // context so its earlier full loads establish the same state as a run using only goto.
50
+ run.onFallback?.('scene');
51
+ started = performance.now();
52
+ result = await drawScene(browser, scene, attempt, signal);
53
+ }
54
+ const { checks, ...drawn } = result;
55
+ if (!(await freshLoadsAgree(browser, scene, attempt, signal, checks, started, checkLook))) {
56
+ // Something an earlier look left behind changed a checked one: draw every look fresh.
57
+ run.onFallback?.('scene');
58
+ const { checks: _, ...fresh } = await drawScene(browser, scene, attempt, signal);
59
+ return { ...fresh, ...requests };
60
+ }
61
+ return { ...drawn, ...requests };
62
+ }
63
+ function drawScene(browser, scene, run, signal, onMove) {
32
64
  return renderScene(browser, run.frames[scene.frame], scene.key, run.sceneTimeout, async (page, advise) => {
33
- const requests = sceneRequests(page, run, scene);
65
+ sceneRequests(page, run, scene);
66
+ let moves = 0;
67
+ const show = sceneLookLoader(page, onMove && run.onFallback, Boolean(onMove), () => {
68
+ moves++;
69
+ onMove?.();
70
+ });
71
+ let last;
72
+ // The last photographed look drawn in place: its saved picture is checked as well.
73
+ let photo;
34
74
  const found = {
35
75
  scene,
36
76
  data: dataWords(scene.props),
@@ -53,7 +93,12 @@ export async function snapScene(browser, scene, run, signal) {
53
93
  !(locale === run.first && photographed(theme.key, mode, run.product)))
54
94
  continue;
55
95
  const url = sceneUrl(run.urls[scene.surface], scene.key, look);
56
- if (await openScene(page, url, locale, late.length ? LATE_WAIT : undefined))
96
+ const mediaWait = late.length ? LATE_WAIT : undefined;
97
+ const before = moves;
98
+ const lateNow = await show(url, locale, mediaWait);
99
+ last = { look, url, mediaWait, late: lateNow };
100
+ const photoMoved = moves > before && locale === run.first && photographed(theme.key, mode, run.product);
101
+ if (lateNow)
57
102
  if (!late.length)
58
103
  late.push({
59
104
  scene: scene.key,
@@ -66,6 +111,8 @@ export async function snapScene(browser, scene, run, signal) {
66
111
  await checkLook(page, look, run, found).catch((error) => {
67
112
  throw pageGone(error) ? new PageLoadError(String(error), { cause: error }) : error;
68
113
  });
114
+ if (photoMoved)
115
+ photo = { last, evidence: await lookEvidence(page, last, run, scene, checkLook) };
69
116
  if (theme === declared) {
70
117
  const details = await advise(async (timeLeft) => (await watchFonts(page, scene.key, theme)?.(timeLeft)) ?? []);
71
118
  if (!details)
@@ -79,11 +126,19 @@ export async function snapScene(browser, scene, run, signal) {
79
126
  }
80
127
  }
81
128
  const { screenshots, cut, problems } = found;
82
- return { screenshots, cut, problems, hints: [...found.hints, ...late], ...requests };
129
+ // A scene with a look moved in place proves its last look against a fresh load, and its
130
+ // last photographed moved look when that is another one.
131
+ const checks = [];
132
+ if (moves > 0 && last) {
133
+ checks.push({ last, evidence: await lookEvidence(page, last, run, scene, checkLook) });
134
+ if (photo && photo.last !== last)
135
+ checks.push(photo);
136
+ }
137
+ return { screenshots, cut, problems, hints: [...found.hints, ...late], checks };
83
138
  }, signal, run);
84
139
  }
85
140
  /** The scene page as it shows one look: photographed when it is reviewed, and checked. */
86
- async function checkLook(page, look, run, found) {
141
+ export async function checkLook(page, look, run, found) {
87
142
  await requireNoErrorOverlay(page);
88
143
  const { theme, mode, locale } = look;
89
144
  const scene = found.scene.key;
@@ -8,7 +8,7 @@ import { configuredSnapshotRedact } from '../ui/snapshot-redaction.js';
8
8
  import { accessDenied } from './access-denied.js';
9
9
  import { readModel } from './data.js';
10
10
  import { MAX_SHOT_HEIGHT } from './full-shot.js';
11
- import { t } from './messages.js';
11
+ import { number, t } from './messages.js';
12
12
  import { newestReport, renderRetries, requireCommitted, shortCommit, unsavedWork, } from './report.js';
13
13
  import { remakeScreenshots, takeSnapshot } from './snapshot.js';
14
14
  import { SnapshotAccessRefused } from './snapshot-refused.js';
@@ -17,7 +17,7 @@ import { shareShots } from './snapshot-shared-shots.js';
17
17
  import { exitOnSignals } from './snapshot-signals.js';
18
18
  export { loadScenes } from './snapshot-setup.js';
19
19
  /** Snapshot (or remake) as the flags say; the screenshots, report and data model on disk. */
20
- async function snapshotted(flags, hints) {
20
+ async function snapshotted(flags, hints, onFallback) {
21
21
  const servers = {};
22
22
  // A signal takes the run's servers down and frees its locks, then ends the process.
23
23
  const unhook = exitOnSignals(() => {
@@ -25,7 +25,7 @@ async function snapshotted(flags, hints) {
25
25
  servers.locks?.release();
26
26
  });
27
27
  try {
28
- return await drawn(flags, hints, servers);
28
+ return await drawn(flags, hints, servers, onFallback);
29
29
  }
30
30
  finally {
31
31
  unhook();
@@ -34,14 +34,14 @@ async function snapshotted(flags, hints) {
34
34
  }
35
35
  }
36
36
  /** `--remake`: the last committed snapshot's screenshots, drawn again. */
37
- async function remade(run) {
37
+ async function remade(run, onFallback) {
38
38
  const { root, dir, scene, options } = run;
39
39
  requireCommitted(root, 'the screenshots are made again from the commit checked out');
40
40
  const report = await newestReport(root);
41
41
  if (!report)
42
42
  throw new Error('No snapshot here to make again: run ape prototype snapshot.');
43
43
  console.log(`Making the screenshots of snapshot ${report.commit} again:`);
44
- const made = await remakeScreenshots({ ...options, commit: report.commit, report });
44
+ const made = await remakeScreenshots({ ...options, commit: report.commit, report, onFallback });
45
45
  const folder = relative(root, join(dir, report.commit)).replaceAll('\\', '/');
46
46
  const base = { folder, commit: report.commit, scene: scene ?? null, remade: true };
47
47
  return {
@@ -58,7 +58,7 @@ async function remade(run) {
58
58
  };
59
59
  }
60
60
  /** The snapshot itself: every scene (or the ones asked for), then its report. */
61
- async function taken(run, commit) {
61
+ async function taken(run, commit, onFallback) {
62
62
  const { root, own, servers, scene, checkout, urls } = run;
63
63
  const unsaved = unsavedWork(root);
64
64
  const design = await designState(root);
@@ -71,6 +71,7 @@ async function taken(run, commit) {
71
71
  return takeSnapshot({
72
72
  ...run.options,
73
73
  commit,
74
+ onFallback,
74
75
  checkCheckout: servers.own
75
76
  ? () => {
76
77
  checkout?.check();
@@ -93,17 +94,17 @@ async function taken(run, commit) {
93
94
  artifacts: { 'data.json': model, ...(design ? { 'design.json': design } : {}) },
94
95
  });
95
96
  }
96
- async function drawn(flags, hints, servers) {
97
+ async function drawn(flags, hints, servers, onFallback) {
97
98
  const run = await setup(flags, servers);
98
99
  if (flags.remake)
99
- return remade(run);
100
+ return remade(run, onFallback);
100
101
  const { root, own, scene, picked, dir } = run;
101
102
  const commit = shortCommit(root, run.checkout?.head);
102
103
  const count = scene
103
104
  ? `scene ${Array.isArray(scene) ? scene.join(', ') : scene}`
104
105
  : `${run.scenes.scenes.length} scenes`;
105
106
  console.log(`Snapshot of ${count}:`);
106
- const report = await taken(run, commit);
107
+ const report = await taken(run, commit, onFallback);
107
108
  if (own && !run.comp && report.scene === undefined && !report.problems.length)
108
109
  await shareShots(root, join(dir, commit), report);
109
110
  const selected = new Set(picked.map((scene) => scene.key));
@@ -167,7 +168,16 @@ function printNotes(result) {
167
168
  /** `ape prototype snapshot`: needs `ape dev` running. Fails (exit 1) when a check fails. */
168
169
  export async function snapshot(flags = {}) {
169
170
  const hints = new Set();
170
- const captured = await captureSnapshotCommand(() => snapshotted(flags, hints), findRoot);
171
+ const fallbacks = { look: 0, scene: 0 };
172
+ const countFallback = (kind) => {
173
+ fallbacks[kind]++;
174
+ };
175
+ const captured = await captureSnapshotCommand(() => snapshotted(flags, hints, countFallback), findRoot);
176
+ if (!flags.json && fallbacks.look + fallbacks.scene > 0)
177
+ console.log(t('prototype.drawFallbacks', {
178
+ looks: number(fallbacks.look),
179
+ scenes: number(fallbacks.scene),
180
+ }));
171
181
  if (captured.kind !== 'passed') {
172
182
  printCommandFailure(captured, flags.json, console.log);
173
183
  const note = captured.kind === 'failed' && !flags.json ? cutNote(captured.metadata?.cut) : '';
@@ -17,9 +17,16 @@ const CHECKS = [
17
17
  'font-samples',
18
18
  'full-shot',
19
19
  'measure',
20
+ 'media-ready',
21
+ 'module-errors',
20
22
  'readable',
21
23
  'scene',
24
+ 'scene-check',
25
+ 'scene-load',
26
+ 'scene-look',
27
+ 'scene-ready',
22
28
  'scene-render',
29
+ 'snapshot-recovery',
23
30
  'snapshot-requests',
24
31
  'snapshot-themes',
25
32
  ];
@@ -6,4 +6,4 @@ export interface SceneRequestFacts {
6
6
  untrackedRequests: boolean;
7
7
  }
8
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 }: Run, scene: Scene): SceneRequestFacts;
9
+ export declare function sceneRequests(page: Page, { urls, hasAsset, requests: found, }: Pick<Run, 'urls' | 'hasAsset' | 'requests'>, scene: Scene): SceneRequestFacts;
@@ -7,7 +7,7 @@ const origin = (url) => {
7
7
  };
8
8
  const apiPath = (url) => /^\/api(?:\/|$)/i.test(url.pathname);
9
9
  /** Context requests include iframes, workers and requests that fail before receiving a response. */
10
- export function sceneRequests(page, { urls, hasAsset, requests: found = { apiCalls: false, untrackedRequests: false } }, scene) {
10
+ export function sceneRequests(page, { urls, hasAsset, requests: found = { apiCalls: false, untrackedRequests: false }, }, scene) {
11
11
  const api = urls.api ? origin(new URL(urls.api)) : undefined;
12
12
  const surfaces = new Set();
13
13
  for (const address of [urls.app, urls.admin])
@@ -180,8 +180,10 @@ export function snapshotServers(root, environment, urls, { owners = systemOwners
180
180
  throw new SnapshotRefused(t('prototype.installChanged'));
181
181
  },
182
182
  async verify() {
183
- for (const [surface, child] of children)
184
- await owned(surface, child);
183
+ const checks = await Promise.allSettled([...children].map(([surface, child]) => owned(surface, child)));
184
+ for (const check of checks)
185
+ if (check.status === 'rejected')
186
+ throw check.reason;
185
187
  },
186
188
  kill,
187
189
  exit: (server) => exits.get(server),
@@ -40,6 +40,7 @@ export interface SnapshotOptions {
40
40
  /** A linked worktree's run draws against a stand-in API: the report says so. */
41
41
  api?: 'stand-in' | undefined;
42
42
  serverExit?: Run['serverExit'];
43
+ onFallback?: Run['onFallback'];
43
44
  /** Scene pages open at once (`--pages`); undefined is `pagesFor` the cores and the free memory. */
44
45
  pages?: number | undefined;
45
46
  /** Keys of the scenes drawn before the others (the change's own); the report keeps its order. */
@@ -39,6 +39,7 @@ function runOf(options) {
39
39
  commit,
40
40
  out: join(options.dir, commit),
41
41
  serverExit: options.serverExit,
42
+ onFallback: options.onFallback,
42
43
  };
43
44
  }
44
45
  /**
@@ -25,6 +25,9 @@ export declare const en: {
25
25
  'ui.compare.noGit': string;
26
26
  'ui.compare.unexpected': string;
27
27
  'ui.snapshot.noChange': string;
28
+ 'ui.shot.invalid': string;
29
+ 'ui.shot.notRunning': string;
30
+ 'ui.shot.failed': string;
28
31
  'ui.snapshot.readFailed': string;
29
32
  'ui.snapshot.proof': string;
30
33
  'ui.snapshot.linked': string;
@@ -25,6 +25,9 @@ export const en = {
25
25
  'ui.compare.noGit': 'Git could not read the repository history. Check the checkout and make sure the commits for the comparison are available.',
26
26
  'ui.compare.unexpected': 'The comparison failed unexpectedly. Run pnpm ape prototype versions --json. If that fails, check the change’s file in prototype/versions/. If the versions look right, report the comparison failure.',
27
27
  'ui.snapshot.noChange': 'There is no change selected for a snapshot.',
28
+ 'ui.shot.invalid': 'The studio asked for a picture it cannot take.',
29
+ 'ui.shot.notRunning': 'The app is not running, so its marked screen cannot be shot.',
30
+ 'ui.shot.failed': 'The marked screen could not be shot: {reason}',
28
31
  'ui.snapshot.readFailed': 'Git could not read the saved source.',
29
32
  'ui.snapshot.proof': 'Record version needs unchanged passing snapshot proof for this change, saved source and checkout. Save the review files and take a new snapshot if needed.',
30
33
  'ui.snapshot.linked': '{coding, select, yes {{here, select, yes {This studio is open in the checkout where {change} is being built} other {{change} is being built in its own checkout}}. Its approved prototype is on main, so there is nothing to record from that checkout. Take snapshot draws it there with its own servers, and Save keeps its snapshot files on the change’s branch.} other {{here, select, yes {This studio is open in {change}’s own checkout} other {{change} is checked out in {path}}}. Take snapshot draws it there with its own servers, and Save keeps its snapshot files on the change’s branch. The studio records only on main, so in a terminal in {here, select, yes {this folder} other {that folder}}: commit all its changes and the new prototype/snapshots folder, then run pnpm ape prototype version {change} --why "what changed".}}',
@@ -25,6 +25,9 @@ export declare const es: {
25
25
  'ui.compare.noGit': string;
26
26
  'ui.compare.unexpected': string;
27
27
  'ui.snapshot.noChange': string;
28
+ 'ui.shot.invalid': string;
29
+ 'ui.shot.notRunning': string;
30
+ 'ui.shot.failed': string;
28
31
  'ui.snapshot.readFailed': string;
29
32
  'ui.snapshot.proof': string;
30
33
  'ui.snapshot.linked': string;
@@ -25,6 +25,9 @@ export const es = {
25
25
  'ui.compare.noGit': 'Git no pudo leer el historial del repositorio. Revisa la copia de trabajo y comprueba que los commits de la comparación estén disponibles.',
26
26
  'ui.compare.unexpected': 'La comparación falló de forma inesperada. Ejecuta pnpm ape prototype versions --json. Si ese comando falla, revisa el archivo del cambio en prototype/versions/. Si las versiones son correctas, informa del fallo de la comparación.',
27
27
  'ui.snapshot.noChange': 'No hay ningún cambio seleccionado para una instantánea.',
28
+ 'ui.shot.invalid': 'El estudio pidió una imagen que no se puede tomar.',
29
+ 'ui.shot.notRunning': 'La app no está en marcha, así que no se puede capturar la pantalla marcada.',
30
+ 'ui.shot.failed': 'No se pudo capturar la pantalla marcada: {reason}',
28
31
  'ui.snapshot.readFailed': 'Git no pudo leer el código guardado.',
29
32
  'ui.snapshot.proof': 'Registrar versión necesita una prueba de captura válida y sin cambios para este cambio, código guardado y copia de trabajo. Guarda los archivos de revisión y toma una nueva captura si es necesario.',
30
33
  'ui.snapshot.linked': '{coding, select, yes {{here, select, yes {Este estudio está abierto en la copia de trabajo donde se está construyendo {change}} other {{change} se está construyendo en su propia copia de trabajo}}. Su prototipo aprobado está en main, así que no hay nada que registrar desde esa copia de trabajo. Tomar instantánea la dibuja allí con sus propios servidores, y Guardar conserva los archivos de su instantánea en la rama del cambio.} other {{here, select, yes {Este estudio está abierto en la copia de trabajo propia de {change}} other {{change} está en la copia de trabajo {path}}}. Tomar instantánea la dibuja allí con sus propios servidores, y Guardar conserva los archivos de su instantánea en la rama del cambio. El estudio registra solo en main, así que en una terminal en {here, select, yes {esta carpeta} other {esa carpeta}}: haz commit de todos sus cambios y de la nueva carpeta prototype/snapshots, y luego ejecuta pnpm ape prototype version {change} --why "qué cambió".}}',
@@ -0,0 +1,13 @@
1
+ import type { PlanFacts } from '@buffcore/contracts/workbench';
2
+ export declare const withoutComments: (text: string) => string;
3
+ export declare const answer: (text: string) => string;
4
+ export declare const plain: (text: string) => string;
5
+ /** A newline wraps a paragraph or list item; only a new marker starts another item. */
6
+ export declare function briefSection(text: string, words?: (text: string) => string): string;
7
+ /** Section spelling, fences and closing hashes follow the original Brief reader. */
8
+ export declare function planSections(text: string): {
9
+ heading: string;
10
+ body: string;
11
+ }[];
12
+ /** Section headings stay as written; the template's prompts are not answers. */
13
+ export declare function parseBrief(text: string | null): PlanFacts['brief'];