@firstdraft.com/cli 0.9.0 → 0.11.0

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.
@@ -0,0 +1,449 @@
1
+ /* global document, scrollX, scrollY, innerWidth, window, IntersectionObserver, getComputedStyle */
2
+
3
+ import { createHash } from "node:crypto";
4
+ import { lstatSync, readFileSync, realpathSync } from "node:fs";
5
+ import path from "node:path";
6
+ import { isUuidV7 } from "./plan-state.js";
7
+
8
+ export class SketchError extends Error {
9
+ /** @param {string} message @param {number} [status] @param {unknown} [response] */
10
+ constructor(message, status, response) {
11
+ super(message);
12
+ this.status = status;
13
+ this.response = response;
14
+ }
15
+ }
16
+ /** @param {string|Buffer} bytes */
17
+ export function digest(bytes) {
18
+ return createHash("sha256").update(bytes).digest("hex");
19
+ }
20
+
21
+ const stableKey = /^[a-zA-Z0-9][-a-zA-Z0-9_]{0,79}$/;
22
+ const media = new Map(
23
+ Object.entries({
24
+ ".html": "text/html; charset=utf-8",
25
+ ".css": "text/css; charset=utf-8",
26
+ ".png": "image/png",
27
+ ".jpg": "image/jpeg",
28
+ ".jpeg": "image/jpeg",
29
+ ".webp": "image/webp",
30
+ ".svg": "image/svg+xml",
31
+ ".woff2": "font/woff2",
32
+ }),
33
+ );
34
+ /** @param {string} cwd */
35
+ export function loadSources(cwd) {
36
+ const root = realpathSync(path.join(cwd, "sketches"));
37
+ if (root !== path.join(realpathSync(cwd), "sketches"))
38
+ throw new SketchError("Use a local sketches directory.");
39
+ /** @param {string} name */
40
+ function load(name) {
41
+ if (
42
+ typeof name !== "string" ||
43
+ !name
44
+ .split("/")
45
+ .every((part) => /^[a-zA-Z0-9_-][a-zA-Z0-9_.-]*$/.test(part))
46
+ )
47
+ throw new SketchError("Sketch paths must be relative to sketches/.");
48
+ const file = path.join(root, name);
49
+ if (realpathSync(file) !== file || !lstatSync(file).isFile())
50
+ throw new SketchError(
51
+ "Sketch sources must be regular files inside sketches/.",
52
+ );
53
+ return readFileSync(file);
54
+ }
55
+ const boardBytes = load("board.json");
56
+ /** @type {{screens:{id:string,name:string,source:string,sample_keys:string[],plan_subjects:string[]}[],assets:string[]}} */
57
+ const board = JSON.parse(boardBytes.toString());
58
+ if (
59
+ !board ||
60
+ !Array.isArray(board.screens) ||
61
+ board.screens.length < 1 ||
62
+ board.screens.length > 32 ||
63
+ !Array.isArray(board.assets) ||
64
+ !board.assets.every((asset) => typeof asset === "string")
65
+ )
66
+ throw new SketchError(
67
+ "board.json requires 1–32 screens and an assets array.",
68
+ );
69
+ const ids = new Set();
70
+ for (const screen of board.screens) {
71
+ if (
72
+ !screen ||
73
+ typeof screen.id !== "string" ||
74
+ !stableKey.test(screen.id) ||
75
+ typeof screen.name !== "string" ||
76
+ !screen.name.trim() ||
77
+ Buffer.byteLength(screen.name) > 256 ||
78
+ screen.name.includes("\0") ||
79
+ typeof screen.source !== "string" ||
80
+ !screen.source.endsWith(".html") ||
81
+ ids.has(screen.id)
82
+ )
83
+ throw new SketchError(
84
+ "Each screen needs a unique id, a name and an HTML source.",
85
+ );
86
+ for (const field of /** @type {const} */ ([
87
+ "sample_keys",
88
+ "plan_subjects",
89
+ ])) {
90
+ if (screen[field] === undefined) screen[field] = [];
91
+ const references = screen[field];
92
+ if (
93
+ !Array.isArray(references) ||
94
+ references.length > 256 ||
95
+ !references.every(isUuidV7)
96
+ )
97
+ throw new SketchError(
98
+ "sample_keys and plan_subjects must be arrays of Plan subject UUIDs.",
99
+ );
100
+ }
101
+ ids.add(screen.id);
102
+ }
103
+ const files = new Map([["board.json", boardBytes]]);
104
+ for (const name of [
105
+ ...board.assets,
106
+ ...board.screens.map((screen) => screen.source),
107
+ ]) {
108
+ if (!media.has(path.extname(name)))
109
+ throw new SketchError(
110
+ "Use HTML, CSS, images or WOFF2 fonts for sketch sources.",
111
+ );
112
+ files.set(name, load(name));
113
+ }
114
+ return { board, files };
115
+ }
116
+
117
+ // Playwright runs this function inside the screen's document.
118
+ /** @param {string} source */
119
+ export function bindPlanValues(source) {
120
+ const plan = JSON.parse(source);
121
+ for (const element of document.querySelectorAll("[data-plan-pointer]")) {
122
+ const pointer = element.getAttribute("data-plan-pointer") ?? "";
123
+ if (
124
+ (pointer !== "" && !pointer.startsWith("/")) ||
125
+ /~(?:[^01]|$)/.test(pointer)
126
+ )
127
+ return "Invalid data-plan-pointer.";
128
+ let value = plan;
129
+ for (const token of pointer.split("/").slice(1)) {
130
+ const key = token.replace(/~1/g, "/").replace(/~0/g, "~");
131
+ if (
132
+ value === null ||
133
+ typeof value !== "object" ||
134
+ (Array.isArray(value) && !/^(?:0|[1-9][0-9]*)$/.test(key)) ||
135
+ !Object.hasOwn(value, key)
136
+ )
137
+ return "A data-plan-pointer must identify a value in the Plan.";
138
+ value = value[key];
139
+ }
140
+ if (!["string", "number", "boolean"].includes(typeof value))
141
+ return "A data-plan-pointer must identify a scalar example value.";
142
+ element.textContent = String(value);
143
+ }
144
+ return null;
145
+ }
146
+
147
+ /** @param {ReturnType<typeof loadSources>} sources @param {string} planSource */
148
+ export async function captureBoard({ board, files }, planSource) {
149
+ try {
150
+ JSON.parse(planSource);
151
+ } catch (error) {
152
+ if (!(error instanceof SyntaxError)) throw error;
153
+ throw new SketchError(
154
+ "The working Foundation Plan must contain valid JSON.",
155
+ );
156
+ }
157
+ const { chromium, errors } = await import("playwright-core");
158
+ let browser;
159
+ let screenViewport = "";
160
+ let operation = "opening the screen";
161
+ try {
162
+ browser = await chromium
163
+ .launch({
164
+ channel: "chrome",
165
+ ...(process.env.FIRSTDRAFT_CHROME_PATH
166
+ ? { executablePath: process.env.FIRSTDRAFT_CHROME_PATH }
167
+ : {}),
168
+ })
169
+ .catch(() => {
170
+ throw new SketchError(
171
+ "Chrome could not launch. Install Chrome or set FIRSTDRAFT_CHROME_PATH to its executable.",
172
+ );
173
+ });
174
+ const context = await browser.newContext({
175
+ deviceScaleFactor: 1,
176
+ colorScheme: "light",
177
+ locale: "en-US",
178
+ timezoneId: "UTC",
179
+ reducedMotion: "reduce",
180
+ serviceWorkers: "block",
181
+ });
182
+ const blocked = new Set();
183
+ let malformedPath = false;
184
+ await context.route("**/*", async (route) => {
185
+ const url = new URL(route.request().url());
186
+ let name;
187
+ try {
188
+ name = decodeURIComponent(url.pathname.slice(1));
189
+ } catch (error) {
190
+ if (!(error instanceof URIError)) throw error;
191
+ malformedPath = true;
192
+ await route.abort();
193
+ return;
194
+ }
195
+ const body =
196
+ url.origin === "https://sketch.invalid" && name !== "board.json"
197
+ ? files.get(name)
198
+ : undefined;
199
+ if (!body) {
200
+ blocked.add(url.origin);
201
+ await route.abort();
202
+ return;
203
+ }
204
+ await route.fulfill({
205
+ body,
206
+ contentType: media.get(path.extname(name)),
207
+ headers: {
208
+ "Content-Security-Policy":
209
+ "default-src 'none'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; base-uri 'none'; frame-src 'none'",
210
+ },
211
+ });
212
+ });
213
+ const page = await context.newPage();
214
+ await page.addInitScript(() => {
215
+ document.addEventListener("securitypolicyviolation", () => {
216
+ /** @type {Window & {sketchAssetBlocked?: boolean}} */ (
217
+ window
218
+ ).sketchAssetBlocked = true;
219
+ });
220
+ });
221
+ async function checkAssets() {
222
+ if (malformedPath)
223
+ throw new SketchError(
224
+ "An asset URL has invalid percent encoding. Correct the path in the screen or its stylesheet.",
225
+ );
226
+ if (
227
+ blocked.size ||
228
+ (await page.evaluate(
229
+ () =>
230
+ /** @type {Window & {sketchAssetBlocked?: boolean}} */ (window)
231
+ .sketchAssetBlocked,
232
+ ))
233
+ )
234
+ throw new SketchError(
235
+ "A screen requested an undeclared or external asset. List eligible local assets in board.json.",
236
+ );
237
+ }
238
+ const thumbnail = await context.newPage();
239
+ const screens = [];
240
+ for (const screen of board.screens) {
241
+ /** @param {number} width @param {number} height */
242
+ async function capture(width, height) {
243
+ screenViewport = `${screen.id} (${width} × ${height})`;
244
+ operation = "opening the screen";
245
+ await page.setViewportSize({ width, height });
246
+ await page.goto("https://sketch.invalid/" + screen.source, {
247
+ waitUntil: "load",
248
+ });
249
+ const bindingError = await page.evaluate(bindPlanValues, planSource);
250
+ if (bindingError) throw new SketchError(bindingError);
251
+ await checkAssets();
252
+ operation = "loading the screen’s images and fonts";
253
+ const readiness = await page.waitForFunction(
254
+ async () => {
255
+ for (const image of document.images) image.loading = "eager";
256
+ await document.fonts.ready;
257
+ try {
258
+ await Promise.all(
259
+ Array.from(document.images)
260
+ .filter(
261
+ (image) =>
262
+ image.checkVisibility() &&
263
+ (image.currentSrc ||
264
+ image.getAttribute("src") ||
265
+ image.getAttribute("srcset")),
266
+ )
267
+ .map((image) => image.decode()),
268
+ );
269
+ } catch (error) {
270
+ if (
271
+ error instanceof DOMException &&
272
+ error.name === "EncodingError"
273
+ )
274
+ return "invalid-image";
275
+ throw error;
276
+ }
277
+ return "ready";
278
+ },
279
+ undefined,
280
+ { timeout: 15000 },
281
+ );
282
+ await checkAssets();
283
+ if ((await readiness.jsonValue()) === "invalid-image")
284
+ throw new SketchError(
285
+ "Chrome could not decode a visible image. Check that its declared source is a valid image file.",
286
+ );
287
+ await page.evaluate(() => {
288
+ for (const animation of document.getAnimations()) {
289
+ if (animation.effect?.getComputedTiming().endTime === Infinity)
290
+ animation.cancel();
291
+ else animation.finish();
292
+ }
293
+ });
294
+ const fullPage = await page.evaluate(() => {
295
+ const { body, documentElement: root } = document;
296
+ // Chrome captures blank pixels below a viewport-height scrolling body.
297
+ // Let the document scroll for capture while leaving inner panels clipped.
298
+ if (
299
+ body.scrollHeight > root.scrollHeight &&
300
+ ["auto", "scroll"].includes(getComputedStyle(body).overflowY)
301
+ ) {
302
+ body.style.setProperty("overflow-y", "visible", "important");
303
+ body.style.setProperty("overflow-x", "clip", "important");
304
+ }
305
+ return {
306
+ width: Math.max(
307
+ body.scrollWidth,
308
+ root.scrollWidth,
309
+ body.offsetWidth,
310
+ root.offsetWidth,
311
+ body.clientWidth,
312
+ root.clientWidth,
313
+ ),
314
+ height: Math.max(
315
+ body.scrollHeight,
316
+ root.scrollHeight,
317
+ body.offsetHeight,
318
+ root.offsetHeight,
319
+ body.clientHeight,
320
+ root.clientHeight,
321
+ ),
322
+ };
323
+ });
324
+ const content_height = fullPage.height;
325
+ if (content_height > 8192 || fullPage.width > width)
326
+ throw new SketchError(
327
+ "Sketch exceeds its viewport width or 8192px maximum height.",
328
+ );
329
+ const elements = await page.evaluate(async (captureHeight) => {
330
+ const keyed = Array.from(
331
+ document.querySelectorAll("[data-sketch-key]"),
332
+ ).filter((element) =>
333
+ element.checkVisibility({
334
+ visibilityProperty: true,
335
+ opacityProperty: true,
336
+ }),
337
+ );
338
+ if (!keyed.length) return [];
339
+
340
+ // Expand only the root viewport to the full-page capture. Chromium still
341
+ // clips each element to its scroll containers and transformed ancestors.
342
+ const intersections =
343
+ await /** @type {Promise<IntersectionObserverEntry[]>} */ (
344
+ new Promise((resolve) => {
345
+ const observer = new IntersectionObserver(
346
+ (entries) => {
347
+ observer.disconnect();
348
+ resolve(entries);
349
+ },
350
+ {
351
+ rootMargin: `0px 0px ${captureHeight}px 0px`,
352
+ },
353
+ );
354
+ for (const element of keyed) observer.observe(element);
355
+ })
356
+ );
357
+ return intersections
358
+ .filter(
359
+ ({ intersectionRect }) =>
360
+ intersectionRect.width > 0 && intersectionRect.height > 0,
361
+ )
362
+ .map(({ target: element, intersectionRect: bounds }) => {
363
+ const x = Math.max(0, Math.floor(bounds.x + scrollX));
364
+ const y = Math.max(0, Math.floor(bounds.y + scrollY));
365
+ return {
366
+ id: element.getAttribute("data-sketch-key"),
367
+ label: (
368
+ element.getAttribute("data-sketch-label") ||
369
+ element.getAttribute("aria-label") ||
370
+ element.textContent ||
371
+ ""
372
+ ).trim(),
373
+ x,
374
+ y,
375
+ width:
376
+ Math.min(innerWidth, Math.ceil(bounds.right + scrollX)) - x,
377
+ height:
378
+ Math.min(captureHeight, Math.ceil(bounds.bottom + scrollY)) -
379
+ y,
380
+ };
381
+ })
382
+ .filter((element) => element.width > 0 && element.height > 0);
383
+ }, content_height);
384
+ if (
385
+ elements.length > 512 ||
386
+ new Set(elements.map((element) => element.id)).size !==
387
+ elements.length ||
388
+ elements.some(
389
+ (element) =>
390
+ !element.id ||
391
+ !stableKey.test(element.id) ||
392
+ !element.label ||
393
+ element.label.includes("\0") ||
394
+ Buffer.byteLength(element.label) > 256,
395
+ )
396
+ )
397
+ throw new SketchError(
398
+ "Visible sketch elements need unique keys and labels of at most 256 bytes.",
399
+ );
400
+ operation = "rasterizing the screen";
401
+ const png = await page.screenshot({ fullPage: true, timeout: 15000 });
402
+ if (
403
+ png.readUInt32BE(16) !== width ||
404
+ png.readUInt32BE(20) !== content_height
405
+ )
406
+ throw new SketchError(
407
+ "The page dimensions changed during capture. Keep the root layout stable while its images load.",
408
+ );
409
+ await checkAssets();
410
+ const thumbWidth = Math.min(width, 480);
411
+ await thumbnail.setViewportSize({
412
+ width: thumbWidth,
413
+ height: Math.ceil((content_height * thumbWidth) / width),
414
+ });
415
+ await thumbnail.setContent(
416
+ `<style>*{margin:0}img{display:block;width:100%}</style><img src="data:image/png;base64,${png.toString("base64")}">`,
417
+ );
418
+ const thumb = await thumbnail.screenshot({ timeout: 15000 });
419
+ return {
420
+ width,
421
+ height,
422
+ content_height,
423
+ elements,
424
+ png_base64: png.toString("base64"),
425
+ thumbnail_base64: thumb.toString("base64"),
426
+ };
427
+ }
428
+ const { source, id, name, sample_keys, plan_subjects } = screen;
429
+ const metadata = { id, name, sample_keys, plan_subjects };
430
+ screens.push({
431
+ ...metadata,
432
+ source_sha256: digest(/** @type {Buffer} */ (files.get(source))),
433
+ desktop: await capture(1280, 800),
434
+ mobile: await capture(390, 844),
435
+ });
436
+ }
437
+ return { version: 1, plan_sha256: digest(planSource), screens };
438
+ } catch (error) {
439
+ if (error instanceof SketchError && screenViewport)
440
+ throw new SketchError(`${screenViewport}: ${error.message}`);
441
+ if (error instanceof errors.TimeoutError && screenViewport)
442
+ throw new SketchError(
443
+ `${screenViewport}: Chrome timed out while ${operation}.`,
444
+ );
445
+ throw error;
446
+ } finally {
447
+ await browser?.close();
448
+ }
449
+ }