mechanica 2.1.0-beta.7 → 2.2.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.
- package/README.md +29 -2
- package/dist/browser.js +2 -0
- package/dist/chunks/{assets-nujjbCx8.js → assets-5a2WdmFg.js} +67 -45
- package/dist/chunks/browser-BCfAv8bW.js +558 -0
- package/dist/chunks/{node-adapter-CSkDXYGO.js → node-adapter-Bm_SloHQ.js} +2 -2
- package/dist/chunks/{rich-text-codec-BSD35k2U.js → rich-text-codec-DCv1X0eZ.js} +8 -2
- package/dist/chunks/{site-DfazSr3_.js → site-BVqx8iKj.js} +1 -1
- package/dist/cli.js +462 -509
- package/dist/editor.css +63 -63
- package/dist/editor.js +5 -4
- package/dist/export.js +13 -5
- package/dist/plugin.js +4 -4
- package/dist/server.js +3 -3
- package/dist/types/cli/args.d.ts +12 -1
- package/dist/types/cli/browser.d.ts +116 -0
- package/dist/types/cli/dev-server.d.ts +13 -0
- package/dist/types/cli/headless.d.ts +25 -16
- package/dist/types/cli/platform/api.d.ts +0 -2
- package/dist/types/cli/platform/credentials.d.ts +22 -0
- package/dist/types/cli/platform/login.d.ts +8 -1
- package/dist/types/cli/platform/session.d.ts +31 -0
- package/dist/types/cli/shot.d.ts +105 -8
- package/package.json +6 -2
package/dist/cli.js
CHANGED
|
@@ -1,40 +1,62 @@
|
|
|
1
|
-
import { t as buildSiteManifest } from "./chunks/site-
|
|
2
|
-
import { J as readImageManifest, K as isDerivedAsset, W as fsAssetStore, X as updateImageManifest, et as withRemoteAssets, it as isRasterImage, nt as analyzeImageBuffer, rt as hasSharp } from "./chunks/rich-text-codec-
|
|
3
|
-
import { a as git, c as
|
|
1
|
+
import { t as buildSiteManifest } from "./chunks/site-BVqx8iKj.js";
|
|
2
|
+
import { J as readImageManifest, K as isDerivedAsset, W as fsAssetStore, X as updateImageManifest, et as withRemoteAssets, it as isRasterImage, nt as analyzeImageBuffer, rt as hasSharp } from "./chunks/rich-text-codec-DCv1X0eZ.js";
|
|
3
|
+
import { _ as request, a as git, c as clearPendingLogin, d as hostOrigin, f as savePendingLogin, g as parseRemoteUrl, h as REMOTE_NAME, i as uploadsIgnored, l as getPendingLogin, m as PlatformError, n as remoteAssetsFor, o as gitAuthEnv, p as saveToken, r as runAssetsPull, s as gitOk, t as pushUploads, u as getToken } from "./chunks/assets-5a2WdmFg.js";
|
|
4
4
|
import { exportBuilt } from "./export.js";
|
|
5
|
+
import { i as openPage, o as findDevServer, t as NavigationError } from "./chunks/browser-BCfAv8bW.js";
|
|
5
6
|
import fs, { readFileSync } from "node:fs";
|
|
6
|
-
import { dirname, join } from "node:path";
|
|
7
|
+
import { dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
7
8
|
import { EDITOR_DIST_DIR, LEGACY_UPLOADS_PREFIX, SITE_MANIFEST_FILE, UPLOADS_PREFIX } from "mechanica-shared";
|
|
8
9
|
import { appendFile, mkdir, readFile, readdir, realpath, rm, writeFile } from "node:fs/promises";
|
|
9
10
|
import os from "node:os";
|
|
10
|
-
import { spawn } from "node:child_process";
|
|
11
11
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
12
12
|
import { build } from "vite";
|
|
13
|
-
import readline from "node:readline";
|
|
14
13
|
//#region src/cli/args.ts
|
|
15
14
|
/** Parse `argv` (without node/script) into a command, positionals and a `--flag[=value]` map. */
|
|
16
|
-
function parseArgs(argv) {
|
|
15
|
+
function parseArgs(argv, options = {}) {
|
|
17
16
|
const [command, ...rest] = argv;
|
|
18
17
|
const args = [];
|
|
19
18
|
const flags = {};
|
|
19
|
+
for (const token of scanArgs(rest, options)) if (token.flag === void 0) args.push(token.value);
|
|
20
|
+
else flags[token.flag] = token.value;
|
|
21
|
+
return {
|
|
22
|
+
command,
|
|
23
|
+
args,
|
|
24
|
+
flags
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Every value a repeatable flag was given, in order — `--section a --section b`
|
|
29
|
+
* → `['a', 'b']`; a bare `--section` contributes `true`. Takes the same `argv`
|
|
30
|
+
* as {@link parseArgs} (command first).
|
|
31
|
+
*/
|
|
32
|
+
function flagValues(argv, name, options = {}) {
|
|
33
|
+
return scanArgs(argv.slice(1), options).filter((token) => token.flag === name).map((token) => token.value);
|
|
34
|
+
}
|
|
35
|
+
function scanArgs(rest, { booleans = [] }) {
|
|
36
|
+
const tokens = [];
|
|
20
37
|
for (let i = 0; i < rest.length; i++) {
|
|
21
38
|
const arg = rest[i];
|
|
22
39
|
if (!arg.startsWith("--")) {
|
|
23
|
-
|
|
40
|
+
tokens.push({ value: arg });
|
|
24
41
|
continue;
|
|
25
42
|
}
|
|
26
43
|
const key = arg.slice(2);
|
|
27
44
|
if (key.includes("=")) {
|
|
28
45
|
const eq = key.indexOf("=");
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
46
|
+
tokens.push({
|
|
47
|
+
flag: key.slice(0, eq),
|
|
48
|
+
value: key.slice(eq + 1)
|
|
49
|
+
});
|
|
50
|
+
} else if (!booleans.includes(key) && rest[i + 1] && !rest[i + 1].startsWith("--")) tokens.push({
|
|
51
|
+
flag: key,
|
|
52
|
+
value: rest[++i]
|
|
53
|
+
});
|
|
54
|
+
else tokens.push({
|
|
55
|
+
flag: key,
|
|
56
|
+
value: true
|
|
57
|
+
});
|
|
32
58
|
}
|
|
33
|
-
return
|
|
34
|
-
command,
|
|
35
|
-
args,
|
|
36
|
-
flags
|
|
37
|
-
};
|
|
59
|
+
return tokens;
|
|
38
60
|
}
|
|
39
61
|
//#endregion
|
|
40
62
|
//#region src/cli/platform/engine-version.ts
|
|
@@ -234,6 +256,89 @@ async function runMigrate(options = {}) {
|
|
|
234
256
|
return changed;
|
|
235
257
|
}
|
|
236
258
|
//#endregion
|
|
259
|
+
//#region src/cli/platform/session.ts
|
|
260
|
+
/** Start a sign-in: the platform makes a request, its codes are kept for this origin. */
|
|
261
|
+
async function startDeviceLogin(origin) {
|
|
262
|
+
const started = await request(origin, "POST", "/api/account/device", { body: { name: `CLI on ${os.hostname()}` } });
|
|
263
|
+
const pending = {
|
|
264
|
+
deviceCode: started.deviceCode,
|
|
265
|
+
userCode: started.userCode,
|
|
266
|
+
verificationUrl: started.verificationUrl,
|
|
267
|
+
expiresAt: new Date(started.expiresAt).toISOString(),
|
|
268
|
+
interval: Math.max(1, Number(started.interval) || 3)
|
|
269
|
+
};
|
|
270
|
+
await savePendingLogin(origin, pending);
|
|
271
|
+
return pending;
|
|
272
|
+
}
|
|
273
|
+
/** What the user is shown: the link, and how long it stays open. */
|
|
274
|
+
function describeDeviceLogin(origin, pending) {
|
|
275
|
+
const minutes = Math.max(1, Math.round((Date.parse(pending.expiresAt) - Date.now()) / 6e4));
|
|
276
|
+
return [
|
|
277
|
+
`To sign in to ${origin}, open this link and approve the request:`,
|
|
278
|
+
"",
|
|
279
|
+
` ${pending.verificationUrl}`,
|
|
280
|
+
"",
|
|
281
|
+
`The link is valid for ${minutes} minute${minutes === 1 ? "" : "s"}.`
|
|
282
|
+
].join("\n");
|
|
283
|
+
}
|
|
284
|
+
/** Ask the platform once whether the request was answered. */
|
|
285
|
+
async function checkDeviceLogin(origin, pending) {
|
|
286
|
+
try {
|
|
287
|
+
const answer = await request(origin, "POST", "/api/account/device/token", { body: { deviceCode: pending.deviceCode } });
|
|
288
|
+
if (answer?.status === "approved" && typeof answer.token === "string") return {
|
|
289
|
+
status: "approved",
|
|
290
|
+
token: answer.token
|
|
291
|
+
};
|
|
292
|
+
if (answer?.status === "denied") return { status: "denied" };
|
|
293
|
+
return { status: "pending" };
|
|
294
|
+
} catch (error) {
|
|
295
|
+
if (error instanceof PlatformError && error.status === 404) return { status: "expired" };
|
|
296
|
+
throw error;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Finish a started sign-in if it was answered: save the token and say who
|
|
301
|
+
* signed in. Null while the request still waits. A denied or expired request
|
|
302
|
+
* is forgotten and reported — the user runs `mechanica login` for a new link.
|
|
303
|
+
*/
|
|
304
|
+
async function completeDeviceLogin(origin, pending) {
|
|
305
|
+
const outcome = await checkDeviceLogin(origin, pending);
|
|
306
|
+
if (outcome.status === "pending") return null;
|
|
307
|
+
await clearPendingLogin(origin);
|
|
308
|
+
if (outcome.status === "denied") throw new Error(`The sign-in request for ${origin} was denied in the browser. Run \`mechanica login\` for a new link.`);
|
|
309
|
+
if (outcome.status === "expired") throw new Error(`The sign-in link for ${origin} has expired (a link is valid for ten minutes). Run \`mechanica login\` for a new link.`);
|
|
310
|
+
const account = await request(origin, "GET", "/api/account", { token: outcome.token });
|
|
311
|
+
const file = await saveToken(origin, outcome.token);
|
|
312
|
+
console.info(`Signed in to ${origin} as ${account.email}`);
|
|
313
|
+
console.info(`Access token saved to ${file}`);
|
|
314
|
+
return outcome.token;
|
|
315
|
+
}
|
|
316
|
+
var sleep$1 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
317
|
+
/** Wait for the approval, asking the platform every `interval` seconds until it comes or the link expires. */
|
|
318
|
+
async function waitForDeviceLogin(origin, pending) {
|
|
319
|
+
for (;;) {
|
|
320
|
+
const token = await completeDeviceLogin(origin, pending);
|
|
321
|
+
if (token) return token;
|
|
322
|
+
await sleep$1(pending.interval * 1e3);
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
/**
|
|
326
|
+
* The token for `origin`: the saved one, or — when `mechanica login` printed
|
|
327
|
+
* a link that has been approved since — the one the platform now hands over.
|
|
328
|
+
* Otherwise an error that says what to do next.
|
|
329
|
+
*/
|
|
330
|
+
async function requireToken(origin) {
|
|
331
|
+
const token = await getToken(origin);
|
|
332
|
+
if (token) return token;
|
|
333
|
+
const pending = await getPendingLogin(origin);
|
|
334
|
+
if (pending) {
|
|
335
|
+
const collected = await completeDeviceLogin(origin, pending);
|
|
336
|
+
if (collected) return collected;
|
|
337
|
+
throw new Error(`Not signed in to ${origin} yet — open ${pending.verificationUrl} and approve the request, then run this command again`);
|
|
338
|
+
}
|
|
339
|
+
throw new Error(`Not logged in to ${origin} — run \`mechanica login\` first`);
|
|
340
|
+
}
|
|
341
|
+
//#endregion
|
|
237
342
|
//#region src/cli/platform/link.ts
|
|
238
343
|
/**
|
|
239
344
|
* `mechanica link <slug>`: attach this project to a site on the platform by
|
|
@@ -317,55 +422,35 @@ async function ignoreUploads(cwd) {
|
|
|
317
422
|
}
|
|
318
423
|
//#endregion
|
|
319
424
|
//#region src/cli/platform/login.ts
|
|
320
|
-
/** Ask one line on the terminal; with `hidden`, the typed characters are not echoed. */
|
|
321
|
-
function prompt(question, hidden = false) {
|
|
322
|
-
return new Promise((resolve) => {
|
|
323
|
-
const rl = readline.createInterface({
|
|
324
|
-
input: process.stdin,
|
|
325
|
-
output: process.stdout,
|
|
326
|
-
terminal: true
|
|
327
|
-
});
|
|
328
|
-
if (hidden) {
|
|
329
|
-
const write = rl._writeToOutput.bind(rl);
|
|
330
|
-
let asked = false;
|
|
331
|
-
rl._writeToOutput = (text) => {
|
|
332
|
-
if (!asked) write(text);
|
|
333
|
-
asked = true;
|
|
334
|
-
};
|
|
335
|
-
}
|
|
336
|
-
rl.question(question, (answer) => {
|
|
337
|
-
rl.close();
|
|
338
|
-
if (hidden) process.stdout.write("\n");
|
|
339
|
-
resolve(answer.trim());
|
|
340
|
-
});
|
|
341
|
-
});
|
|
342
|
-
}
|
|
343
425
|
/**
|
|
344
426
|
* `mechanica login`: sign in to the platform and keep an access token for this
|
|
345
427
|
* machine. With `--token` the given token is stored as is (CI, or a token made
|
|
346
|
-
* in the dashboard)
|
|
428
|
+
* in the dashboard). Otherwise the sign-in happens in the browser (see
|
|
429
|
+
* `session.ts`): a link is printed, and the token arrives once it is approved.
|
|
430
|
+
*
|
|
431
|
+
* In a terminal the command waits for the approval. Without one — a coding
|
|
432
|
+
* agent runs it, and shows its output only once it has ended — it prints the
|
|
433
|
+
* link and returns: the next `mechanica link` / `push` finishes the sign-in.
|
|
434
|
+
* `--wait` / `--no-wait` decide either way.
|
|
347
435
|
*/
|
|
348
436
|
async function runLogin(options) {
|
|
349
437
|
const origin = hostOrigin(options.host);
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
console.info(`
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
const session = await request(origin, "POST", "/api/account/login", { body: {
|
|
357
|
-
login,
|
|
358
|
-
password
|
|
359
|
-
} });
|
|
360
|
-
token = (await request(origin, "POST", "/api/account/tokens", {
|
|
361
|
-
token: session.accessToken,
|
|
362
|
-
body: { name: `CLI on ${os.hostname()}` }
|
|
363
|
-
})).token;
|
|
438
|
+
if (options.token) {
|
|
439
|
+
const account = await request(origin, "GET", "/api/account", { token: options.token });
|
|
440
|
+
const file = await saveToken(origin, options.token);
|
|
441
|
+
console.info(`Logged in to ${origin} as ${account.email}`);
|
|
442
|
+
console.info(`Access token saved to ${file}`);
|
|
443
|
+
return;
|
|
364
444
|
}
|
|
365
|
-
const
|
|
366
|
-
|
|
367
|
-
console.info(
|
|
368
|
-
|
|
445
|
+
const pending = await startDeviceLogin(origin);
|
|
446
|
+
console.info(describeDeviceLogin(origin, pending));
|
|
447
|
+
console.info("");
|
|
448
|
+
if (!(options.wait ?? process.stdin.isTTY === true)) {
|
|
449
|
+
console.info("Once it is approved, run `mechanica link <slug>` or `mechanica push`: the next command finishes the sign-in.\nWorking through a coding agent? Show the link to the person you work for, and go on when they say it is approved.");
|
|
450
|
+
return;
|
|
451
|
+
}
|
|
452
|
+
console.info("Waiting for the approval in the browser… (Ctrl+C to stop; the next `mechanica` command would finish the sign-in)");
|
|
453
|
+
await waitForDeviceLogin(origin, pending);
|
|
369
454
|
}
|
|
370
455
|
//#endregion
|
|
371
456
|
//#region src/cli/platform/bundle-format.ts
|
|
@@ -559,27 +644,23 @@ async function runPush() {
|
|
|
559
644
|
console.info(`\n${branch} is live at ${deploy.url ?? status.url} — ${deploy.pages} page(s)`);
|
|
560
645
|
}
|
|
561
646
|
//#endregion
|
|
562
|
-
//#region src/cli/
|
|
563
|
-
/**
|
|
564
|
-
* Headless-browser plumbing shared by `mechanica shot` and `mechanica thumbs`:
|
|
565
|
-
* dev-server discovery, browser discovery/spawn, and a minimal CDP client.
|
|
566
|
-
*
|
|
567
|
-
* Talks raw CDP over the platform `WebSocket` instead of using an automation
|
|
568
|
-
* library: Playwright/Puppeteer launch handshakes rely on Node-only fd pipes
|
|
569
|
-
* that hang under Bun, and screenshots need only a handful of CDP calls.
|
|
570
|
-
*/
|
|
647
|
+
//#region src/cli/dev-server.ts
|
|
571
648
|
/**
|
|
572
649
|
* Find a dev server to render against: an explicit origin, a running local
|
|
573
650
|
* Mechanica dev server, or an ephemeral one booted from the project's
|
|
574
651
|
* `vite.config.ts` and torn down afterwards.
|
|
652
|
+
*
|
|
653
|
+
* The only browser-side helper that needs Vite, kept out of `headless.ts` so
|
|
654
|
+
* the public `mechanica/browser` entry never pulls it in.
|
|
575
655
|
*/
|
|
576
656
|
async function resolveServer(flag) {
|
|
577
657
|
if (flag) return {
|
|
578
658
|
origin: flag.replace(/\/+$/, ""),
|
|
579
659
|
close: async () => {}
|
|
580
660
|
};
|
|
581
|
-
|
|
582
|
-
|
|
661
|
+
const running = await findDevServer();
|
|
662
|
+
if (running) return {
|
|
663
|
+
origin: running,
|
|
583
664
|
close: async () => {}
|
|
584
665
|
};
|
|
585
666
|
console.info("No running dev server found — starting one…");
|
|
@@ -596,299 +677,11 @@ async function resolveServer(flag) {
|
|
|
596
677
|
close: () => server.close()
|
|
597
678
|
};
|
|
598
679
|
}
|
|
599
|
-
async function isMechanicaServer(origin) {
|
|
600
|
-
try {
|
|
601
|
-
return (await fetch(`${origin}/@mechanica/folders`, { signal: AbortSignal.timeout(1e3) })).ok;
|
|
602
|
-
} catch {
|
|
603
|
-
return false;
|
|
604
|
-
}
|
|
605
|
-
}
|
|
606
|
-
async function setViewport(cdp, sessionId, width, height = 900) {
|
|
607
|
-
await cdp.send("Emulation.setDeviceMetricsOverride", {
|
|
608
|
-
width,
|
|
609
|
-
height,
|
|
610
|
-
deviceScaleFactor: 1,
|
|
611
|
-
mobile: false
|
|
612
|
-
}, sessionId);
|
|
613
|
-
}
|
|
614
|
-
async function evaluateValue(cdp, sessionId, expression) {
|
|
615
|
-
return (await cdp.send("Runtime.evaluate", {
|
|
616
|
-
expression,
|
|
617
|
-
returnByValue: true
|
|
618
|
-
}, sessionId)).result?.value;
|
|
619
|
-
}
|
|
620
|
-
/**
|
|
621
|
-
* Poll an expression on the page until it is `true` or the timeout elapses.
|
|
622
|
-
* Evaluate errors (execution context destroyed mid-navigation) count as "not
|
|
623
|
-
* ready yet" rather than failing the wait.
|
|
624
|
-
*/
|
|
625
|
-
async function waitForCondition(cdp, sessionId, expression, timeout) {
|
|
626
|
-
const deadline = Date.now() + timeout;
|
|
627
|
-
while (Date.now() < deadline) {
|
|
628
|
-
try {
|
|
629
|
-
if (await evaluateValue(cdp, sessionId, expression)) return;
|
|
630
|
-
} catch {}
|
|
631
|
-
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
632
|
-
}
|
|
633
|
-
throw new Error(`Timed out after ${timeout}ms waiting for the page to become ready`);
|
|
634
|
-
}
|
|
635
|
-
/** Wait for web fonts and all images — normal pages have no injected ready flag. */
|
|
636
|
-
async function settlePageMedia(cdp, sessionId) {
|
|
637
|
-
await cdp.send("Runtime.evaluate", {
|
|
638
|
-
expression: `Promise.all([
|
|
639
|
-
document.fonts ? document.fonts.ready : null,
|
|
640
|
-
...[...document.images].map((img) =>
|
|
641
|
-
img.complete ? null : new Promise((done) => { img.onload = done; img.onerror = done })),
|
|
642
|
-
].filter(Boolean)).then(() => true)`,
|
|
643
|
-
awaitPromise: true,
|
|
644
|
-
returnByValue: true
|
|
645
|
-
}, sessionId);
|
|
646
|
-
}
|
|
647
|
-
/** Freeze animations/transitions so captures are deterministic across runs. */
|
|
648
|
-
async function freezeAnimations(cdp, sessionId) {
|
|
649
|
-
await cdp.send("Runtime.evaluate", { expression: `{
|
|
650
|
-
const style = document.createElement('style')
|
|
651
|
-
style.textContent = '*, *::before, *::after { animation: none !important; transition: none !important; caret-color: transparent !important; }'
|
|
652
|
-
document.head.appendChild(style)
|
|
653
|
-
}` }, sessionId);
|
|
654
|
-
}
|
|
655
|
-
/** Chromium refuses to encode arbitrarily tall captures — cap and say so. */
|
|
656
|
-
var MAX_SHOT_HEIGHT = 12e3;
|
|
657
|
-
/** The full document size as a screenshot clip. */
|
|
658
|
-
async function fullPageClip(cdp, sessionId) {
|
|
659
|
-
const metrics = await cdp.send("Page.getLayoutMetrics", {}, sessionId);
|
|
660
|
-
const size = metrics.cssContentSize ?? metrics.contentSize;
|
|
661
|
-
const height = Math.min(size.height, MAX_SHOT_HEIGHT);
|
|
662
|
-
if (height < size.height) console.info(`(page is ${Math.round(size.height)}px tall — clipped to ${MAX_SHOT_HEIGHT}px)`);
|
|
663
|
-
return {
|
|
664
|
-
x: 0,
|
|
665
|
-
y: 0,
|
|
666
|
-
width: size.width,
|
|
667
|
-
height
|
|
668
|
-
};
|
|
669
|
-
}
|
|
670
|
-
/**
|
|
671
|
-
* Spawn a headless Chromium-based browser with a DevTools endpoint and connect
|
|
672
|
-
* to it. Prefers browsers already on the machine (Edge ships with Windows,
|
|
673
|
-
* Chrome is everywhere), so nothing needs downloading.
|
|
674
|
-
*/
|
|
675
|
-
async function launchBrowser(explicitPath) {
|
|
676
|
-
const executable = findBrowserExecutable(explicitPath);
|
|
677
|
-
const userDataDir = fs.mkdtempSync(join(os.tmpdir(), "mechanica-shot-"));
|
|
678
|
-
const child = spawn(executable.path, [
|
|
679
|
-
"--headless=new",
|
|
680
|
-
"--remote-debugging-port=0",
|
|
681
|
-
`--user-data-dir=${userDataDir}`,
|
|
682
|
-
"--no-first-run",
|
|
683
|
-
"--no-default-browser-check",
|
|
684
|
-
"--disable-extensions",
|
|
685
|
-
"--hide-scrollbars",
|
|
686
|
-
"about:blank"
|
|
687
|
-
], { stdio: [
|
|
688
|
-
"ignore",
|
|
689
|
-
"ignore",
|
|
690
|
-
"pipe"
|
|
691
|
-
] });
|
|
692
|
-
const cleanup = async () => {
|
|
693
|
-
const exited = new Promise((resolve) => {
|
|
694
|
-
if (child.exitCode != null) return resolve();
|
|
695
|
-
child.once("exit", () => resolve());
|
|
696
|
-
setTimeout(resolve, 3e3);
|
|
697
|
-
});
|
|
698
|
-
child.kill();
|
|
699
|
-
await exited;
|
|
700
|
-
for (let attempt = 0; attempt < 3; attempt++) try {
|
|
701
|
-
fs.rmSync(userDataDir, {
|
|
702
|
-
recursive: true,
|
|
703
|
-
force: true
|
|
704
|
-
});
|
|
705
|
-
return;
|
|
706
|
-
} catch {
|
|
707
|
-
await new Promise((resolve) => setTimeout(resolve, 300));
|
|
708
|
-
}
|
|
709
|
-
};
|
|
710
|
-
let endpoint;
|
|
711
|
-
try {
|
|
712
|
-
endpoint = await waitForDevtoolsEndpoint(child, 2e4);
|
|
713
|
-
} catch (error) {
|
|
714
|
-
await cleanup();
|
|
715
|
-
throw new Error(`Failed to start ${executable.label} (${executable.path}): ${error instanceof Error ? error.message : error}`);
|
|
716
|
-
}
|
|
717
|
-
const client = await CdpClient.connect(endpoint);
|
|
718
|
-
return {
|
|
719
|
-
client,
|
|
720
|
-
close: async () => {
|
|
721
|
-
await client.send("Browser.close").catch(() => {});
|
|
722
|
-
client.dispose();
|
|
723
|
-
await cleanup();
|
|
724
|
-
}
|
|
725
|
-
};
|
|
726
|
-
}
|
|
727
|
-
/** Read the spawned browser's stderr until it prints its DevTools WebSocket URL. */
|
|
728
|
-
function waitForDevtoolsEndpoint(child, timeout) {
|
|
729
|
-
return new Promise((resolve, reject) => {
|
|
730
|
-
let buffer = "";
|
|
731
|
-
const timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`no DevTools endpoint within ${timeout}ms`)), timeout);
|
|
732
|
-
child.stderr.on("data", (chunk) => {
|
|
733
|
-
buffer += chunk.toString();
|
|
734
|
-
const match = buffer.match(/DevTools listening on (ws:\/\/\S+)/);
|
|
735
|
-
if (match) {
|
|
736
|
-
clearTimeout(timer);
|
|
737
|
-
resolve(match[1]);
|
|
738
|
-
}
|
|
739
|
-
});
|
|
740
|
-
child.on("error", (error) => {
|
|
741
|
-
clearTimeout(timer);
|
|
742
|
-
reject(error);
|
|
743
|
-
});
|
|
744
|
-
child.on("exit", (code) => {
|
|
745
|
-
clearTimeout(timer);
|
|
746
|
-
reject(/* @__PURE__ */ new Error(`browser exited early (code ${code})`));
|
|
747
|
-
});
|
|
748
|
-
});
|
|
749
|
-
}
|
|
750
|
-
/** Find a Chromium-based executable: an explicit path, or a known install location. */
|
|
751
|
-
function findBrowserExecutable(explicitPath) {
|
|
752
|
-
if (explicitPath) {
|
|
753
|
-
if (!fs.existsSync(explicitPath)) throw new Error(`--browser not found: ${explicitPath}`);
|
|
754
|
-
return {
|
|
755
|
-
label: "browser from --browser",
|
|
756
|
-
path: explicitPath
|
|
757
|
-
};
|
|
758
|
-
}
|
|
759
|
-
const candidates = platformBrowserCandidates();
|
|
760
|
-
const found = candidates.find((candidate) => fs.existsSync(candidate.path));
|
|
761
|
-
if (!found) {
|
|
762
|
-
const looked = candidates.map((c) => ` ${c.label}: ${c.path}`).join("\n");
|
|
763
|
-
throw new Error(`No Chromium-based browser found. Looked for:\n${looked}\nInstall Chrome or Edge, or pass --browser <path-to-executable>.`);
|
|
764
|
-
}
|
|
765
|
-
return found;
|
|
766
|
-
}
|
|
767
|
-
function platformBrowserCandidates() {
|
|
768
|
-
if (process.platform === "win32") {
|
|
769
|
-
const programFiles = process.env["ProgramFiles"] ?? "C:\\Program Files";
|
|
770
|
-
const programFilesX86 = process.env["ProgramFiles(x86)"] ?? "C:\\Program Files (x86)";
|
|
771
|
-
const localAppData = process.env["LOCALAPPDATA"] ?? join(os.homedir(), "AppData", "Local");
|
|
772
|
-
return [
|
|
773
|
-
{
|
|
774
|
-
label: "Microsoft Edge",
|
|
775
|
-
path: join(programFilesX86, "Microsoft", "Edge", "Application", "msedge.exe")
|
|
776
|
-
},
|
|
777
|
-
{
|
|
778
|
-
label: "Microsoft Edge",
|
|
779
|
-
path: join(programFiles, "Microsoft", "Edge", "Application", "msedge.exe")
|
|
780
|
-
},
|
|
781
|
-
{
|
|
782
|
-
label: "Google Chrome",
|
|
783
|
-
path: join(programFiles, "Google", "Chrome", "Application", "chrome.exe")
|
|
784
|
-
},
|
|
785
|
-
{
|
|
786
|
-
label: "Google Chrome",
|
|
787
|
-
path: join(localAppData, "Google", "Chrome", "Application", "chrome.exe")
|
|
788
|
-
}
|
|
789
|
-
];
|
|
790
|
-
}
|
|
791
|
-
if (process.platform === "darwin") return [
|
|
792
|
-
{
|
|
793
|
-
label: "Google Chrome",
|
|
794
|
-
path: "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
|
|
795
|
-
},
|
|
796
|
-
{
|
|
797
|
-
label: "Microsoft Edge",
|
|
798
|
-
path: "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"
|
|
799
|
-
},
|
|
800
|
-
{
|
|
801
|
-
label: "Chromium",
|
|
802
|
-
path: "/Applications/Chromium.app/Contents/MacOS/Chromium"
|
|
803
|
-
}
|
|
804
|
-
];
|
|
805
|
-
return [
|
|
806
|
-
{
|
|
807
|
-
label: "Google Chrome",
|
|
808
|
-
path: "/usr/bin/google-chrome"
|
|
809
|
-
},
|
|
810
|
-
{
|
|
811
|
-
label: "Chromium",
|
|
812
|
-
path: "/usr/bin/chromium"
|
|
813
|
-
},
|
|
814
|
-
{
|
|
815
|
-
label: "Chromium",
|
|
816
|
-
path: "/usr/bin/chromium-browser"
|
|
817
|
-
},
|
|
818
|
-
{
|
|
819
|
-
label: "Microsoft Edge",
|
|
820
|
-
path: "/usr/bin/microsoft-edge"
|
|
821
|
-
}
|
|
822
|
-
];
|
|
823
|
-
}
|
|
824
|
-
/**
|
|
825
|
-
* A minimal Chrome DevTools Protocol client over the platform `WebSocket`
|
|
826
|
-
* (native in Bun and Node ≥ 22): request/response matching by id, plus event
|
|
827
|
-
* fan-out. Flat session mode — pass a `sessionId` to address a page target.
|
|
828
|
-
*/
|
|
829
|
-
var CdpClient = class CdpClient {
|
|
830
|
-
ws;
|
|
831
|
-
nextId = 1;
|
|
832
|
-
pending = /* @__PURE__ */ new Map();
|
|
833
|
-
listeners = [];
|
|
834
|
-
constructor(ws) {
|
|
835
|
-
this.ws = ws;
|
|
836
|
-
ws.onmessage = (event) => this.onMessage(String(event.data));
|
|
837
|
-
ws.onclose = () => {
|
|
838
|
-
for (const { reject } of this.pending.values()) reject(/* @__PURE__ */ new Error("CDP connection closed"));
|
|
839
|
-
this.pending.clear();
|
|
840
|
-
};
|
|
841
|
-
}
|
|
842
|
-
static connect(url) {
|
|
843
|
-
return new Promise((resolve, reject) => {
|
|
844
|
-
const ws = new WebSocket(url);
|
|
845
|
-
const timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`CDP connect timeout: ${url}`)), 1e4);
|
|
846
|
-
ws.onopen = () => {
|
|
847
|
-
clearTimeout(timer);
|
|
848
|
-
resolve(new CdpClient(ws));
|
|
849
|
-
};
|
|
850
|
-
ws.onerror = () => {
|
|
851
|
-
clearTimeout(timer);
|
|
852
|
-
reject(/* @__PURE__ */ new Error(`CDP connection failed: ${url}`));
|
|
853
|
-
};
|
|
854
|
-
});
|
|
855
|
-
}
|
|
856
|
-
send(method, params = {}, sessionId) {
|
|
857
|
-
const id = this.nextId++;
|
|
858
|
-
this.ws.send(JSON.stringify({
|
|
859
|
-
id,
|
|
860
|
-
method,
|
|
861
|
-
params,
|
|
862
|
-
...sessionId ? { sessionId } : {}
|
|
863
|
-
}));
|
|
864
|
-
return new Promise((resolve, reject) => this.pending.set(id, {
|
|
865
|
-
resolve,
|
|
866
|
-
reject
|
|
867
|
-
}));
|
|
868
|
-
}
|
|
869
|
-
onEvent(listener) {
|
|
870
|
-
this.listeners.push(listener);
|
|
871
|
-
}
|
|
872
|
-
dispose() {
|
|
873
|
-
try {
|
|
874
|
-
this.ws.close();
|
|
875
|
-
} catch {}
|
|
876
|
-
}
|
|
877
|
-
onMessage(raw) {
|
|
878
|
-
const message = JSON.parse(raw);
|
|
879
|
-
if (typeof message.id === "number") {
|
|
880
|
-
const pending = this.pending.get(message.id);
|
|
881
|
-
if (!pending) return;
|
|
882
|
-
this.pending.delete(message.id);
|
|
883
|
-
if (message.error) pending.reject(/* @__PURE__ */ new Error(`${message.error.message ?? "CDP error"}`));
|
|
884
|
-
else pending.resolve(message.result ?? {});
|
|
885
|
-
return;
|
|
886
|
-
}
|
|
887
|
-
if (typeof message.method === "string") for (const listener of this.listeners) listener(message.method, message.params ?? {}, message.sessionId);
|
|
888
|
-
}
|
|
889
|
-
};
|
|
890
680
|
//#endregion
|
|
891
681
|
//#region src/cli/shot.ts
|
|
682
|
+
var USAGE = "Usage: mechanica shot <blockId | /page/path | URL | file.html> [--page </path>] [--data <json|@file>] [--width 1440,768] [--section <css>]… [--scroll <px[,px…]>] [--no-freeze] [--full] [--out <path>] [--server <url>] [--browser <path>]";
|
|
683
|
+
/** Readiness flag of the standalone block preview route. */
|
|
684
|
+
var PREVIEW_READY = "window.__MECHANICA_PREVIEW_READY__ === true";
|
|
892
685
|
/** Parse a `--width` value into a list of positive integers. Defaults to `[1440]`. */
|
|
893
686
|
function parseWidths(value) {
|
|
894
687
|
if (!value) return [1440];
|
|
@@ -896,6 +689,13 @@ function parseWidths(value) {
|
|
|
896
689
|
if (widths.length === 0 || widths.some((w) => !Number.isFinite(w) || w <= 0)) throw new Error(`Invalid --width value "${value}" — expected e.g. 1440 or 1440,768,390`);
|
|
897
690
|
return widths;
|
|
898
691
|
}
|
|
692
|
+
/** Parse a `--scroll` value (px from the top, comma-separated). Undefined when absent. */
|
|
693
|
+
function parseScrolls(value) {
|
|
694
|
+
if (value === void 0) return void 0;
|
|
695
|
+
const parts = value.split(",").map((part) => part.trim());
|
|
696
|
+
if (parts.some((part) => !/^\d+$/.test(part))) throw new Error(`Invalid --scroll value "${value}" — expected pixels from the top, e.g. 800 or 0,800,1600`);
|
|
697
|
+
return parts.map(Number);
|
|
698
|
+
}
|
|
899
699
|
/** Resolve `--data`: inline JSON or `@file`, validated to a JSON object. */
|
|
900
700
|
function resolveDataArg(value) {
|
|
901
701
|
if (!value) return void 0;
|
|
@@ -915,13 +715,22 @@ function previewUrl(origin, blockId, data) {
|
|
|
915
715
|
const query = data ? `?data=${encodeURIComponent(JSON.stringify(data))}` : "";
|
|
916
716
|
return `${base}/@mechanica/preview/${encodeURIComponent(blockId)}${query}`;
|
|
917
717
|
}
|
|
918
|
-
/**
|
|
919
|
-
|
|
920
|
-
|
|
718
|
+
/**
|
|
719
|
+
* Resolve the output PNG path for one capture. `variant` (`-<section>`,
|
|
720
|
+
* `-y<scroll>`) is always part of the name; the `-w<width>` suffix only when
|
|
721
|
+
* shooting several widths. An `--out` ending in `.png` is a file name, any
|
|
722
|
+
* other value a directory.
|
|
723
|
+
*/
|
|
724
|
+
function outputPath(out, name, width, multi, variant = "") {
|
|
725
|
+
const suffix = `${variant}${multi ? `-w${width}` : ""}`;
|
|
921
726
|
if (!out) return join(".mech", "shots", `${name}${suffix}.png`);
|
|
922
|
-
if (out.endsWith(".png")) return
|
|
727
|
+
if (out.endsWith(".png")) return suffix ? out.replace(/\.png$/, `${suffix}.png`) : out;
|
|
923
728
|
return join(out, `${name}${suffix}.png`);
|
|
924
729
|
}
|
|
730
|
+
/** The name suffix of one capture: `-<section slug>` and/or `-y<scroll>`. */
|
|
731
|
+
function shotVariant(sectionSlug, scroll) {
|
|
732
|
+
return `${sectionSlug ? `-${sectionSlug}` : ""}${scroll !== void 0 ? `-y${scroll}` : ""}`;
|
|
733
|
+
}
|
|
925
734
|
/** `/` → `index`, `/docs/getting-started` → `docs-getting-started`. */
|
|
926
735
|
function pageSlug(path) {
|
|
927
736
|
const trimmed = path.replace(/^\/+|\/+$/g, "");
|
|
@@ -931,98 +740,250 @@ function pageSlug(path) {
|
|
|
931
740
|
function normalizePagePath(path) {
|
|
932
741
|
return "/" + path.trim().replace(/^\/+|\/+$/g, "");
|
|
933
742
|
}
|
|
934
|
-
|
|
743
|
+
/** Lowercase letters and digits (any script) joined by single dashes. */
|
|
744
|
+
function slugify(value) {
|
|
745
|
+
return value.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/g, "");
|
|
746
|
+
}
|
|
747
|
+
/**
|
|
748
|
+
* One file-name slug per `--section` selector: `#hero` → `hero`,
|
|
749
|
+
* `.stage > .pin` → `stage-pin`. A selector with no letters or digits becomes
|
|
750
|
+
* `section`; repeats get `-2`, `-3`…
|
|
751
|
+
*/
|
|
752
|
+
function sectionSlugs(selectors) {
|
|
753
|
+
const seen = /* @__PURE__ */ new Map();
|
|
754
|
+
return selectors.map((selector) => {
|
|
755
|
+
const base = slugify(selector).slice(0, 40).replace(/-+$/, "") || "section";
|
|
756
|
+
const count = (seen.get(base) ?? 0) + 1;
|
|
757
|
+
seen.set(base, count);
|
|
758
|
+
return count === 1 ? base : `${base}-${count}`;
|
|
759
|
+
});
|
|
760
|
+
}
|
|
761
|
+
var WINDOWS_DRIVE_PATH = /^[a-zA-Z]:[\\/]/;
|
|
762
|
+
var RELATIVE_PATH = /^\.\.?[\\/]/;
|
|
763
|
+
var HTML_FILE = /\.html?$/i;
|
|
935
764
|
/**
|
|
936
|
-
*
|
|
937
|
-
*
|
|
938
|
-
*
|
|
939
|
-
*
|
|
940
|
-
*
|
|
765
|
+
* Classify a `shot` target, in this order:
|
|
766
|
+
* - `--page </path>` → that page;
|
|
767
|
+
* - `http://…` / `https://…` → a URL, opened as is;
|
|
768
|
+
* - `file://…`, a Windows drive path (`C:\…`), a `./` or `../` path, or any
|
|
769
|
+
* path ending in `.html`/`.htm` → a local file (relative to `cwd`);
|
|
770
|
+
* - anything else starting with `/` → a page of this project;
|
|
771
|
+
* - anything else → a block id.
|
|
772
|
+
*/
|
|
773
|
+
function classifyTarget(target, page, cwd = process.cwd()) {
|
|
774
|
+
if (page) return {
|
|
775
|
+
kind: "page",
|
|
776
|
+
path: normalizePagePath(page)
|
|
777
|
+
};
|
|
778
|
+
const value = target?.trim();
|
|
779
|
+
if (!value) throw new Error(USAGE);
|
|
780
|
+
if (/^https?:\/\//i.test(value)) return {
|
|
781
|
+
kind: "url",
|
|
782
|
+
url: parseUrl(value)
|
|
783
|
+
};
|
|
784
|
+
if (/^file:\/\//i.test(value)) {
|
|
785
|
+
const url = parseUrl(value);
|
|
786
|
+
return {
|
|
787
|
+
kind: "file",
|
|
788
|
+
url,
|
|
789
|
+
file: filePathOf(url)
|
|
790
|
+
};
|
|
791
|
+
}
|
|
792
|
+
if (WINDOWS_DRIVE_PATH.test(value) || RELATIVE_PATH.test(value) || HTML_FILE.test(value)) {
|
|
793
|
+
const file = resolve(cwd, value);
|
|
794
|
+
return {
|
|
795
|
+
kind: "file",
|
|
796
|
+
url: pathToFileURL(file).href,
|
|
797
|
+
file
|
|
798
|
+
};
|
|
799
|
+
}
|
|
800
|
+
if (value.startsWith("/")) return {
|
|
801
|
+
kind: "page",
|
|
802
|
+
path: normalizePagePath(value)
|
|
803
|
+
};
|
|
804
|
+
return {
|
|
805
|
+
kind: "block",
|
|
806
|
+
blockId: value
|
|
807
|
+
};
|
|
808
|
+
}
|
|
809
|
+
function parseUrl(value) {
|
|
810
|
+
try {
|
|
811
|
+
return new URL(value).href;
|
|
812
|
+
} catch {
|
|
813
|
+
throw new Error(`Invalid URL "${value}"`);
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
function filePathOf(url) {
|
|
817
|
+
try {
|
|
818
|
+
return fileURLToPath(url);
|
|
819
|
+
} catch {
|
|
820
|
+
return;
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
/**
|
|
824
|
+
* Default output name of a URL or file shot:
|
|
825
|
+
* - a URL → its host (no `www.`, port appended) and path, extension dropped:
|
|
826
|
+
* `https://example.com/business/evolve` → `example-com-business-evolve`;
|
|
827
|
+
* - a file → its path relative to `cwd` (or its last three path segments when
|
|
828
|
+
* it lies outside), extension dropped: `design/evolve-level/index.html` →
|
|
829
|
+
* `design-evolve-level-index`.
|
|
830
|
+
*/
|
|
831
|
+
function foreignShotName(target, cwd = process.cwd()) {
|
|
832
|
+
if (target.kind === "url") {
|
|
833
|
+
const url = new URL(target.url);
|
|
834
|
+
return slugify(`${url.hostname.replace(/^www\./, "") + (url.port ? `-${url.port}` : "")}/${stripExtension(url.pathname)}`) || "shot";
|
|
835
|
+
}
|
|
836
|
+
if (target.kind !== "file") throw new Error(`Not a URL or file target: ${target.kind}`);
|
|
837
|
+
const file = target.file ?? decodeURIComponent(new URL(target.url).pathname);
|
|
838
|
+
const rel = relative(cwd, file);
|
|
839
|
+
const inside = rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
|
|
840
|
+
const segments = (inside ? rel : file).split(/[\\/]+/).filter(Boolean);
|
|
841
|
+
return slugify(stripExtension((inside ? segments : segments.slice(-3)).join("/"))) || "shot";
|
|
842
|
+
}
|
|
843
|
+
function stripExtension(path) {
|
|
844
|
+
return path.replace(/\.[^./\\]+$/, "");
|
|
845
|
+
}
|
|
846
|
+
/**
|
|
847
|
+
* How each capture is framed: `--section` boxes, else `--full` (whole
|
|
848
|
+
* document), else the viewport when scrolling (so sticky/pinned states are
|
|
849
|
+
* what's in the picture), else the block element for block shots and the
|
|
850
|
+
* whole document for pages, URLs and files.
|
|
851
|
+
*/
|
|
852
|
+
function captureMode(kind, flags) {
|
|
853
|
+
if (flags.section) return "section";
|
|
854
|
+
if (flags.full) return "full";
|
|
855
|
+
if (flags.scroll) return "viewport";
|
|
856
|
+
return kind === "block" ? "block" : "full";
|
|
857
|
+
}
|
|
858
|
+
/** Resolve and validate a `shot` invocation without touching a browser or a server. */
|
|
859
|
+
function planShot(target, options = {}, cwd = process.cwd()) {
|
|
860
|
+
const shotTarget = classifyTarget(target, options.page, cwd);
|
|
861
|
+
const isBlock = shotTarget.kind === "block";
|
|
862
|
+
if (!isBlock && options.data) throw new Error("--data applies to block shots only");
|
|
863
|
+
const selectors = options.section ?? [];
|
|
864
|
+
if (selectors.length && isBlock) throw new Error("--section applies to page, URL and file shots — a block shot is already clipped to its block");
|
|
865
|
+
if (selectors.some((selector) => !selector.trim())) throw new Error("--section needs a CSS selector, e.g. --section \"#hero\"");
|
|
866
|
+
const slugs = sectionSlugs(selectors);
|
|
867
|
+
const scrolls = parseScrolls(options.scroll);
|
|
868
|
+
return {
|
|
869
|
+
target: shotTarget,
|
|
870
|
+
name: shotTarget.kind === "block" ? shotTarget.blockId : shotTarget.kind === "page" ? `page-${pageSlug(shotTarget.path)}` : foreignShotName(shotTarget, cwd),
|
|
871
|
+
widths: parseWidths(options.width),
|
|
872
|
+
scrolls,
|
|
873
|
+
sections: selectors.map((selector, index) => ({
|
|
874
|
+
selector: selector.trim(),
|
|
875
|
+
slug: slugs[index]
|
|
876
|
+
})),
|
|
877
|
+
data: resolveDataArg(options.data),
|
|
878
|
+
mode: captureMode(shotTarget.kind, {
|
|
879
|
+
section: selectors.length > 0,
|
|
880
|
+
full: options.full,
|
|
881
|
+
scroll: !!scrolls
|
|
882
|
+
}),
|
|
883
|
+
freeze: !options.noFreeze
|
|
884
|
+
};
|
|
885
|
+
}
|
|
886
|
+
/**
|
|
887
|
+
* `mechanica shot <target>` — render one block through the dev preview route,
|
|
888
|
+
* a whole page (editor overlay stripped), or a foreign document (any URL, or
|
|
889
|
+
* a local `.html` file such as a design handoff) in a headless Chromium and
|
|
890
|
+
* write PNG screenshot(s): per width, per scroll offset, per `--section`.
|
|
891
|
+
* Made for agent loops: prints the image paths plus any console/render errors,
|
|
892
|
+
* and fails loudly when the block or page failed to render.
|
|
941
893
|
*/
|
|
942
894
|
async function runShot(target, options = {}) {
|
|
943
|
-
const
|
|
944
|
-
const
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
const data = resolveDataArg(options.data);
|
|
950
|
-
const server = await resolveServer(options.server);
|
|
951
|
-
let browser;
|
|
895
|
+
const plan = planShot(target, options);
|
|
896
|
+
const shotTarget = plan.target;
|
|
897
|
+
if (shotTarget.kind === "file" && shotTarget.file) checkLocalFile(shotTarget.file, target);
|
|
898
|
+
const local = shotTarget.kind === "block" || shotTarget.kind === "page";
|
|
899
|
+
const server = local ? await resolveServer(options.server) : void 0;
|
|
900
|
+
let page;
|
|
952
901
|
try {
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
const { sessionId } = await cdp.send("Target.attachToTarget", {
|
|
957
|
-
targetId,
|
|
958
|
-
flatten: true
|
|
902
|
+
page = await openPage(void 0, {
|
|
903
|
+
width: plan.widths[0],
|
|
904
|
+
browser: options.browser
|
|
959
905
|
});
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
}
|
|
970
|
-
});
|
|
971
|
-
await cdp.send("Runtime.enable", {}, sessionId);
|
|
972
|
-
await cdp.send("Page.enable", {}, sessionId);
|
|
973
|
-
await setViewport(cdp, sessionId, widths[0]);
|
|
974
|
-
await cdp.send("Emulation.setEmulatedMedia", { features: [{
|
|
975
|
-
name: "prefers-reduced-motion",
|
|
976
|
-
value: "reduce"
|
|
977
|
-
}] }, sessionId);
|
|
978
|
-
if (pagePath) await ensurePageExists(server.origin, pagePath);
|
|
979
|
-
const url = pagePath ? `${server.origin}${pagePath}?mechanica-shot=1` : previewUrl(server.origin, blockId, data);
|
|
980
|
-
const navigation = await cdp.send("Page.navigate", { url }, sessionId);
|
|
981
|
-
if (navigation.errorText) throw new Error(`Failed to open ${url}: ${navigation.errorText} (is this a Mechanica project?)`);
|
|
982
|
-
let previewError = null;
|
|
983
|
-
if (pagePath) {
|
|
984
|
-
await waitForCondition(cdp, sessionId, "document.readyState === 'complete'", 15e3);
|
|
985
|
-
await settlePageMedia(cdp, sessionId);
|
|
986
|
-
} else {
|
|
987
|
-
await waitForCondition(cdp, sessionId, "window.__MECHANICA_PREVIEW_READY__ === true", 15e3);
|
|
988
|
-
previewError = await evaluateValue(cdp, sessionId, "window.__MECHANICA_PREVIEW_ERROR__ ?? null");
|
|
906
|
+
if (shotTarget.kind === "page") await ensurePageExists(server.origin, shotTarget.path);
|
|
907
|
+
const url = shotUrl(shotTarget, server, plan.data);
|
|
908
|
+
try {
|
|
909
|
+
await page.goto(url, shotTarget.kind === "block" ? {
|
|
910
|
+
ready: PREVIEW_READY,
|
|
911
|
+
settle: false
|
|
912
|
+
} : {});
|
|
913
|
+
} catch (error) {
|
|
914
|
+
if (!(error instanceof NavigationError)) throw error;
|
|
915
|
+
throw new Error(local ? `${error.message} (is this a Mechanica project?)` : error.message);
|
|
989
916
|
}
|
|
990
|
-
await
|
|
917
|
+
const previewError = shotTarget.kind === "block" ? await page.evaluate("window.__MECHANICA_PREVIEW_ERROR__ ?? null") : null;
|
|
918
|
+
if (plan.freeze && !plan.scrolls) await page.freezeAnimations();
|
|
991
919
|
const outputs = [];
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
await
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
920
|
+
const failures = [];
|
|
921
|
+
for (const width of plan.widths) {
|
|
922
|
+
await page.setViewport(width);
|
|
923
|
+
await page.nextFrame();
|
|
924
|
+
for (const scroll of plan.scrolls ?? [void 0]) {
|
|
925
|
+
if (scroll !== void 0) {
|
|
926
|
+
if (plan.freeze) await page.unfreezeAnimations();
|
|
927
|
+
const reached = await page.scrollTo(scroll);
|
|
928
|
+
if (reached + 1 < scroll) console.info(`(at ${width}px the page scrolls only to ${Math.round(reached)}px)`);
|
|
929
|
+
await page.settle();
|
|
930
|
+
if (plan.freeze) await page.freezeAnimations();
|
|
931
|
+
}
|
|
932
|
+
for (const section of plan.sections.length ? plan.sections : [void 0]) {
|
|
933
|
+
const out = outputPath(options.out, plan.name, width, plan.widths.length > 1, shotVariant(section?.slug, scroll));
|
|
934
|
+
let png;
|
|
935
|
+
try {
|
|
936
|
+
png = await capture(page, plan.mode, section?.selector, previewError);
|
|
937
|
+
} catch (error) {
|
|
938
|
+
if (!section) throw error;
|
|
939
|
+
const where = `at ${width}px` + (scroll !== void 0 ? `, scrolled to ${scroll}px` : "");
|
|
940
|
+
failures.push(`--section "${section.selector}" ${where}: ${error instanceof Error ? error.message : error}`);
|
|
941
|
+
continue;
|
|
942
|
+
}
|
|
943
|
+
await mkdir(dirname(out), { recursive: true });
|
|
944
|
+
fs.writeFileSync(out, png);
|
|
945
|
+
outputs.push(out);
|
|
1014
946
|
}
|
|
1015
|
-
}
|
|
1016
|
-
fs.writeFileSync(out, Buffer.from(shot.data, "base64"));
|
|
1017
|
-
outputs.push(out);
|
|
947
|
+
}
|
|
1018
948
|
}
|
|
1019
|
-
for (const line of
|
|
949
|
+
for (const line of page.messages) console.info(line);
|
|
1020
950
|
for (const out of outputs) console.info(`✓ ${out}`);
|
|
1021
951
|
if (previewError) throw new Error(`Block preview failed: ${previewError}`);
|
|
1022
|
-
if (
|
|
952
|
+
if (shotTarget.kind === "page" && page.messages.some((line) => line.startsWith("[pageerror]"))) throw new Error("The page threw while rendering — see the [pageerror] output above");
|
|
953
|
+
if (failures.length === 1) throw new Error(failures[0]);
|
|
954
|
+
if (failures.length) {
|
|
955
|
+
for (const failure of failures) console.error(`✗ ${failure}`);
|
|
956
|
+
throw new Error(`${failures.length} section captures failed — see the ✗ lines above`);
|
|
957
|
+
}
|
|
1023
958
|
} finally {
|
|
1024
|
-
await
|
|
1025
|
-
await server
|
|
959
|
+
await page?.close();
|
|
960
|
+
await server?.close();
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
/** A local target must be an existing file — a directory would render as a file listing. */
|
|
964
|
+
function checkLocalFile(file, raw) {
|
|
965
|
+
const stat = fs.statSync(file, { throwIfNoEntry: false });
|
|
966
|
+
if (stat?.isFile()) return;
|
|
967
|
+
const problem = stat ? `${file} is a directory, not an HTML file` : `File not found: ${file}`;
|
|
968
|
+
const msys = process.env.MSYSTEM && !HTML_FILE.test(raw) && WINDOWS_DRIVE_PATH.test(raw);
|
|
969
|
+
throw new Error(msys ? `${problem}. If you meant a page path, Git Bash rewrote it: write it with two slashes (//about) or set MSYS_NO_PATHCONV=1` : problem);
|
|
970
|
+
}
|
|
971
|
+
function shotUrl(target, server, data) {
|
|
972
|
+
switch (target.kind) {
|
|
973
|
+
case "block": return previewUrl(server.origin, target.blockId, data);
|
|
974
|
+
case "page": return `${server.origin}${target.path}?mechanica-shot=1`;
|
|
975
|
+
default: return target.url;
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
async function capture(page, mode, selector, previewError) {
|
|
979
|
+
switch (mode) {
|
|
980
|
+
case "section": return page.screenshot({ section: selector });
|
|
981
|
+
case "viewport": return page.screenshot();
|
|
982
|
+
case "full": return page.screenshot({ full: true });
|
|
983
|
+
case "block": {
|
|
984
|
+
const clip = previewError ? null : await page.sectionClip("[data-block-id]").catch(() => null);
|
|
985
|
+
return page.screenshot(clip ? { clip } : { full: true });
|
|
986
|
+
}
|
|
1026
987
|
}
|
|
1027
988
|
}
|
|
1028
989
|
/** Fail early with the list of real pages instead of shooting an empty 200. */
|
|
@@ -1072,7 +1033,7 @@ function orphanThumbs(files, slugs) {
|
|
|
1072
1033
|
async function runThumbs(prefix, options = {}) {
|
|
1073
1034
|
const normalizedPrefix = prefix ? normalizePagePath(prefix) : void 0;
|
|
1074
1035
|
const server = await resolveServer(options.server);
|
|
1075
|
-
let
|
|
1036
|
+
let tab;
|
|
1076
1037
|
try {
|
|
1077
1038
|
const listed = await fetch(`${server.origin}/@mechanica/pages`);
|
|
1078
1039
|
if (!listed.ok) throw new Error(`Could not list pages (${listed.status}) — is this a Mechanica project?`);
|
|
@@ -1084,43 +1045,29 @@ async function runThumbs(prefix, options = {}) {
|
|
|
1084
1045
|
}
|
|
1085
1046
|
const outDir = options.out ?? join(".mech", "thumbs");
|
|
1086
1047
|
await mkdir(outDir, { recursive: true });
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
targetId,
|
|
1092
|
-
flatten: true
|
|
1048
|
+
tab = await openPage(void 0, {
|
|
1049
|
+
width: CAPTURE_WIDTH,
|
|
1050
|
+
height: VIEWPORT_HEIGHT,
|
|
1051
|
+
browser: options.browser
|
|
1093
1052
|
});
|
|
1094
|
-
await cdp.send("Page.enable", {}, sessionId);
|
|
1095
|
-
await cdp.send("Runtime.enable", {}, sessionId);
|
|
1096
|
-
await setViewport(cdp, sessionId, CAPTURE_WIDTH, VIEWPORT_HEIGHT);
|
|
1097
|
-
await cdp.send("Emulation.setEmulatedMedia", { features: [{
|
|
1098
|
-
name: "prefers-reduced-motion",
|
|
1099
|
-
value: "reduce"
|
|
1100
|
-
}] }, sessionId);
|
|
1101
1053
|
const failures = [];
|
|
1102
1054
|
for (const page of targets) try {
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
await
|
|
1106
|
-
await settlePageMedia(cdp, sessionId);
|
|
1107
|
-
await freezeAnimations(cdp, sessionId);
|
|
1108
|
-
const metrics = await cdp.send("Page.getLayoutMetrics", {}, sessionId);
|
|
1055
|
+
await tab.goto(`${server.origin}${page.path}?mechanica-shot=1`);
|
|
1056
|
+
await tab.freezeAnimations();
|
|
1057
|
+
const metrics = await tab.send("Page.getLayoutMetrics");
|
|
1109
1058
|
const contentSize = metrics.cssContentSize ?? metrics.contentSize;
|
|
1110
1059
|
const height = Math.min(Math.ceil(contentSize.height), MAX_CAPTURE_HEIGHT);
|
|
1111
|
-
const
|
|
1112
|
-
format: "png",
|
|
1113
|
-
captureBeyondViewport: true,
|
|
1060
|
+
const png = await tab.screenshot({
|
|
1114
1061
|
clip: {
|
|
1115
1062
|
x: 0,
|
|
1116
1063
|
y: 0,
|
|
1117
1064
|
width: CAPTURE_WIDTH,
|
|
1118
|
-
height
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
}
|
|
1065
|
+
height
|
|
1066
|
+
},
|
|
1067
|
+
scale: THUMB_WIDTH / CAPTURE_WIDTH
|
|
1068
|
+
});
|
|
1122
1069
|
const out = join(outDir, `${pageSlug(page.path)}.png`);
|
|
1123
|
-
fs.writeFileSync(out,
|
|
1070
|
+
fs.writeFileSync(out, png);
|
|
1124
1071
|
console.info(`✓ ${page.path} → ${out}`);
|
|
1125
1072
|
} catch (error) {
|
|
1126
1073
|
failures.push(page.path);
|
|
@@ -1135,7 +1082,7 @@ async function runThumbs(prefix, options = {}) {
|
|
|
1135
1082
|
}
|
|
1136
1083
|
if (failures.length) throw new Error(`Failed to render ${failures.length} page(s): ${failures.join(", ")}`);
|
|
1137
1084
|
} finally {
|
|
1138
|
-
await
|
|
1085
|
+
await tab?.close();
|
|
1139
1086
|
await server.close();
|
|
1140
1087
|
}
|
|
1141
1088
|
}
|
|
@@ -1153,7 +1100,7 @@ var BLOCK_THUMB_WIDTH = 240;
|
|
|
1153
1100
|
*/
|
|
1154
1101
|
async function runBlockThumbs(filter, options = {}) {
|
|
1155
1102
|
const server = await resolveServer(options.server);
|
|
1156
|
-
let
|
|
1103
|
+
let tab;
|
|
1157
1104
|
try {
|
|
1158
1105
|
const listed = await fetch(`${server.origin}/@mechanica/blocks`);
|
|
1159
1106
|
if (!listed.ok) throw new Error(`Could not list blocks (${listed.status}) — is this a Mechanica project?`);
|
|
@@ -1165,44 +1112,34 @@ async function runBlockThumbs(filter, options = {}) {
|
|
|
1165
1112
|
}
|
|
1166
1113
|
const outDir = options.out ?? join(".mech", "thumbs", "blocks");
|
|
1167
1114
|
await mkdir(outDir, { recursive: true });
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
targetId,
|
|
1173
|
-
flatten: true
|
|
1115
|
+
tab = await openPage(void 0, {
|
|
1116
|
+
width: BLOCK_CAPTURE_WIDTH,
|
|
1117
|
+
height: BLOCK_MAX_HEIGHT,
|
|
1118
|
+
browser: options.browser
|
|
1174
1119
|
});
|
|
1175
|
-
await cdp.send("Page.enable", {}, sessionId);
|
|
1176
|
-
await cdp.send("Runtime.enable", {}, sessionId);
|
|
1177
|
-
await setViewport(cdp, sessionId, BLOCK_CAPTURE_WIDTH, BLOCK_MAX_HEIGHT);
|
|
1178
|
-
await cdp.send("Emulation.setEmulatedMedia", { features: [{
|
|
1179
|
-
name: "prefers-reduced-motion",
|
|
1180
|
-
value: "reduce"
|
|
1181
|
-
}] }, sessionId);
|
|
1182
1120
|
const failures = [];
|
|
1183
1121
|
for (const block of targets) try {
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1122
|
+
await tab.goto(previewUrl(server.origin, block.id), {
|
|
1123
|
+
ready: PREVIEW_READY,
|
|
1124
|
+
settle: false
|
|
1125
|
+
});
|
|
1126
|
+
const previewError = await tab.evaluate("window.__MECHANICA_PREVIEW_ERROR__ ?? null");
|
|
1188
1127
|
if (previewError) throw new Error(previewError);
|
|
1189
|
-
await
|
|
1190
|
-
await freezeAnimations(
|
|
1191
|
-
const measured = await
|
|
1128
|
+
await tab.settle();
|
|
1129
|
+
await tab.freezeAnimations();
|
|
1130
|
+
const measured = await tab.evaluate(`document.querySelector('[data-block-id]')?.getBoundingClientRect().height ?? 0`);
|
|
1192
1131
|
const height = Math.min(BLOCK_MAX_HEIGHT, Math.max(BLOCK_MIN_HEIGHT, Math.ceil(measured)));
|
|
1193
|
-
const
|
|
1194
|
-
format: "png",
|
|
1195
|
-
captureBeyondViewport: true,
|
|
1132
|
+
const png = await tab.screenshot({
|
|
1196
1133
|
clip: {
|
|
1197
1134
|
x: 0,
|
|
1198
1135
|
y: 0,
|
|
1199
1136
|
width: BLOCK_CAPTURE_WIDTH,
|
|
1200
|
-
height
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
}
|
|
1137
|
+
height
|
|
1138
|
+
},
|
|
1139
|
+
scale: BLOCK_THUMB_WIDTH / BLOCK_CAPTURE_WIDTH
|
|
1140
|
+
});
|
|
1204
1141
|
const out = join(outDir, `${block.id}.png`);
|
|
1205
|
-
fs.writeFileSync(out,
|
|
1142
|
+
fs.writeFileSync(out, png);
|
|
1206
1143
|
console.info(`✓ ${block.id} → ${out}`);
|
|
1207
1144
|
} catch (error) {
|
|
1208
1145
|
failures.push(block.id);
|
|
@@ -1217,7 +1154,7 @@ async function runBlockThumbs(filter, options = {}) {
|
|
|
1217
1154
|
}
|
|
1218
1155
|
if (failures.length) throw new Error(`Failed to render ${failures.length} block(s): ${failures.join(", ")}`);
|
|
1219
1156
|
} finally {
|
|
1220
|
-
await
|
|
1157
|
+
await tab?.close();
|
|
1221
1158
|
await server.close();
|
|
1222
1159
|
}
|
|
1223
1160
|
}
|
|
@@ -1237,8 +1174,12 @@ Usage:
|
|
|
1237
1174
|
--site-name <name> adds WebSite JSON-LD;
|
|
1238
1175
|
--assets-url <origin> serves /assets and /media from
|
|
1239
1176
|
a CDN base — files still land in export/)
|
|
1240
|
-
mechanica login Sign in to the Mechanica platform
|
|
1241
|
-
|
|
1177
|
+
mechanica login Sign in to the Mechanica platform: prints a link to
|
|
1178
|
+
open and approve in the browser, and keeps the access
|
|
1179
|
+
token for this machine. In a terminal it waits for the
|
|
1180
|
+
approval; otherwise the next link/push finishes the
|
|
1181
|
+
sign-in (--wait, --no-wait, --host <url>, or
|
|
1182
|
+
--token <token> to store a token made in the dashboard)
|
|
1242
1183
|
mechanica link <slug> Point this repository at a site on the platform
|
|
1243
1184
|
(--create makes the site, --name "Site name")
|
|
1244
1185
|
mechanica push Publish the committed project: pull what was edited
|
|
@@ -1248,8 +1189,14 @@ Usage:
|
|
|
1248
1189
|
the site, any other gets an address of its own
|
|
1249
1190
|
mechanica shot <blockId> Screenshot one block via the dev preview route
|
|
1250
1191
|
mechanica shot </path> Screenshot a whole page (editor overlay stripped)
|
|
1192
|
+
mechanica shot <url | file.html>
|
|
1193
|
+
Screenshot any URL or local HTML file (a design
|
|
1194
|
+
handoff) the same way, without a dev server
|
|
1251
1195
|
(--page </path>, --data <json|@file>, --width 1440,768,
|
|
1252
|
-
--
|
|
1196
|
+
--section <css> (repeatable: one PNG per section),
|
|
1197
|
+
--scroll <px[,px…]> (viewport after scrolling),
|
|
1198
|
+
--no-freeze, --full, --out <path>, --server <url>,
|
|
1199
|
+
--browser <path>)
|
|
1253
1200
|
mechanica thumbs [/path] Thumbnail every page (or those under /path) into
|
|
1254
1201
|
.mech/thumbs/ for the editor's page browser
|
|
1255
1202
|
(--out <dir>, --server <url>, --browser <path>)
|
|
@@ -1267,10 +1214,12 @@ Usage:
|
|
|
1267
1214
|
mechanica migrate Bring .mech content up to the current format: uploads
|
|
1268
1215
|
are referenced as /media/<file> (was /@mechanica/assets/)
|
|
1269
1216
|
`;
|
|
1217
|
+
var PARSE_OPTIONS = { booleans: ["full", "no-freeze"] };
|
|
1270
1218
|
/** CLI entry: dispatch a command to its handler. */
|
|
1271
1219
|
async function run(argv) {
|
|
1272
|
-
const { command, args, flags } = parseArgs(argv);
|
|
1220
|
+
const { command, args, flags } = parseArgs(argv, PARSE_OPTIONS);
|
|
1273
1221
|
const str = (value) => typeof value === "string" ? value : void 0;
|
|
1222
|
+
const required = (value) => value === true ? "" : str(value);
|
|
1274
1223
|
switch (command) {
|
|
1275
1224
|
case "build": return runBuild({ editor: flags.editor === true });
|
|
1276
1225
|
case "export": return runExport({
|
|
@@ -1288,7 +1237,8 @@ async function run(argv) {
|
|
|
1288
1237
|
return;
|
|
1289
1238
|
case "login": return runLogin({
|
|
1290
1239
|
host: str(flags.host),
|
|
1291
|
-
token: str(flags.token)
|
|
1240
|
+
token: str(flags.token),
|
|
1241
|
+
wait: flags.wait === true ? true : flags["no-wait"] === true ? false : void 0
|
|
1292
1242
|
});
|
|
1293
1243
|
case "link": return runLink(args[0], {
|
|
1294
1244
|
host: str(flags.host),
|
|
@@ -1303,7 +1253,10 @@ async function run(argv) {
|
|
|
1303
1253
|
out: str(flags.out),
|
|
1304
1254
|
server: str(flags.server),
|
|
1305
1255
|
browser: str(flags.browser),
|
|
1306
|
-
full: flags.full === true
|
|
1256
|
+
full: flags.full === true,
|
|
1257
|
+
section: flagValues(argv, "section", PARSE_OPTIONS).map((value) => required(value) ?? ""),
|
|
1258
|
+
scroll: required(flags.scroll),
|
|
1259
|
+
noFreeze: flags["no-freeze"] === true
|
|
1307
1260
|
});
|
|
1308
1261
|
case "thumbs": {
|
|
1309
1262
|
const thumbsOptions = {
|