@softure-ai/marketing-kit 0.1.9 → 0.1.11

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 (67) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +124 -5
  3. package/dist/cli/main.js +42 -6
  4. package/dist/cli/main.js.map +1 -1
  5. package/dist/config/config.d.ts +2 -0
  6. package/dist/config/config.d.ts.map +1 -1
  7. package/dist/config/config.js +1 -0
  8. package/dist/config/config.js.map +1 -1
  9. package/dist/config/placeholders.d.ts +32 -0
  10. package/dist/config/placeholders.d.ts.map +1 -0
  11. package/dist/config/placeholders.js +41 -0
  12. package/dist/config/placeholders.js.map +1 -0
  13. package/dist/config/schema.d.ts +3758 -0
  14. package/dist/config/schema.d.ts.map +1 -1
  15. package/dist/config/schema.js +84 -0
  16. package/dist/config/schema.js.map +1 -1
  17. package/dist/config/shot-steps.d.ts +1101 -0
  18. package/dist/config/shot-steps.d.ts.map +1 -0
  19. package/dist/config/shot-steps.js +65 -0
  20. package/dist/config/shot-steps.js.map +1 -0
  21. package/dist/record/actions.d.ts +3 -10
  22. package/dist/record/actions.d.ts.map +1 -1
  23. package/dist/record/actions.js +7 -23
  24. package/dist/record/actions.js.map +1 -1
  25. package/dist/record/locator.d.ts +10 -0
  26. package/dist/record/locator.d.ts.map +1 -0
  27. package/dist/record/locator.js +24 -0
  28. package/dist/record/locator.js.map +1 -0
  29. package/dist/screenshot/gates.d.ts +55 -5
  30. package/dist/screenshot/gates.d.ts.map +1 -1
  31. package/dist/screenshot/gates.js +58 -5
  32. package/dist/screenshot/gates.js.map +1 -1
  33. package/dist/screenshot/prepare.d.ts +18 -0
  34. package/dist/screenshot/prepare.d.ts.map +1 -0
  35. package/dist/screenshot/prepare.js +60 -0
  36. package/dist/screenshot/prepare.js.map +1 -0
  37. package/dist/screenshot/screenshot.d.ts +9 -2
  38. package/dist/screenshot/screenshot.d.ts.map +1 -1
  39. package/dist/screenshot/screenshot.js +140 -8
  40. package/dist/screenshot/screenshot.js.map +1 -1
  41. package/dist/screenshot/shot-texts.d.ts +26 -0
  42. package/dist/screenshot/shot-texts.d.ts.map +1 -0
  43. package/dist/screenshot/shot-texts.js +55 -0
  44. package/dist/screenshot/shot-texts.js.map +1 -0
  45. package/dist/screenshot/sign-in.d.ts +34 -0
  46. package/dist/screenshot/sign-in.d.ts.map +1 -0
  47. package/dist/screenshot/sign-in.js +66 -0
  48. package/dist/screenshot/sign-in.js.map +1 -0
  49. package/dist/screenshot/steps.d.ts +13 -0
  50. package/dist/screenshot/steps.d.ts.map +1 -0
  51. package/dist/screenshot/steps.js +82 -0
  52. package/dist/screenshot/steps.js.map +1 -0
  53. package/package.json +2 -2
  54. package/schema/marketing.schema.json +3080 -10
  55. package/src/cli/main.ts +40 -6
  56. package/src/config/config.ts +3 -0
  57. package/src/config/placeholders.ts +60 -0
  58. package/src/config/schema.ts +89 -0
  59. package/src/config/shot-steps.ts +79 -0
  60. package/src/record/actions.ts +5 -31
  61. package/src/record/locator.ts +37 -0
  62. package/src/screenshot/gates.ts +77 -5
  63. package/src/screenshot/prepare.ts +64 -0
  64. package/src/screenshot/screenshot.ts +146 -9
  65. package/src/screenshot/shot-texts.ts +72 -0
  66. package/src/screenshot/sign-in.ts +91 -0
  67. package/src/screenshot/steps.ts +85 -0
package/src/cli/main.ts CHANGED
@@ -12,12 +12,14 @@ import { findMachineProblem } from "../render/preflight.js";
12
12
  import { runHyperframes } from "../render/hyperframes.js";
13
13
  import { renderFilm } from "../render/render.js";
14
14
  import { takePageScreenshot, takeScreenshots, type ScreenshotBrowser, type ScreenshotEntry, type ScreenshotResult } from "../screenshot/screenshot.js";
15
+ import { findPlaceholders } from "../config/placeholders.js";
16
+ import { runPrepare } from "../screenshot/prepare.js";
17
+ import { findUnsetVariable, resolveShotTexts, usesData, type ShotTexts } from "../screenshot/shot-texts.js";
15
18
  import { findStorageStateProblem } from "../screenshot/storage-state.js";
16
19
  import { isPlaceholderKey } from "../voice/placeholder.js";
17
20
  import { splitIntoBeats } from "../voice/voiceover.js";
18
21
  import { CliFailure, fail } from "./failure.js";
19
22
  import { loadFilm, type LoadedFilm } from "./films.js";
20
- import { writeOgImages } from "./og.js";
21
23
  import { getRecordingDay, readOptions, type EntryShotsOptions, type FilmOptions, type PageShotsOptions } from "./options.js";
22
24
  import { ensureServer } from "./server.js";
23
25
  import { getFilmVoiceover, produceVoiceover, produceVoiceovers, readJson } from "./voice.js";
@@ -206,21 +208,50 @@ async function pageShot(config: MarketingConfig, options: PageShotsOptions): Pro
206
208
  reportScreenshots([result]);
207
209
  }
208
210
 
211
+ /**
212
+ * The run's texts with `{env:…}` and `{data:…}` replaced. `signIn.prepare` runs only when an entry is signed in or
213
+ * reads its data, after the app answers; its output and the resolved values are never printed.
214
+ */
215
+ function prepareShotTexts(config: MarketingConfig, texts: ShotTexts, baseUrl: string): ShotTexts {
216
+ const needsPrepare = config.signIn?.prepare !== undefined && (texts.signIn !== null || usesData(texts));
217
+ let data: Record<string, string> | null = null;
218
+ if (needsPrepare && config.signIn?.prepare !== undefined) {
219
+ const [program, ...args] = config.signIn.prepare;
220
+ console.log(`prepare: ${config.signIn.prepare.join(" ")}.`);
221
+ // The schema requires at least one element.
222
+ const prepared = runPrepare([program as string, ...args], { cwd: config.root, baseUrl: new URL(baseUrl).origin });
223
+ if (!prepared.ok) fail(`${prepared.error}.`);
224
+ data = prepared.data;
225
+ }
226
+ const resolved = resolveShotTexts(texts, { env: process.env, data });
227
+ if (!resolved.ok) fail(`${resolved.error}.`);
228
+ return resolved.texts;
229
+ }
230
+
209
231
  async function shots(config: MarketingConfig, options: EntryShotsOptions): Promise<void> {
210
- const entries = resolveStorageStates(config, selectScreenshots(config, options.shotId));
211
- const [first] = entries;
212
- const target = { url: new URL(first.path, config.app.baseUrl).href, ownUrl: `http://localhost:${config.app.port}${first.path}` };
213
- const server = await ensureServer(config, target, options.url === undefined ? undefined : new URL(first.path, options.url).href);
232
+ const selected = resolveStorageStates(config, selectScreenshots(config, options.shotId));
233
+ const isSignedIn = selected.some((entry) => entry.signedIn);
234
+ const texts: ShotTexts = { entries: selected, signIn: isSignedIn ? config.signIn : null };
235
+ // Before the app starts or the account is seeded: a variable the shell lacks costs nothing to report.
236
+ const unset = findUnsetVariable(texts, process.env);
237
+ if (unset !== null) fail(`{env:${unset}} is not set in the environment; marketing.json reads it for the screenshots.`);
238
+ // The page that tells whether the app answers: the first path without a placeholder (a path such as
239
+ // /accounts/{data:id} would answer 404 before the preparation), else the root.
240
+ const probePath = selected.map((entry) => entry.path).find((path) => findPlaceholders(path).length === 0) ?? "/";
241
+ const target = { url: new URL(probePath, config.app.baseUrl).href, ownUrl: `http://localhost:${config.app.port}${probePath}` };
242
+ const server = await ensureServer(config, target, options.url === undefined ? undefined : new URL(probePath, options.url).href);
214
243
  const outDir = join(config.output.dir, "screenshots");
215
244
  let results;
216
245
  try {
217
- console.log(`screenshots: ${entries.length} from ${new URL(server.url).origin}.`);
246
+ const { entries, signIn } = prepareShotTexts(config, texts, server.url);
247
+ console.log(`screenshots: ${entries.length} from ${new URL(server.url).origin}${signIn === null ? "" : `, signed in at ${signIn.path}`}.`);
218
248
  results = await takeScreenshots({
219
249
  entries,
220
250
  baseUrl: server.url,
221
251
  outDir,
222
252
  executablePath: process.env.PLAYWRIGHT_CHROMIUM_PATH || undefined,
223
253
  browser: getScreenshotBrowser(config),
254
+ ...(signIn === null ? {} : { signIn }),
224
255
  });
225
256
  } finally {
226
257
  server.stop();
@@ -236,6 +267,9 @@ async function main(argv: string[]): Promise<void> {
236
267
  if (!loaded.ok) fail(loaded.error);
237
268
  const { config } = loaded;
238
269
  if (options.command === "og") {
270
+ // Loaded here, not at the top: satori is the only consumer, and a broken satori release must not take down the
271
+ // other commands (#254).
272
+ const { writeOgImages } = await import("./og.js");
239
273
  await writeOgImages(config, options.imageId);
240
274
  return;
241
275
  }
@@ -101,6 +101,8 @@ export interface MarketingConfig {
101
101
  videos: VideoConfig[];
102
102
  social: { linkTemplate: string } | null;
103
103
  screenshots: MarketingJson["screenshots"];
104
+ /** How `shots` signs in for `signedIn` entries; null without a `signIn` block. */
105
+ signIn: NonNullable<MarketingJson["signIn"]> | null;
104
106
  ogImages: MarketingJson["ogImages"];
105
107
  sfx: Partial<Record<SfxEvent, string>>;
106
108
  output: { dir: string; buildDir: string; quality: Quality };
@@ -227,6 +229,7 @@ export function loadMarketingConfig(path: string): LoadConfigResult {
227
229
  videos: resolveVideos(data, at),
228
230
  social: data.social === undefined ? null : { linkTemplate: data.social.linkTemplate },
229
231
  screenshots: data.screenshots,
232
+ signIn: data.signIn ?? null,
230
233
  ogImages: data.ogImages,
231
234
  sfx: Object.fromEntries(SFX_EVENTS.flatMap((event) => (data.sfx[event] === undefined ? [] : [[event, at(data.sfx[event])]]))),
232
235
  output: { dir: at(data.output.dir), buildDir: at(data.output.buildDir), quality: data.output.quality },
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Placeholders in the text of a screenshot or of the sign-in: `{env:NAME}` reads the environment (a password stays
3
+ * out of marketing.json), `{data:key}` reads what `signIn.prepare` printed (a value of the seeded account, so the
4
+ * phrase gate proves the frame shows that account). Pure: the CLI supplies both sources.
5
+ */
6
+
7
+ export const PLACEHOLDER_KINDS = ["env", "data"] as const;
8
+
9
+ export type PlaceholderKind = (typeof PLACEHOLDER_KINDS)[number];
10
+
11
+ export interface Placeholder {
12
+ kind: PlaceholderKind;
13
+ key: string;
14
+ }
15
+
16
+ /** `{env:NAME}` or `{data:key}`; the key is an identifier, so a brace in ordinary text never matches by accident. */
17
+ const PLACEHOLDER_PATTERN = /\{(env|data):([A-Za-z_][A-Za-z0-9_]*)\}/g;
18
+ /** Any `{word:…}` that looks like a placeholder, to refuse a misspelt kind instead of leaving it in the text. */
19
+ const PLACEHOLDER_LIKE_PATTERN = /\{[A-Za-z]+:[^{}\s]*\}/g;
20
+ const WHOLE_PLACEHOLDER_PATTERN = /^\{(?:env|data):[A-Za-z_][A-Za-z0-9_]*\}$/;
21
+
22
+ export function findPlaceholders(text: string): Placeholder[] {
23
+ return [...text.matchAll(PLACEHOLDER_PATTERN)].map((match) => ({ kind: match[1] as PlaceholderKind, key: match[2] ?? "" }));
24
+ }
25
+
26
+ /** The first `{kind:…}` whose kind or key is not a placeholder this kit knows, or null. */
27
+ export function findMalformedPlaceholder(text: string): string | null {
28
+ for (const match of text.matchAll(PLACEHOLDER_LIKE_PATTERN)) {
29
+ if (!WHOLE_PLACEHOLDER_PATTERN.test(match[0])) return match[0];
30
+ }
31
+ return null;
32
+ }
33
+
34
+ export interface PlaceholderSources {
35
+ env: Readonly<Record<string, string | undefined>>;
36
+ /** What `signIn.prepare` printed; null when it did not run. */
37
+ data: Readonly<Record<string, string>> | null;
38
+ }
39
+
40
+ export type ResolveResult = { ok: true; value: string } | { ok: false; error: string };
41
+
42
+ /**
43
+ * The text with every placeholder replaced; `encode` applies to the inserted values only (a page path). An unset
44
+ * variable or a key the preparation did not print is an error naming the placeholder, never its value.
45
+ */
46
+ export function resolvePlaceholders(text: string, sources: PlaceholderSources, encode: (value: string) => string = (value) => value): ResolveResult {
47
+ for (const { kind, key } of findPlaceholders(text)) {
48
+ if (kind === "env" && (sources.env[key] === undefined || sources.env[key] === "")) {
49
+ return { ok: false, error: `{env:${key}} is not set in the environment` };
50
+ }
51
+ if (kind === "data" && sources.data === null) return { ok: false, error: `{data:${key}} needs signIn.prepare, which did not run` };
52
+ if (kind === "data" && !Object.hasOwn(sources.data ?? {}, key)) {
53
+ return { ok: false, error: `{data:${key}} is not in what signIn.prepare printed (keys: ${Object.keys(sources.data ?? {}).join(", ") || "none"})` };
54
+ }
55
+ }
56
+ const value = text.replace(PLACEHOLDER_PATTERN, (_match, kind: PlaceholderKind, key: string) =>
57
+ encode(kind === "env" ? (sources.env[key] ?? "") : (sources.data?.[key] ?? "")),
58
+ );
59
+ return { ok: true, value };
60
+ }
@@ -20,7 +20,9 @@ import { actionSchema, type SceneAction } from "./actions-schema.js";
20
20
  import { COLOR_ROLES, COLOR_THEMES, isHexColor, type ColorRole } from "./colors.js";
21
21
  import { DAY_PATTERN, isCalendarDay } from "./day.js";
22
22
  import { getOgImageNames } from "./og-image-names.js";
23
+ import { findMalformedPlaceholder, findPlaceholders } from "./placeholders.js";
23
24
  import { getScreenshotNames } from "./screenshot-names.js";
25
+ import { cropSchema, shotStepSchema } from "./shot-steps.js";
24
26
 
25
27
  /**
26
28
  * `marketing.json`: everything product-specific about a project's marketing material. One zod schema
@@ -493,12 +495,85 @@ export const screenshotSchema = z.strictObject({
493
495
  storageState: relativePath
494
496
  .optional()
495
497
  .describe("A Playwright storage state (cookies and localStorage as JSON), relative to the folder of marketing.json, to capture a signed-in screen. It holds a session: keep it out of git."),
498
+ signedIn: z.boolean().default(false).describe("Capture signed in through the signIn block: shots signs in once per run and keeps the session in memory. Not with storageState."),
499
+ steps: z
500
+ .array(shotStepSchema)
501
+ .default([])
502
+ .describe("Done in order after the page loaded, before any gate reads it, e.g. a click that opens a collapsed section; a failing step refuses the shot."),
503
+ crop: cropSchema
504
+ .optional()
505
+ .describe("Capture one element at a fixed aspect ratio (e.g. 4:3 around a chart) instead of the viewport: as wide as the element, from its top edge (or crop.top's). Not with full or scrollTo."),
506
+ hide: z
507
+ .array(z.string().regex(SELECTOR_PATTERN, "must be a CSS selector without { } ; < > \\ or /*"))
508
+ .default([])
509
+ .describe("CSS selectors hidden in this entry's shots only, on top of app.hideSelectors (a print state: hint buttons, disclosure arrows); the shot is refused when one still shows an element in the frame."),
496
510
  }).superRefine((entry, context) => {
497
511
  if (entry.full && entry.scrollTo !== undefined) {
498
512
  context.addIssue({ code: "custom", path: ["scrollTo"], message: "is one viewport frame at a scroll position; a full-page shot has none, so drop full or scrollTo" });
499
513
  }
514
+ if (entry.crop !== undefined && entry.full) context.addIssue({ code: "custom", path: ["crop"], message: "frames one element; a full-page shot has no element to frame, so drop full or crop" });
515
+ if (entry.crop !== undefined && entry.scrollTo !== undefined) {
516
+ context.addIssue({ code: "custom", path: ["crop"], message: "places the frame on its element; scrollTo would place it too, so drop one of them" });
517
+ }
518
+ if (entry.signedIn && entry.storageState !== undefined) {
519
+ context.addIssue({ code: "custom", path: ["signedIn"], message: "signs in through signIn; storageState is another session, so drop one of them" });
520
+ }
521
+ checkPlaceholderText(entry.path, ["path"], context);
522
+ checkPlaceholderText(entry.expect, ["expect"], context);
523
+ entry.steps.forEach((step, index) => {
524
+ if (step.do === "fill") checkPlaceholderText(step.value, ["steps", index, "value"], context);
525
+ });
500
526
  });
501
527
 
528
+ /** Refuses `{kind:…}` text that is not `{env:NAME}` or `{data:key}`, so a misspelt placeholder never reaches the page. */
529
+ function checkPlaceholderText(text: string, path: (string | number)[], context: z.RefinementCtx): void {
530
+ const malformed = findMalformedPlaceholder(text);
531
+ if (malformed !== null) context.addIssue({ code: "custom", path, message: `${malformed} is not a placeholder: use {env:NAME} or {data:key}` });
532
+ }
533
+
534
+ /** Every text of the sign-in and the screenshots that may hold `{data:key}`, with its path in marketing.json. */
535
+ function listPlaceholderTexts(config: { signIn?: SignInConfig | undefined; screenshots: ScreenshotConfig[] }): { text: string; path: (string | number)[] }[] {
536
+ const texts: { text: string; path: (string | number)[] }[] = [];
537
+ const addSteps = (steps: readonly ShotStepConfig[], prefix: (string | number)[]) =>
538
+ steps.forEach((step, index) => {
539
+ if (step.do === "fill") texts.push({ text: step.value, path: [...prefix, "steps", index, "value"] });
540
+ });
541
+ if (config.signIn !== undefined) {
542
+ addSteps(config.signIn.steps, ["signIn"]);
543
+ texts.push({ text: config.signIn.expect, path: ["signIn", "expect"] });
544
+ }
545
+ config.screenshots.forEach((entry, index) => {
546
+ texts.push({ text: entry.path, path: ["screenshots", index, "path"] }, { text: entry.expect, path: ["screenshots", index, "expect"] });
547
+ addSteps(entry.steps, ["screenshots", index]);
548
+ });
549
+ return texts;
550
+ }
551
+
552
+ type ScreenshotConfig = z.output<typeof screenshotSchema>;
553
+ type ShotStepConfig = z.output<typeof shotStepSchema>;
554
+
555
+ export const signInSchema = z
556
+ .strictObject({
557
+ prepare: z
558
+ .array(nonEmpty)
559
+ .min(1)
560
+ .optional()
561
+ .describe(
562
+ "A command (arguments, no shell, run in the folder of marketing.json once the app answers, with MARKETING_BASE_URL set) that creates and seeds the account; its last line of output is a JSON object of strings or numbers, read as {data:key}. Its output is not printed.",
563
+ ),
564
+ path: pagePath.describe("The sign-in page, e.g. /login."),
565
+ steps: z.array(shotStepSchema).min(1, "needs at least one step").describe("What signs in on that page: fill the e-mail and password ({env:NAME} or {data:key}), click the button."),
566
+ expect: nonBlank.describe("A phrase only a signed-in page shows, within 15 s of the last step; without it the sign-in fails and so does every signedIn screenshot."),
567
+ })
568
+ .superRefine((signIn, context) => {
569
+ checkPlaceholderText(signIn.expect, ["expect"], context);
570
+ signIn.steps.forEach((step, index) => {
571
+ if (step.do === "fill") checkPlaceholderText(step.value, ["steps", index, "value"], context);
572
+ });
573
+ });
574
+
575
+ type SignInConfig = z.output<typeof signInSchema>;
576
+
502
577
  /** Named sizes of `ogImages[].size`: the share card and the three social formats. */
503
578
  export const OG_SIZE_PRESETS = {
504
579
  landscape: [1200, 630],
@@ -647,6 +722,9 @@ export const marketingSchema = z
647
722
  videos: z.array(videoSchema).min(1, "needs at least one video").describe("The films, at least one."),
648
723
  social: socialSchema.optional().describe("Post copy for the films: the link, the platforms and their channel codes."),
649
724
  screenshots: z.array(screenshotSchema).default([]).describe("Screenshots taken by softure-marketing shots."),
725
+ signIn: signInSchema
726
+ .optional()
727
+ .describe("How softure-marketing shots signs in for the screenshots with signedIn: true, and the optional command that prepares the account."),
650
728
  ogImages: z.array(ogImageSchema).default([]).describe("Open Graph images rendered by softure-marketing og."),
651
729
  layout: layoutSchema
652
730
  .optional()
@@ -699,6 +777,17 @@ export const marketingSchema = z
699
777
  fileOwners.set(name, owner ?? index);
700
778
  }
701
779
  });
780
+ config.screenshots.forEach((entry, index) => {
781
+ if (entry.signedIn && config.signIn === undefined) {
782
+ context.addIssue({ code: "custom", path: ["screenshots", index, "signedIn"], message: "needs a signIn block that says how to sign in" });
783
+ }
784
+ });
785
+ if (config.signIn?.prepare === undefined) {
786
+ for (const { text, path } of listPlaceholderTexts(config)) {
787
+ const data = findPlaceholders(text).find((placeholder) => placeholder.kind === "data");
788
+ if (data !== undefined) context.addIssue({ code: "custom", path, message: `{data:${data.key}} needs signIn.prepare, the command that prints the data` });
789
+ }
790
+ }
702
791
  const videoIds = new Set(config.videos.map((video) => video.id));
703
792
  const posted = new Set<string>();
704
793
  config.social?.posts.forEach((post, index) => {
@@ -0,0 +1,79 @@
1
+ import { z } from "zod";
2
+
3
+ import { locatorSchema } from "./actions-schema.js";
4
+
5
+ /**
6
+ * What a screenshot does on the page before it is judged: the sign-in form (`signIn.steps`) and an entry's own
7
+ * `steps` (open collapsed sections, hide what a still image should not show). Plain Playwright calls on a locator,
8
+ * with no camera and no timing: a screenshot records nothing in between. `crop` frames one element at a fixed aspect
9
+ * ratio instead of the viewport, optionally from the top edge of another one.
10
+ */
11
+
12
+ /** A Playwright key name, modifiers joined with `+`; Playwright itself refuses a name it does not know. */
13
+ const KEY_PATTERN = /^\S+$/;
14
+ /** `W:H` with whole numbers from 1 to 9999, e.g. `4:3`. */
15
+ export const ASPECT_PATTERN = /^[1-9]\d{0,3}:[1-9]\d{0,3}$/;
16
+ /** More columns than a chart ever shows; the cap only keeps a typo from reading as "keep everything". */
17
+ const MAX_KEEP_LAST = 1000;
18
+
19
+ const target = locatorSchema.describe("The element, as a locator descriptor with exactly one of role, text, label, testId, css.");
20
+
21
+ export const shotStepSchema = z.discriminatedUnion("do", [
22
+ z.strictObject({
23
+ do: z.literal("fill").describe("Replaces the value of an input, e.g. the e-mail of the sign-in form."),
24
+ target,
25
+ value: z.string().describe("The value; {env:NAME} and {data:key} are replaced. Never printed, so a password may go here as {env:NAME}."),
26
+ }),
27
+ z.strictObject({
28
+ do: z.literal("click").describe("Clicks the element, e.g. the submit button or a collapsed section's summary."),
29
+ target,
30
+ }),
31
+ z.strictObject({
32
+ do: z.literal("check").describe("Ticks a checkbox or radio button, e.g. the terms of a sign-up form."),
33
+ target,
34
+ }),
35
+ z.strictObject({
36
+ do: z.literal("press").describe("Presses a key on the focused element, e.g. Enter."),
37
+ key: z.string().regex(KEY_PATTERN, "must be a key name such as Enter or Escape").describe("A Playwright key name; modifiers joined with +."),
38
+ }),
39
+ z.strictObject({
40
+ do: z.literal("open").describe("Opens every matching <details> element (nth picks one), e.g. every disclosure of a card; fails when a match is not a <details> or does not stay open."),
41
+ target: locatorSchema.describe("The <details> elements, as a locator descriptor with exactly one of role, text, label, testId, css; every match is opened."),
42
+ }),
43
+ z.strictObject({
44
+ do: z.literal("hide").describe("Hides every match but the last keepLast (display: none), e.g. all but the last three columns of a horizontally scrolling chart."),
45
+ target: locatorSchema.describe("The elements, as a locator descriptor with exactly one of role, text, label, testId, css; every match counts."),
46
+ keepLast: z
47
+ .number()
48
+ .int()
49
+ .min(0)
50
+ .max(MAX_KEEP_LAST)
51
+ .default(0)
52
+ .describe(`How many of the last matches stay shown (0-${MAX_KEEP_LAST}, default 0); the step fails when there are not more matches than this.`),
53
+ }),
54
+ ]);
55
+
56
+ export type ShotStep = z.output<typeof shotStepSchema>;
57
+
58
+ export interface Aspect {
59
+ width: number;
60
+ height: number;
61
+ }
62
+
63
+ export const cropSchema = z.strictObject({
64
+ target: locatorSchema.describe("The element framed: exactly one match (nth picks one of several)."),
65
+ top: locatorSchema
66
+ .optional()
67
+ .describe("An element inside target whose top edge starts the frame instead of target's (e.g. a row of a card); exactly one match. The width stays target's."),
68
+ aspect: z
69
+ .string()
70
+ .regex(ASPECT_PATTERN, "must be W:H with whole numbers, e.g. 4:3")
71
+ .transform((value): Aspect => {
72
+ const [width, height] = value.split(":").map(Number);
73
+ return { width: width ?? 1, height: height ?? 1 };
74
+ })
75
+ .describe("The frame's width to height, e.g. 4:3: as wide as the element (plus padding), from its top edge down."),
76
+ padding: z.number().int().min(0).max(200).default(0).describe("CSS pixels of the page around the element on the left, right and top (0-200, default 0)."),
77
+ });
78
+
79
+ export type Crop = z.output<typeof cropSchema>;
@@ -1,46 +1,20 @@
1
- import type { Locator, Page } from "playwright";
1
+ import type { Locator } from "playwright";
2
2
 
3
- import type { LocatorDescriptor, SceneAction, TextMatch } from "../config/actions-schema.js";
3
+ import type { LocatorDescriptor, SceneAction } from "../config/actions-schema.js";
4
4
  import type { ActionBeat } from "../config/config.js";
5
5
  import { formatIssuePath } from "../config/issues.js";
6
6
  import type { Director, Scene } from "../film.js";
7
+ import { getLocator, type LocatorSource } from "./locator.js";
7
8
  import { ScreenGuardError } from "./record.js";
8
9
 
10
+ export { getLocator, type LocatorSource };
11
+
9
12
  /**
10
13
  * Beat `actions` from `marketing.json`, played on the Director: each descriptor becomes a Playwright
11
14
  * locator and each action the Director call of the same name. An action that fails names its JSON
12
15
  * path, so the author knows which entry of the config to fix.
13
16
  */
14
17
 
15
- /** The part of a page that builds locators. */
16
- export type LocatorSource = Pick<Page, "getByRole" | "getByText" | "getByLabel" | "getByTestId" | "locator">;
17
-
18
- function toMatcher(match: TextMatch): string | RegExp {
19
- return typeof match === "string" ? match : new RegExp(match.regex, match.flags);
20
- }
21
-
22
- export function getLocator(page: LocatorSource, descriptor: LocatorDescriptor): Locator {
23
- const locator = buildLocator(page, descriptor);
24
- return descriptor.nth === null ? locator : locator.nth(descriptor.nth);
25
- }
26
-
27
- function buildLocator(page: LocatorSource, descriptor: LocatorDescriptor): Locator {
28
- switch (descriptor.kind) {
29
- case "role":
30
- return descriptor.name === null
31
- ? page.getByRole(descriptor.role)
32
- : page.getByRole(descriptor.role, { name: toMatcher(descriptor.name), ...(descriptor.exact ? { exact: true } : {}) });
33
- case "text":
34
- return page.getByText(toMatcher(descriptor.text), descriptor.exact ? { exact: true } : undefined);
35
- case "label":
36
- return page.getByLabel(toMatcher(descriptor.label), descriptor.exact ? { exact: true } : undefined);
37
- case "testId":
38
- return page.getByTestId(descriptor.testId);
39
- case "css":
40
- return descriptor.hasText === null ? page.locator(descriptor.css) : page.locator(descriptor.css, { hasText: toMatcher(descriptor.hasText) });
41
- }
42
- }
43
-
44
18
  function getLocators(page: LocatorSource, target: LocatorDescriptor | LocatorDescriptor[]): Locator | Locator[] {
45
19
  return Array.isArray(target) ? target.map((descriptor) => getLocator(page, descriptor)) : getLocator(page, target);
46
20
  }
@@ -0,0 +1,37 @@
1
+ import type { Locator, Page } from "playwright";
2
+
3
+ import type { LocatorDescriptor, TextMatch } from "../config/actions-schema.js";
4
+
5
+ /**
6
+ * A locator descriptor from `marketing.json` as a Playwright locator: the beats' actions and the screenshots'
7
+ * steps and crops find elements the same way.
8
+ */
9
+
10
+ /** The part of a page that builds locators. */
11
+ export type LocatorSource = Pick<Page, "getByRole" | "getByText" | "getByLabel" | "getByTestId" | "locator">;
12
+
13
+ function toMatcher(match: TextMatch): string | RegExp {
14
+ return typeof match === "string" ? match : new RegExp(match.regex, match.flags);
15
+ }
16
+
17
+ export function getLocator(page: LocatorSource, descriptor: LocatorDescriptor): Locator {
18
+ const locator = buildLocator(page, descriptor);
19
+ return descriptor.nth === null ? locator : locator.nth(descriptor.nth);
20
+ }
21
+
22
+ function buildLocator(page: LocatorSource, descriptor: LocatorDescriptor): Locator {
23
+ switch (descriptor.kind) {
24
+ case "role":
25
+ return descriptor.name === null
26
+ ? page.getByRole(descriptor.role)
27
+ : page.getByRole(descriptor.role, { name: toMatcher(descriptor.name), ...(descriptor.exact ? { exact: true } : {}) });
28
+ case "text":
29
+ return page.getByText(toMatcher(descriptor.text), descriptor.exact ? { exact: true } : undefined);
30
+ case "label":
31
+ return page.getByLabel(toMatcher(descriptor.label), descriptor.exact ? { exact: true } : undefined);
32
+ case "testId":
33
+ return page.getByTestId(descriptor.testId);
34
+ case "css":
35
+ return descriptor.hasText === null ? page.locator(descriptor.css) : page.locator(descriptor.css, { hasText: toMatcher(descriptor.hasText) });
36
+ }
37
+ }
@@ -1,11 +1,15 @@
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, none of the entry's hidden
7
+ * selectors still shows an element in the frame, the file is not suspiciously small, and no earlier file of the run
8
+ * has the same bytes. A blank page, an error page, a half-loaded one, an
9
+ * empty account or a frame of the wrong place fails at least one of them.
6
10
  */
7
11
 
8
- export const SCREENSHOT_GATES = ["load", "status", "scroll", "phrase", "size"] as const;
12
+ export const SCREENSHOT_GATES = ["sign-in", "load", "status", "steps", "scroll", "phrase", "crop", "hide", "size", "duplicate"] as const;
9
13
 
10
14
  export type ScreenshotGate = (typeof SCREENSHOT_GATES)[number];
11
15
 
@@ -33,3 +37,71 @@ export function findSizeFailure(bytes: number, minBytes: number): string | null
33
37
  if (bytes >= minBytes) return null;
34
38
  return `the file has ${bytes} bytes, below minBytes ${minBytes} (a blank or broken page); deleted`;
35
39
  }
40
+
41
+ /** A rectangle in CSS pixels, in document coordinates (from the page's top-left corner, not the viewport's). */
42
+ export interface Rect {
43
+ x: number;
44
+ y: number;
45
+ width: number;
46
+ height: number;
47
+ }
48
+
49
+ export type CropFrameResult = { ok: true; frame: Rect } | { ok: false; message: string };
50
+
51
+ export interface CropFrameInput {
52
+ /** The element, in document coordinates. */
53
+ element: Rect;
54
+ /** `crop.top`'s top edge in document coordinates: where the frame starts instead of the element's top edge. */
55
+ top?: number;
56
+ /** The page's scrollable size. */
57
+ page: { width: number; height: number };
58
+ aspect: Aspect;
59
+ padding: number;
60
+ }
61
+
62
+ /**
63
+ * The frame of a crop in whole CSS pixels: as wide as the element plus the padding on each side, from the padding
64
+ * above its top edge (or above `top`), as tall as the aspect asks. Refused when `top` lies outside the element, whose
65
+ * frame would then not show it, and when the frame would run past the page, which would leave part of the file empty
66
+ * or cut it short.
67
+ */
68
+ export function findCropFrame({ element, top, page, aspect, padding }: CropFrameInput): CropFrameResult {
69
+ if (top !== undefined && top < element.y) return { ok: false, message: `crop.top's top edge lies ${Math.round(element.y - top)} px above crop.target` };
70
+ if (top !== undefined && top >= element.y + element.height) {
71
+ return { ok: false, message: `crop.top's top edge lies ${Math.round(top - element.y - element.height)} px below crop.target's bottom edge` };
72
+ }
73
+ const x = Math.floor(element.x - padding);
74
+ const y = Math.floor((top ?? element.y) - padding);
75
+ const width = Math.round(element.width + 2 * padding);
76
+ const height = Math.round((width * aspect.height) / aspect.width);
77
+ const ratio = `${aspect.width}:${aspect.height}`;
78
+ if (width < 1) return { ok: false, message: `the crop's element has no width, so a ${ratio} frame has nothing to show` };
79
+ if (x < 0) return { ok: false, message: `the ${ratio} frame starts ${-x} px left of the page; lower crop.padding` };
80
+ if (y < 0) return { ok: false, message: `the ${ratio} frame starts ${-y} px above the page; lower crop.padding` };
81
+ 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` };
82
+ if (y + height > page.height) {
83
+ return { ok: false, message: `the ${ratio} frame (${width}×${height} px) runs ${y + height - page.height} px past the page's bottom edge` };
84
+ }
85
+ return { ok: true, frame: { x, y, width, height } };
86
+ }
87
+
88
+ /** Device pixels round once per side, so the file may be one pixel off the frame × scale. */
89
+ const DIMENSION_TOLERANCE_PX = 1;
90
+
91
+ /** Null when the PNG is the frame at the device scale; otherwise what it is instead. */
92
+ export function findDimensionFailure(file: { width: number; height: number }, frame: { width: number; height: number }, scale: number): string | null {
93
+ const width = Math.round(frame.width * scale);
94
+ const height = Math.round(frame.height * scale);
95
+ const isWithin = Math.abs(file.width - width) <= DIMENSION_TOLERANCE_PX && Math.abs(file.height - height) <= DIMENSION_TOLERANCE_PX;
96
+ if (isWithin) return null;
97
+ return `the file is ${file.width}×${file.height} px, not the crop's ${width}×${height} px; deleted`;
98
+ }
99
+
100
+ /** Null when no hidden selector shows an element in the frame; otherwise the first that does, and how many. */
101
+ export function findHideFailure(counts: readonly { selector: string; shown: number | null }[]): string | null {
102
+ for (const { selector, shown } of counts) {
103
+ if (shown === null) return `hide "${selector}" is not a selector the browser can parse`;
104
+ if (shown > 0) return `hide "${selector}" still shows ${shown} element${shown === 1 ? "" : "s"} in the frame`;
105
+ }
106
+ return null;
107
+ }
@@ -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
+ }