@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.
- package/CHANGELOG.md +31 -0
- package/README.md +124 -5
- 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 +3758 -0
- package/dist/config/schema.d.ts.map +1 -1
- package/dist/config/schema.js +84 -0
- package/dist/config/schema.js.map +1 -1
- package/dist/config/shot-steps.d.ts +1101 -0
- package/dist/config/shot-steps.d.ts.map +1 -0
- package/dist/config/shot-steps.js +65 -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 +55 -5
- package/dist/screenshot/gates.d.ts.map +1 -1
- package/dist/screenshot/gates.js +58 -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 +140 -8
- 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 +13 -0
- package/dist/screenshot/steps.d.ts.map +1 -0
- package/dist/screenshot/steps.js +82 -0
- package/dist/screenshot/steps.js.map +1 -0
- package/package.json +2 -2
- package/schema/marketing.schema.json +3080 -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 +89 -0
- package/src/config/shot-steps.ts +79 -0
- package/src/record/actions.ts +5 -31
- package/src/record/locator.ts +37 -0
- package/src/screenshot/gates.ts +77 -5
- package/src/screenshot/prepare.ts +64 -0
- package/src/screenshot/screenshot.ts +146 -9
- package/src/screenshot/shot-texts.ts +72 -0
- package/src/screenshot/sign-in.ts +91 -0
- package/src/screenshot/steps.ts +85 -0
|
@@ -1,20 +1,27 @@
|
|
|
1
|
-
import {
|
|
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";
|
|
5
6
|
|
|
7
|
+
import type { LocatorDescriptor } from "../config/actions-schema.js";
|
|
6
8
|
import type { ColorTheme } from "../config/colors.js";
|
|
7
9
|
import type { MarketingJson } from "../config/schema.js";
|
|
8
10
|
import { getScreenshotNames, getScreenshotShots } from "../config/screenshot-names.js";
|
|
11
|
+
import type { Crop } from "../config/shot-steps.js";
|
|
9
12
|
import { containsPhrase } from "../film.js";
|
|
10
|
-
import {
|
|
13
|
+
import { getLocator } from "../record/locator.js";
|
|
14
|
+
import { findCropFrame, findDimensionFailure, findHideFailure, findScrollFailure, findSizeFailure, findStatusFailure, type Rect, type ScreenshotGate } from "./gates.js";
|
|
15
|
+
import { readPageText, signIn, type SessionState, type SignInPlan } from "./sign-in.js";
|
|
16
|
+
import { runShotSteps } from "./steps.js";
|
|
11
17
|
|
|
12
18
|
/**
|
|
13
19
|
* `softure-marketing shots`: the `screenshots` entries of `marketing.json`. Each shot of an entry
|
|
14
20
|
* (one per colour scheme, `config/screenshot-names.ts`) gets a fresh browser context with the entry's viewport, device
|
|
15
21
|
* scale and motion preference, and is kept only when it passes every gate (`gates.ts`) on its own.
|
|
16
22
|
* 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.
|
|
23
|
+
* not even an older one: a stale PNG must never look like a fresh pass. Entries with `signedIn` share one sign-in
|
|
24
|
+
* per run, and no two kept files of a run may have the same bytes.
|
|
18
25
|
*/
|
|
19
26
|
|
|
20
27
|
export type ScreenshotEntry = MarketingJson["screenshots"][number];
|
|
@@ -40,6 +47,8 @@ export interface TakeScreenshotsOptions {
|
|
|
40
47
|
browser: ScreenshotBrowser;
|
|
41
48
|
/** A Chromium to use instead of Playwright's own (`PLAYWRIGHT_CHROMIUM_PATH`). */
|
|
42
49
|
executablePath?: string;
|
|
50
|
+
/** How `signedIn` entries sign in, placeholders resolved; without it, every `signedIn` shot is refused. */
|
|
51
|
+
signIn?: SignInPlan;
|
|
43
52
|
}
|
|
44
53
|
|
|
45
54
|
/** `id` is the entry's, `name` the file's without `.png` (`<id>` or `<id>-<scheme>`). */
|
|
@@ -76,7 +85,9 @@ async function scrollThroughPage(page: Page): Promise<void> {
|
|
|
76
85
|
async function waitForPhrase(page: Page, phrase: string): Promise<boolean> {
|
|
77
86
|
const deadline = Date.now() + PHRASE_TIMEOUT_MS;
|
|
78
87
|
for (;;) {
|
|
79
|
-
|
|
88
|
+
// A step may have started a navigation; its page is read on the next poll.
|
|
89
|
+
const text = await readPageText(page);
|
|
90
|
+
if (text !== null && containsPhrase(text, phrase)) return true;
|
|
80
91
|
if (Date.now() >= deadline) return false;
|
|
81
92
|
await page.waitForTimeout(PHRASE_POLL_MS);
|
|
82
93
|
}
|
|
@@ -94,6 +105,72 @@ interface ShotTarget {
|
|
|
94
105
|
file: string;
|
|
95
106
|
}
|
|
96
107
|
|
|
108
|
+
/** Width and height of a PNG from its IHDR chunk. */
|
|
109
|
+
function readPngSize(file: string): { width: number; height: number } {
|
|
110
|
+
const bytes = readFileSync(file);
|
|
111
|
+
return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20) };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
type CropMeasure = { ok: true; frame: Rect } | { ok: false; message: string };
|
|
115
|
+
|
|
116
|
+
/** The one element a crop locator names, in document coordinates; `key` names it in the refusal. */
|
|
117
|
+
async function measureElement(page: Page, descriptor: LocatorDescriptor, key: string): Promise<{ ok: true; rect: Rect } | { ok: false; message: string }> {
|
|
118
|
+
const locator = getLocator(page, descriptor);
|
|
119
|
+
const count = await locator.count();
|
|
120
|
+
if (count === 0) return { ok: false, message: `no element matches ${key}` };
|
|
121
|
+
if (count > 1) return { ok: false, message: `${key} matches ${count} elements; add nth to pick one` };
|
|
122
|
+
const rect = await locator.evaluate((node) => {
|
|
123
|
+
const box = node.getBoundingClientRect();
|
|
124
|
+
return { x: box.left + window.scrollX, y: box.top + window.scrollY, width: box.width, height: box.height };
|
|
125
|
+
});
|
|
126
|
+
return { ok: true, rect };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** The crop's frame from its element (and `crop.top`'s top edge) and the page's scrollable size. */
|
|
130
|
+
async function measureCrop(page: Page, crop: Crop): Promise<CropMeasure> {
|
|
131
|
+
const element = await measureElement(page, crop.target, "crop.target");
|
|
132
|
+
if (!element.ok) return element;
|
|
133
|
+
let top: number | undefined;
|
|
134
|
+
if (crop.top !== undefined) {
|
|
135
|
+
const topElement = await measureElement(page, crop.top, "crop.top");
|
|
136
|
+
if (!topElement.ok) return topElement;
|
|
137
|
+
top = topElement.rect.y;
|
|
138
|
+
}
|
|
139
|
+
const size = await page.evaluate(() => ({ width: document.documentElement.scrollWidth, height: document.documentElement.scrollHeight }));
|
|
140
|
+
return findCropFrame({ element: element.rect, ...(top === undefined ? {} : { top }), page: size, aspect: crop.aspect, padding: crop.padding });
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* How many rendered elements each hidden selector still matches inside the frame (document coordinates; the
|
|
145
|
+
* viewport when null); `shown: null` for a selector the browser cannot parse.
|
|
146
|
+
*/
|
|
147
|
+
async function countShownHidden(page: Page, selectors: readonly string[], frame: Rect | null): Promise<{ selector: string; shown: number | null }[]> {
|
|
148
|
+
return page.evaluate(
|
|
149
|
+
({ selectors, frame }) => {
|
|
150
|
+
const area = frame ?? { x: window.scrollX, y: window.scrollY, width: window.innerWidth, height: window.innerHeight };
|
|
151
|
+
return selectors.map((selector) => {
|
|
152
|
+
let nodes: Element[];
|
|
153
|
+
try {
|
|
154
|
+
nodes = [...document.querySelectorAll(selector)];
|
|
155
|
+
} catch {
|
|
156
|
+
// A selector the browser cannot parse is reported by the gate as such.
|
|
157
|
+
return { selector, shown: null };
|
|
158
|
+
}
|
|
159
|
+
const shown = nodes.filter((node) => {
|
|
160
|
+
if (!node.checkVisibility({ opacityProperty: true, visibilityProperty: true })) return false;
|
|
161
|
+
const box = node.getBoundingClientRect();
|
|
162
|
+
if (box.width === 0 || box.height === 0) return false;
|
|
163
|
+
const left = box.left + window.scrollX;
|
|
164
|
+
const top = box.top + window.scrollY;
|
|
165
|
+
return left < area.x + area.width && left + box.width > area.x && top < area.y + area.height && top + box.height > area.y;
|
|
166
|
+
}).length;
|
|
167
|
+
return { selector, shown };
|
|
168
|
+
});
|
|
169
|
+
},
|
|
170
|
+
{ selectors, frame },
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
|
|
97
174
|
async function takeOne(page: Page, target: ShotTarget): Promise<ScreenshotResult> {
|
|
98
175
|
const { entry, name, url } = target;
|
|
99
176
|
const refuse = (gate: ScreenshotGate, message: string): ScreenshotResult => ({ ok: false, id: entry.id, name, gate, message });
|
|
@@ -120,6 +197,8 @@ async function takeOne(page: Page, target: ShotTarget): Promise<ScreenshotResult
|
|
|
120
197
|
async function captureLoadedPage(page: Page, target: ShotTarget): Promise<ScreenshotResult> {
|
|
121
198
|
const { entry, name, url, file } = target;
|
|
122
199
|
await page.evaluate(() => document.fonts.ready);
|
|
200
|
+
const stepFailure = await runShotSteps(page, entry.steps, "steps");
|
|
201
|
+
if (stepFailure !== null) return { ok: false, id: entry.id, name, gate: "steps", message: stepFailure };
|
|
123
202
|
if (entry.full) await scrollThroughPage(page);
|
|
124
203
|
if (entry.scrollTo !== undefined) {
|
|
125
204
|
const reached = await page.evaluate((top) => {
|
|
@@ -133,7 +212,30 @@ async function captureLoadedPage(page: Page, target: ShotTarget): Promise<Screen
|
|
|
133
212
|
if (!(await waitForPhrase(page, entry.expect))) {
|
|
134
213
|
return { ok: false, id: entry.id, name, gate: "phrase", message: `${url} does not show "${entry.expect}"` };
|
|
135
214
|
}
|
|
136
|
-
|
|
215
|
+
let frame: Rect | null = null;
|
|
216
|
+
if (entry.crop !== undefined) {
|
|
217
|
+
const crop = await measureCrop(page, entry.crop);
|
|
218
|
+
if (!crop.ok) return { ok: false, id: entry.id, name, gate: "crop", message: crop.message };
|
|
219
|
+
frame = crop.frame;
|
|
220
|
+
}
|
|
221
|
+
if (entry.hide.length > 0) {
|
|
222
|
+
const area = frame ?? (entry.full ? await page.evaluate(() => ({ x: 0, y: 0, width: document.documentElement.scrollWidth, height: document.documentElement.scrollHeight })) : null);
|
|
223
|
+
const hideFailure = findHideFailure(await countShownHidden(page, entry.hide, area));
|
|
224
|
+
if (hideFailure !== null) return { ok: false, id: entry.id, name, gate: "hide", message: hideFailure };
|
|
225
|
+
}
|
|
226
|
+
if (frame === null) {
|
|
227
|
+
await page.screenshot({ path: file, fullPage: entry.full });
|
|
228
|
+
} else {
|
|
229
|
+
// Document coordinates with fullPage: a sticky header stays at the page's top instead of over the element.
|
|
230
|
+
await page.screenshot({ path: file, fullPage: true, clip: frame });
|
|
231
|
+
}
|
|
232
|
+
if (frame !== null) {
|
|
233
|
+
const dimensionFailure = findDimensionFailure(readPngSize(file), frame, entry.scale);
|
|
234
|
+
if (dimensionFailure !== null) {
|
|
235
|
+
rmSync(file, { force: true });
|
|
236
|
+
return { ok: false, id: entry.id, name, gate: "crop", message: dimensionFailure };
|
|
237
|
+
}
|
|
238
|
+
}
|
|
137
239
|
const bytes = statSync(file).size;
|
|
138
240
|
const sizeFailure = findSizeFailure(bytes, entry.minBytes);
|
|
139
241
|
if (sizeFailure !== null) {
|
|
@@ -153,10 +255,12 @@ interface TakeShotOptions {
|
|
|
153
255
|
settings: ScreenshotBrowser;
|
|
154
256
|
target: ShotTarget;
|
|
155
257
|
scheme: ColorTheme;
|
|
258
|
+
/** The run's sign-in session, for a `signedIn` entry. */
|
|
259
|
+
session?: SessionState;
|
|
156
260
|
}
|
|
157
261
|
|
|
158
262
|
async function takeShot(options: TakeShotOptions): Promise<ScreenshotResult> {
|
|
159
|
-
const { browser, settings, target, scheme } = options;
|
|
263
|
+
const { browser, settings, target, scheme, session } = options;
|
|
160
264
|
const { entry } = target;
|
|
161
265
|
const context = await browser.newContext({
|
|
162
266
|
viewport: { width: entry.width, height: entry.height },
|
|
@@ -167,13 +271,15 @@ async function takeShot(options: TakeShotOptions): Promise<ScreenshotResult> {
|
|
|
167
271
|
reducedMotion: entry.motion,
|
|
168
272
|
// Resolved to an absolute path by the caller (the CLI resolves it against the folder of marketing.json).
|
|
169
273
|
...(entry.storageState === undefined ? {} : { storageState: entry.storageState }),
|
|
274
|
+
...(session === undefined ? {} : { storageState: session }),
|
|
170
275
|
});
|
|
171
276
|
try {
|
|
172
277
|
const page = await context.newPage();
|
|
173
278
|
// One tag per selector, so a selector the browser cannot parse drops only its own rule;
|
|
174
279
|
// instant scrolling, because "smooth" would still be moving when the full page is captured.
|
|
175
280
|
// An init script, so the rules hold from the first paint, before the gates read the page.
|
|
176
|
-
const
|
|
281
|
+
const hidden = [...settings.hideSelectors, ...target.entry.hide];
|
|
282
|
+
const css = [...hidden.map((selector) => `${selector}{display:none!important}`), "html{scroll-behavior:auto!important}"];
|
|
177
283
|
await page.addInitScript((rules: string[]) => {
|
|
178
284
|
document.addEventListener("DOMContentLoaded", () => {
|
|
179
285
|
for (const rule of rules) {
|
|
@@ -189,18 +295,49 @@ async function takeShot(options: TakeShotOptions): Promise<ScreenshotResult> {
|
|
|
189
295
|
}
|
|
190
296
|
}
|
|
191
297
|
|
|
192
|
-
/**
|
|
298
|
+
/**
|
|
299
|
+
* Refuses a kept file whose bytes an earlier kept file of the run already has (the page did not change between the
|
|
300
|
+
* two shots, or two entries frame the same thing), and deletes it; remembers the others.
|
|
301
|
+
*/
|
|
302
|
+
function refuseDuplicate(result: ScreenshotResult, seen: Map<string, string>): ScreenshotResult {
|
|
303
|
+
if (!result.ok) return result;
|
|
304
|
+
const hash = createHash("sha256").update(readFileSync(result.file)).digest("hex");
|
|
305
|
+
const earlier = seen.get(hash);
|
|
306
|
+
if (earlier === undefined) {
|
|
307
|
+
seen.set(hash, result.name);
|
|
308
|
+
return result;
|
|
309
|
+
}
|
|
310
|
+
rmSync(result.file, { force: true });
|
|
311
|
+
const message = `the file has the same bytes as ${earlier}.png: the page did not change between the two shots; deleted`;
|
|
312
|
+
return { ok: false, id: result.id, name: result.name, gate: "duplicate", message };
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* Takes every shot of every entry in order; one failing shot does not stop the others. The sign-in runs once,
|
|
317
|
+
* before the first `signedIn` entry; when it fails, every `signedIn` shot is refused with its reason.
|
|
318
|
+
*/
|
|
193
319
|
export async function takeScreenshots(options: TakeScreenshotsOptions): Promise<ScreenshotResult[]> {
|
|
194
320
|
const { entries, baseUrl, outDir, browser: settings } = options;
|
|
195
321
|
mkdirSync(outDir, { recursive: true });
|
|
196
322
|
const browser = await chromium.launch(options.executablePath === undefined ? {} : { executablePath: options.executablePath });
|
|
197
323
|
const results: ScreenshotResult[] = [];
|
|
324
|
+
const seen = new Map<string, string>();
|
|
325
|
+
let signedIn: Awaited<ReturnType<typeof signIn>> | null = null;
|
|
198
326
|
try {
|
|
199
327
|
for (const entry of entries) {
|
|
200
328
|
removeEntryFiles(outDir, entry);
|
|
329
|
+
if (entry.signedIn && signedIn === null) {
|
|
330
|
+
signedIn = options.signIn === undefined ? { ok: false, message: "no signIn block says how to sign in" } : await signIn({ browser, baseUrl, settings, plan: options.signIn });
|
|
331
|
+
}
|
|
201
332
|
for (const shot of getScreenshotShots(entry, settings.colorScheme)) {
|
|
333
|
+
if (entry.signedIn && signedIn?.ok === false) {
|
|
334
|
+
results.push({ ok: false, id: entry.id, name: shot.name, gate: "sign-in", message: signedIn.message });
|
|
335
|
+
continue;
|
|
336
|
+
}
|
|
202
337
|
const target = { entry, name: shot.name, url: new URL(entry.path, baseUrl).href, file: getScreenshotFile(outDir, shot.name) };
|
|
203
|
-
|
|
338
|
+
const session = entry.signedIn && signedIn?.ok === true ? signedIn.session : undefined;
|
|
339
|
+
const result = await takeShot({ browser, settings, target, scheme: shot.scheme, ...(session === undefined ? {} : { session }) });
|
|
340
|
+
results.push(refuseDuplicate(result, seen));
|
|
204
341
|
}
|
|
205
342
|
}
|
|
206
343
|
} 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
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import type { Browser, BrowserContext, Page } from "playwright";
|
|
2
|
+
|
|
3
|
+
import type { ShotStep } from "../config/shot-steps.js";
|
|
4
|
+
import { containsPhrase } from "../film.js";
|
|
5
|
+
import { findStatusFailure } from "./gates.js";
|
|
6
|
+
import type { ScreenshotBrowser } from "./screenshot.js";
|
|
7
|
+
import { runShotSteps } from "./steps.js";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* `signIn` of marketing.json, done once per `shots` run: the sign-in page, its steps, then a phrase only a
|
|
11
|
+
* signed-in page shows. The session (cookies and localStorage) stays in memory and opens every `signedIn: true`
|
|
12
|
+
* screenshot; it is never written to disk. Values are resolved before they get here and never printed.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/** The sign-in with its placeholders resolved. */
|
|
16
|
+
export interface SignInPlan {
|
|
17
|
+
path: string;
|
|
18
|
+
steps: ShotStep[];
|
|
19
|
+
expect: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export type SessionState = Awaited<ReturnType<BrowserContext["storageState"]>>;
|
|
23
|
+
|
|
24
|
+
export type SignInResult = { ok: true; session: SessionState } | { ok: false; message: string };
|
|
25
|
+
|
|
26
|
+
const NAVIGATION_TIMEOUT_MS = 30_000;
|
|
27
|
+
/** The submit usually navigates and the next page loads its data: more time than a screenshot's 5 s. */
|
|
28
|
+
export const SIGN_IN_PHRASE_TIMEOUT_MS = 15_000;
|
|
29
|
+
const PHRASE_POLL_MS = 250;
|
|
30
|
+
|
|
31
|
+
function describeError(error: unknown): string {
|
|
32
|
+
return error instanceof Error ? (error.message.split("\n")[0] ?? error.name) : String(error);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The page's visible text, or null while a navigation replaces the document (its context is destroyed). */
|
|
36
|
+
export async function readPageText(page: Page): Promise<string | null> {
|
|
37
|
+
try {
|
|
38
|
+
return await page.locator("body").innerText({ timeout: PHRASE_POLL_MS * 4 });
|
|
39
|
+
} catch {
|
|
40
|
+
// A navigation in flight or a body not there yet: the next poll reads the new page.
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function waitForSignedIn(page: Page, phrase: string): Promise<boolean> {
|
|
46
|
+
const deadline = Date.now() + SIGN_IN_PHRASE_TIMEOUT_MS;
|
|
47
|
+
for (;;) {
|
|
48
|
+
const text = await readPageText(page);
|
|
49
|
+
if (text !== null && containsPhrase(text, phrase)) return true;
|
|
50
|
+
if (Date.now() >= deadline) return false;
|
|
51
|
+
await page.waitForTimeout(PHRASE_POLL_MS);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface SignInOptions {
|
|
56
|
+
browser: Browser;
|
|
57
|
+
baseUrl: string;
|
|
58
|
+
settings: ScreenshotBrowser;
|
|
59
|
+
plan: SignInPlan;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export async function signIn(options: SignInOptions): Promise<SignInResult> {
|
|
63
|
+
const { browser, baseUrl, settings, plan } = options;
|
|
64
|
+
const url = new URL(plan.path, baseUrl).href;
|
|
65
|
+
const context = await browser.newContext({ colorScheme: settings.colorScheme, locale: settings.locale, timezoneId: settings.timezone });
|
|
66
|
+
try {
|
|
67
|
+
const page = await context.newPage();
|
|
68
|
+
let status: number | null;
|
|
69
|
+
try {
|
|
70
|
+
const response = await page.goto(url, { waitUntil: "load", timeout: NAVIGATION_TIMEOUT_MS });
|
|
71
|
+
status = response?.status() ?? null;
|
|
72
|
+
} catch (error) {
|
|
73
|
+
// Any navigation failure (refused connection, DNS, timeout) is the app's, not a bug of ours.
|
|
74
|
+
return { ok: false, message: `loading the sign-in page ${url}: ${describeError(error)}` };
|
|
75
|
+
}
|
|
76
|
+
const statusFailure = findStatusFailure(status, url);
|
|
77
|
+
if (statusFailure !== null) return { ok: false, message: `the sign-in page: ${statusFailure}` };
|
|
78
|
+
const stepFailure = await runShotSteps(page, plan.steps, "signIn.steps");
|
|
79
|
+
if (stepFailure !== null) return { ok: false, message: stepFailure };
|
|
80
|
+
if (!(await waitForSignedIn(page, plan.expect))) {
|
|
81
|
+
return { ok: false, message: `after the sign-in steps, ${new URL(page.url()).pathname} does not show "${plan.expect}" within ${SIGN_IN_PHRASE_TIMEOUT_MS / 1000} s` };
|
|
82
|
+
}
|
|
83
|
+
const session = await context.storageState();
|
|
84
|
+
if (session.cookies.length === 0 && session.origins.length === 0) {
|
|
85
|
+
return { ok: false, message: `the page shows "${plan.expect}", but the browser holds no session (no cookie, no localStorage); pick a phrase only a signed-in page shows` };
|
|
86
|
+
}
|
|
87
|
+
return { ok: true, session };
|
|
88
|
+
} finally {
|
|
89
|
+
await context.close();
|
|
90
|
+
}
|
|
91
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import type { Locator, Page } from "playwright";
|
|
2
|
+
|
|
3
|
+
import type { ShotStep } from "../config/shot-steps.js";
|
|
4
|
+
import { getLocator } from "../record/locator.js";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Steps of the sign-in and of a screenshot entry, done in order on the page. A step that cannot be done (its
|
|
8
|
+
* element never appears, matches several, is not an input, is not a `<details>`) is the page's or the config's
|
|
9
|
+
* fault, so it comes back as a message naming the step; the message never carries a `fill` value, which may be a
|
|
10
|
+
* password. `open` and `hide` act on every match of their target; the others need exactly one.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** Long enough for a client-side page to render the element, short enough that a typo does not hang the run. */
|
|
14
|
+
export const STEP_TIMEOUT_MS = 10_000;
|
|
15
|
+
|
|
16
|
+
function describeError(error: unknown): string {
|
|
17
|
+
return error instanceof Error ? (error.message.split("\n")[0] ?? error.name) : String(error);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async function runStep(page: Page, step: ShotStep): Promise<void> {
|
|
21
|
+
const timeout = STEP_TIMEOUT_MS;
|
|
22
|
+
switch (step.do) {
|
|
23
|
+
case "fill":
|
|
24
|
+
return getLocator(page, step.target).fill(step.value, { timeout });
|
|
25
|
+
case "click":
|
|
26
|
+
return getLocator(page, step.target).click({ timeout });
|
|
27
|
+
case "check":
|
|
28
|
+
return getLocator(page, step.target).check({ timeout });
|
|
29
|
+
case "press":
|
|
30
|
+
return page.keyboard.press(step.key);
|
|
31
|
+
case "open":
|
|
32
|
+
return openEvery(getLocator(page, step.target));
|
|
33
|
+
case "hide":
|
|
34
|
+
return hideAllButLast(getLocator(page, step.target), step.keepLast);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Waits for the first match like the other steps do; a step on every match needs at least one. */
|
|
39
|
+
async function waitForMatches(locator: Locator): Promise<void> {
|
|
40
|
+
await locator.first().waitFor({ state: "attached", timeout: STEP_TIMEOUT_MS });
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Opens every match; refuses a match that is not a `<details>` and one that did not stay open. */
|
|
44
|
+
async function openEvery(locator: Locator): Promise<void> {
|
|
45
|
+
await waitForMatches(locator);
|
|
46
|
+
const outcome = await locator.evaluateAll((nodes) => {
|
|
47
|
+
const notDetails = nodes.filter((node) => !(node instanceof HTMLDetailsElement)).length;
|
|
48
|
+
if (notDetails > 0) return { total: nodes.length, notDetails, closed: 0 };
|
|
49
|
+
for (const node of nodes) (node as HTMLDetailsElement).open = true;
|
|
50
|
+
// Details sharing a name form an exclusive group: opening one closes the others.
|
|
51
|
+
const closed = nodes.filter((node) => !(node as HTMLDetailsElement).open).length;
|
|
52
|
+
return { total: nodes.length, notDetails, closed };
|
|
53
|
+
});
|
|
54
|
+
if (outcome.notDetails > 0) {
|
|
55
|
+
const verb = outcome.notDetails === 1 ? "is" : "are";
|
|
56
|
+
throw new Error(`${outcome.notDetails} of ${outcome.total} matches ${verb} not a <details> element`);
|
|
57
|
+
}
|
|
58
|
+
if (outcome.closed > 0) throw new Error(`${outcome.closed} of ${outcome.total} <details> did not stay open (details sharing a name show one at a time)`);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Hides every match but the last `keepLast`; refuses when that would hide nothing (the selector is likely wrong). */
|
|
62
|
+
async function hideAllButLast(locator: Locator, keepLast: number): Promise<void> {
|
|
63
|
+
await waitForMatches(locator);
|
|
64
|
+
const total = await locator.evaluateAll((nodes, keep) => {
|
|
65
|
+
if (nodes.length <= keep) return nodes.length;
|
|
66
|
+
for (const node of nodes.slice(0, nodes.length - keep)) {
|
|
67
|
+
if (node instanceof HTMLElement || node instanceof SVGElement) node.style.setProperty("display", "none", "important");
|
|
68
|
+
}
|
|
69
|
+
return nodes.length;
|
|
70
|
+
}, keepLast);
|
|
71
|
+
if (total <= keepLast) throw new Error(`matches ${total} elements, not more than keepLast ${keepLast}, so nothing would be hidden`);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Null when every step was done; otherwise which one failed (`<where>[<index>] (<do>)`) and why. */
|
|
75
|
+
export async function runShotSteps(page: Page, steps: readonly ShotStep[], where: string): Promise<string | null> {
|
|
76
|
+
for (const [index, step] of steps.entries()) {
|
|
77
|
+
try {
|
|
78
|
+
await runStep(page, step);
|
|
79
|
+
} catch (error) {
|
|
80
|
+
// Every Playwright failure of a step (timeout, strict mode, not an input) is the page's or the config's.
|
|
81
|
+
return `${where}[${index}] (${step.do}): ${describeError(error)}`;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return null;
|
|
85
|
+
}
|