@softure-ai/marketing-kit 0.1.9 → 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.
- package/CHANGELOG.md +19 -0
- package/README.md +83 -4
- package/dist/cli/main.js +42 -6
- package/dist/cli/main.js.map +1 -1
- package/dist/config/config.d.ts +2 -0
- package/dist/config/config.d.ts.map +1 -1
- package/dist/config/config.js +1 -0
- package/dist/config/config.js.map +1 -1
- package/dist/config/placeholders.d.ts +32 -0
- package/dist/config/placeholders.d.ts.map +1 -0
- package/dist/config/placeholders.js +41 -0
- package/dist/config/placeholders.js.map +1 -0
- package/dist/config/schema.d.ts +2206 -0
- package/dist/config/schema.d.ts.map +1 -1
- package/dist/config/schema.js +80 -0
- package/dist/config/schema.js.map +1 -1
- package/dist/config/shot-steps.d.ts +637 -0
- package/dist/config/shot-steps.d.ts.map +1 -0
- package/dist/config/shot-steps.js +44 -0
- package/dist/config/shot-steps.js.map +1 -0
- package/dist/record/actions.d.ts +3 -10
- package/dist/record/actions.d.ts.map +1 -1
- package/dist/record/actions.js +7 -23
- package/dist/record/actions.js.map +1 -1
- package/dist/record/locator.d.ts +10 -0
- package/dist/record/locator.d.ts.map +1 -0
- package/dist/record/locator.js +24 -0
- package/dist/record/locator.js.map +1 -0
- package/dist/screenshot/gates.d.ts +46 -5
- package/dist/screenshot/gates.d.ts.map +1 -1
- package/dist/screenshot/gates.js +41 -5
- package/dist/screenshot/gates.js.map +1 -1
- package/dist/screenshot/prepare.d.ts +18 -0
- package/dist/screenshot/prepare.d.ts.map +1 -0
- package/dist/screenshot/prepare.js +60 -0
- package/dist/screenshot/prepare.js.map +1 -0
- package/dist/screenshot/screenshot.d.ts +9 -2
- package/dist/screenshot/screenshot.d.ts.map +1 -1
- package/dist/screenshot/screenshot.js +86 -7
- package/dist/screenshot/screenshot.js.map +1 -1
- package/dist/screenshot/shot-texts.d.ts +26 -0
- package/dist/screenshot/shot-texts.d.ts.map +1 -0
- package/dist/screenshot/shot-texts.js +55 -0
- package/dist/screenshot/shot-texts.js.map +1 -0
- package/dist/screenshot/sign-in.d.ts +34 -0
- package/dist/screenshot/sign-in.d.ts.map +1 -0
- package/dist/screenshot/sign-in.js +66 -0
- package/dist/screenshot/sign-in.js.map +1 -0
- package/dist/screenshot/steps.d.ts +12 -0
- package/dist/screenshot/steps.d.ts.map +1 -0
- package/dist/screenshot/steps.js +38 -0
- package/dist/screenshot/steps.js.map +1 -0
- package/package.json +2 -2
- package/schema/marketing.schema.json +1842 -10
- package/src/cli/main.ts +40 -6
- package/src/config/config.ts +3 -0
- package/src/config/placeholders.ts +60 -0
- package/src/config/schema.ts +85 -0
- package/src/config/shot-steps.ts +58 -0
- package/src/record/actions.ts +5 -31
- package/src/record/locator.ts +37 -0
- package/src/screenshot/gates.ts +60 -5
- package/src/screenshot/prepare.ts +64 -0
- package/src/screenshot/screenshot.ts +89 -8
- package/src/screenshot/shot-texts.ts +72 -0
- package/src/screenshot/sign-in.ts +91 -0
- package/src/screenshot/steps.ts +44 -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
|
|
211
|
-
const
|
|
212
|
-
const
|
|
213
|
-
|
|
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
|
-
|
|
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
|
}
|
package/src/config/config.ts
CHANGED
|
@@ -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
|
+
}
|
package/src/config/schema.ts
CHANGED
|
@@ -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,81 @@ 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. Not with full or scrollTo."),
|
|
496
506
|
}).superRefine((entry, context) => {
|
|
497
507
|
if (entry.full && entry.scrollTo !== undefined) {
|
|
498
508
|
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
509
|
}
|
|
510
|
+
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" });
|
|
511
|
+
if (entry.crop !== undefined && entry.scrollTo !== undefined) {
|
|
512
|
+
context.addIssue({ code: "custom", path: ["crop"], message: "places the frame on its element; scrollTo would place it too, so drop one of them" });
|
|
513
|
+
}
|
|
514
|
+
if (entry.signedIn && entry.storageState !== undefined) {
|
|
515
|
+
context.addIssue({ code: "custom", path: ["signedIn"], message: "signs in through signIn; storageState is another session, so drop one of them" });
|
|
516
|
+
}
|
|
517
|
+
checkPlaceholderText(entry.path, ["path"], context);
|
|
518
|
+
checkPlaceholderText(entry.expect, ["expect"], context);
|
|
519
|
+
entry.steps.forEach((step, index) => {
|
|
520
|
+
if (step.do === "fill") checkPlaceholderText(step.value, ["steps", index, "value"], context);
|
|
521
|
+
});
|
|
500
522
|
});
|
|
501
523
|
|
|
524
|
+
/** Refuses `{kind:…}` text that is not `{env:NAME}` or `{data:key}`, so a misspelt placeholder never reaches the page. */
|
|
525
|
+
function checkPlaceholderText(text: string, path: (string | number)[], context: z.RefinementCtx): void {
|
|
526
|
+
const malformed = findMalformedPlaceholder(text);
|
|
527
|
+
if (malformed !== null) context.addIssue({ code: "custom", path, message: `${malformed} is not a placeholder: use {env:NAME} or {data:key}` });
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/** Every text of the sign-in and the screenshots that may hold `{data:key}`, with its path in marketing.json. */
|
|
531
|
+
function listPlaceholderTexts(config: { signIn?: SignInConfig | undefined; screenshots: ScreenshotConfig[] }): { text: string; path: (string | number)[] }[] {
|
|
532
|
+
const texts: { text: string; path: (string | number)[] }[] = [];
|
|
533
|
+
const addSteps = (steps: readonly ShotStepConfig[], prefix: (string | number)[]) =>
|
|
534
|
+
steps.forEach((step, index) => {
|
|
535
|
+
if (step.do === "fill") texts.push({ text: step.value, path: [...prefix, "steps", index, "value"] });
|
|
536
|
+
});
|
|
537
|
+
if (config.signIn !== undefined) {
|
|
538
|
+
addSteps(config.signIn.steps, ["signIn"]);
|
|
539
|
+
texts.push({ text: config.signIn.expect, path: ["signIn", "expect"] });
|
|
540
|
+
}
|
|
541
|
+
config.screenshots.forEach((entry, index) => {
|
|
542
|
+
texts.push({ text: entry.path, path: ["screenshots", index, "path"] }, { text: entry.expect, path: ["screenshots", index, "expect"] });
|
|
543
|
+
addSteps(entry.steps, ["screenshots", index]);
|
|
544
|
+
});
|
|
545
|
+
return texts;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
type ScreenshotConfig = z.output<typeof screenshotSchema>;
|
|
549
|
+
type ShotStepConfig = z.output<typeof shotStepSchema>;
|
|
550
|
+
|
|
551
|
+
export const signInSchema = z
|
|
552
|
+
.strictObject({
|
|
553
|
+
prepare: z
|
|
554
|
+
.array(nonEmpty)
|
|
555
|
+
.min(1)
|
|
556
|
+
.optional()
|
|
557
|
+
.describe(
|
|
558
|
+
"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.",
|
|
559
|
+
),
|
|
560
|
+
path: pagePath.describe("The sign-in page, e.g. /login."),
|
|
561
|
+
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."),
|
|
562
|
+
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."),
|
|
563
|
+
})
|
|
564
|
+
.superRefine((signIn, context) => {
|
|
565
|
+
checkPlaceholderText(signIn.expect, ["expect"], context);
|
|
566
|
+
signIn.steps.forEach((step, index) => {
|
|
567
|
+
if (step.do === "fill") checkPlaceholderText(step.value, ["steps", index, "value"], context);
|
|
568
|
+
});
|
|
569
|
+
});
|
|
570
|
+
|
|
571
|
+
type SignInConfig = z.output<typeof signInSchema>;
|
|
572
|
+
|
|
502
573
|
/** Named sizes of `ogImages[].size`: the share card and the three social formats. */
|
|
503
574
|
export const OG_SIZE_PRESETS = {
|
|
504
575
|
landscape: [1200, 630],
|
|
@@ -647,6 +718,9 @@ export const marketingSchema = z
|
|
|
647
718
|
videos: z.array(videoSchema).min(1, "needs at least one video").describe("The films, at least one."),
|
|
648
719
|
social: socialSchema.optional().describe("Post copy for the films: the link, the platforms and their channel codes."),
|
|
649
720
|
screenshots: z.array(screenshotSchema).default([]).describe("Screenshots taken by softure-marketing shots."),
|
|
721
|
+
signIn: signInSchema
|
|
722
|
+
.optional()
|
|
723
|
+
.describe("How softure-marketing shots signs in for the screenshots with signedIn: true, and the optional command that prepares the account."),
|
|
650
724
|
ogImages: z.array(ogImageSchema).default([]).describe("Open Graph images rendered by softure-marketing og."),
|
|
651
725
|
layout: layoutSchema
|
|
652
726
|
.optional()
|
|
@@ -699,6 +773,17 @@ export const marketingSchema = z
|
|
|
699
773
|
fileOwners.set(name, owner ?? index);
|
|
700
774
|
}
|
|
701
775
|
});
|
|
776
|
+
config.screenshots.forEach((entry, index) => {
|
|
777
|
+
if (entry.signedIn && config.signIn === undefined) {
|
|
778
|
+
context.addIssue({ code: "custom", path: ["screenshots", index, "signedIn"], message: "needs a signIn block that says how to sign in" });
|
|
779
|
+
}
|
|
780
|
+
});
|
|
781
|
+
if (config.signIn?.prepare === undefined) {
|
|
782
|
+
for (const { text, path } of listPlaceholderTexts(config)) {
|
|
783
|
+
const data = findPlaceholders(text).find((placeholder) => placeholder.kind === "data");
|
|
784
|
+
if (data !== undefined) context.addIssue({ code: "custom", path, message: `{data:${data.key}} needs signIn.prepare, the command that prints the data` });
|
|
785
|
+
}
|
|
786
|
+
}
|
|
702
787
|
const videoIds = new Set(config.videos.map((video) => video.id));
|
|
703
788
|
const posted = new Set<string>();
|
|
704
789
|
config.social?.posts.forEach((post, index) => {
|
|
@@ -0,0 +1,58 @@
|
|
|
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 a collapsed section). Plain Playwright calls on a locator, with no camera and no timing: a screenshot
|
|
8
|
+
* records nothing in between. `crop` frames one element at a fixed aspect ratio instead of the viewport.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/** A Playwright key name, modifiers joined with `+`; Playwright itself refuses a name it does not know. */
|
|
12
|
+
const KEY_PATTERN = /^\S+$/;
|
|
13
|
+
/** `W:H` with whole numbers from 1 to 9999, e.g. `4:3`. */
|
|
14
|
+
export const ASPECT_PATTERN = /^[1-9]\d{0,3}:[1-9]\d{0,3}$/;
|
|
15
|
+
|
|
16
|
+
const target = locatorSchema.describe("The element, as a locator descriptor with exactly one of role, text, label, testId, css.");
|
|
17
|
+
|
|
18
|
+
export const shotStepSchema = z.discriminatedUnion("do", [
|
|
19
|
+
z.strictObject({
|
|
20
|
+
do: z.literal("fill").describe("Replaces the value of an input, e.g. the e-mail of the sign-in form."),
|
|
21
|
+
target,
|
|
22
|
+
value: z.string().describe("The value; {env:NAME} and {data:key} are replaced. Never printed, so a password may go here as {env:NAME}."),
|
|
23
|
+
}),
|
|
24
|
+
z.strictObject({
|
|
25
|
+
do: z.literal("click").describe("Clicks the element, e.g. the submit button or a collapsed section's summary."),
|
|
26
|
+
target,
|
|
27
|
+
}),
|
|
28
|
+
z.strictObject({
|
|
29
|
+
do: z.literal("check").describe("Ticks a checkbox or radio button, e.g. the terms of a sign-up form."),
|
|
30
|
+
target,
|
|
31
|
+
}),
|
|
32
|
+
z.strictObject({
|
|
33
|
+
do: z.literal("press").describe("Presses a key on the focused element, e.g. Enter."),
|
|
34
|
+
key: z.string().regex(KEY_PATTERN, "must be a key name such as Enter or Escape").describe("A Playwright key name; modifiers joined with +."),
|
|
35
|
+
}),
|
|
36
|
+
]);
|
|
37
|
+
|
|
38
|
+
export type ShotStep = z.output<typeof shotStepSchema>;
|
|
39
|
+
|
|
40
|
+
export interface Aspect {
|
|
41
|
+
width: number;
|
|
42
|
+
height: number;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export const cropSchema = z.strictObject({
|
|
46
|
+
target: locatorSchema.describe("The element framed: exactly one match (nth picks one of several)."),
|
|
47
|
+
aspect: z
|
|
48
|
+
.string()
|
|
49
|
+
.regex(ASPECT_PATTERN, "must be W:H with whole numbers, e.g. 4:3")
|
|
50
|
+
.transform((value): Aspect => {
|
|
51
|
+
const [width, height] = value.split(":").map(Number);
|
|
52
|
+
return { width: width ?? 1, height: height ?? 1 };
|
|
53
|
+
})
|
|
54
|
+
.describe("The frame's width to height, e.g. 4:3: as wide as the element (plus padding), from its top edge down."),
|
|
55
|
+
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)."),
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
export type Crop = z.output<typeof cropSchema>;
|
package/src/record/actions.ts
CHANGED
|
@@ -1,46 +1,20 @@
|
|
|
1
|
-
import type { Locator
|
|
1
|
+
import type { Locator } from "playwright";
|
|
2
2
|
|
|
3
|
-
import type { LocatorDescriptor, SceneAction
|
|
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
|
+
}
|
package/src/screenshot/gates.ts
CHANGED
|
@@ -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 (
|
|
3
|
-
* answered below HTTP 400, it reached the requested scroll offset, it shows the expected phrase,
|
|
4
|
-
*
|
|
5
|
-
* the
|
|
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
|
+
}
|