@softure-ai/marketing-kit 0.1.8 → 0.1.10

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 (85) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +111 -8
  3. package/dist/cli/main.js +42 -6
  4. package/dist/cli/main.js.map +1 -1
  5. package/dist/config/actions-schema.d.ts +7 -1
  6. package/dist/config/actions-schema.d.ts.map +1 -1
  7. package/dist/config/actions-schema.js +18 -3
  8. package/dist/config/actions-schema.js.map +1 -1
  9. package/dist/config/config.d.ts +2 -0
  10. package/dist/config/config.d.ts.map +1 -1
  11. package/dist/config/config.js +2 -1
  12. package/dist/config/config.js.map +1 -1
  13. package/dist/config/placeholders.d.ts +32 -0
  14. package/dist/config/placeholders.d.ts.map +1 -0
  15. package/dist/config/placeholders.js +41 -0
  16. package/dist/config/placeholders.js.map +1 -0
  17. package/dist/config/schema.d.ts +2214 -1
  18. package/dist/config/schema.d.ts.map +1 -1
  19. package/dist/config/schema.js +93 -4
  20. package/dist/config/schema.js.map +1 -1
  21. package/dist/config/shot-steps.d.ts +637 -0
  22. package/dist/config/shot-steps.d.ts.map +1 -0
  23. package/dist/config/shot-steps.js +44 -0
  24. package/dist/config/shot-steps.js.map +1 -0
  25. package/dist/film.d.ts +20 -5
  26. package/dist/film.d.ts.map +1 -1
  27. package/dist/film.js.map +1 -1
  28. package/dist/record/actions.d.ts +3 -10
  29. package/dist/record/actions.d.ts.map +1 -1
  30. package/dist/record/actions.js +13 -24
  31. package/dist/record/actions.js.map +1 -1
  32. package/dist/record/locator.d.ts +10 -0
  33. package/dist/record/locator.d.ts.map +1 -0
  34. package/dist/record/locator.js +24 -0
  35. package/dist/record/locator.js.map +1 -0
  36. package/dist/record/record.d.ts.map +1 -1
  37. package/dist/record/record.js +51 -17
  38. package/dist/record/record.js.map +1 -1
  39. package/dist/record/screen-guard.d.ts +13 -0
  40. package/dist/record/screen-guard.d.ts.map +1 -0
  41. package/dist/record/screen-guard.js +27 -0
  42. package/dist/record/screen-guard.js.map +1 -0
  43. package/dist/screenshot/gates.d.ts +46 -5
  44. package/dist/screenshot/gates.d.ts.map +1 -1
  45. package/dist/screenshot/gates.js +41 -5
  46. package/dist/screenshot/gates.js.map +1 -1
  47. package/dist/screenshot/prepare.d.ts +18 -0
  48. package/dist/screenshot/prepare.d.ts.map +1 -0
  49. package/dist/screenshot/prepare.js +60 -0
  50. package/dist/screenshot/prepare.js.map +1 -0
  51. package/dist/screenshot/screenshot.d.ts +9 -2
  52. package/dist/screenshot/screenshot.d.ts.map +1 -1
  53. package/dist/screenshot/screenshot.js +86 -7
  54. package/dist/screenshot/screenshot.js.map +1 -1
  55. package/dist/screenshot/shot-texts.d.ts +26 -0
  56. package/dist/screenshot/shot-texts.d.ts.map +1 -0
  57. package/dist/screenshot/shot-texts.js +55 -0
  58. package/dist/screenshot/shot-texts.js.map +1 -0
  59. package/dist/screenshot/sign-in.d.ts +34 -0
  60. package/dist/screenshot/sign-in.d.ts.map +1 -0
  61. package/dist/screenshot/sign-in.js +66 -0
  62. package/dist/screenshot/sign-in.js.map +1 -0
  63. package/dist/screenshot/steps.d.ts +12 -0
  64. package/dist/screenshot/steps.d.ts.map +1 -0
  65. package/dist/screenshot/steps.js +38 -0
  66. package/dist/screenshot/steps.js.map +1 -0
  67. package/package.json +3 -2
  68. package/schema/marketing.schema.json +1893 -18
  69. package/src/cli/main.ts +40 -6
  70. package/src/config/actions-schema.ts +18 -3
  71. package/src/config/config.ts +4 -1
  72. package/src/config/placeholders.ts +60 -0
  73. package/src/config/schema.ts +104 -5
  74. package/src/config/shot-steps.ts +58 -0
  75. package/src/film.ts +15 -5
  76. package/src/record/actions.ts +11 -32
  77. package/src/record/locator.ts +37 -0
  78. package/src/record/record.ts +53 -19
  79. package/src/record/screen-guard.ts +37 -0
  80. package/src/screenshot/gates.ts +60 -5
  81. package/src/screenshot/prepare.ts +64 -0
  82. package/src/screenshot/screenshot.ts +89 -8
  83. package/src/screenshot/shot-texts.ts +72 -0
  84. package/src/screenshot/sign-in.ts +91 -0
  85. package/src/screenshot/steps.ts +44 -0
@@ -5,8 +5,9 @@ import { chromium, type Locator } from "playwright";
5
5
 
6
6
  import { fitScale, getGeometry, unionRect, type Rect } from "../compose/timeline.js";
7
7
  import type { ColorTheme } from "../config/colors.js";
8
- import { containsPhrase, sceneBeats, type CueName, type Director, type Film } from "../film.js";
8
+ import { sceneBeats, type Beat, type CueName, type Director, type Film } from "../film.js";
9
9
  import type { BeatVoice } from "../voice/voiceover.js";
10
+ import { describeCheckScreenFailure, describeSentenceFailure, findMissingPhrases, getCheckScreenPhrases } from "./screen-guard.js";
10
11
 
11
12
  /**
12
13
  * Recording of the real app **frame by frame**, with the page clock frozen.
@@ -26,6 +27,8 @@ export const FPS = 30;
26
27
  const DT = 1000 / FPS;
27
28
  /** Limit of one scene action: longer means the app looks different from what the scene expects. */
28
29
  const ACTION_TIMEOUT_MS = 5000;
30
+ /** How long one typed character or pressed key stays on screen before the next. */
31
+ const KEY_SECONDS = 0.13;
29
32
 
30
33
  export interface CameraCue {
31
34
  f: number;
@@ -96,7 +99,8 @@ export async function recordFilm(options: RecordOptions): Promise<RecordingLog>
96
99
  mkdirSync(framesDir, { recursive: true });
97
100
 
98
101
  const voiceById = new Map(voices.map((voice) => [voice.id, voice]));
99
- const expectedBeats = sceneBeats(film).map((beat) => beat.id);
102
+ const sentenceById = new Map(sceneBeats(film).map((beat) => [beat.id, beat]));
103
+ const expectedBeats = [...sentenceById.keys()];
100
104
  const log: RecordingLog = {
101
105
  voiceoverKey: options.voiceoverKey,
102
106
  beatIds: expectedBeats,
@@ -157,7 +161,8 @@ export async function recordFilm(options: RecordOptions): Promise<RecordingLog>
157
161
 
158
162
  let virtualMs = 0;
159
163
  let frame = 0;
160
- let current: { id: string; f0: number } | null = null;
164
+ /** The sentence being recorded; `isGuardChecked` once a checkScreen inside it checked its own phrases. */
165
+ let current: { id: string; f0: number; sentence: Beat; isGuardChecked: boolean } | null = null;
161
166
  let guardChecked = false;
162
167
 
163
168
  const where = (): string => (current === null ? "before the first sentence" : `sentence "${current.id}"`);
@@ -196,6 +201,10 @@ export async function recordFilm(options: RecordOptions): Promise<RecordingLog>
196
201
  for (let i = 0, count = Math.round(seconds * FPS); i < count; i += 1) await shoot();
197
202
  }
198
203
 
204
+ async function readScreenText(): Promise<string> {
205
+ return (await page.locator(settings.screenGuardSelector).first().innerText()).replace(/\s+/g, " ");
206
+ }
207
+
199
208
  async function rectOf(target: Locator): Promise<Rect> {
200
209
  try {
201
210
  // "visible", not "attached": a hidden element has a 0×0 rectangle and a tap would miss.
@@ -249,13 +258,21 @@ export async function recordFilm(options: RecordOptions): Promise<RecordingLog>
249
258
  );
250
259
  }
251
260
  const voice = voiceById.get(id);
252
- if (voice === undefined) throw new Error(`No voiceover for sentence "${id}".`);
253
- current = { id, f0: frame };
261
+ const sentence = sentenceById.get(id);
262
+ if (voice === undefined || sentence === undefined) throw new Error(`No voiceover for sentence "${id}".`);
263
+ const state = { id, f0: frame, sentence, isGuardChecked: false };
264
+ current = state;
254
265
  await actions();
255
266
  const minFrames = Math.round((voice.end - voice.start + (beatOptions?.pad ?? 0.35)) * FPS);
256
- const missing = minFrames - (frame - current.f0);
267
+ const missing = minFrames - (frame - state.f0);
257
268
  if (missing > 0) await hold(missing / FPS);
258
- log.beats.push({ id, f0: current.f0, f1: frame });
269
+ // The sentence's own phrases, on its last frame, unless a checkScreen inside it already checked them.
270
+ const phrases = sentence.screenGuard ?? [];
271
+ if (!state.isGuardChecked && phrases.length > 0) {
272
+ const absent = findMissingPhrases(await readScreenText(), phrases);
273
+ if (absent.length > 0) throw new ScreenGuardError(describeSentenceFailure(id, absent, filmPath));
274
+ }
275
+ log.beats.push({ id, f0: state.f0, f1: frame });
259
276
  },
260
277
 
261
278
  async until(word) {
@@ -290,11 +307,19 @@ export async function recordFilm(options: RecordOptions): Promise<RecordingLog>
290
307
  for (const character of text) {
291
308
  log.keys.push(frame);
292
309
  await page.keyboard.type(character);
293
- await hold(typeOptions?.perChar ?? 0.13);
310
+ await hold(typeOptions?.perChar ?? KEY_SECONDS);
294
311
  }
295
312
  },
296
313
 
297
- async fill(name, value) {
314
+ async press(key, pressOptions) {
315
+ for (let i = 0, times = pressOptions?.times ?? 1; i < times; i += 1) {
316
+ log.keys.push(frame);
317
+ await page.keyboard.press(key);
318
+ await hold(pressOptions?.perKey ?? KEY_SECONDS);
319
+ }
320
+ },
321
+
322
+ async fill(name, value, fillOptions) {
298
323
  const input = page.locator(`input[name=${name}]`);
299
324
  await ensureVisible(input);
300
325
  const rect = await rectOf(input);
@@ -302,6 +327,19 @@ export async function recordFilm(options: RecordOptions): Promise<RecordingLog>
302
327
  const scale = isDesktop ? Math.min(1.55, fitScale(geometry, rect)) : 1.55;
303
328
  log.camera.push({ f: frame, kind: "focus", rect, scale, whoosh: false });
304
329
  await director.tap(input, { after: 0.2 });
330
+ // A tap leaves the caret where the finger landed and selects nothing: typed keys would join the old value.
331
+ // An empty field presses nothing, so it records frame for frame as before.
332
+ if (fillOptions?.clear !== false && (await input.inputValue()) !== "") {
333
+ await director.press("ControlOrMeta+A");
334
+ await director.press("Backspace");
335
+ const left = await input.inputValue();
336
+ if (left !== "") {
337
+ throw new Error(
338
+ `${where()}: ${String(input)} still holds "${left}" after select all and Backspace; ` +
339
+ `the app puts a value back. Set "clear": false or fix the scene: ${filmPath}`,
340
+ );
341
+ }
342
+ }
305
343
  await director.type(value);
306
344
  },
307
345
 
@@ -341,16 +379,10 @@ export async function recordFilm(options: RecordOptions): Promise<RecordingLog>
341
379
  },
342
380
 
343
381
  async checkScreen() {
344
- const text = (await page.locator(settings.screenGuardSelector).first().innerText()).replace(/\s+/g, " ");
345
- const missing = film.screenGuard.filter((phrase) => !containsPhrase(text, phrase));
346
- if (missing.length > 0) {
347
- throw new ScreenGuardError(
348
- `The screen does not say what the voiceover says: missing ${missing.map((p) => `"${p}"`).join(", ")}. ` +
349
- `The app counts from the recording day: if the voiceover was paid for on another day, pin that day in the video's ` +
350
- `"today" (or pass --today=YYYY-MM-DD); otherwise fix the sentences and phrases in ${filmPath}.`,
351
- );
352
- }
382
+ const missing = findMissingPhrases(await readScreenText(), getCheckScreenPhrases(film.screenGuard, current?.sentence ?? null));
383
+ if (missing.length > 0) throw new ScreenGuardError(describeCheckScreenFailure(missing, filmPath));
353
384
  guardChecked = true;
385
+ if (current !== null) current.isGuardChecked = true;
354
386
  },
355
387
  };
356
388
 
@@ -362,7 +394,9 @@ export async function recordFilm(options: RecordOptions): Promise<RecordingLog>
362
394
  `The scene recorded ${log.beats.length} of ${expectedBeats.length} sentences; "${expectedBeats[log.beats.length]}" is missing.`,
363
395
  );
364
396
  }
365
- if (!guardChecked) throw new Error("The scene never called checkScreen(): a film without the screen guard could say what the screen does not show.");
397
+ if (!guardChecked && film.screenGuard.length > 0) {
398
+ throw new Error("The scene never called checkScreen(): the video's screenGuard phrases were never checked, so the film could say what the screen does not show.");
399
+ }
366
400
  if (log.stills[film.hook.still] === undefined) {
367
401
  throw new Error(`The scene did not save the opening frame "${film.hook.still}" (still).`);
368
402
  }
@@ -0,0 +1,37 @@
1
+ import { containsPhrase, type Beat } from "../film.js";
2
+
3
+ /**
4
+ * The screen guard's rules, apart from the browser: which phrases a check covers and what a failure says. The
5
+ * video's `screenGuard` is checked at every `checkScreen`; a sentence's own `screenGuard` at a `checkScreen` inside
6
+ * that sentence, or, without one, when the sentence ends, so each number is proven on screen while it is spoken.
7
+ */
8
+
9
+ /** The phrases a `checkScreen` covers: the video's, plus the current sentence's own (none before the first sentence). */
10
+ export function getCheckScreenPhrases(videoPhrases: readonly string[], sentence: Beat | null): string[] {
11
+ return [...videoPhrases, ...(sentence?.screenGuard ?? [])];
12
+ }
13
+
14
+ /** The phrases the screen's text does not contain as whole words, in their order. */
15
+ export function findMissingPhrases(text: string, phrases: readonly string[]): string[] {
16
+ return phrases.filter((phrase) => !containsPhrase(text, phrase));
17
+ }
18
+
19
+ const quote = (phrases: readonly string[]): string => phrases.map((phrase) => `"${phrase}"`).join(", ");
20
+
21
+ function describeFix(filmPath: string): string {
22
+ return (
23
+ `The app counts from the recording day: if the voiceover was paid for on another day, pin that day in the video's ` +
24
+ `"today" (or pass --today=YYYY-MM-DD); otherwise fix the sentences and phrases in ${filmPath}.`
25
+ );
26
+ }
27
+
28
+ export function describeCheckScreenFailure(missing: readonly string[], filmPath: string): string {
29
+ return `The screen does not say what the voiceover says: missing ${quote(missing)}. ${describeFix(filmPath)}`;
30
+ }
31
+
32
+ export function describeSentenceFailure(sentenceId: string, missing: readonly string[], filmPath: string): string {
33
+ return (
34
+ `Sentence "${sentenceId}" ended without its screenGuard phrases on screen: missing ${quote(missing)}. ` +
35
+ `Reveal them before the sentence ends, or check them where they show with a checkScreen inside the sentence. ${describeFix(filmPath)}`
36
+ );
37
+ }
@@ -1,11 +1,14 @@
1
+ import type { Aspect } from "../config/shot-steps.js";
2
+
1
3
  /**
2
- * The quality gates a screenshot passes before it is kept (FIRE's screenshot script): the page
3
- * answered below HTTP 400, it reached the requested scroll offset, it shows the expected phrase, and
4
- * the file is not suspiciously small. A blank page, an error page, a half-loaded one or a frame of
5
- * the wrong place fails at least one of them.
4
+ * The quality gates a screenshot passes before it is kept: the sign-in worked (signed-in entries), the page
5
+ * answered below HTTP 400, its steps ran, it reached the requested scroll offset, it shows the expected phrase, a
6
+ * crop found its one element and fits the page and the file has the frame's size, the file is not suspiciously
7
+ * small, and no earlier file of the run has the same bytes. A blank page, an error page, a half-loaded one, an
8
+ * empty account or a frame of the wrong place fails at least one of them.
6
9
  */
7
10
 
8
- export const SCREENSHOT_GATES = ["load", "status", "scroll", "phrase", "size"] as const;
11
+ export const SCREENSHOT_GATES = ["sign-in", "load", "status", "steps", "scroll", "phrase", "crop", "size", "duplicate"] as const;
9
12
 
10
13
  export type ScreenshotGate = (typeof SCREENSHOT_GATES)[number];
11
14
 
@@ -33,3 +36,55 @@ export function findSizeFailure(bytes: number, minBytes: number): string | null
33
36
  if (bytes >= minBytes) return null;
34
37
  return `the file has ${bytes} bytes, below minBytes ${minBytes} (a blank or broken page); deleted`;
35
38
  }
39
+
40
+ /** A rectangle in CSS pixels, in document coordinates (from the page's top-left corner, not the viewport's). */
41
+ export interface Rect {
42
+ x: number;
43
+ y: number;
44
+ width: number;
45
+ height: number;
46
+ }
47
+
48
+ export type CropFrameResult = { ok: true; frame: Rect } | { ok: false; message: string };
49
+
50
+ export interface CropFrameInput {
51
+ /** The element, in document coordinates. */
52
+ element: Rect;
53
+ /** The page's scrollable size. */
54
+ page: { width: number; height: number };
55
+ aspect: Aspect;
56
+ padding: number;
57
+ }
58
+
59
+ /**
60
+ * The frame of a crop in whole CSS pixels: as wide as the element plus the padding on each side, from the padding
61
+ * above its top edge, as tall as the aspect asks. Refused when it would run past the page, which would leave part of
62
+ * the file empty or cut it short.
63
+ */
64
+ export function findCropFrame({ element, page, aspect, padding }: CropFrameInput): CropFrameResult {
65
+ const x = Math.floor(element.x - padding);
66
+ const y = Math.floor(element.y - padding);
67
+ const width = Math.round(element.width + 2 * padding);
68
+ const height = Math.round((width * aspect.height) / aspect.width);
69
+ const ratio = `${aspect.width}:${aspect.height}`;
70
+ if (width < 1) return { ok: false, message: `the crop's element has no width, so a ${ratio} frame has nothing to show` };
71
+ if (x < 0) return { ok: false, message: `the ${ratio} frame starts ${-x} px left of the page; lower crop.padding` };
72
+ if (y < 0) return { ok: false, message: `the ${ratio} frame starts ${-y} px above the page; lower crop.padding` };
73
+ if (x + width > page.width) return { ok: false, message: `the ${ratio} frame runs ${x + width - page.width} px past the page's right edge; lower crop.padding` };
74
+ if (y + height > page.height) {
75
+ return { ok: false, message: `the ${ratio} frame (${width}×${height} px) runs ${y + height - page.height} px past the page's bottom edge` };
76
+ }
77
+ return { ok: true, frame: { x, y, width, height } };
78
+ }
79
+
80
+ /** Device pixels round once per side, so the file may be one pixel off the frame × scale. */
81
+ const DIMENSION_TOLERANCE_PX = 1;
82
+
83
+ /** Null when the PNG is the frame at the device scale; otherwise what it is instead. */
84
+ export function findDimensionFailure(file: { width: number; height: number }, frame: { width: number; height: number }, scale: number): string | null {
85
+ const width = Math.round(frame.width * scale);
86
+ const height = Math.round(frame.height * scale);
87
+ const isWithin = Math.abs(file.width - width) <= DIMENSION_TOLERANCE_PX && Math.abs(file.height - height) <= DIMENSION_TOLERANCE_PX;
88
+ if (isWithin) return null;
89
+ return `the file is ${file.width}×${file.height} px, not the crop's ${width}×${height} px; deleted`;
90
+ }
@@ -0,0 +1,64 @@
1
+ import { spawnSync } from "node:child_process";
2
+
3
+ /**
4
+ * `signIn.prepare`: the app's own command that creates and seeds the account the signed-in screenshots show, and
5
+ * prints what the frames must show as `{data:key}`. Its output may hold the account's password, so it is parsed and
6
+ * never echoed; its error stream goes to the terminal as the command writes it.
7
+ */
8
+
9
+ /** A seed script that runs longer than this is stuck, not slow. */
10
+ const PREPARE_TIMEOUT_MS = 10 * 60_000;
11
+ /** Seed scripts print logs; the cap only stops a runaway one from filling memory. */
12
+ const MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
13
+
14
+ export type PrepareResult = { ok: true; data: Record<string, string> } | { ok: false; error: string };
15
+
16
+ /** The data from the last non-empty line of the output: a JSON object of strings or numbers. */
17
+ export function parsePrepareOutput(stdout: string): PrepareResult {
18
+ const lastLine = stdout
19
+ .split("\n")
20
+ .map((line) => line.trim())
21
+ .filter((line) => line.length > 0)
22
+ .at(-1);
23
+ const expected = 'its last line of output must be a JSON object of strings or numbers, e.g. {"email": "demo@example.com", "total": "12,345"}';
24
+ if (lastLine === undefined) return { ok: false, error: `signIn.prepare printed nothing; ${expected}` };
25
+ let parsed: unknown;
26
+ try {
27
+ parsed = JSON.parse(lastLine);
28
+ } catch {
29
+ // The line may hold a password, so the parse error, which quotes it, is not passed on.
30
+ return { ok: false, error: `signIn.prepare's last line is not JSON; ${expected}` };
31
+ }
32
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return { ok: false, error: `signIn.prepare's last line is not a JSON object; ${expected}` };
33
+ const data: Record<string, string> = {};
34
+ for (const [key, value] of Object.entries(parsed)) {
35
+ if (typeof value === "string") data[key] = value;
36
+ else if (typeof value === "number" && Number.isFinite(value)) data[key] = String(value);
37
+ else return { ok: false, error: `signIn.prepare's value "${key}" is not a string or a number; ${expected}` };
38
+ }
39
+ return { ok: true, data };
40
+ }
41
+
42
+ export interface RunPrepareOptions {
43
+ /** The folder of marketing.json. */
44
+ cwd: string;
45
+ /** The app's address, handed to the command as MARKETING_BASE_URL. */
46
+ baseUrl: string;
47
+ }
48
+
49
+ /** Runs the command (no shell) and reads its data; a failure names the exit, never the output. */
50
+ export function runPrepare(command: readonly [string, ...string[]], options: RunPrepareOptions): PrepareResult {
51
+ const [program, ...args] = command;
52
+ const result = spawnSync(program, args, {
53
+ cwd: options.cwd,
54
+ env: { ...process.env, MARKETING_BASE_URL: options.baseUrl },
55
+ encoding: "utf8",
56
+ stdio: ["ignore", "pipe", "inherit"],
57
+ timeout: PREPARE_TIMEOUT_MS,
58
+ maxBuffer: MAX_OUTPUT_BYTES,
59
+ });
60
+ const shown = command.join(" ");
61
+ if (result.error !== undefined) return { ok: false, error: `signIn.prepare (${shown}) could not run: ${result.error.message}` };
62
+ if (result.status !== 0) return { ok: false, error: `signIn.prepare (${shown}) ended with code ${String(result.status ?? result.signal)}` };
63
+ return parsePrepareOutput(result.stdout);
64
+ }
@@ -1,4 +1,5 @@
1
- import { mkdirSync, rmSync, statSync } from "node:fs";
1
+ import { createHash } from "node:crypto";
2
+ import { mkdirSync, readFileSync, rmSync, statSync } from "node:fs";
2
3
  import { basename, dirname, extname, join } from "node:path";
3
4
 
4
5
  import { chromium, errors, type Browser, type Page } from "playwright";
@@ -7,14 +8,18 @@ import type { ColorTheme } from "../config/colors.js";
7
8
  import type { MarketingJson } from "../config/schema.js";
8
9
  import { getScreenshotNames, getScreenshotShots } from "../config/screenshot-names.js";
9
10
  import { containsPhrase } from "../film.js";
10
- import { findScrollFailure, findSizeFailure, findStatusFailure, type ScreenshotGate } from "./gates.js";
11
+ import { getLocator } from "../record/locator.js";
12
+ import { findCropFrame, findDimensionFailure, findScrollFailure, findSizeFailure, findStatusFailure, type ScreenshotGate } from "./gates.js";
13
+ import { readPageText, signIn, type SessionState, type SignInPlan } from "./sign-in.js";
14
+ import { runShotSteps } from "./steps.js";
11
15
 
12
16
  /**
13
17
  * `softure-marketing shots`: the `screenshots` entries of `marketing.json`. Each shot of an entry
14
18
  * (one per colour scheme, `config/screenshot-names.ts`) gets a fresh browser context with the entry's viewport, device
15
19
  * scale and motion preference, and is kept only when it passes every gate (`gates.ts`) on its own.
16
20
  * Every file an entry could write is removed before it runs, so a failed shot leaves no file behind,
17
- * not even an older one: a stale PNG must never look like a fresh pass.
21
+ * not even an older one: a stale PNG must never look like a fresh pass. Entries with `signedIn` share one sign-in
22
+ * per run, and no two kept files of a run may have the same bytes.
18
23
  */
19
24
 
20
25
  export type ScreenshotEntry = MarketingJson["screenshots"][number];
@@ -40,6 +45,8 @@ export interface TakeScreenshotsOptions {
40
45
  browser: ScreenshotBrowser;
41
46
  /** A Chromium to use instead of Playwright's own (`PLAYWRIGHT_CHROMIUM_PATH`). */
42
47
  executablePath?: string;
48
+ /** How `signedIn` entries sign in, placeholders resolved; without it, every `signedIn` shot is refused. */
49
+ signIn?: SignInPlan;
43
50
  }
44
51
 
45
52
  /** `id` is the entry's, `name` the file's without `.png` (`<id>` or `<id>-<scheme>`). */
@@ -76,7 +83,9 @@ async function scrollThroughPage(page: Page): Promise<void> {
76
83
  async function waitForPhrase(page: Page, phrase: string): Promise<boolean> {
77
84
  const deadline = Date.now() + PHRASE_TIMEOUT_MS;
78
85
  for (;;) {
79
- if (containsPhrase(await page.locator("body").innerText(), phrase)) return true;
86
+ // A step may have started a navigation; its page is read on the next poll.
87
+ const text = await readPageText(page);
88
+ if (text !== null && containsPhrase(text, phrase)) return true;
80
89
  if (Date.now() >= deadline) return false;
81
90
  await page.waitForTimeout(PHRASE_POLL_MS);
82
91
  }
@@ -94,6 +103,26 @@ interface ShotTarget {
94
103
  file: string;
95
104
  }
96
105
 
106
+ /** Width and height of a PNG from its IHDR chunk. */
107
+ function readPngSize(file: string): { width: number; height: number } {
108
+ const bytes = readFileSync(file);
109
+ return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20) };
110
+ }
111
+
112
+ /** The element's rectangle in document coordinates and the page's scrollable size. */
113
+ async function measureCrop(page: Page, entry: ScreenshotEntry & { crop: NonNullable<ScreenshotEntry["crop"]> }): Promise<{ ok: true; frame: { x: number; y: number; width: number; height: number } } | { ok: false; message: string }> {
114
+ const locator = getLocator(page, entry.crop.target);
115
+ const count = await locator.count();
116
+ if (count === 0) return { ok: false, message: "no element matches crop.target" };
117
+ if (count > 1) return { ok: false, message: `crop.target matches ${count} elements; add nth to pick one` };
118
+ const element = await locator.evaluate((node) => {
119
+ const rect = node.getBoundingClientRect();
120
+ return { x: rect.left + window.scrollX, y: rect.top + window.scrollY, width: rect.width, height: rect.height };
121
+ });
122
+ const size = await page.evaluate(() => ({ width: document.documentElement.scrollWidth, height: document.documentElement.scrollHeight }));
123
+ return findCropFrame({ element, page: size, aspect: entry.crop.aspect, padding: entry.crop.padding });
124
+ }
125
+
97
126
  async function takeOne(page: Page, target: ShotTarget): Promise<ScreenshotResult> {
98
127
  const { entry, name, url } = target;
99
128
  const refuse = (gate: ScreenshotGate, message: string): ScreenshotResult => ({ ok: false, id: entry.id, name, gate, message });
@@ -120,6 +149,8 @@ async function takeOne(page: Page, target: ShotTarget): Promise<ScreenshotResult
120
149
  async function captureLoadedPage(page: Page, target: ShotTarget): Promise<ScreenshotResult> {
121
150
  const { entry, name, url, file } = target;
122
151
  await page.evaluate(() => document.fonts.ready);
152
+ const stepFailure = await runShotSteps(page, entry.steps, "steps");
153
+ if (stepFailure !== null) return { ok: false, id: entry.id, name, gate: "steps", message: stepFailure };
123
154
  if (entry.full) await scrollThroughPage(page);
124
155
  if (entry.scrollTo !== undefined) {
125
156
  const reached = await page.evaluate((top) => {
@@ -133,7 +164,23 @@ async function captureLoadedPage(page: Page, target: ShotTarget): Promise<Screen
133
164
  if (!(await waitForPhrase(page, entry.expect))) {
134
165
  return { ok: false, id: entry.id, name, gate: "phrase", message: `${url} does not show "${entry.expect}"` };
135
166
  }
136
- await page.screenshot({ path: file, fullPage: entry.full });
167
+ let frame: { width: number; height: number } | null = null;
168
+ if (entry.crop === undefined) {
169
+ await page.screenshot({ path: file, fullPage: entry.full });
170
+ } else {
171
+ const crop = await measureCrop(page, { ...entry, crop: entry.crop });
172
+ if (!crop.ok) return { ok: false, id: entry.id, name, gate: "crop", message: crop.message };
173
+ // Document coordinates with fullPage: a sticky header stays at the page's top instead of over the element.
174
+ await page.screenshot({ path: file, fullPage: true, clip: crop.frame });
175
+ frame = crop.frame;
176
+ }
177
+ if (frame !== null) {
178
+ const dimensionFailure = findDimensionFailure(readPngSize(file), frame, entry.scale);
179
+ if (dimensionFailure !== null) {
180
+ rmSync(file, { force: true });
181
+ return { ok: false, id: entry.id, name, gate: "crop", message: dimensionFailure };
182
+ }
183
+ }
137
184
  const bytes = statSync(file).size;
138
185
  const sizeFailure = findSizeFailure(bytes, entry.minBytes);
139
186
  if (sizeFailure !== null) {
@@ -153,10 +200,12 @@ interface TakeShotOptions {
153
200
  settings: ScreenshotBrowser;
154
201
  target: ShotTarget;
155
202
  scheme: ColorTheme;
203
+ /** The run's sign-in session, for a `signedIn` entry. */
204
+ session?: SessionState;
156
205
  }
157
206
 
158
207
  async function takeShot(options: TakeShotOptions): Promise<ScreenshotResult> {
159
- const { browser, settings, target, scheme } = options;
208
+ const { browser, settings, target, scheme, session } = options;
160
209
  const { entry } = target;
161
210
  const context = await browser.newContext({
162
211
  viewport: { width: entry.width, height: entry.height },
@@ -167,6 +216,7 @@ async function takeShot(options: TakeShotOptions): Promise<ScreenshotResult> {
167
216
  reducedMotion: entry.motion,
168
217
  // Resolved to an absolute path by the caller (the CLI resolves it against the folder of marketing.json).
169
218
  ...(entry.storageState === undefined ? {} : { storageState: entry.storageState }),
219
+ ...(session === undefined ? {} : { storageState: session }),
170
220
  });
171
221
  try {
172
222
  const page = await context.newPage();
@@ -189,18 +239,49 @@ async function takeShot(options: TakeShotOptions): Promise<ScreenshotResult> {
189
239
  }
190
240
  }
191
241
 
192
- /** Takes every shot of every entry in order; one failing shot does not stop the others. */
242
+ /**
243
+ * Refuses a kept file whose bytes an earlier kept file of the run already has (the page did not change between the
244
+ * two shots, or two entries frame the same thing), and deletes it; remembers the others.
245
+ */
246
+ function refuseDuplicate(result: ScreenshotResult, seen: Map<string, string>): ScreenshotResult {
247
+ if (!result.ok) return result;
248
+ const hash = createHash("sha256").update(readFileSync(result.file)).digest("hex");
249
+ const earlier = seen.get(hash);
250
+ if (earlier === undefined) {
251
+ seen.set(hash, result.name);
252
+ return result;
253
+ }
254
+ rmSync(result.file, { force: true });
255
+ const message = `the file has the same bytes as ${earlier}.png: the page did not change between the two shots; deleted`;
256
+ return { ok: false, id: result.id, name: result.name, gate: "duplicate", message };
257
+ }
258
+
259
+ /**
260
+ * Takes every shot of every entry in order; one failing shot does not stop the others. The sign-in runs once,
261
+ * before the first `signedIn` entry; when it fails, every `signedIn` shot is refused with its reason.
262
+ */
193
263
  export async function takeScreenshots(options: TakeScreenshotsOptions): Promise<ScreenshotResult[]> {
194
264
  const { entries, baseUrl, outDir, browser: settings } = options;
195
265
  mkdirSync(outDir, { recursive: true });
196
266
  const browser = await chromium.launch(options.executablePath === undefined ? {} : { executablePath: options.executablePath });
197
267
  const results: ScreenshotResult[] = [];
268
+ const seen = new Map<string, string>();
269
+ let signedIn: Awaited<ReturnType<typeof signIn>> | null = null;
198
270
  try {
199
271
  for (const entry of entries) {
200
272
  removeEntryFiles(outDir, entry);
273
+ if (entry.signedIn && signedIn === null) {
274
+ signedIn = options.signIn === undefined ? { ok: false, message: "no signIn block says how to sign in" } : await signIn({ browser, baseUrl, settings, plan: options.signIn });
275
+ }
201
276
  for (const shot of getScreenshotShots(entry, settings.colorScheme)) {
277
+ if (entry.signedIn && signedIn?.ok === false) {
278
+ results.push({ ok: false, id: entry.id, name: shot.name, gate: "sign-in", message: signedIn.message });
279
+ continue;
280
+ }
202
281
  const target = { entry, name: shot.name, url: new URL(entry.path, baseUrl).href, file: getScreenshotFile(outDir, shot.name) };
203
- results.push(await takeShot({ browser, settings, target, scheme: shot.scheme }));
282
+ const session = entry.signedIn && signedIn?.ok === true ? signedIn.session : undefined;
283
+ const result = await takeShot({ browser, settings, target, scheme: shot.scheme, ...(session === undefined ? {} : { session }) });
284
+ results.push(refuseDuplicate(result, seen));
204
285
  }
205
286
  }
206
287
  } finally {
@@ -0,0 +1,72 @@
1
+ import type { ShotStep } from "../config/shot-steps.js";
2
+ import { findPlaceholders, resolvePlaceholders, type PlaceholderSources } from "../config/placeholders.js";
3
+ import type { ScreenshotEntry } from "./screenshot.js";
4
+ import type { SignInPlan } from "./sign-in.js";
5
+
6
+ /**
7
+ * Every text of a `shots` run that may hold `{env:NAME}` or `{data:key}` (the sign-in's step values and phrase, each
8
+ * entry's path, phrase and step values), resolved in one place with the place it came from, so an error names the
9
+ * key to fix and never a value.
10
+ */
11
+
12
+ export interface ShotTexts {
13
+ entries: ScreenshotEntry[];
14
+ signIn: SignInPlan | null;
15
+ }
16
+
17
+ export type ResolveShotTextsResult = { ok: true; texts: ShotTexts } | { ok: false; error: string };
18
+
19
+ class UnresolvedText extends Error {}
20
+
21
+ function resolveSteps(steps: readonly ShotStep[], where: string, resolve: (text: string, where: string) => string): ShotStep[] {
22
+ return steps.map((step, index) => (step.do === "fill" ? { ...step, value: resolve(step.value, `${where}[${index}].value`) } : step));
23
+ }
24
+
25
+ /** The texts with their placeholders replaced; a page path gets its inserted values URL-encoded. */
26
+ export function resolveShotTexts(texts: ShotTexts, sources: PlaceholderSources): ResolveShotTextsResult {
27
+ const resolve = (text: string, where: string, encode?: (value: string) => string): string => {
28
+ const result = resolvePlaceholders(text, sources, encode);
29
+ if (!result.ok) throw new UnresolvedText(`${where}: ${result.error}`);
30
+ return result.value;
31
+ };
32
+ try {
33
+ const signIn =
34
+ texts.signIn === null
35
+ ? null
36
+ : { path: texts.signIn.path, steps: resolveSteps(texts.signIn.steps, "signIn.steps", resolve), expect: resolve(texts.signIn.expect, "signIn.expect") };
37
+ const entries = texts.entries.map((entry) => {
38
+ const where = `screenshot "${entry.id}"`;
39
+ return {
40
+ ...entry,
41
+ path: resolve(entry.path, `${where} path`, encodeURIComponent),
42
+ expect: resolve(entry.expect, `${where} expect`),
43
+ steps: resolveSteps(entry.steps, `${where} steps`, resolve),
44
+ };
45
+ });
46
+ return { ok: true, texts: { entries, signIn } };
47
+ } catch (error) {
48
+ if (error instanceof UnresolvedText) return { ok: false, error: error.message };
49
+ throw error;
50
+ }
51
+ }
52
+
53
+ function listTexts(texts: ShotTexts): string[] {
54
+ const stepValues = (steps: readonly ShotStep[]) => steps.flatMap((step) => (step.do === "fill" ? [step.value] : []));
55
+ const signIn = texts.signIn === null ? [] : [...stepValues(texts.signIn.steps), texts.signIn.expect];
56
+ return [...signIn, ...texts.entries.flatMap((entry) => [entry.path, entry.expect, ...stepValues(entry.steps)])];
57
+ }
58
+
59
+ /** Whether any text reads what `signIn.prepare` prints. */
60
+ export function usesData(texts: ShotTexts): boolean {
61
+ return listTexts(texts).some((text) => findPlaceholders(text).some((placeholder) => placeholder.kind === "data"));
62
+ }
63
+
64
+ /** The first `{env:NAME}` the environment does not set, checked before the app starts or the preparation runs. */
65
+ export function findUnsetVariable(texts: ShotTexts, env: Readonly<Record<string, string | undefined>>): string | null {
66
+ for (const text of listTexts(texts)) {
67
+ for (const { kind, key } of findPlaceholders(text)) {
68
+ if (kind === "env" && (env[key] === undefined || env[key] === "")) return key;
69
+ }
70
+ }
71
+ return null;
72
+ }