Skip to content
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,19 @@ External scenario modules own one specific screenshot's data, custom CSS, and
browser steps while reusing this runner's temporary site and high-resolution
capture. Pass their path with `--scenario`; the scenario's `name` sets the PNG
filename directly inside `--output`. A scenario can set its own viewport when a
wider layout is part of the screenshot.
wider layout is part of the screenshot. Set `adminSetup: false` when the
scenario needs to capture the site before setup. The runner skips admin setup,
Stripe, and the saved theme, then applies the scenario's CSS after its browser
steps.

Pass `--layers` with an external scenario to also write transparent background,
controls, and text layers. They are named
`<scenario-name>__layer-<layer>.png` next to the normal screenshot.

```bash
deno task screenshot --scenario ../tickets-site/scripts/screenshots/charity-events.js \
--layers --output ../tickets-site/images/screenshots
```

Pass `--social` (one of `facebook`, `instagram-landscape`,
`instagram-portrait`, `instagram-square`, a comma-separated list, or `all`) to
Expand Down
2 changes: 1 addition & 1 deletion deno.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"test": "deno run --v8-flags=--expose-gc -A scripts/run-tests.ts",
"test:coverage": "deno run --v8-flags=--expose-gc -A scripts/run-tests.ts --coverage",
"test:files": "deno run --v8-flags=--expose-gc -A scripts/run-test-files.ts",
"test:screenshot-contract": "deno test --no-check -A test/scripts/screenshots-browser.contract.ts",
"test:screenshot-contract": "deno test --no-check -A test/scripts/*-browser.contract.ts",
"specs": "deno run --v8-flags=--expose-gc -A scripts/run-specs.ts",
"specs:evidence": "deno run --v8-flags=--expose-gc -A scripts/run-spec-evidence.ts",
"specs:check": "deno run --allow-read scripts/check-specs.ts",
Expand Down
1 change: 0 additions & 1 deletion scripts/mutation/equivalent-mutants/scripts.txt
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,6 @@ scripts/process.ts::beforeTimeout.delayed.timeout~0g1xgyk = → += # the hand

# Isolated mutation runs: the exit code before any path has set one.
scripts/mutation/isolation.ts::runInSnapshot.exitCode~1tg3w08 1 → 0 # every path overwrites this before it is returned: the claim always runs its callback, which either sets 130 on an interrupt or hands back a child whose status sets the code, and any throw is caught and sets it there
scripts/mutation/isolation.ts::keepFiles~1lmhedv 0 → 1 # keepFiles' interrupted arm only runs once wasInterrupted() has latched true, and finishChild then takes the `interrupted ? 130` branch, so the number this arm hands back is never read
scripts/mutation/isolation.ts::runInSnapshot.copyBack~11e4190 ?? → || # run.copyBack is a list or undefined, and a list — empty included — is truthy, so only undefined reaches the fallback and both operators yield the same []
scripts/stale-claim.ts::startClaimTouching.scheduleNextTouch.timeout~1tjxi69 = → += # the uncancelled timer's one late touch bails on the stopped flag before any read or write
src/shared/db/migrations.ts::initDb~0hi1ix2 ?? → || # opts.allowMissingSettings is boolean | undefined, and false ?? false and false || false both yield false
Expand Down
11 changes: 11 additions & 0 deletions scripts/mutation/isolation-lock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,3 +92,14 @@ export const withCopyBackLock = <Result>(
root: string,
run: LockBody<Result>,
): Promise<Result> => withFileLock(copyBackLockPath(root), run);

/** Recheck whether copy-back is still wanted after waiting for its lock. */
export const withCopyBackLockWhen = <Result>(
root: string,
shouldRun: () => boolean,
skippedResult: Result,
run: LockBody<Result>,
): Promise<Result> =>
withCopyBackLock(root, () =>
shouldRun() ? run() : Promise.resolve(skippedResult),
);
26 changes: 7 additions & 19 deletions scripts/mutation/isolation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import {
runIsOwned,
} from "./isolation-cleanup.ts";
import {
withCopyBackLock,
withCopyBackLockWhen,
withRunClaim,
withRunClaimGuard,
} from "./isolation-lock.ts";
Expand Down Expand Up @@ -145,23 +145,6 @@ const settleRecord = (
): MutationRunRecord =>
interrupted ? markInterrupted(record) : markFinished(record, code);

/**
* Bring the run's kept files back, one run at a time across the checkout. The
* question is asked again inside the lock: waiting for it is a moment long
* enough to be interrupted, and an interrupted run keeps nothing.
*/
const keepFiles = (
wasInterrupted: () => boolean,
root: string,
workRoot: string,
copyBack: CopyBackFile[],
): Promise<number> =>
withCopyBackLock(root, () =>
wasInterrupted()
? Promise.resolve(0)
: bringFilesBack(root, workRoot, copyBack),
);

/**
* Record the child's result, then bring back what the run means to keep. The
* supervisor's claim on the run stays fresh throughout, so a clear-up
Expand All @@ -178,7 +161,12 @@ const finishChild = async (
const failedToKeep =
wasInterrupted() || copyBack.length === 0
? 0
: await keepFiles(wasInterrupted, root, record.workRoot, copyBack);
: await withCopyBackLockWhen(
root,
() => !wasInterrupted(),
0,
() => bringFilesBack(root, record.workRoot, copyBack),
);
const interrupted = wasInterrupted();
// A run that could not keep its files failed, whatever the child said.
const exitCode = interrupted ? 130 : failedToKeep || code;
Expand Down
46 changes: 33 additions & 13 deletions scripts/screenshots.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,16 @@ import {
startScreenshotAppServer,
} from "./screenshots/app-server.ts";
import { chromiumExecutable } from "./screenshots/browser.ts";
import { capturePreparedPage } from "./screenshots/capture.ts";
import {
capturePreparedLayers,
capturePreparedPage,
} from "./screenshots/capture.ts";
import { isCompactWidth, isolateElementCss } from "./screenshots/checks.ts";
import type { Rgb } from "./screenshots/color.ts";
import {
addScreenshotStyle,
SCREENSHOT_LAYER_NAMES,
} from "./screenshots/layers.ts";
import {
parseScreenshotOptions,
type ScreenshotName,
Expand Down Expand Up @@ -252,20 +259,17 @@ const captureScenario = async (
server: ScreenshotAppServer,
outputDir: string,
social: readonly SocialTargetName[] = [],
layers = false,
): Promise<void> => {
const { baseUrl } = server;
await setupAdmin(page, baseUrl, scenario.setupUsername);
await server.enableStripe();
await applyTheme(
page,
baseUrl,
"default",
`${scenario.css}\n${
scenario.elementSelector
? isolateElementCss(scenario.elementSelector)
: ""
}`,
);
const captureCss = `${scenario.css}\n${
scenario.elementSelector ? isolateElementCss(scenario.elementSelector) : ""
}`;
if (scenario.adminSetup !== false) {
await setupAdmin(page, baseUrl, scenario.setupUsername);
await server.enableStripe();
Comment thread
stefan-burke marked this conversation as resolved.
Resolved
await applyTheme(page, baseUrl, "default", captureCss);
}
await scenario.run({
balancePathFor: async (attendeeId) => {
const { signBalanceToken } = await import("#shared/balance-link.ts");
Expand All @@ -275,6 +279,9 @@ const captureScenario = async (
page,
submit: (formSelector) => submit(page, formSelector),
});
if (scenario.adminSetup === false) {
await addScreenshotStyle(page, captureCss);
}
await waitForScreenshotPage(page);
const outputPath = join(outputDir, `${scenario.name}.png`);
const background = await captureAndWrite(
Expand All @@ -284,6 +291,18 @@ const captureScenario = async (
scenario.fullPage,
);
console.log(`${scenario.name}.png`);
if (layers) {
const captures = await capturePreparedLayers(
page,
scenario.elementSelector,
scenario.fullPage,
);
for (const layer of SCREENSHOT_LAYER_NAMES) {
const name = `${scenario.name}__layer-${layer}.png`;
await Deno.writeFile(join(outputDir, name), captures[layer]);
console.log(name);
}
}
await writeSocialVariants(
outputPath,
outputDir,
Expand Down Expand Up @@ -319,6 +338,7 @@ const main = async (): Promise<void> => {
server,
outputDir,
options.social ?? [],
options.layers ?? false,
);
return;
}
Expand Down
27 changes: 18 additions & 9 deletions scripts/screenshots/app-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@ import {
} from "#scripts/process.ts";
import {
type StartupCleanup,
startOnFirstUse,
startWithFailureCleanup,
waitForHealthy,
} from "#scripts/screenshots/server.ts";
import {
findAvailablePort,
reserveAvailablePort,
startStripeMock,
stripeMockEnv,
} from "#scripts/stripe-mock.ts";
Expand All @@ -33,25 +34,32 @@ const startAppServer = async ({
add,
run,
}: StartupCleanup): Promise<ScreenshotAppServer> => {
const stripeMock = await startStripeMock();
add(stripeMock.stop);
const stripePort = reserveAvailablePort();
add(stripePort.release);
const enableStripeMock = startOnFirstUse(async () => {
stripePort.release();
return await startStripeMock({ port: stripePort.port });
}, add);
const tempDir = await Deno.makeTempDir({ prefix: "tickets-screenshots-" });
add(() => removeTree(tempDir));
const port = findAvailablePort();
const baseUrl = `http://127.0.0.1:${port}`;
const appPort = reserveAvailablePort();
add(appPort.release);
const baseUrl = `http://127.0.0.1:${appPort.port}`;
const dbUrl = `file:${join(tempDir, "screenshots.db")}`;
const child = denoCommand(["run", "-A", "src/index.ts"], {
const command = denoCommand(["run", "-A", "src/index.ts"], {
cwd: ROOT,
env: {
...Deno.env.toObject(),
...stripeMockEnv(stripeMock.port),
...stripeMockEnv(stripePort.port),
DB_ENCRYPTION_KEY: DB_KEY,
DB_URL: dbUrl,
PORT: String(port),
PORT: String(appPort.port),
},
stderr: "inherit",
stdout: "null",
}).spawn();
});
appPort.release();
const child = command.spawn();
add(() => stopProcess(child, STOP_TIMEOUT_MS));

const deadline = Date.now() + TIMEOUT_MS;
Expand All @@ -66,6 +74,7 @@ const startAppServer = async ({
return {
baseUrl,
enableStripe: async () => {
await enableStripeMock();
Deno.env.set("DB_ENCRYPTION_KEY", DB_KEY);
Deno.env.set("DB_URL", dbUrl);
const { settings } = await import("#shared/db/settings.ts");
Expand Down
Loading