@marver-design/marver 0.27.0 → 0.27.2

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.
Files changed (82) hide show
  1. package/CHANGELOG.md +94 -0
  2. package/README.md +5 -2
  3. package/dist/{anchor-check-ChdDqL5z.mjs → anchor-check-gkxkPAIv.mjs} +1 -1
  4. package/dist/{board-tree-DRioF94d.mjs → board-tree-BXR8dw4b.mjs} +3 -1
  5. package/dist/{boards-CGg6piKF.mjs → boards-BHKP5yhI.mjs} +1 -1
  6. package/dist/{boards-DlTcpF47.mjs → boards-BqUqKNW8.mjs} +4 -4
  7. package/dist/{build-DZnFysGU.mjs → build-VgNg4rr8.mjs} +7 -22
  8. package/dist/cli.mjs +32 -18
  9. package/dist/{collab-Dxg2trOK.mjs → collab-BEAcXrBb.mjs} +1 -1
  10. package/dist/{comments-DxOkCSNE.mjs → comments-YEU1Zhv9.mjs} +4 -4
  11. package/dist/{context-HQ4Giw58.mjs → context-Ccjrhr1J.mjs} +3 -3
  12. package/dist/{daemon-BSA0lV8d.mjs → daemon-Dc9AH0M3.mjs} +4 -4
  13. package/dist/{dev-eQJhWsqg.mjs → dev-ri6nAlRp.mjs} +11 -11
  14. package/dist/{init-COD0x48i.mjs → init-W0nxR1OY.mjs} +3 -3
  15. package/dist/{link-DDXZVGtv.mjs → link-CdTgn94Y.mjs} +4 -4
  16. package/dist/{ls-D7O1G505.mjs → ls-BZ5TAtd5.mjs} +1 -1
  17. package/dist/{manifest-Nl3KSVOk.mjs → manifest-aFyDmL8C.mjs} +2 -2
  18. package/dist/{marks-CWM3WJjc.mjs → marks-BF9pNEgH.mjs} +2 -2
  19. package/dist/{marks-CKgzucHZ.mjs → marks-CnCCfAbD.mjs} +3 -3
  20. package/dist/{marver-id-gate-BjF6v4bT.mjs → marver-id-gate-D-R0hSt_.mjs} +1 -1
  21. package/dist/perf-DkAUFT6W.mjs +1319 -0
  22. package/dist/perf-jam-BaH3Lg0m.mjs +635 -0
  23. package/dist/{plugin-C-E7omsh.mjs → plugin-B8UghYuF.mjs} +2592 -112
  24. package/dist/{poster-Bx83ZYVK.mjs → poster-BNgafWMK.mjs} +1 -1
  25. package/dist/{profile-Bh5Y5zpW.mjs → profile-jIS6BcAs.mjs} +1 -1
  26. package/dist/{publish-bakes-aljgm45S.mjs → publish-bakes-38Nja78p.mjs} +3 -3
  27. package/dist/{recover-t9Pno3u9.mjs → recover-B8AiI29B.mjs} +2 -2
  28. package/dist/{serve-C8rVheYk.mjs → serve-Dp3nHstu.mjs} +3 -3
  29. package/dist/{share-W5H3BNvP.mjs → share-Ce4tP7ji.mjs} +1 -1
  30. package/dist/{shot-DoHLl6ig.mjs → shot-CMQgMVZm.mjs} +1 -1
  31. package/dist/{shot-LFhC-WYD.mjs → shot-Ch24tiMO.mjs} +30 -5
  32. package/dist/{slots-DCDo3N0x.mjs → slots-CFNnegCc.mjs} +8 -1
  33. package/dist/{sync-BQVlHZpx.mjs → sync-CQdGARJ9.mjs} +1 -1
  34. package/dist/{work-BroFwnup.mjs → work-Bxz-ObF3.mjs} +3 -3
  35. package/dist/{work-Bp1p39kq.mjs → work-CNhFF9pU.mjs} +1 -1
  36. package/docs/jam-session.md +2 -1
  37. package/docs/performance.md +197 -35
  38. package/package.json +1 -1
  39. package/src/client/content/video.tsx +10 -2
  40. package/src/client/shell/App.tsx +10 -3
  41. package/src/client/shell/Comments.tsx +5 -3
  42. package/src/client/shell/ContextMenu.tsx +5 -3
  43. package/src/client/shell/LockedApp.tsx +3 -0
  44. package/src/client/shell/Play.tsx +4 -2
  45. package/src/client/shell/Tip.tsx +3 -1
  46. package/src/client/shell/api.ts +47 -20
  47. package/src/client/shell/app-bridge.ts +254 -0
  48. package/src/client/shell/app-perf.ts +92 -0
  49. package/src/client/shell/canvas/Canvas.tsx +115 -22
  50. package/src/client/shell/canvas/FrameNode.tsx +10 -6
  51. package/src/client/shell/canvas/admission.ts +23 -8
  52. package/src/client/shell/canvas/ctl.ts +6 -0
  53. package/src/client/shell/canvas/sleep.ts +57 -17
  54. package/src/client/shell/canvas/updates.ts +2 -1
  55. package/src/client/shell/inset.ts +44 -0
  56. package/src/client/shell/jam-capture.ts +19 -14
  57. package/src/client/shell/jam-keys.ts +8 -3
  58. package/src/client/shell/jam-panel.tsx +6 -3
  59. package/src/client/shell/jam-voice.ts +48 -10
  60. package/src/client/shell/main.tsx +14 -1
  61. package/src/client/shell/marks-ui.tsx +5 -3
  62. package/src/client/shell/marver-app.ts +21 -0
  63. package/src/client/shell/perf-run-probe.ts +34 -0
  64. package/src/client/shell/perf-run.ts +70 -0
  65. package/src/client/shell/perf.ts +11 -0
  66. package/src/client/shell/recorder.ts +45 -3
  67. package/src/client/shell/store.ts +52 -24
  68. package/src/client/shell/styles.css +47 -15
  69. package/src/client/shell/unsaved.ts +81 -0
  70. package/src/client/shell/whiteout-probes.ts +141 -0
  71. package/src/shared/app-api.ts +205 -0
  72. package/src/shared/app-perf.ts +308 -0
  73. package/src/shared/logo-sniff.ts +86 -0
  74. package/src/shared/machine.ts +132 -0
  75. package/src/shared/perf-run.ts +177 -0
  76. package/templates/AGENTS-embedded.md +3 -0
  77. package/templates/AGENTS-studio.md +3 -0
  78. package/templates/instructions/boards.md +3 -1
  79. package/dist/bake-DM_uWgAA.mjs +0 -786
  80. package/dist/perf-BWzQwZqj.mjs +0 -369
  81. package/dist/perf-BoDSkbEb.mjs +0 -429
  82. package/dist/perf-jam-D55U3FZK.mjs +0 -242
@@ -1,17 +1,22 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.mjs";
1
2
  import { a as ROUTE, i as PKG, r as NAME } from "./cli.mjs";
2
- import { c as nodeExists, d as readMembership, f as readRegistry, h as hash, i as checkBoardsDir, l as parseBoard, m as withRegistryLock, o as isRegularFile, r as boardFields, s as listBoardFiles, t as AUTHOR_FIELDS, u as pinFrames } from "./boards-CGg6piKF.mjs";
3
- import { A as settableStatuses, D as readStatusWord, E as readReason, O as readType, T as readCapability, _ as wireKids, a as buildTree, c as folderMap, g as validateWire, h as readTitle, k as resolveType, m as readDescription, n as BOARD_NAME, r as FOLDERS_FILE, t as ALL_SCENES, x as HAS_STATUS } from "./board-tree-DRioF94d.mjs";
4
- import { c as setSceneTitle, d as annotateBoards, f as planNames, m as readContextFacts, n as isNoteFile, o as rendersDoc, p as planWithStage, r as layoutDocSource, s as scanFrames, t as affectedFrameIds, u as writeManifest } from "./manifest-Nl3KSVOk.mjs";
5
- import { r as boardsChanged } from "./work-Bp1p39kq.mjs";
6
- import { h as workspaceId, o as originOf } from "./slots-DCDo3N0x.mjs";
7
- import { n as localProfile, t as isConnected } from "./profile-Bh5Y5zpW.mjs";
3
+ import { c as nodeExists, d as readMembership, f as readRegistry, h as hash, i as checkBoardsDir, l as parseBoard, m as withRegistryLock, o as isRegularFile, r as boardFields, s as listBoardFiles, t as AUTHOR_FIELDS, u as pinFrames } from "./boards-BHKP5yhI.mjs";
4
+ import { A as resolveType, D as readReason, E as readCapability, O as readStatusWord, S as HAS_STATUS, _ as validateWire, a as buildTree, c as folderMap, g as readTitle, h as readDescription, j as settableStatuses, k as readType, n as BOARD_NAME, r as FOLDERS_FILE, t as ALL_SCENES, v as wireKids } from "./board-tree-BXR8dw4b.mjs";
5
+ import { c as setSceneTitle, d as annotateBoards, f as planNames, m as readContextFacts, n as isNoteFile, o as rendersDoc, p as planWithStage, r as layoutDocSource, s as scanFrames, t as affectedFrameIds, u as writeManifest } from "./manifest-aFyDmL8C.mjs";
6
+ import { r as boardsChanged } from "./work-CNhFF9pU.mjs";
7
+ import { h as workspaceId, i as marverHome, o as originOf } from "./slots-CFNnegCc.mjs";
8
+ import { n as localProfile, t as isConnected } from "./profile-jIS6BcAs.mjs";
8
9
  import { i as onPath, n as AGENT_NAMES, r as detectAgent, t as AGENT_BIN } from "./agent-BsieQGTD.mjs";
9
- import { a as observe, n as docRevs, r as initMarks, s as recordChanged, t as docRev } from "./marks-CKgzucHZ.mjs";
10
- import { n as logPage, r as logReload, s as tidyPerfDir, t as PAGE_BODY_MAX } from "./perf-BWzQwZqj.mjs";
11
- import { closeSync, copyFileSync, existsSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, watch, writeFileSync } from "node:fs";
12
- import { basename, dirname, join, relative, resolve, sep } from "node:path";
10
+ import { a as observe, n as docRevs, r as initMarks, s as recordChanged, t as docRev } from "./marks-CnCCfAbD.mjs";
11
+ import { a as appendRun, f as tidyPerfDir, i as PAGE_BODY_MAX, o as logPage, s as logReload } from "./perf-jam-BaH3Lg0m.mjs";
12
+ import { c as pool, d as withBrowser, f as Browser, l as shotConcurrency, m as launchFlags, r as SURFACE, t as AREA } from "./shot-Ch24tiMO.mjs";
13
+ import { closeSync, constants, copyFileSync, existsSync, fstatSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, realpathSync, renameSync, rmSync, statSync, utimesSync, watch, writeFileSync } from "node:fs";
14
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
13
15
  import { fileURLToPath, pathToFileURL } from "node:url";
14
- import { createHmac, randomBytes } from "node:crypto";
16
+ import { createHash, createHmac, randomBytes } from "node:crypto";
17
+ import { arch, cpus, totalmem } from "node:os";
18
+ import { execFile } from "node:child_process";
19
+ import { stat } from "node:fs/promises";
15
20
  //#region src/server/config.ts
16
21
  const DEFAULTS = {
17
22
  mode: "studio",
@@ -421,6 +426,2235 @@ function measuringFrames(root, frames) {
421
426
  return out;
422
427
  }
423
428
  //#endregion
429
+ //#region src/shared/perf-run.ts
430
+ /** A run's own generated id: the same in the URL, the request headers and the output line (A3.4). */
431
+ const RUN_ID = /^[0-9a-f]{16}$/;
432
+ /** The header every request of a run's page carries. */
433
+ const RUN_HEADER = "x-mv-perfrun";
434
+ /** The query parameter: on the shell's URL (`?mvperfrun=<id>`), and added by `withWs()` to frame URLs, the play stage and Jam pictures. */
435
+ const RUN_PARAM = "mvperfrun";
436
+ /** `&warm=1`: the unrecorded warm-up load - the recorder runs and posts nothing. */
437
+ const WARM_PARAM = "warm";
438
+ /**
439
+ * The only mutating requests a run may make, under `${ROUTE}/api/` (A3.8 #17): its own page records, and the
440
+ * sleep bakes - `POST /api/bakes` only fills a derived cache, so it is allowed and never counted (A3.4). GET and
441
+ * HEAD always pass. `POST /api/poster` is refused for any run id, registered or not.
442
+ */
443
+ const RUN_ALLOWED = [{
444
+ method: "POST",
445
+ path: "perf/page"
446
+ }, {
447
+ method: "POST",
448
+ path: "bakes"
449
+ }];
450
+ /** May a run send this? `apiPath` is the path under `${ROUTE}/api/` (no leading slash, no query), or null for any other path. */
451
+ function allowedInRun(method, apiPath) {
452
+ const m = method.toUpperCase();
453
+ if (m === "GET" || m === "HEAD") return true;
454
+ if (apiPath === null) return false;
455
+ return RUN_ALLOWED.some((a) => a.method === m && a.path === apiPath);
456
+ }
457
+ //#endregion
458
+ //#region src/shared/sleep-rule.ts
459
+ /** The element's own background and filter, read once BEFORE any override touches it. */
460
+ function readOwn(cs) {
461
+ return {
462
+ img: cs.backgroundImage,
463
+ color: cs.backgroundColor,
464
+ size: cs.backgroundSize,
465
+ pos: cs.backgroundPosition,
466
+ rep: cs.backgroundRepeat,
467
+ org: cs.backgroundOrigin,
468
+ clip: cs.backgroundClip,
469
+ filter: cs.filter
470
+ };
471
+ }
472
+ function sleepRule(selector, o, texture) {
473
+ const img = o.img === "none" ? "" : o.img + ",";
474
+ const colorClip = o.clip.split(",").pop().trim() || "border-box";
475
+ return selector + "{backdrop-filter:none!important;-webkit-backdrop-filter:none!important;" + (o.filter === "none" ? "filter:opacity(1)!important;" : "") + "background-color:transparent!important;background-image:" + img + "linear-gradient(" + o.color + "," + o.color + "),url(\"" + texture + "\")!important;background-size:" + (img ? o.size + "," : "") + "auto,100% 100%!important;background-position:" + (img ? o.pos + "," : "") + "0 0,0 0!important;background-repeat:" + (img ? o.rep + "," : "") + "no-repeat,no-repeat!important;background-origin:" + (img ? o.org + "," : "") + "border-box,border-box!important;background-clip:" + (img ? o.clip + "," : "") + colorClip + ",border-box!important}";
476
+ }
477
+ //#endregion
478
+ //#region src/server/bake.ts
479
+ /**
480
+ * Effect compilation - what lets a hi-fi frame SLEEP on the canvas (spec 16).
481
+ *
482
+ * A frame at rest is its own live document. What makes a glass design unrenderable at scale is not
483
+ * layout or text but its effects: every `backdrop-filter` is a compositor render surface that reads
484
+ * back what is behind it on every composited frame, and under a scaled canvas the tiles behind it
485
+ * re-raster on every zoom step. At rest nothing behind a glass surface changes, so its filtered
486
+ * backdrop is a constant - a texture. This module computes those textures with Chrome itself, so
487
+ * the pixels are the compositor's own, and CERTIFIES each one before it ships:
488
+ *
489
+ * 1. render the frame headless at the node's width/height/theme (DPR 2) and settle it like the
490
+ * shot pipeline does, plus SVG images, running animations and a DOM-quiet window
491
+ * 2. DETECT every element with a computed backdrop-filter; level overlapping elements (an element
492
+ * over an earlier one bakes one level later, so its backdrop contains the earlier one's result)
493
+ * 3. a WARMED, STABLE reference: one hide-and-show cycle first (tiles under the targets then sit in
494
+ * the state every later capture is in), captured until two consecutive captures are identical
495
+ * 4. per level: hide this level and above with opacity (a descendant can undo `visibility`), ONE
496
+ * screenshot, and one filter page that cuts every crop at integer device pixels, tiles it 3x3
497
+ * with mirrored copies (Chrome's backdrop blur reads only the element's own region and mirrors
498
+ * at its edges) and applies the element's own filter list by CSS; one screenshot of that page,
499
+ * sliced back into the textures at TEXTURE_DSF
500
+ * 5. certification: apply everything, render, and diff the INSIDE of each element's rounded
501
+ * shape (eroded 3 device px - a composited edge and an inline edge differ by an AA halo) against
502
+ * the reference; then re-apply only what passed and certify THAT composition (a rejected
503
+ * neighbour changes a backdrop); then check that no element's box moved
504
+ *
505
+ * The override the shell will use is the one certified here (src/shared/sleep-rule.ts):
506
+ * `backdrop-filter: none` under a static `filter` (the containing block stays, the compositor layer
507
+ * goes) with the texture under the element's own background layers. Layout is never touched.
508
+ */
509
+ var bake_exports = /* @__PURE__ */ __exportAll({
510
+ ASK_MAX: () => ASK_MAX,
511
+ COMPILING: () => COMPILING,
512
+ LOOPING: () => LOOPING,
513
+ NORMAL_OWNER: () => NORMAL_OWNER,
514
+ RUN_ENDED: () => RUN_ENDED,
515
+ STOP_ASKING: () => STOP_ASKING,
516
+ TIMED_OUT: () => TIMED_OUT,
517
+ bakeBatch: () => bakeBatch,
518
+ bakeIn: () => bakeIn,
519
+ bakeKey: () => bakeKey,
520
+ bakeSeams: () => bakeSeams,
521
+ bakesEnded: () => bakesEnded,
522
+ endRunBakes: () => endRunBakes,
523
+ flightKey: () => flightKey,
524
+ jobsIdle: () => jobsIdle,
525
+ jobsOf: () => jobsOf,
526
+ ofTheFrame: () => ofTheFrame,
527
+ pruneBakes: () => pruneBakes
528
+ });
529
+ const DSF = 2;
530
+ /** Texture device px per CSS px. Blur is scale-tolerant: 1x matches 2x on identity at 2x zoom
531
+ * (29 px > 8 of 5.18 M, none > 32) at a quarter of the memory; 0.5x fails on 30 px pills. */
532
+ const TEXTURE_DSF = 1;
533
+ const DEADLINE_MS = 45e3;
534
+ /** What a compile past its deadline answers. */
535
+ const TIMED_OUT = "the bake timed out";
536
+ /** The refusal for a frame with a looping animation: it rests paused, never compiled. */
537
+ const LOOPING = "a looping animation - the frame rests paused, uncompiled";
538
+ /** The largest frame an ask may name, in CSS px: the shot pipeline's bitmap budget at DPR 2. */
539
+ const ASK_MAX = {
540
+ side: Math.floor(SURFACE / DSF),
541
+ area: Math.floor(AREA / 4)
542
+ };
543
+ const MAX_TARGETS = 200;
544
+ /** One element's texture, in CSS px (its 3x3 mirrored tiling is filtered in a page of its own). */
545
+ const MAX_TARGET_AREA = 4e6;
546
+ const KEYS_PER_GEN = 400;
547
+ /** Runs INSIDE the frame document: the effect census and the paint-order levelling. Assigns
548
+ * data-mv-bake ids so later passes address elements without re-walking. */
549
+ const DETECT = `(() => {
550
+ const sel = (el) => {
551
+ const seg = []
552
+ for (let cur = el; cur && cur !== document.documentElement; cur = cur.parentElement) {
553
+ if (cur.id) { seg.unshift('#' + CSS.escape(cur.id)); break }
554
+ const tag = cur.tagName.toLowerCase()
555
+ let n = 1
556
+ for (let s = cur.previousElementSibling; s; s = s.previousElementSibling) if (s.tagName === cur.tagName) n++
557
+ seg.unshift(tag + ':nth-of-type(' + n + ')')
558
+ }
559
+ return seg.join('>')
560
+ }
561
+ const glass = []
562
+ for (const el of document.querySelectorAll('*')) {
563
+ const cs = getComputedStyle(el)
564
+ const bf = cs.backdropFilter || cs.webkitBackdropFilter
565
+ if (!bf || bf === 'none') continue
566
+ const r = el.getBoundingClientRect()
567
+ if (r.width < 1 || r.height < 1) continue
568
+ el.setAttribute('data-mv-glass', '')
569
+ glass.push({ el, bf, r })
570
+ }
571
+ window.__mvBakeDetected = glass.length
572
+ // glass inside glass: the inner element reads its ancestor's UNFILTERED backdrop (measured in
573
+ // Chrome 152), which no texture on either of them reproduces - both stay live
574
+ const out = []
575
+ let i = 0
576
+ for (const { el, bf, r } of glass) {
577
+ if ((el.parentElement && el.parentElement.closest('[data-mv-glass]')) || el.querySelector('[data-mv-glass]')) continue
578
+ el.setAttribute('data-mv-bake', String(i))
579
+ out.push({ i: i++, sel: sel(el), rect: { x: r.x, y: r.y, w: r.width, h: r.height }, filter: bf })
580
+ }
581
+ for (const { el } of glass) el.removeAttribute('data-mv-glass')
582
+ const level = new Array(out.length).fill(0)
583
+ const hit = (a, b) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h
584
+ for (let k = 0; k < out.length; k++) for (let j = 0; j < k; j++) if (hit(out[k].rect, out[j].rect)) level[k] = Math.max(level[k], level[j] + 1)
585
+ return out.map((t, k) => ({ ...t, level: level[k] }))
586
+ })()`;
587
+ /** Runs inside the frame document: hide the targets at or above \`level\` (opacity, the authored
588
+ * inline declaration remembered and restored exactly), show the rest, apply \`bakes\` as the
589
+ * override the shell will use. */
590
+ const APPLY = `((level, bakes) => {
591
+ const readOwn = ${readOwn.toString()}
592
+ const sleepRule = ${sleepRule.toString()}
593
+ let st = document.getElementById('mv-bake-style')
594
+ if (!st) { st = document.createElement('style'); st.id = 'mv-bake-style'; document.head.appendChild(st) }
595
+ const rules = []
596
+ // no authored transition may animate the override in: the shell installs it the same way
597
+ for (const el of document.querySelectorAll('[data-mv-bake]')) el.style.setProperty('transition-property', 'none', 'important')
598
+ for (const el of document.querySelectorAll('[data-mv-bake]')) {
599
+ const i = el.getAttribute('data-mv-bake')
600
+ const b = bakes.find((x) => String(x.i) === i)
601
+ if (!b) continue
602
+ // the element's OWN background, read once before any override touches it
603
+ const own = el.dataset.mvOwn ? JSON.parse(el.dataset.mvOwn) : readOwn(getComputedStyle(el))
604
+ if (!el.dataset.mvOwn) el.dataset.mvOwn = JSON.stringify(own)
605
+ rules.push(sleepRule('[data-mv-bake="' + i + '"]', own, b.texture))
606
+ }
607
+ st.textContent = rules.join('\\n')
608
+ for (const el of document.querySelectorAll('[data-mv-bake]')) {
609
+ const i = Number(el.getAttribute('data-mv-bake'))
610
+ const t = window.__mvBakeTargets.find((x) => x.i === i)
611
+ if (t && t.level >= level) {
612
+ if (!('mvOpacity' in el.dataset)) el.dataset.mvOpacity = JSON.stringify([el.style.getPropertyValue('opacity'), el.style.getPropertyPriority('opacity')])
613
+ el.style.setProperty('opacity', '0', 'important')
614
+ } else if ('mvOpacity' in el.dataset) {
615
+ const [v, p] = JSON.parse(el.dataset.mvOpacity)
616
+ if (v) el.style.setProperty('opacity', v, p); else el.style.removeProperty('opacity')
617
+ delete el.dataset.mvOpacity
618
+ }
619
+ }
620
+ return true
621
+ })`;
622
+ /** Every element's box, for the geometry guard (a lost containing block would move a fixed child). */
623
+ const GEOMETRY = `Array.from(document.querySelectorAll('body *')).map((el) => { const r = el.getBoundingClientRect(); return [r.x, r.y, r.width, r.height] })`;
624
+ const PAINTED = `new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => r(true))))`;
625
+ /** The filter page: ONE screenshot of the level comes in; every element's crop is cut from it in-page
626
+ * at integer device pixels, tiled 3x3 with mirrored copies, filtered by CSS with the element's own
627
+ * filter list and clipped to its box - stacked so one screenshot yields every texture. */
628
+ function filterPage(full, items, dsf, tex) {
629
+ return `<!doctype html><html><head><meta charset=utf-8><style>html,body{margin:0;background:transparent}.clip{overflow:hidden;position:absolute;left:0}canvas{position:absolute;display:block}</style></head><body>
630
+ <script>
631
+ const items = ${JSON.stringify(items)}, dsf = ${dsf}, tex = ${tex}
632
+ const img = new Image()
633
+ img.onload = () => {
634
+ let top = 0
635
+ for (const it of items) {
636
+ const sx = Math.round(it.x * dsf), sy = Math.round(it.y * dsf), sw = Math.round(it.w * dsf), sh = Math.round(it.h * dsf)
637
+ const cw = it.w, ch = it.h
638
+ const tw = Math.max(1, Math.round(cw * tex)), th = Math.max(1, Math.round(ch * tex))
639
+ const clip = document.createElement('div'); clip.className = 'clip'; clip.id = 'c' + it.i
640
+ clip.style.top = top + 'px'; clip.style.width = cw + 'px'; clip.style.height = ch + 'px'
641
+ clip.dataset.box = [Math.round(top * tex), tw, th].join(',')
642
+ const c = document.createElement('canvas'); c.width = 3 * tw; c.height = 3 * th
643
+ c.style.left = -cw + 'px'; c.style.top = -ch + 'px'; c.style.width = (3 * cw) + 'px'; c.style.height = (3 * ch) + 'px'; c.style.filter = it.filter
644
+ const g = c.getContext('2d')
645
+ for (let ty = 0; ty < 3; ty++) for (let tx = 0; tx < 3; tx++) {
646
+ g.save(); g.translate(tx * tw, ty * th)
647
+ const fx = tx === 1 ? 1 : -1, fy = ty === 1 ? 1 : -1
648
+ g.translate(fx < 0 ? tw : 0, fy < 0 ? th : 0); g.scale(fx, fy)
649
+ g.drawImage(img, sx, sy, sw, sh, 0, 0, tw, th); g.restore()
650
+ }
651
+ clip.appendChild(c); document.body.appendChild(clip)
652
+ top += Math.ceil(ch) + 8
653
+ }
654
+ document.body.style.height = top + 'px'
655
+ window.__mvReady = true
656
+ }
657
+ img.src = ${JSON.stringify(full)}
658
+ <\/script></body></html>`;
659
+ }
660
+ const SLICE = `((shot) => new Promise((res) => { const im = new Image(); im.onload = () => {
661
+ const out = {}
662
+ for (const clip of document.querySelectorAll('.clip')) {
663
+ const [y, w, h] = clip.dataset.box.split(',').map(Number)
664
+ const c = document.createElement('canvas'); c.width = w; c.height = h
665
+ c.getContext('2d').drawImage(im, 0, y, w, h, 0, 0, w, h)
666
+ out[clip.id.slice(1)] = c.toDataURL('image/png')
667
+ }
668
+ res(out)
669
+ }; im.src = 'data:image/png;base64,' + shot }))`;
670
+ /** Runs in the frame page: are two captures the same picture within GPU dither (no channel differs by more than 2)? */
671
+ const NEAR = `((a, b) => (async () => {
672
+ const load = (d) => new Promise((r) => { const im = new Image(); im.onload = () => r(im); im.src = 'data:image/png;base64,' + d })
673
+ const [ia, ib] = await Promise.all([load(a), load(b)])
674
+ const px = (im) => { const c = document.createElement('canvas'); c.width = im.width; c.height = im.height; const g = c.getContext('2d', { willReadFrequently: true }); g.drawImage(im, 0, 0); return g.getImageData(0, 0, c.width, c.height).data }
675
+ const A = px(ia), B = px(ib)
676
+ if (A.length !== B.length) return false
677
+ for (let i = 0; i < A.length; i++) if (Math.abs(A[i] - B[i]) > 2) return false
678
+ return true
679
+ })())`;
680
+ /** Runs in the frame page: diff \`baked\` against \`reference\` inside each target's rounded shape,
681
+ * and over the rest of the frame - an override may not change one pixel outside the boxes it owns. */
682
+ const CERTIFY = `((reference, baked, rects, width) => (async () => {
683
+ const load = (d) => new Promise((r) => { const im = new Image(); im.onload = () => r(im); im.src = 'data:image/png;base64,' + d })
684
+ const [ia, ib] = await Promise.all([load(reference), load(baked)])
685
+ const px = (im) => { const c = document.createElement('canvas'); c.width = im.width; c.height = im.height; const g = c.getContext('2d', { willReadFrequently: true }); g.drawImage(im, 0, 0); return { d: g.getImageData(0, 0, c.width, c.height).data, w: c.width, h: c.height } }
686
+ const A = px(ia), B = px(ib), k = A.w / width, E = 3
687
+ const owned = new Uint8Array(A.w * A.h)
688
+ const verdicts = rects.map((t) => {
689
+ const x0 = Math.max(0, Math.floor(t.rect.x * k) + E), y0 = Math.max(0, Math.floor(t.rect.y * k) + E)
690
+ const x1 = Math.min(A.w, Math.ceil((t.rect.x + t.rect.w) * k) - E), y1 = Math.min(A.h, Math.ceil((t.rect.y + t.rect.h) * k) - E)
691
+ const el = document.querySelector(t.sel); const cs = el ? getComputedStyle(el) : null
692
+ const rad = (v) => Math.max(0, Math.min(parseFloat(v) || 0, Math.min(t.rect.w, t.rect.h) / 2) * k - E)
693
+ const R = cs ? [rad(cs.borderTopLeftRadius), rad(cs.borderTopRightRadius), rad(cs.borderBottomRightRadius), rad(cs.borderBottomLeftRadius)] : [0, 0, 0, 0]
694
+ const inside = (x, y) => {
695
+ const cx = [x0 + R[0], x1 - R[1], x1 - R[2], x0 + R[3]], cy = [y0 + R[0], y0 + R[1], y1 - R[2], y1 - R[3]]
696
+ const c = x < x0 + R[0] && y < y0 + R[0] ? 0 : x >= x1 - R[1] && y < y0 + R[1] ? 1 : x >= x1 - R[2] && y >= y1 - R[2] ? 2 : x < x0 + R[3] && y >= y1 - R[3] ? 3 : -1
697
+ if (c < 0) return true
698
+ const dx = x + 0.5 - cx[c], dy = y + 0.5 - cy[c]
699
+ return dx * dx + dy * dy <= R[c] * R[c]
700
+ }
701
+ // the perimeter - the box minus the eroded shape - is where a composited edge and an inline
702
+ // edge differ by an anti-aliasing halo; a tint painted into a transparent border shows there
703
+ // as a solid band, so it has its own, looser gate
704
+ const X0 = Math.max(0, Math.floor(t.rect.x * k)), Y0 = Math.max(0, Math.floor(t.rect.y * k))
705
+ const X1 = Math.min(A.w, Math.ceil((t.rect.x + t.rect.w) * k)), Y1 = Math.min(A.h, Math.ceil((t.rect.y + t.rect.h) * k))
706
+ let maxErr = 0, bad = 0, n = 0, ringBad = 0, ringN = 0
707
+ for (let y = Y0; y < Y1; y++) for (let x = X0; x < X1; x++) {
708
+ owned[y * A.w + x] = 1
709
+ const i = (y * A.w + x) * 4
710
+ const d = Math.max(Math.abs(A.d[i] - B.d[i]), Math.abs(A.d[i+1] - B.d[i+1]), Math.abs(A.d[i+2] - B.d[i+2]))
711
+ if (x >= x0 && x < x1 && y >= y0 && y < y1 && inside(x, y)) { if (d > maxErr) maxErr = d; if (d > 8) bad++; n++ }
712
+ else { if (d > 48) ringBad++; ringN++ }
713
+ }
714
+ return { maxErr, bad, n, ringBad, ringN }
715
+ })
716
+ // outside every box: a changed pixel here is an anti-aliased edge next to a former layer (sparse,
717
+ // a few per block) or a real change of paint (a blob) - counted per 16x16 device-pixel block
718
+ const cols = Math.ceil(A.w / 16), blocks = new Uint16Array(cols * Math.ceil(A.h / 16))
719
+ let maxErr = 0, bad = 0, gt32 = 0, n = 0, blockMax = 0
720
+ for (let p = 0; p < owned.length; p++) {
721
+ if (owned[p]) continue
722
+ const i = p * 4
723
+ const d = Math.max(Math.abs(A.d[i] - B.d[i]), Math.abs(A.d[i+1] - B.d[i+1]), Math.abs(A.d[i+2] - B.d[i+2]))
724
+ if (d > maxErr) maxErr = d; if (d > 8) bad++; n++
725
+ if (d > 32) { gt32++; const b = ((p / A.w) >> 4) * cols + ((p % A.w) >> 4); if (++blocks[b] > blockMax) blockMax = blocks[b] }
726
+ }
727
+ return { verdicts, outside: { maxErr, bad, gt32, n, blockMax } }
728
+ })())`;
729
+ const passes = (v) => !!v && v.n >= 64 && v.maxErr <= 32 && v.bad <= v.n * .005 && v.ringBad <= v.ringN * .05;
730
+ /** The frame outside the boxes: at most 0.05 % of its pixels beyond 32 levels and no 16x16 block
731
+ * more than a quarter changed (measured: 154 of 2.5 M, 22 per block at worst, on the largest real
732
+ * frame; a 60x40 CSS px blob fills its blocks). */
733
+ const untouched = (o) => !!o && o.gt32 <= o.n * 5e-4 && o.blockMax <= 64;
734
+ /** Compile one frame inside a browser the caller owns. */
735
+ async function bakeIn(b, opts) {
736
+ const { url, width, height } = opts;
737
+ const t0 = Date.now();
738
+ const me = {};
739
+ let targetId;
740
+ let timedOut = false;
741
+ const deadline = setTimeout(() => {
742
+ timedOut = true;
743
+ b.abort(me, TIMED_OUT);
744
+ }, DEADLINE_MS);
745
+ const closeTarget = async (id) => {
746
+ let t;
747
+ await Promise.race([b.send("Target.closeTarget", { targetId: id }).catch(() => {}), new Promise((r) => {
748
+ t = setTimeout(r, 2e3);
749
+ })]);
750
+ clearTimeout(t);
751
+ };
752
+ try {
753
+ targetId = (await b.send("Target.createTarget", { url: "about:blank" }, void 0, me)).targetId;
754
+ const sessionId = (await b.send("Target.attachToTarget", {
755
+ targetId,
756
+ flatten: true
757
+ }, void 0, me)).sessionId;
758
+ const send = (m, p = {}, sid = sessionId) => b.send(m, p, sid, me);
759
+ const ev = async (expression, awaitPromise = false) => (await send("Runtime.evaluate", {
760
+ expression,
761
+ returnByValue: true,
762
+ awaitPromise
763
+ })).result?.value;
764
+ const wait = (ms) => new Promise((r) => setTimeout(r, ms));
765
+ const capture = async () => (await send("Page.captureScreenshot", {
766
+ format: "png",
767
+ captureBeyondViewport: true,
768
+ clip: {
769
+ x: 0,
770
+ y: 0,
771
+ width,
772
+ height,
773
+ scale: 1
774
+ }
775
+ })).data;
776
+ await send("Emulation.setDeviceMetricsOverride", {
777
+ width,
778
+ height,
779
+ deviceScaleFactor: DSF,
780
+ mobile: false
781
+ });
782
+ await send("Page.enable");
783
+ await send("Runtime.enable");
784
+ const nav = await send("Page.navigate", { url });
785
+ if (nav?.errorText && nav.errorText !== "net::ERR_ABORTED") return {
786
+ ok: false,
787
+ error: `could not load the frame (${nav.errorText})`
788
+ };
789
+ const readyBy = Date.now() + 3e4;
790
+ let rendered = false;
791
+ while (!rendered && Date.now() < readyBy) {
792
+ rendered = !!await ev(`(() => { const el = document.getElementById('root') ?? document.body; return !!el && el.childElementCount > 0 && document.readyState !== 'loading' })()`);
793
+ if (!rendered) await wait(100);
794
+ }
795
+ if (!rendered) return {
796
+ ok: false,
797
+ error: "the frame never rendered"
798
+ };
799
+ await ev(`document.fonts.ready.then(() => true)`, true);
800
+ const unsettled = await ev(`new Promise((r) => { const t = Date.now(); const tick = () => {
801
+ const H = innerHeight, W = innerWidth
802
+ let pending = 0
803
+ if (typeof window.__mvLodBusy === 'function' && window.__mvLodBusy() > 0) pending++
804
+ if (typeof window.__mvPosterBusy === 'function' && window.__mvPosterBusy() > 0) pending++
805
+ for (const im of document.images) { if (im.complete) continue; const b = im.getBoundingClientRect(); if (b.bottom < 0 || b.top > H || b.right < 0 || b.left > W) continue; pending++ }
806
+ for (const c of document.querySelectorAll('.mv-chart')) if (!c.querySelector('svg, canvas')) pending++
807
+ for (const d of document.querySelectorAll('.mv-diagram')) if (!d.querySelector('.mv-diagram-svg svg, .mv-diagram-err')) pending++
808
+ if (!pending || Date.now() - t > 6000) r(pending); else setTimeout(tick, 60) }; tick() })`, true);
809
+ if (unsettled) return {
810
+ ok: false,
811
+ error: `the frame did not settle (${unsettled} image(s) or chart(s) still loading)`
812
+ };
813
+ await ev(`Promise.all(Array.from(document.querySelectorAll('image')).map((el) => { const href = el.getAttribute('href') || el.getAttribute('xlink:href'); if (!href) return 1; const im = new Image(); im.src = new URL(href, location.href).href; return im.decode().catch(() => 1) })).then(() => true)`, true);
814
+ if (await ev(`document.getAnimations().some((a) => { const t = a.effect && a.effect.getComputedTiming(); return !!t && t.iterations === Infinity && a.playState === 'running' })`)) return {
815
+ ok: false,
816
+ error: LOOPING
817
+ };
818
+ await ev(`Promise.race([Promise.all(document.getAnimations().map((a) => a.finished.catch(() => 1))), new Promise((r) => setTimeout(r, 5000))]).then(() => true)`, true);
819
+ await ev(`new Promise((resolve) => { let timer = 0; const done = () => { mo.disconnect(); resolve(true) }; const mo = new MutationObserver(() => { clearTimeout(timer); timer = setTimeout(done, 250) }); mo.observe(document.documentElement, { subtree: true, childList: true, attributes: true, characterData: true }); timer = setTimeout(done, 250); setTimeout(done, 3000) })`, true);
820
+ await ev(PAINTED, true);
821
+ const err = await ev(`window.__mvFrameError || ''`);
822
+ if (err) return {
823
+ ok: false,
824
+ error: `the frame rendered an error - ${err}`
825
+ };
826
+ const posterSkipped = await ev(`document.documentElement.hasAttribute('data-mv-poster-skipped')`) === true ? { posterSkipped: true } : {};
827
+ const targets = await ev(`(window.__mvBakeTargets = ${DETECT})`);
828
+ const effects = Number(await ev("window.__mvBakeDetected")) || 0;
829
+ if (!targets?.length) return {
830
+ ok: true,
831
+ targets: [],
832
+ levels: 0,
833
+ rejected: 0,
834
+ ms: Date.now() - t0,
835
+ effects,
836
+ ...posterSkipped
837
+ };
838
+ if (targets.length > MAX_TARGETS) return {
839
+ ok: false,
840
+ error: `too many effects to compile (${targets.length})`
841
+ };
842
+ if (targets.some((t) => t.rect.w * t.rect.h > MAX_TARGET_AREA)) return {
843
+ ok: false,
844
+ error: "an effect larger than the texture budget"
845
+ };
846
+ const levels = Math.max(...targets.map((t) => t.level)) + 1;
847
+ const geometryBefore = await ev(GEOMETRY);
848
+ await ev(`${APPLY}(0, [])`);
849
+ await ev(PAINTED, true);
850
+ await ev(`${APPLY}(${levels}, [])`);
851
+ await ev(PAINTED, true);
852
+ await wait(300);
853
+ let reference = await capture(), stable = false;
854
+ let previous = "";
855
+ for (let i = 0; i < 8; i++) {
856
+ await wait(400);
857
+ const again = await capture();
858
+ if (again === reference || await ev(`${NEAR}(${JSON.stringify(reference)}, ${JSON.stringify(again)})`, true)) {
859
+ stable = true;
860
+ break;
861
+ }
862
+ previous = reference;
863
+ reference = again;
864
+ }
865
+ if (!stable) {
866
+ if (process.env.MV_BAKE_DEBUG) {
867
+ mkdirSync(process.env.MV_BAKE_DEBUG, { recursive: true });
868
+ writeFileSync(join(process.env.MV_BAKE_DEBUG, `unstable-a-${Date.now()}.png`), Buffer.from(previous, "base64"));
869
+ writeFileSync(join(process.env.MV_BAKE_DEBUG, `unstable-b-${Date.now()}.png`), Buffer.from(reference, "base64"));
870
+ }
871
+ return {
872
+ ok: false,
873
+ error: "the frame never stopped changing - nothing to certify against"
874
+ };
875
+ }
876
+ const bakes = [];
877
+ const done = /* @__PURE__ */ new Map();
878
+ for (let level = 0; level < levels; level++) {
879
+ await ev(`${APPLY}(${level}, ${JSON.stringify(bakes)})`);
880
+ await ev(PAINTED, true);
881
+ const mine = targets.filter((t) => t.level === level);
882
+ const full = await capture();
883
+ const items = mine.map((t) => ({
884
+ i: t.i,
885
+ x: t.rect.x,
886
+ y: t.rect.y,
887
+ w: t.rect.w,
888
+ h: t.rect.h,
889
+ filter: t.filter
890
+ }));
891
+ const { targetId: ft } = await b.send("Target.createTarget", { url: "about:blank" }, void 0, me);
892
+ try {
893
+ const { sessionId: fs } = await b.send("Target.attachToTarget", {
894
+ targetId: ft,
895
+ flatten: true
896
+ }, void 0, me);
897
+ const totalH = items.reduce((a, c) => a + Math.ceil(c.h) + 9, 0);
898
+ await b.send("Emulation.setDeviceMetricsOverride", {
899
+ width: Math.ceil(Math.max(...items.map((c) => c.w))),
900
+ height: Math.min(16e3, totalH),
901
+ deviceScaleFactor: TEXTURE_DSF,
902
+ mobile: false
903
+ }, fs, me);
904
+ await b.send("Page.enable", {}, fs, me);
905
+ const { frameTree } = await b.send("Page.getFrameTree", {}, fs, me);
906
+ await b.send("Page.setDocumentContent", {
907
+ frameId: frameTree.frame.id,
908
+ html: filterPage(`data:image/png;base64,${full}`, items, DSF, TEXTURE_DSF)
909
+ }, fs, me);
910
+ await b.send("Runtime.evaluate", {
911
+ expression: `new Promise((r) => { const t = () => window.__mvReady ? requestAnimationFrame(() => requestAnimationFrame(() => r(true))) : setTimeout(t, 20); t() })`,
912
+ awaitPromise: true,
913
+ returnByValue: true
914
+ }, fs, me);
915
+ const fshot = (await b.send("Page.captureScreenshot", {
916
+ format: "png",
917
+ captureBeyondViewport: true
918
+ }, fs, me)).data;
919
+ const textures = (await b.send("Runtime.evaluate", {
920
+ expression: `${SLICE}(${JSON.stringify(fshot)})`,
921
+ awaitPromise: true,
922
+ returnByValue: true
923
+ }, fs, me)).result.value;
924
+ for (const t of mine) {
925
+ const texture = textures[String(t.i)];
926
+ if (!texture) continue;
927
+ bakes.push({
928
+ i: t.i,
929
+ texture
930
+ });
931
+ done.set(t.i, {
932
+ sel: t.sel,
933
+ rect: t.rect,
934
+ filter: t.filter,
935
+ level,
936
+ texture,
937
+ verified: false,
938
+ maxErr: 255,
939
+ bad: -1
940
+ });
941
+ }
942
+ } finally {
943
+ await closeTarget(ft);
944
+ }
945
+ }
946
+ const certify = async (set) => {
947
+ await ev(`${APPLY}(${levels}, ${JSON.stringify(set)})`);
948
+ await ev(PAINTED, true);
949
+ const baked = await capture();
950
+ if (process.env.MV_BAKE_DEBUG) {
951
+ const d = join(process.env.MV_BAKE_DEBUG, new URL(url).pathname.replace(/[^\w.-]+/g, "_"));
952
+ mkdirSync(d, { recursive: true });
953
+ writeFileSync(join(d, "reference.png"), Buffer.from(reference, "base64"));
954
+ writeFileSync(join(d, `baked-${set.length}.png`), Buffer.from(baked, "base64"));
955
+ }
956
+ const rects = set.map((s) => done.get(s.i)).map((t) => ({
957
+ sel: t.sel,
958
+ rect: t.rect
959
+ }));
960
+ return await ev(`${CERTIFY}(${JSON.stringify(reference)}, ${JSON.stringify(baked)}, ${JSON.stringify(rects)}, ${width})`, true);
961
+ };
962
+ let set = bakes, settled = false, outside;
963
+ for (let round = 0; set.length && round <= levels + 1 && !settled; round++) {
964
+ const { verdicts, outside: o } = await certify(set);
965
+ outside = o;
966
+ set.forEach((s, k) => {
967
+ const t = done.get(s.i);
968
+ t.verified = passes(verdicts[k]);
969
+ t.maxErr = verdicts[k]?.maxErr ?? 255;
970
+ t.bad = verdicts[k]?.bad ?? -1;
971
+ });
972
+ const next = set.filter((s) => done.get(s.i).verified);
973
+ settled = next.length === set.length;
974
+ set = next;
975
+ }
976
+ if (settled && set.length && !untouched(outside)) settled = false;
977
+ if (!settled) for (const s of set) done.get(s.i).verified = false;
978
+ const geometryAfter = await ev(GEOMETRY);
979
+ if (geometryBefore.length !== geometryAfter.length || geometryBefore.some((r, k) => r.some((v, j) => Math.abs(v - geometryAfter[k][j]) > .01))) for (const t of done.values()) t.verified = false;
980
+ const out = [...done.values()];
981
+ return {
982
+ ok: true,
983
+ targets: out,
984
+ levels,
985
+ rejected: out.filter((t) => !t.verified).length,
986
+ ms: Date.now() - t0,
987
+ outside,
988
+ effects,
989
+ ...posterSkipped
990
+ };
991
+ } catch (err) {
992
+ return {
993
+ ok: false,
994
+ error: timedOut ? TIMED_OUT : err.message
995
+ };
996
+ } finally {
997
+ clearTimeout(deadline);
998
+ b.abort(me, "the bake finished");
999
+ if (targetId && !b.dead) await closeTarget(targetId);
1000
+ }
1001
+ }
1002
+ /** Where a compiled frame lives on disk: design/.local/bakes/<generation>/<key>/. The generation
1003
+ * is the dev server's source generation (bumped on any watched change), so a stale bake can never
1004
+ * be served after an edit; older generations are removed as new ones appear. */
1005
+ function bakeKey(ask) {
1006
+ return createHash("sha1").update(`${ask.frame}|${ask.theme}|${Math.round(ask.w)}|${Math.round(ask.h)}`).digest("hex").slice(0, 16);
1007
+ }
1008
+ function cacheDir(root, gen, key) {
1009
+ return join(root, "design", ".local", "bakes", String(gen), key);
1010
+ }
1011
+ /** The cache lives INSIDE the project: a `bakes` directory that resolves elsewhere (a symlink) is
1012
+ * never read, written or pruned. */
1013
+ function cacheInside(root) {
1014
+ const base = join(root, "design", ".local", "bakes");
1015
+ if (!existsSync(base)) return true;
1016
+ try {
1017
+ return realpathSync(base).startsWith(realpathSync(root) + sep);
1018
+ } catch {
1019
+ return false;
1020
+ }
1021
+ }
1022
+ function readCached(root, gen, ask, urlBase) {
1023
+ const key = bakeKey(ask);
1024
+ const dir = cacheDir(root, gen, key);
1025
+ try {
1026
+ const meta = JSON.parse(readFileSync(join(dir, "bake.json"), "utf8"));
1027
+ try {
1028
+ const now = /* @__PURE__ */ new Date();
1029
+ utimesSync(dir, now, now);
1030
+ } catch {}
1031
+ return {
1032
+ ...ask,
1033
+ ok: true,
1034
+ targets: meta.targets.map((t) => ({
1035
+ ...t,
1036
+ texture: t.verified ? `${urlBase}/${gen}/${key}/${t.texture}` : ""
1037
+ })),
1038
+ levels: meta.levels,
1039
+ rejected: meta.rejected,
1040
+ ms: 0
1041
+ };
1042
+ } catch {
1043
+ return null;
1044
+ }
1045
+ }
1046
+ function writeCached(root, gen, ask, r, urlBase, protect) {
1047
+ const key = bakeKey(ask);
1048
+ const dir = cacheDir(root, gen, key);
1049
+ const gdir = join(root, "design", ".local", "bakes", String(gen));
1050
+ mkdirSync(gdir, { recursive: true });
1051
+ if (!existsSync(join(gdir, "owner"))) writeFileSync(join(gdir, "owner"), String(process.pid));
1052
+ try {
1053
+ const names = readdirSync(gdir).filter((n) => !n.includes(".tmp-") && n !== key && n !== "owner" && !protect.has(n));
1054
+ if (names.length >= KEYS_PER_GEN) names.map((n) => ({
1055
+ n,
1056
+ t: statSync(join(gdir, n)).mtimeMs
1057
+ })).sort((a, b) => a.t - b.t).slice(0, names.length - KEYS_PER_GEN + 1).forEach(({ n }) => rmSync(join(gdir, n), {
1058
+ recursive: true,
1059
+ force: true
1060
+ }));
1061
+ } catch {}
1062
+ const tmp = `${dir}.tmp-${process.pid}`;
1063
+ rmSync(tmp, {
1064
+ recursive: true,
1065
+ force: true
1066
+ });
1067
+ mkdirSync(tmp, { recursive: true });
1068
+ const targets = r.targets.map((t, i) => {
1069
+ if (!t.verified) return {
1070
+ ...t,
1071
+ texture: ""
1072
+ };
1073
+ const name = `${i}.png`;
1074
+ writeFileSync(join(tmp, name), Buffer.from(t.texture.slice(t.texture.indexOf(",") + 1), "base64"));
1075
+ return {
1076
+ ...t,
1077
+ texture: name
1078
+ };
1079
+ });
1080
+ writeFileSync(join(tmp, "bake.json"), JSON.stringify({
1081
+ targets,
1082
+ levels: r.levels,
1083
+ rejected: r.rejected,
1084
+ ms: r.ms,
1085
+ outside: r.outside
1086
+ }));
1087
+ rmSync(dir, {
1088
+ recursive: true,
1089
+ force: true
1090
+ });
1091
+ try {
1092
+ renameSync(tmp, dir);
1093
+ } catch (e) {
1094
+ rmSync(tmp, {
1095
+ recursive: true,
1096
+ force: true
1097
+ });
1098
+ throw new Error(`could not write the compiled frame: ${e.message}`);
1099
+ }
1100
+ return {
1101
+ ...ask,
1102
+ ok: true,
1103
+ targets: targets.map((t) => ({
1104
+ ...t,
1105
+ texture: t.verified ? `${urlBase}/${gen}/${key}/${t.texture}` : ""
1106
+ })),
1107
+ levels: r.levels,
1108
+ rejected: r.rejected,
1109
+ ms: r.ms
1110
+ };
1111
+ }
1112
+ const alive = (pid) => {
1113
+ try {
1114
+ process.kill(pid, 0);
1115
+ return true;
1116
+ } catch (e) {
1117
+ return e.code === "EPERM";
1118
+ }
1119
+ };
1120
+ /** Drop every generation but the current one and those another live server owns (called at start
1121
+ * and when the generation bumps). */
1122
+ function pruneBakes(root, keep) {
1123
+ const base = join(root, "design", ".local", "bakes");
1124
+ if (!existsSync(base) || !cacheInside(root)) return;
1125
+ try {
1126
+ for (const name of readdirSync(base)) {
1127
+ if (name === String(keep)) continue;
1128
+ let owner = 0;
1129
+ try {
1130
+ owner = Number(readFileSync(join(base, name, "owner"), "utf8"));
1131
+ } catch {}
1132
+ if (owner && owner !== process.pid && alive(owner)) continue;
1133
+ rmSync(join(base, name), {
1134
+ recursive: true,
1135
+ force: true
1136
+ });
1137
+ }
1138
+ } catch {}
1139
+ }
1140
+ const NORMAL_OWNER = "normal";
1141
+ const flightKey = (root, gen, ask, owner = NORMAL_OWNER) => `${root}|${gen}|${bakeKey(ask)}|${owner}`;
1142
+ /**
1143
+ * An owner's compiles now (A3.8 #18): `queued` waiting for the pool, `running` in `bakeIn`, each bounded by its 45 s
1144
+ * deadline. The run's driver reads it directly: a run is bake-idle when the page's four counts and these two are zero.
1145
+ */
1146
+ function jobsOf(owner) {
1147
+ const j = jobs.get(owner);
1148
+ return j ? {
1149
+ queued: j.queued,
1150
+ running: j.running
1151
+ } : {
1152
+ queued: 0,
1153
+ running: 0
1154
+ };
1155
+ }
1156
+ const jobs = /* @__PURE__ */ new Map();
1157
+ const idleWaiters = /* @__PURE__ */ new Map();
1158
+ /** A job of `owner` moves from one state to the next: the counts follow, and an owner left with none is idle. */
1159
+ function move(owner, from, to) {
1160
+ const j = jobs.get(owner) ?? {
1161
+ queued: 0,
1162
+ running: 0
1163
+ };
1164
+ if (from === "queued") j.queued--;
1165
+ else if (from === "running") j.running--;
1166
+ if (to === "queued") j.queued++;
1167
+ else if (to === "running") j.running++;
1168
+ if (j.queued > 0 || j.running > 0) {
1169
+ jobs.set(owner, j);
1170
+ return;
1171
+ }
1172
+ jobs.delete(owner);
1173
+ const ws = idleWaiters.get(owner);
1174
+ idleWaiters.delete(owner);
1175
+ for (const w of ws ?? []) w();
1176
+ }
1177
+ /** Once `owner` has no compile queued or running: true, or false when `ms` passed first. */
1178
+ function jobsIdle(owner, ms) {
1179
+ if (!jobs.has(owner)) return Promise.resolve(true);
1180
+ return new Promise((resolve) => {
1181
+ let set = idleWaiters.get(owner);
1182
+ if (!set) idleWaiters.set(owner, set = /* @__PURE__ */ new Set());
1183
+ const done = () => {
1184
+ clearTimeout(t);
1185
+ resolve(true);
1186
+ };
1187
+ const t = setTimeout(() => {
1188
+ set.delete(done);
1189
+ resolve(false);
1190
+ }, ms);
1191
+ set.add(done);
1192
+ });
1193
+ }
1194
+ /** What a compile of a run that has ended answers, without rendering (A3.8 #19). */
1195
+ const RUN_ENDED = "the run ended";
1196
+ /** Runs that ended, cancelled or not: their compiles not started yet answer RUN_ENDED (bounded, oldest out). */
1197
+ const ended = /* @__PURE__ */ new Set();
1198
+ /** A run's own answers, in memory while it runs: a compile whose document skipped a missing poster, which never
1199
+ * fills the shared cache - its later asks find it here. */
1200
+ const runAnswers = /* @__PURE__ */ new Map();
1201
+ /** Has this run ended (its compiles answer RUN_ENDED)? */
1202
+ const bakesEnded = (owner) => owner !== "normal" && ended.has(owner);
1203
+ /** Each run's compiles not started yet - waiting for the lane or for the pool - by the function that ends one: a run's
1204
+ * end settles them at once, never on their turn (the review of a3-runs' fixes, minor #3). */
1205
+ const queuedJobs = /* @__PURE__ */ new Map();
1206
+ /**
1207
+ * A run ends (A3.8 #19, #20): its compiles not started answer RUN_ENDED at once, without rendering - those waiting for
1208
+ * the lane behind another batch and those waiting for the pool alike; one already rendering finishes (its frame URL
1209
+ * names the run, so it asks for no poster) and keeps nothing for the run; its answers and its failures go. The driver
1210
+ * then waits for its running jobs (`jobsIdle`).
1211
+ */
1212
+ function endRunBakes(owner) {
1213
+ if (owner === "normal") return;
1214
+ ended.add(owner);
1215
+ if (ended.size > 256) ended.delete(ended.values().next().value);
1216
+ runAnswers.delete(owner);
1217
+ for (const k of [...failed.keys()]) if (k.endsWith(`|${owner}`)) failed.delete(k);
1218
+ for (const end of [...queuedJobs.get(owner) ?? []]) end();
1219
+ }
1220
+ /** Test seams, in the suite's build only (test-build.ts: the npm build drops them) - the environment's read only with
1221
+ * MARVER_SLOT_BASE set (the suite's marker, as RUN_T's):
1222
+ * MV_BAKE_HOLD_MS holds each compile that long before it renders, so a test can find one still compiling.
1223
+ * `deadlineMs` (in-process only) shortens a compile's 45 s deadline, so a test can force "the bake timed out".
1224
+ * MV_BAKE_STOP_ASKING=1 answers a caller who stops waiting STOP_ASKING instead of COMPILING: the page takes it for a
1225
+ * failed compile, retries once and asks no more, so it goes idle while the server still compiles - the page's own 15
1226
+ * looks at a COMPILING outlast any held compile (A3.8 r1 #4's case, added by the review of a3-runs). */
1227
+ const bakeSeams = {};
1228
+ const holdMs = () => {
1229
+ return 0;
1230
+ };
1231
+ /** The suite's answer for a compile still running, under MV_BAKE_STOP_ASKING (above). */
1232
+ const STOP_ASKING = "still compiling - the suite asks the page to stop asking";
1233
+ const stillCompiling = () => COMPILING;
1234
+ /** Compiles in flight, by generation and key: identical asks - inside one request or across
1235
+ * concurrent ones - share one compile. */
1236
+ const inflight = /* @__PURE__ */ new Map();
1237
+ /** Compiles that FAILED for the frame's own reasons (it loops, never stops changing, never settles,
1238
+ * timed out - a run's only, `keptFor` -, has too many effects), by generation and key, so it is answered at once from memory
1239
+ * instead of being compiled again on every rest. The generation is in the key: an edit retries it.
1240
+ * Only these are kept - anything else (the source moved mid-compile, the browser or its pipe died,
1241
+ * a cache write failed) says nothing about the frame and is tried again. */
1242
+ const failed = /* @__PURE__ */ new Map();
1243
+ const FAILED_MAX = 2e3;
1244
+ /** Is this failure kept for `owner`? Of the frame, and - for a timeout - a run's alone: a run's failures go with it,
1245
+ * but a normal caller's 45 s deadline passed under a loaded machine as often as for the frame (a first compile of a
1246
+ * fresh canvas took 24 s under the suite), and kept it would leave the frame live until an edit. A normal caller's
1247
+ * timeout is tried again at its next ask, as before 0.27.2. */
1248
+ const keptFor = (owner, error) => ofTheFrame(error) && !(owner === "normal" && error === "the bake timed out");
1249
+ const ofTheFrame = (error) => error === "a looping animation - the frame rests paused, uncompiled" || /^the frame (never stopped changing|did not settle|never rendered|rendered an error)|(^|: )the bake timed out$|^too many effects|^an effect larger than/.test(error);
1250
+ /** The answer for a compile still running when a request stops waiting (`waitMs`): the frame stays
1251
+ * live for now, and its next ask finds the result in the cache. */
1252
+ const COMPILING = "compiling - ask again";
1253
+ /** Compile many frames as ONE operation (one browser, `shotConcurrency()` at a time), the cache
1254
+ * first. `urlFor(ask)` gives the frame's own URL; `urlBase` is where textures are served from;
1255
+ * `live()` is the source generation NOW - a compile the source outran is not published. */
1256
+ async function bakeBatch(opts) {
1257
+ const { root, gen, asks, urlFor, urlBase, live, log, waitMs } = opts;
1258
+ const owner = opts.owner ?? "normal";
1259
+ if (!cacheInside(root)) return asks.map((ask) => ({
1260
+ ...ask,
1261
+ ok: false,
1262
+ error: "design/.local/bakes resolves outside the project"
1263
+ }));
1264
+ const key = (ask) => flightKey(root, gen, ask, owner);
1265
+ const theirs = owner === "normal" ? void 0 : runAnswers.get(owner);
1266
+ const answers = asks.map((ask) => {
1267
+ const error = failed.get(key(ask));
1268
+ if (error !== void 0) return {
1269
+ ...ask,
1270
+ ok: false,
1271
+ error
1272
+ };
1273
+ return readCached(root, gen, ask, urlBase) ?? theirs?.get(key(ask)) ?? (bakesEnded(owner) ? {
1274
+ ...ask,
1275
+ ok: false,
1276
+ error: "the run ended"
1277
+ } : null);
1278
+ });
1279
+ const protect = new Set(asks.map(bakeKey));
1280
+ const misses = /* @__PURE__ */ new Map();
1281
+ asks.forEach((ask, i) => {
1282
+ if (answers[i]) return;
1283
+ const k = key(ask);
1284
+ const m = misses.get(k);
1285
+ if (m) m.at.push(i);
1286
+ else misses.set(k, {
1287
+ ask,
1288
+ at: [i]
1289
+ });
1290
+ });
1291
+ const mine = [];
1292
+ const unqueue = (job) => {
1293
+ if (!job.end) return;
1294
+ const s = queuedJobs.get(owner);
1295
+ s?.delete(job.end);
1296
+ if (s && !s.size) queuedJobs.delete(owner);
1297
+ job.end = void 0;
1298
+ };
1299
+ const settle = (job, a) => {
1300
+ if (job.state === "done") return;
1301
+ unqueue(job);
1302
+ move(owner, job.state, "done");
1303
+ job.state = "done";
1304
+ job.resolve(a);
1305
+ };
1306
+ const runEnded = (job) => settle(job, {
1307
+ ...job.ask,
1308
+ ok: false,
1309
+ error: RUN_ENDED
1310
+ });
1311
+ const waits = [...misses.entries()].map(([k, m]) => {
1312
+ let p = inflight.get(k);
1313
+ if (!p) {
1314
+ p = new Promise((resolve) => {
1315
+ const job = {
1316
+ ask: m.ask,
1317
+ resolve,
1318
+ state: "queued"
1319
+ };
1320
+ mine.push(job);
1321
+ move(owner, null, "queued");
1322
+ if (owner !== "normal") {
1323
+ job.end = () => runEnded(job);
1324
+ let s = queuedJobs.get(owner);
1325
+ if (!s) queuedJobs.set(owner, s = /* @__PURE__ */ new Set());
1326
+ s.add(job.end);
1327
+ }
1328
+ });
1329
+ inflight.set(k, p);
1330
+ p.then(() => inflight.delete(k));
1331
+ }
1332
+ return p.then((a) => {
1333
+ for (const i of m.at) answers[i] = {
1334
+ ...a,
1335
+ ...m.ask
1336
+ };
1337
+ });
1338
+ });
1339
+ async function compile() {
1340
+ try {
1341
+ await withBrowser("shot", (b) => pool(shotConcurrency(), mine, async (job) => {
1342
+ if (job.state !== "queued") return;
1343
+ if (bakesEnded(owner)) return runEnded(job);
1344
+ const cached = readCached(root, gen, job.ask, urlBase);
1345
+ if (cached) return settle(job, cached);
1346
+ unqueue(job);
1347
+ move(owner, "queued", "running");
1348
+ job.state = "running";
1349
+ const hold = holdMs();
1350
+ if (hold) await new Promise((r) => setTimeout(r, hold));
1351
+ const r = await bakeIn(b, {
1352
+ url: urlFor(job.ask),
1353
+ width: Math.round(job.ask.w),
1354
+ height: Math.round(job.ask.h)
1355
+ }).catch((e) => ({
1356
+ ok: false,
1357
+ error: e.message
1358
+ }));
1359
+ if (live && live() !== gen) return settle(job, {
1360
+ ...job.ask,
1361
+ ok: false,
1362
+ error: "the source changed during the compile"
1363
+ });
1364
+ let a;
1365
+ if (r.ok && r.posterSkipped) {
1366
+ a = {
1367
+ ...job.ask,
1368
+ ok: true,
1369
+ targets: r.targets.map((t) => ({
1370
+ ...t,
1371
+ texture: t.verified ? t.texture : ""
1372
+ })),
1373
+ levels: r.levels,
1374
+ rejected: r.rejected,
1375
+ ms: r.ms,
1376
+ posterSkipped: true
1377
+ };
1378
+ if (owner !== "normal" && !bakesEnded(owner)) {
1379
+ let m = runAnswers.get(owner);
1380
+ if (!m) runAnswers.set(owner, m = /* @__PURE__ */ new Map());
1381
+ m.set(key(job.ask), a);
1382
+ }
1383
+ } else try {
1384
+ a = r.ok ? writeCached(root, gen, job.ask, r, urlBase, protect) : {
1385
+ ...job.ask,
1386
+ ...r
1387
+ };
1388
+ } catch (e) {
1389
+ a = {
1390
+ ...job.ask,
1391
+ ok: false,
1392
+ error: e.message
1393
+ };
1394
+ }
1395
+ if (!a.ok && keptFor(owner, a.error) && !bakesEnded(owner)) {
1396
+ if (failed.size >= FAILED_MAX) failed.clear();
1397
+ failed.set(key(job.ask), a.error);
1398
+ }
1399
+ log?.(a);
1400
+ settle(job, a);
1401
+ }), {
1402
+ skip: () => bakesEnded(owner),
1403
+ skipped: []
1404
+ });
1405
+ for (const job of mine) runEnded(job);
1406
+ } catch (e) {
1407
+ for (const job of mine) settle(job, {
1408
+ ...job.ask,
1409
+ ok: false,
1410
+ error: e.message
1411
+ });
1412
+ }
1413
+ }
1414
+ const work = mine.length ? compile() : Promise.resolve();
1415
+ const all = owner === "normal" ? work.then(() => Promise.all(waits)) : Promise.all(waits);
1416
+ if (waitMs === void 0) {
1417
+ await all;
1418
+ return answers;
1419
+ }
1420
+ let timer;
1421
+ await Promise.race([all, new Promise((r) => {
1422
+ timer = setTimeout(r, waitMs);
1423
+ })]);
1424
+ clearTimeout(timer);
1425
+ const still = stillCompiling();
1426
+ return answers.map((a, i) => a ?? {
1427
+ ...asks[i],
1428
+ ok: false,
1429
+ error: still
1430
+ });
1431
+ }
1432
+ //#endregion
1433
+ //#region src/server/perf-inputs.ts
1434
+ /**
1435
+ * A run's inputs (spec 28 A3.4, A3.8 #21): the fingerprint that says two runs measured the same thing, and the
1436
+ * sticky flag that says the inputs changed during one. One set by construction: every file the dev server's own
1437
+ * watcher watches (`getWatched()`) - outside the root too: Vite watches a file a frame imports from outside the root
1438
+ * (a monorepo sibling package's source) once a page has loaded it - plus the board files and `_sizes.json` (which
1439
+ * that watcher ignores but which shape the layout and heights), git status playing no part. Owner: the headless
1440
+ * stream.
1441
+ *
1442
+ * FROZEN signatures (A3.8 #53). A fingerprint taken before the watcher is ready (30 s at most) is null, and the run
1443
+ * is invalid (`inputs`). Narrows, stated: a frame importing from a folder the watcher ignores (a sibling package's
1444
+ * `dist/`) is not in it. `inputPaths` and `hashInputs` (added by the review of a3-runs): a run fingerprints once its
1445
+ * warm-up has loaded the board, and its end hashes the same paths again - a file the watcher adds later is the sticky
1446
+ * flag's, so loading a frame's imports never changes a run's inputs.
1447
+ *
1448
+ * A run's set is the board's own (the review of a3-runs' fixes, minor #2): the watcher keeps every file outside the
1449
+ * root that any page ever loaded until the dev server restarts, so in a monorepo a run after a normal tab opened
1450
+ * another board hashed that board's sibling imports too, and two runs with nothing changed differed. Under the root
1451
+ * the set is still every watched file; outside it, only the watched files the run's own warm-up page requested and
1452
+ * the files those modules import directly (`InputsWatch.loaded`, from Vite's module graph: a stylesheet's inlined
1453
+ * `@import`s and a plugin's watched files are imported modules there), and the watched `tsconfig`/`jsconfig` files in
1454
+ * a folder above one of them (Vite watches the tsconfig that compiles a module; it is no import). Narrows, stated: a
1455
+ * tsconfig outside the root reached only by another's `extends`, from a folder above none of the run's files, is not
1456
+ * in a run's set. `fingerprint()` without a run - and `GET /api/perf/inputs` without `?run=` - still reads every
1457
+ * watched file.
1458
+ *
1459
+ * The sticky flag is the run registry's (`runs.changed`, perf-run.ts): plugin.ts tells it every event of the same
1460
+ * watcher, every change of a board file or `_sizes.json` its own boards watcher sees, and a Vite restart.
1461
+ */
1462
+ var perf_inputs_exports = /* @__PURE__ */ __exportAll({
1463
+ boardInputs: () => boardInputs,
1464
+ fileOfUrl: () => fileOfUrl,
1465
+ fingerprint: () => fingerprint,
1466
+ hashInputs: () => hashInputs,
1467
+ inputPaths: () => inputPaths,
1468
+ loadedFiles: () => loadedFiles
1469
+ });
1470
+ /** The file a request URL names in the dev server: `/@fs/<absolute>` one outside the root, else a path under Vite's
1471
+ * root; null for Vite's own ids (`/@vite/client`, `/@id/...`) and a URL that is no path. Its query is dropped. */
1472
+ function fileOfUrl(url, viteRoot, base = "/") {
1473
+ let path;
1474
+ try {
1475
+ path = decodeURIComponent(new URL(url, "http://x").pathname);
1476
+ } catch {
1477
+ return null;
1478
+ }
1479
+ if (base !== "/" && path.startsWith(base)) path = `/${path.slice(base.length)}`;
1480
+ if (path.startsWith("/@fs/")) {
1481
+ const abs = path.slice(4);
1482
+ return /^\/[A-Za-z]:\//.test(abs) ? abs.slice(1) : abs;
1483
+ }
1484
+ if (path.startsWith("/@")) return null;
1485
+ return join(viteRoot, path);
1486
+ }
1487
+ /** The files a page's requests loaded, each with the files its modules import directly (Vite records a stylesheet's
1488
+ * inlined `@import`s and a plugin's `addWatchFile` as imported modules) - one level: every module the page ran is
1489
+ * itself a request. */
1490
+ function loadedFiles(urls, viteRoot, graph, base = "/") {
1491
+ const out = /* @__PURE__ */ new Set();
1492
+ for (const u of urls) {
1493
+ const f = fileOfUrl(u, viteRoot, base);
1494
+ if (!f) continue;
1495
+ out.add(f);
1496
+ for (const m of graph?.getModulesByFile(f) ?? []) for (const d of m.importedModules) if (d.file) out.add(d.file);
1497
+ }
1498
+ return [...out];
1499
+ }
1500
+ /** Is `p` under `root`? */
1501
+ const under = (root, p) => {
1502
+ const r = relative(root, p);
1503
+ return r !== ".." && !r.startsWith(`..${sep}`) && !isAbsolute(r);
1504
+ };
1505
+ /** A compiler config Vite watches for the modules below it. */
1506
+ const CONFIG_FILE = /^[jt]sconfig(\..*)?\.json$/;
1507
+ /** Every folder above these files. */
1508
+ function above(files) {
1509
+ const dirs = /* @__PURE__ */ new Set();
1510
+ for (const f of files) for (let d = dirname(f); !dirs.has(d); d = dirname(d)) {
1511
+ dirs.add(d);
1512
+ if (dirname(d) === d) break;
1513
+ }
1514
+ return dirs;
1515
+ }
1516
+ /** The board files the watcher never sees: every `design/boards/*.json`, `_sizes.json` among them - regular files only. */
1517
+ function boardInputs(root) {
1518
+ const dir = join(root, "design", "boards");
1519
+ let names = [];
1520
+ try {
1521
+ names = readdirSync(dir);
1522
+ } catch {
1523
+ return [];
1524
+ }
1525
+ return names.filter((n) => n.endsWith(".json")).map((n) => join(dir, n)).filter((p) => {
1526
+ try {
1527
+ return lstatSync(p).isFile();
1528
+ } catch {
1529
+ return false;
1530
+ }
1531
+ });
1532
+ }
1533
+ /** Every path the fingerprint reads now: each the watcher watches under the root, and the board files - and outside
1534
+ * the root each watched one, or with `urls` (a run's own page's requests, and `w.loaded`) only those the page loaded;
1535
+ * null before the watcher is ready. Directories among them are dropped when hashed. */
1536
+ async function inputPaths(root, w, urls) {
1537
+ if (!await w.ready()) return null;
1538
+ const own = urls && w.loaded ? new Set(w.loaded(urls)) : null;
1539
+ const dirs = own ? above(own) : null;
1540
+ const paths = /* @__PURE__ */ new Set();
1541
+ for (const [dir, names] of Object.entries(w.watched())) {
1542
+ const base = isAbsolute(dir) ? dir : join(root, dir);
1543
+ for (const n of names) {
1544
+ const p = join(base, n);
1545
+ if (!own || under(root, p) || own.has(p) || CONFIG_FILE.test(n) && dirs.has(base)) paths.add(p);
1546
+ }
1547
+ }
1548
+ for (const p of boardInputs(root)) paths.add(p);
1549
+ return [...paths];
1550
+ }
1551
+ /** These paths' fingerprint: each file's path from the root (`../` for one outside it), size and mtime. A path that
1552
+ * is gone or no file counts for nothing - so one deleted since changes it. */
1553
+ async function hashInputs(root, paths) {
1554
+ const lines = [];
1555
+ for (let i = 0; i < paths.length; i += 64) {
1556
+ const got = await Promise.all(paths.slice(i, i + 64).map(async (p) => {
1557
+ const st = await stat(p).catch(() => null);
1558
+ return st?.isFile() ? `${relative(root, p).split(sep).join("/")}\0${st.size}\0${st.mtimeMs}` : null;
1559
+ }));
1560
+ for (const l of got) if (l) lines.push(l);
1561
+ }
1562
+ lines.sort();
1563
+ return {
1564
+ hash: createHash("sha256").update(lines.join("\n")).digest("hex").slice(0, 16),
1565
+ files: lines.length
1566
+ };
1567
+ }
1568
+ /** The fingerprint of every watched file, plus the board files and `_sizes.json`; null before the watcher is ready. */
1569
+ async function fingerprint(root, w) {
1570
+ const paths = await inputPaths(root, w);
1571
+ return paths ? hashInputs(root, paths) : null;
1572
+ }
1573
+ /** The host's two spawns, by absolute path (A3.2: every spawn `execFile` with an absolute path). */
1574
+ const HOST_SPAWNS = {
1575
+ sysctl: {
1576
+ file: "/usr/sbin/sysctl",
1577
+ args: ["-n", ...[
1578
+ "hw.perflevel0.physicalcpu",
1579
+ "hw.perflevel1.physicalcpu",
1580
+ "hw.model"
1581
+ ]]
1582
+ },
1583
+ swVers: {
1584
+ file: "/usr/bin/sw_vers",
1585
+ args: ["-productVersion"]
1586
+ }
1587
+ };
1588
+ /**
1589
+ * The host with its two spawns read (added by the recorder stream, so the app and a headless run parse them alike and
1590
+ * their `hostHash` meets): `sysctl`'s stdout for HOST_SYSCTL - null when it exited non-zero - and `sw_vers
1591
+ * -productVersion`'s, null when it failed. `sysctl` gives all three of P cores, E cores and the model, or none: an
1592
+ * unknown oid shifts the lines (an Intel Mac has no perflevels), so anything but three lines that each parse leaves all
1593
+ * three as `base` has them ('unknown'). The rules are machine-host.ts's own (`parseHostSysctl`, `parseOs`), so a host
1594
+ * hashes alike whichever side parsed it.
1595
+ */
1596
+ function withHostSpawns(base, sysctl, swVers) {
1597
+ const out = {
1598
+ ...base,
1599
+ cores: { ...base.cores }
1600
+ };
1601
+ const l = typeof sysctl === "string" ? sysctl.trim().split("\n").map((x) => x.trim()) : [];
1602
+ const n = (x) => x !== void 0 && /^\d{1,4}$/.test(x) ? Number(x) : null;
1603
+ const p = n(l[0]), e = n(l[1]), model = l.length === 3 && /^[\w,. -]{1,64}$/.test(l[2]) ? l[2] : null;
1604
+ if (p !== null && e !== null && model !== null) {
1605
+ out.cores.p = p;
1606
+ out.cores.e = e;
1607
+ out.model = model;
1608
+ }
1609
+ const v = typeof swVers === "string" ? swVers.trim() : "";
1610
+ if (/^\d+(\.\d+){0,3}$/.test(v)) out.os = v;
1611
+ return out;
1612
+ }
1613
+ /**
1614
+ * The host read the one way the app (machine.ts) and a headless run (machine-host.ts `hostProfile`) both read it:
1615
+ * `base` (machine-host.ts `basicHost()`), then the two spawns through the caller's own `run`, each tried once more
1616
+ * when it fails - one busy moment at a launch would otherwise give that launch a `hostHash` of its own - then
1617
+ * `withHostSpawns`.
1618
+ */
1619
+ async function readHost(base, run) {
1620
+ const twice = async (s) => await run(s.file, s.args) ?? await run(s.file, s.args);
1621
+ const [sys, sw] = await Promise.all([twice(HOST_SPAWNS.sysctl), twice(HOST_SPAWNS.swVers)]);
1622
+ return withHostSpawns(base, sys, sw);
1623
+ }
1624
+ /**
1625
+ * Canonical JSON: object keys sorted at every depth, arrays in order, no whitespace; `undefined` members dropped as
1626
+ * JSON.stringify drops them. Two equal profiles give the same text whatever order their fields were built in.
1627
+ */
1628
+ function canonical(v) {
1629
+ if (v === null || typeof v !== "object") {
1630
+ const s = JSON.stringify(v);
1631
+ return s === void 0 ? "null" : s;
1632
+ }
1633
+ if (Array.isArray(v)) return `[${v.map((x) => x === void 0 || typeof x === "function" ? "null" : canonical(x)).join(",")}]`;
1634
+ const o = v;
1635
+ return `{${Object.keys(o).filter((k) => o[k] !== void 0 && typeof o[k] !== "function").sort().map((k) => `${JSON.stringify(k)}:${canonical(o[k])}`).join(",")}}`;
1636
+ }
1637
+ //#endregion
1638
+ //#region src/server/machine-host.ts
1639
+ /**
1640
+ * A headless run's host profile (spec 28 A3.2, A3.8 #11): what this Mac is, as a run can know it without Electron -
1641
+ * chip, cores, model, memory, macOS, power - written as its own profile to `~/.marver/perf/machine/<hash>.json`
1642
+ * (700/600, content-addressed, as the app writes its own) and carried inline in each run line. Its `hostHash` is the
1643
+ * one the app's profile shares (src/shared/machine.ts), so runs and app records of one Mac meet. Owner: the headless
1644
+ * stream.
1645
+ *
1646
+ * FROZEN signatures (A3.8 #53). Every spawn is `execFile` with an absolute path and a 2 s timeout; a failure is
1647
+ * 'unknown'; off macOS every field is 'unknown' but `arch`, `memGB` and `chip`.
1648
+ *
1649
+ * One reader for both writers (the review of a3-runs, minor #8): the host is `readHost(basicHost(), spawn)` from
1650
+ * src/shared/machine.ts - the floor here, the two spawns and their rules there (`withHostSpawns`) - which the app's
1651
+ * machine.ts reads its host with too, so the two hash a host alike by construction, not by two copies kept equal.
1652
+ * `parseHostSysctl` and `parseOs` read through `withHostSpawns`.
1653
+ */
1654
+ /** The profile's hash: the same function the app uses for its own (A3.8 #11). */
1655
+ const profileHash = (p) => createHash("sha256").update(canonical(p)).digest("hex").slice(0, 16);
1656
+ /** What Node knows with no spawn: the floor every profile starts from. */
1657
+ function basicHost() {
1658
+ const c = cpus();
1659
+ return {
1660
+ chip: c[0]?.model?.trim() || "unknown",
1661
+ cores: {
1662
+ total: c.length,
1663
+ p: "unknown",
1664
+ e: "unknown"
1665
+ },
1666
+ model: "unknown",
1667
+ memGB: Math.round(totalmem() / 2 ** 30),
1668
+ os: "unknown",
1669
+ arch: arch()
1670
+ };
1671
+ }
1672
+ const PMSET = "/usr/bin/pmset";
1673
+ const SPAWN_MS = 2e3;
1674
+ /** One spawn's standard output, or null: it could not start, exited non-zero or ran past 2 s. */
1675
+ const spawnOut = (bin, args, ms = SPAWN_MS) => new Promise((resolve) => {
1676
+ try {
1677
+ execFile(bin, [...args], {
1678
+ timeout: ms,
1679
+ encoding: "utf8",
1680
+ maxBuffer: 65536
1681
+ }, (err, out) => resolve(err ? null : String(out)));
1682
+ } catch {
1683
+ resolve(null);
1684
+ }
1685
+ });
1686
+ /** `pmset -g ps`'s first line names the source: "Now drawing from 'AC Power'" or "'Battery Power'". */
1687
+ function parsePower(out) {
1688
+ const m = /drawing from '([^']+)'/.exec(out ?? "");
1689
+ return m?.[1] === "AC Power" ? "ac" : m?.[1] === "Battery Power" ? "battery" : "unknown";
1690
+ }
1691
+ /** The host, read as the app reads its own (`readHost`, src/shared/machine.ts): this floor, then `sysctl -n
1692
+ * hw.perflevel0.physicalcpu hw.perflevel1.physicalcpu hw.model` and `sw_vers -productVersion`, each tried once more
1693
+ * when it fails. */
1694
+ async function hostProfile() {
1695
+ return process.platform === "darwin" ? readHost(basicHost(), (file, args) => spawnOut(file, args)) : basicHost();
1696
+ }
1697
+ /** Where the power comes from now (`pmset -g ps`); unknown off macOS. */
1698
+ const powerSource = async () => process.platform === "darwin" ? parsePower(await spawnOut(PMSET, ["-g", "ps"])) : "unknown";
1699
+ /** The run's profile, written to `<MARVER_HOME>/perf/machine/<hash>.json` (or touched when it exists): its hash. The
1700
+ * write is best effort - a run never fails for its profile - and a file is never rewritten: a profile is immutable,
1701
+ * its name its content's hash. */
1702
+ async function writeHeadlessProfile(home) {
1703
+ const [host, power] = await Promise.all([hostProfile(), powerSource()]);
1704
+ const profile = {
1705
+ v: 1,
1706
+ kind: "headless",
1707
+ host,
1708
+ hostHash: profileHash(host),
1709
+ power
1710
+ };
1711
+ const hash = profileHash(profile);
1712
+ try {
1713
+ const dir = join(home, "perf", "machine");
1714
+ mkdirSync(dir, {
1715
+ recursive: true,
1716
+ mode: 448
1717
+ });
1718
+ const file = join(dir, `${hash}.json`);
1719
+ if (existsSync(file)) {
1720
+ const now = /* @__PURE__ */ new Date();
1721
+ utimesSync(file, now, now);
1722
+ } else {
1723
+ const tmp = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
1724
+ try {
1725
+ writeFileSync(tmp, JSON.stringify(profile, null, 2) + "\n", {
1726
+ flag: "wx",
1727
+ mode: 384
1728
+ });
1729
+ renameSync(tmp, file);
1730
+ } catch {
1731
+ rmSync(tmp, { force: true });
1732
+ }
1733
+ }
1734
+ } catch {}
1735
+ return {
1736
+ hash,
1737
+ profile
1738
+ };
1739
+ }
1740
+ //#endregion
1741
+ //#region src/server/update.ts
1742
+ /**
1743
+ * Update discovery - dev only, and deliberately boring about privacy: one anonymous
1744
+ * registry metadata GET per day (the same request `npm view` makes), cached in
1745
+ * design/.local/, nothing sent beyond the request itself. Offline, slow, or
1746
+ * firewalled registries degrade to silence. MARVER_NO_UPDATE_CHECK=1 disables it.
1747
+ * Published bundles never check anything - viewers are not the owner.
1748
+ */
1749
+ const TTL = 864e5;
1750
+ /** Installed version: walk up from this module to the package's own package.json
1751
+ * (one level from dist/, two from src/server/ - the walk covers both). */
1752
+ function installedVersion() {
1753
+ let dir = dirname(fileURLToPath(import.meta.url));
1754
+ for (let i = 0; i < 4; i++) {
1755
+ try {
1756
+ const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
1757
+ if (pkg.name === "@marver-design/marver") return pkg.version;
1758
+ } catch {}
1759
+ dir = dirname(dir);
1760
+ }
1761
+ return null;
1762
+ }
1763
+ /** Strictly-newer numeric compare; anything non-numeric (prerelease tags) compares false. */
1764
+ const newer = (a, b) => {
1765
+ const pa = a.split(".").map((n) => parseInt(n, 10));
1766
+ const pb = b.split(".").map((n) => parseInt(n, 10));
1767
+ for (let i = 0; i < 3; i++) {
1768
+ const x = pa[i] ?? 0, y = pb[i] ?? 0;
1769
+ if (!Number.isFinite(x) || !Number.isFinite(y)) return false;
1770
+ if (x !== y) return x > y;
1771
+ }
1772
+ return false;
1773
+ };
1774
+ /** The latest published version when strictly newer than installed, else null. Never throws. */
1775
+ async function checkUpdate(root) {
1776
+ if (process.env.MARVER_NO_UPDATE_CHECK) return null;
1777
+ const current = installedVersion();
1778
+ if (!current) return null;
1779
+ const latest = await latestVersion(root);
1780
+ return latest && newer(latest, current) ? latest : null;
1781
+ }
1782
+ async function latestVersion(root) {
1783
+ const cacheFile = join(root, "design", ".local", "update-check.json");
1784
+ const wellFormed = (v) => typeof v === "string" && /^\d+\.\d+\.\d+$/.test(v);
1785
+ try {
1786
+ const c = JSON.parse(readFileSync(cacheFile, "utf8"));
1787
+ const age = Date.now() - c.checkedAt;
1788
+ if (typeof c.checkedAt === "number" && age >= 0 && age < TTL) return wellFormed(c.latest) ? c.latest : null;
1789
+ } catch {}
1790
+ let latest = null;
1791
+ try {
1792
+ const res = await fetch(`https://registry.npmjs.org/${encodeURIComponent(PKG)}/latest`, { signal: AbortSignal.timeout(3e3) });
1793
+ if (res.ok) {
1794
+ const v = (await res.json())?.version;
1795
+ if (wellFormed(v)) latest = v;
1796
+ }
1797
+ } catch {}
1798
+ try {
1799
+ mkdirSync(join(root, "design", ".local"), { recursive: true });
1800
+ writeFileSync(cacheFile, JSON.stringify({
1801
+ checkedAt: Date.now(),
1802
+ latest
1803
+ }) + "\n");
1804
+ } catch {}
1805
+ return latest;
1806
+ }
1807
+ //#endregion
1808
+ //#region src/server/perf-run.ts
1809
+ /**
1810
+ * Headless perf runs, the server's half (spec 28 A3.4, A3.8 #17-#22): the run registry, the barrier, and the
1811
+ * driver of script 1 in the canvas's own headless Chrome (cdp.ts's `Browser`, never `shootFrame()`, which makes
1812
+ * posters on purpose). Owner: the headless stream. The contract with the page is src/shared/perf-run.ts.
1813
+ *
1814
+ * - `perfRunBarrier()`, mounted right after the workspace guard (plugin.ts), **refuses and counts** any other
1815
+ * mutating request whose run id it finds: the `x-mv-perfrun` header, else the `Referer`'s query (a frame's own
1816
+ * fetch; best effort). Counts are per run id. `POST /api/poster` is refused for any run id, registered or not.
1817
+ * - The server, never the page, stamps `run` on a run's records (perf.ts `logPage(root, raws, { run })`).
1818
+ * - `POST /api/perf/run` reads the whole body before it registers a run; from then on the run is cancelled when the
1819
+ * response closes before it finished (`res.on('close')` with `res.writableFinished` false), never `req.on('close')`.
1820
+ *
1821
+ * FROZEN (A3.8 #53): `RunReg`, `runs`, `runIdOf`, `perfRunBarrier`, `runOnce`'s signature, `RUN_T`. `RunOptions`
1822
+ * gained an optional `watch` (the headless stream): the fingerprint needs the dev server's watcher.
1823
+ *
1824
+ * The driver (script 1, A3.8 #20): one headless Chrome per run. The warm-up in a context of its own, waited for until
1825
+ * its load settled (or was cut) and the run is bake-idle, 60 s at most, else `bakes: 'cold'`. The measured load in a
1826
+ * fresh context - cache off, 1440 x 900 at scale 2, `--slow`'s 4x CPU throttling set before it loads - and its three
1827
+ * gestures only once it is bake-idle (30 s, else invalid `bakes`). In `finally` the throttling reset and the context
1828
+ * disposed, the browser closed, the run's queued compiles ended and its running ones awaited, 300 ms for a change
1829
+ * event on its way: only then the line (runs.jsonl), and the next repeat.
1830
+ *
1831
+ * Nothing waits on the page for ever (the review of a3-runs, major #1): a same-origin frame's script that never
1832
+ * returns stops the shell's main thread with it, and the page then answers no CDP call. Every call to a page has
1833
+ * `callMs` (15 s) to answer; one that does not marks the page `stalled`, settles all of its calls at once (and every
1834
+ * later one), and the run ends cut `unresponsive`, its heap sampling stopped. A run that drives past `runMs` (7 min)
1835
+ * ends cut `overrun`.
1836
+ *
1837
+ * The review of a3-runs' fixes: a run's inputs outside the root are the files its own warm-up page loaded (the CDP
1838
+ * requests of that page and its frames, perf-inputs.ts), so a normal tab on another board changes nothing of them; its
1839
+ * queued compiles end the moment it halts or its script ends, before its pages close; a compile still running 50 s
1840
+ * after its end says so in the line (`bakesPending`) and makes the next run `overlapped`; the gestures the line counts
1841
+ * are the driver's own three, after a fit come to rest; only a crash - the page's, the browser's, or a browser-level
1842
+ * call never answered - is `crash`, any other failure of the driver is cut `driver: <why>`; and the run's records past
1843
+ * the collector's bound count as lost (`records`).
1844
+ */
1845
+ var perf_run_exports = /* @__PURE__ */ __exportAll({
1846
+ Halt: () => Halt,
1847
+ REPORT_FRAMES_MAX: () => REPORT_FRAMES_MAX,
1848
+ RUN_ALLOWED: () => RUN_ALLOWED,
1849
+ RUN_HEADER: () => RUN_HEADER,
1850
+ RUN_ID: () => RUN_ID,
1851
+ RUN_PARAM: () => RUN_PARAM,
1852
+ RUN_SCRIPT: () => 1,
1853
+ RUN_T: () => RUN_T,
1854
+ WARM_PARAM: () => WARM_PARAM,
1855
+ allowedInRun: () => allowedInRun,
1856
+ closePage: () => closePage,
1857
+ failureOf: () => failureOf,
1858
+ measureGestures: () => measureGestures,
1859
+ openPage: () => openPage,
1860
+ perfRunBarrier: () => perfRunBarrier,
1861
+ readRunRequest: () => readRunRequest,
1862
+ readWhole: () => readWhole,
1863
+ runIdOf: () => runIdOf,
1864
+ runInputPaths: () => runInputPaths,
1865
+ runLine: () => runLine,
1866
+ runOnce: () => runOnce,
1867
+ runSeams: () => runSeams,
1868
+ runT: () => runT,
1869
+ runUrl: () => runUrl,
1870
+ runs: () => runs,
1871
+ serveRun: () => serveRun,
1872
+ timedGesture: () => timedGesture
1873
+ });
1874
+ /** The driver's durations (A3.4, A3.8 #20, #22); overridable only when `MARVER_SLOT_BASE` is set (the tests' marker).
1875
+ * `callMs` and `runMs` were added by the review of a3-runs: a call to a page unanswered for `callMs` ends the run cut
1876
+ * `unresponsive`; a run that drives past `runMs` - more than every deadline above it added up - ends cut `overrun`. */
1877
+ const RUN_T = {
1878
+ warmMs: 6e4,
1879
+ settleMs: 12e4,
1880
+ bakeIdleMs: 3e4,
1881
+ gestureEndMs: 5e3,
1882
+ fitIdleMs: 3e3,
1883
+ eventMs: 16,
1884
+ pauseMs: 500,
1885
+ heapMs: 1e3,
1886
+ statusMs: 100,
1887
+ watcherLagMs: 300,
1888
+ watcherReadyMs: 3e4,
1889
+ heartbeatMs: 1e4,
1890
+ callMs: 15e3,
1891
+ runMs: 42e4
1892
+ };
1893
+ /** The page's own bound on `flush()` (recorder.ts): the driver waits that long, and `callMs` more. */
1894
+ const FLUSH_MS = 15e3;
1895
+ const RECORDS_MAX = 2e4;
1896
+ const live = /* @__PURE__ */ new Map();
1897
+ /** Module state, so Vite's in-place restart keeps it (A3.8 #22). */
1898
+ const runs = {
1899
+ /** a new run with its own id */
1900
+ register(board, id) {
1901
+ if (!RUN_ID.test(id)) throw new Error("perf-run: a run id is 16 hex");
1902
+ const reg = {
1903
+ id,
1904
+ board,
1905
+ startedAt: Date.now(),
1906
+ phase: "warm",
1907
+ forbidden: 0,
1908
+ forbiddenPaths: [],
1909
+ inputsChanged: null,
1910
+ records: [],
1911
+ overlapped: live.size > 0
1912
+ };
1913
+ for (const other of live.values()) other.overlapped = true;
1914
+ live.set(id, reg);
1915
+ return reg;
1916
+ },
1917
+ get: (id) => live.get(id),
1918
+ /** the run ends: unregistered, and handed back for its line */
1919
+ end(id) {
1920
+ const r = live.get(id);
1921
+ live.delete(id);
1922
+ return r;
1923
+ },
1924
+ /** a mutating request refused for `id` (an unregistered id counts nowhere) */
1925
+ forbidden(id, what) {
1926
+ const r = live.get(id);
1927
+ if (!r) return;
1928
+ r.forbidden += 1;
1929
+ if (r.forbiddenPaths.length < 10) r.forbiddenPaths.push(what);
1930
+ },
1931
+ /** a watched file changed: every registered run's sticky flag */
1932
+ changed(file) {
1933
+ for (const r of live.values()) r.inputsChanged ??= file;
1934
+ },
1935
+ /** Vite restarted in place (an .env or config edit, A3.8 #22): every registered run's inputs changed, and the old
1936
+ * server's close is about to end its stream - which must not read as the client going away */
1937
+ restarted() {
1938
+ for (const r of live.values()) {
1939
+ r.restarted = true;
1940
+ r.inputsChanged ??= "(the dev server restarted)";
1941
+ }
1942
+ },
1943
+ /** a run's cleaned records (perf.ts logPage's `kept`) */
1944
+ records(id, recs) {
1945
+ const r = live.get(id);
1946
+ if (!r) return;
1947
+ for (const x of recs) if (r.records.length < RECORDS_MAX) r.records.push(x);
1948
+ else r.overflow = (r.overflow ?? 0) + 1;
1949
+ },
1950
+ active: () => [...live.values()]
1951
+ };
1952
+ /** A request's run id: the header, else `mvperfrun` in the Referer's query; null when it names none. */
1953
+ function runIdOf(req) {
1954
+ const h = req.headers[RUN_HEADER];
1955
+ const head = Array.isArray(h) ? h[0] : h;
1956
+ if (typeof head === "string" && RUN_ID.test(head)) return head;
1957
+ const ref = req.headers.referer;
1958
+ if (typeof ref !== "string") return null;
1959
+ try {
1960
+ const id = new URL(ref).searchParams.get(RUN_PARAM);
1961
+ return id && RUN_ID.test(id) ? id : null;
1962
+ } catch {
1963
+ return null;
1964
+ }
1965
+ }
1966
+ /** The server's barrier (A3.8 #17), right after the workspace guard: a run's mutating request outside the allowed list is refused (403) and counted. */
1967
+ function perfRunBarrier() {
1968
+ return (req, res, next) => {
1969
+ const method = (req.method ?? "GET").toUpperCase();
1970
+ if (method === "GET" || method === "HEAD" || method === "OPTIONS") return next();
1971
+ const id = runIdOf(req);
1972
+ if (!id) return next();
1973
+ let path = "/";
1974
+ try {
1975
+ path = new URL(req.url ?? "/", "http://x").pathname;
1976
+ } catch {}
1977
+ const base = `${ROUTE}/api/`;
1978
+ if (allowedInRun(method, path.startsWith(base) ? path.slice(base.length) : null)) return next();
1979
+ runs.forbidden(id, `${method} ${path}`);
1980
+ res.statusCode = 403;
1981
+ res.setHeader("content-type", "application/json");
1982
+ res.setHeader(RUN_HEADER, "refused");
1983
+ res.end("{\"error\":\"a perf run is read-only\"}");
1984
+ };
1985
+ }
1986
+ /** In-process test seams: the driver the route runs, durations, every CDP call the driver makes. Never set outside tests,
1987
+ * and read in the suite's build only (test-build.ts: the npm build drops them, MV_PERF_RUN_T too). */
1988
+ const runSeams = {};
1989
+ /** RUN_T, with the suite's overrides: `runSeams.t` in-process, `MV_PERF_RUN_T` (JSON) for a dev server a test starts -
1990
+ * both read only with MARVER_SLOT_BASE set (the suite's marker). */
1991
+ function runT() {
1992
+ return { ...RUN_T };
1993
+ }
1994
+ /** The shell's address for a run's load: its run id, the warm-up's mark, the board. */
1995
+ const runUrl = (origin, board, id, warm) => `${origin}/?${RUN_PARAM}=${id}${warm ? `&${WARM_PARAM}=1` : ""}#/b/${encodeURIComponent(board)}`;
1996
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
1997
+ /** The last runs' own input paths, for `GET /api/perf/inputs?run=<id>` (the review of a3-runs' fixes): a run's set
1998
+ * outside the root is its page's, which no request without the run can rebuild. Module state, the newest 32. */
1999
+ const RUN_PATHS_MAX = 32;
2000
+ const runPaths = /* @__PURE__ */ new Map();
2001
+ /** The paths run `id` fingerprinted, while this dev server keeps them. */
2002
+ const runInputPaths = (id) => runPaths.get(id);
2003
+ /** Runs whose compiles outlived the wait at their end: a run registered while one of them still compiles is
2004
+ * overlapped (its measurement ran beside that compile). */
2005
+ const lingering = /* @__PURE__ */ new Set();
2006
+ function anyLingering() {
2007
+ for (const r of lingering) {
2008
+ const j = jobsOf(r);
2009
+ if (j.queued + j.running === 0) lingering.delete(r);
2010
+ }
2011
+ return lingering.size > 0;
2012
+ }
2013
+ var Halt = class extends Error {
2014
+ why;
2015
+ constructor(why) {
2016
+ super(why);
2017
+ this.why = why;
2018
+ }
2019
+ };
2020
+ /** A browser-level call that never answered: the browser is gone, a crash. */
2021
+ var BrowserSilent = class extends Error {};
2022
+ /** A promise given `ms` to settle, else rejected with `what` (a browser-level call: one that never answers is a crash). */
2023
+ function within(p, ms, what) {
2024
+ let t;
2025
+ return Promise.race([p, new Promise((_, reject) => {
2026
+ t = setTimeout(() => reject(new BrowserSilent(`${what}: no answer in ${ms} ms`)), ms);
2027
+ })]).finally(() => clearTimeout(t));
2028
+ }
2029
+ /**
2030
+ * A fresh context: 1440 x 900 at scale 2, the cache on or off, and with `slow` the CPU throttled 4x before anything
2031
+ * loads. Its calls are its own (one owner, cdp.ts `abort`): each has `callMs` to answer, else the page is `stalled`
2032
+ * and every call of it settles; `halt` (the run stopping: cancelled, or past its cap) settles them all too.
2033
+ */
2034
+ async function openPage(b, o) {
2035
+ const T = runT();
2036
+ const own = {};
2037
+ const offs = [];
2038
+ const page = {
2039
+ context: "",
2040
+ session: "",
2041
+ slow: o.slow,
2042
+ crashed: false,
2043
+ stalled: false,
2044
+ send: (m, p = {}, ms) => call(m, p, page.session, ms),
2045
+ async eval(expression, awaitPromise = false, ms) {
2046
+ const r = await call("Runtime.evaluate", {
2047
+ expression,
2048
+ returnByValue: true,
2049
+ awaitPromise
2050
+ }, page.session, ms);
2051
+ if (r?.exceptionDetails) throw new Error(`the page threw: ${r.exceptionDetails.exception?.description ?? r.exceptionDetails.text ?? "an error"}`);
2052
+ return r?.result?.value;
2053
+ },
2054
+ stop: () => {
2055
+ for (const off of offs.splice(0)) off();
2056
+ }
2057
+ };
2058
+ function call(m, p = {}, sid, ms = T.callMs) {
2059
+ const sent = b.send(m, p, sid, own);
2060
+ let t;
2061
+ const late = new Promise((_, reject) => {
2062
+ t = setTimeout(() => {
2063
+ reject(new Halt("unresponsive"));
2064
+ page.stalled = true;
2065
+ b.abort(own, `the page stopped answering (${m}, ${ms} ms)`);
2066
+ }, ms);
2067
+ });
2068
+ return Promise.race([sent, late]).finally(() => clearTimeout(t));
2069
+ }
2070
+ const halt = o.halt;
2071
+ if (halt) {
2072
+ const onHalt = () => b.abort(own, String(halt.reason ?? "halted"));
2073
+ if (halt.aborted) onHalt();
2074
+ else {
2075
+ halt.addEventListener("abort", onHalt, { once: true });
2076
+ offs.push(() => halt.removeEventListener("abort", onHalt));
2077
+ }
2078
+ }
2079
+ try {
2080
+ const { browserContextId } = await call("Target.createBrowserContext", { disposeOnDetach: true });
2081
+ page.context = browserContextId;
2082
+ const { targetId } = await call("Target.createTarget", {
2083
+ url: "about:blank",
2084
+ browserContextId,
2085
+ newWindow: true,
2086
+ width: 1440,
2087
+ height: 900
2088
+ });
2089
+ const { sessionId } = await call("Target.attachToTarget", {
2090
+ targetId,
2091
+ flatten: true
2092
+ });
2093
+ page.session = sessionId;
2094
+ offs.push(b.on((m) => {
2095
+ if (m.sessionId === sessionId && (m.method === "Inspector.targetCrashed" || m.method === "Target.targetCrashed")) page.crashed = true;
2096
+ }));
2097
+ await page.send("Inspector.enable").catch((e) => {
2098
+ if (page.stalled) throw e;
2099
+ });
2100
+ await page.send("Page.enable");
2101
+ await page.send("Runtime.enable");
2102
+ await page.send("Network.enable");
2103
+ await page.send("Network.setCacheDisabled", { cacheDisabled: !o.cache });
2104
+ await page.send("Emulation.setDeviceMetricsOverride", {
2105
+ width: 1440,
2106
+ height: 900,
2107
+ deviceScaleFactor: 2,
2108
+ mobile: false
2109
+ });
2110
+ if (o.slow) await page.send("Emulation.setCPUThrottlingRate", { rate: 4 });
2111
+ } catch (e) {
2112
+ page.stop();
2113
+ throw e;
2114
+ }
2115
+ return page;
2116
+ }
2117
+ /** The page's end, outside the run's own calls (they may be aborted): the throttling reset, then its context disposed -
2118
+ * each bounded, never throwing. */
2119
+ async function closePage(b, page) {
2120
+ page.stop();
2121
+ const bounded = async (m, p, sid) => {
2122
+ let t;
2123
+ await Promise.race([b.send(m, p, sid).catch(() => {}), new Promise((r) => {
2124
+ t = setTimeout(r, 2e3);
2125
+ })]);
2126
+ clearTimeout(t);
2127
+ };
2128
+ if (page.slow) await bounded("Emulation.setCPUThrottlingRate", { rate: 1 }, page.session);
2129
+ await bounded("Target.disposeBrowserContext", { browserContextId: page.context });
2130
+ }
2131
+ /** The page's status, or null while it has none (a navigation under way, the probe not installed yet). A page that
2132
+ * stopped answering is no null: the run halts. */
2133
+ const status = (p) => p.eval("window.__mvPerfRun ? window.__mvPerfRun.status() : null").catch((e) => {
2134
+ if (p.stalled) throw e instanceof Halt ? e : new Halt("unresponsive");
2135
+ return null;
2136
+ });
2137
+ /** The status until `pred` holds (every `statusMs`), or `ms` passed: which, and the last status read. `halt` throws
2138
+ * when the run must stop - checked before every read; each read itself has `callMs` to answer. */
2139
+ async function until(p, pred, ms, halt) {
2140
+ const T = runT();
2141
+ const by = Date.now() + ms;
2142
+ let s = null;
2143
+ for (;;) {
2144
+ halt();
2145
+ s = await status(p);
2146
+ if (s && pred(s)) return {
2147
+ ok: true,
2148
+ status: s
2149
+ };
2150
+ if (Date.now() >= by || p.crashed) return {
2151
+ ok: false,
2152
+ status: s
2153
+ };
2154
+ await sleep(T.statusMs);
2155
+ }
2156
+ }
2157
+ /** The run is bake-idle (A3.8 #18): the page's four counts and the server's jobs for the run, all zero. */
2158
+ const bakeIdle = (id) => (s) => s.bakeIdle && jobsOf(id).queued === 0 && jobsOf(id).running === 0;
2159
+ const loadEnded = (s) => s.load?.state === "settled" || s.load?.state === "cut";
2160
+ /** Wheel events on an absolute schedule (`eventMs` apart, A3.8 #20): never awaiting an ack, at most 8 outstanding.
2161
+ * An event the page never acks settles at `callMs` (the page then stalled), so the window always drains. */
2162
+ async function wheels(p, at, series, halt) {
2163
+ const T = runT();
2164
+ const t0 = performance.now();
2165
+ let i = 0, outstanding = 0;
2166
+ const sent = [];
2167
+ for (const s of series) for (let k = 0; k < s.n; k++) {
2168
+ halt();
2169
+ const wait = t0 + i++ * T.eventMs - performance.now();
2170
+ if (wait > 0) await sleep(wait);
2171
+ while (outstanding >= 8) {
2172
+ halt();
2173
+ await sleep(1);
2174
+ }
2175
+ outstanding++;
2176
+ sent.push(p.send("Input.dispatchMouseEvent", {
2177
+ type: "mouseWheel",
2178
+ x: at.x,
2179
+ y: at.y,
2180
+ deltaX: s.deltaX ?? 0,
2181
+ deltaY: s.deltaY ?? 0,
2182
+ modifiers: s.ctrl ? 2 : 0
2183
+ }).catch(() => {}).finally(() => {
2184
+ outstanding--;
2185
+ }));
2186
+ }
2187
+ await Promise.all(sent);
2188
+ halt();
2189
+ }
2190
+ /** The intervals `__mvPerf.report()` keeps, the newest (perf.ts MAX). */
2191
+ const REPORT_FRAMES_MAX = 1200;
2192
+ /**
2193
+ * Did a gesture time its frames (the review of a3-runs, major #2)? rAF ticked in it: two intervals or more, perf.ts's
2194
+ * own rule for a gesture it records - `before` and `after` are `report().gestureFrames` around it. A page that reads as
2195
+ * hidden while its timers run (Chrome 156's occluded windows, 0.27.0) ends every gesture with none. A report already
2196
+ * full counts as timed.
2197
+ */
2198
+ const timedGesture = (before, after) => after - before >= 2 || after >= 1200;
2199
+ /**
2200
+ * Script 1's gestures on a measured page already bake-idle (A3.8 #20): fit, the pointer at the canvas's centre, the
2201
+ * frames reset, then zoom in, zoom out and one pan that turns back - each ended by the shell, 5 s at most, and timed.
2202
+ * The fit's own motion is a gesture to the page (the review of a3-runs' fixes, minor #4): a fit not at rest within its
2203
+ * 3 s gets the gestures' 5 s more before the frames are reset and the first gesture's count is read - else the run is
2204
+ * invalid (`gesture`) - and `gestures` counts the driver's own three that the shell ended, never the page's total
2205
+ * since its load.
2206
+ */
2207
+ async function measureGestures(p, hp) {
2208
+ const T = runT();
2209
+ const atRest = await p.eval("window.__mvPerfRun.fit()", true, T.fitIdleMs + T.callMs) === true || (await until(p, (s) => !s.moving, T.gestureEndMs, hp)).ok;
2210
+ const c = await p.eval("window.__mvPerfRun.centre()");
2211
+ await p.send("Input.dispatchMouseEvent", {
2212
+ type: "mouseMoved",
2213
+ x: c.x,
2214
+ y: c.y
2215
+ });
2216
+ await p.eval("window.__mvPerf && window.__mvPerf.reset()");
2217
+ const report = () => p.eval("window.__mvPerf ? window.__mvPerf.report() : null");
2218
+ const gesture = async (series) => {
2219
+ const before = (await status(p))?.gestures ?? 0;
2220
+ const sampled = (await report())?.gestureFrames ?? 0;
2221
+ await wheels(p, c, series, hp);
2222
+ const ended = (await until(p, (s) => s.gestures > before && !s.moving, T.gestureEndMs, hp)).ok;
2223
+ return {
2224
+ ended,
2225
+ timed: ended && timedGesture(sampled, (await report())?.gestureFrames ?? 0)
2226
+ };
2227
+ };
2228
+ const three = [];
2229
+ three.push(await gesture([{
2230
+ n: 40,
2231
+ deltaY: -100,
2232
+ ctrl: true
2233
+ }]));
2234
+ await sleep(T.pauseMs);
2235
+ three.push(await gesture([{
2236
+ n: 40,
2237
+ deltaY: 100,
2238
+ ctrl: true
2239
+ }]));
2240
+ await sleep(T.pauseMs);
2241
+ three.push(await gesture([{
2242
+ n: 60,
2243
+ deltaX: 50
2244
+ }, {
2245
+ n: 60,
2246
+ deltaX: -50
2247
+ }]));
2248
+ const r = await report();
2249
+ return {
2250
+ gestures: three.filter((g) => g.ended).length,
2251
+ gesturesOk: atRest && three.every((g) => g.timed),
2252
+ stats: r && r.gestureFrames ? {
2253
+ p50: r.frameP50 ?? null,
2254
+ p95: r.frameP95 ?? null,
2255
+ over33ms: r.over33ms ?? 0
2256
+ } : null
2257
+ };
2258
+ }
2259
+ /**
2260
+ * What a driver's failure says in the line (the review of a3-runs' fixes, minor #5): the client gone is `cancelled`;
2261
+ * a halt (the page stopped answering, the run past its cap) is cut with its reason; a crash is only the page's, the
2262
+ * browser's, or a browser-level call never answered; anything else - a page script that threw (a reload between two
2263
+ * reads, the probe gone), a driver bug - is cut `driver: <why>`. Null: no browser ever ran - no run happened, and no
2264
+ * line says one did.
2265
+ */
2266
+ function failureOf(e, at) {
2267
+ const why = at.clientGone ? "cancelled" : e instanceof Halt ? e.why : at.stalled ? "unresponsive" : at.halted;
2268
+ if (why === "cancelled") return { cancelled: true };
2269
+ if (why) return { cut: why };
2270
+ if (at.browser === "none") return null;
2271
+ if (at.pageCrashed || at.browser === "dead" || e instanceof BrowserSilent) return { crashed: true };
2272
+ return { cut: `driver: ${String(e?.message ?? e).slice(0, 300)}` };
2273
+ }
2274
+ /** The run line (A3.8 #22): what the page's records (the run's collector) and the driver saw; validity the first
2275
+ * reason that holds, in INVALID_REASONS' order - but a run the dev server's in-place restart ended is `inputs`
2276
+ * whatever else held: its stream closed with the old server, which is no client going away. */
2277
+ function runLine(reg, s) {
2278
+ const seen = /* @__PURE__ */ new Set();
2279
+ const recs = reg.records.filter((r) => {
2280
+ const k = `${r.ws}/${r.page}/${r.seq}`;
2281
+ if (seen.has(k)) return false;
2282
+ seen.add(k);
2283
+ return true;
2284
+ });
2285
+ const load = recs.find((r) => r.kind === "load" && r.cause === "boot");
2286
+ const own = load ? recs.filter((r) => r.load === load.request) : [];
2287
+ const commit = own.find((r) => r.kind === "commit"), settled = own.find((r) => r.kind === "settled");
2288
+ const moves = own.filter((r) => r.kind === "move");
2289
+ const errors = recs.filter((r) => r.kind === "error").length;
2290
+ const badFrames = settled ? (settled.missing ?? 0) + (settled.neverReady ?? 0) : 0;
2291
+ const lost = recs.filter((r) => r.kind === "dropped" && r.reason !== "errors").reduce((n, r) => n + (typeof r.n === "number" && r.n > 0 ? r.n : 1), 0) + (reg.overflow ?? 0);
2292
+ const reasons = [
2293
+ ["cancelled", s.cancelled],
2294
+ ["crash", s.crashed],
2295
+ ["inputs", !s.inputs || s.inputsEnd !== s.inputs.hash || reg.inputsChanged !== null],
2296
+ ["writes", reg.forbidden > 0],
2297
+ ["cut", s.cut !== void 0],
2298
+ ["frames", badFrames > 0],
2299
+ ["errors", errors > 0],
2300
+ ["bakes", s.bakesMissed],
2301
+ ["gesture", !s.gesturesOk || !s.stats],
2302
+ ["records", !s.landed || !settled || lost > 0]
2303
+ ];
2304
+ const invalid = reg.restarted ? "inputs" : reasons.find(([, holds]) => holds)?.[0];
2305
+ return {
2306
+ v: 1,
2307
+ script: 1,
2308
+ run: s.id,
2309
+ where: "headless",
2310
+ ts: s.startedAt,
2311
+ board: s.board,
2312
+ inputs: s.inputs,
2313
+ inputsEnd: s.inputsEnd,
2314
+ frames: typeof commit?.frames === "number" ? commit.frames : null,
2315
+ marver: installedVersion() ?? "0.0.0",
2316
+ chrome: s.chrome,
2317
+ flags: launchFlags(),
2318
+ renderer: s.renderer,
2319
+ machine: s.machine,
2320
+ host: s.host,
2321
+ power: s.power,
2322
+ slow: s.slow,
2323
+ bakes: s.bakes,
2324
+ postersMissing: s.postersSkipped,
2325
+ saved: commit ? {
2326
+ measuring: commit.measuring ?? 0,
2327
+ savedHeights: commit.savedHeights ?? 0
2328
+ } : null,
2329
+ loadToSettledMs: load && settled && typeof load.sinceNav === "number" && typeof settled.ms === "number" ? load.sinceNav + settled.ms : null,
2330
+ settledMs: typeof settled?.ms === "number" ? settled.ms : null,
2331
+ moves: moves.filter((m) => !m.late).length,
2332
+ lateMoves: moves.filter((m) => m.late).length,
2333
+ gestures: s.gestures,
2334
+ p50: s.stats?.p50 ?? null,
2335
+ p95: s.stats?.p95 ?? null,
2336
+ over33ms: s.stats ? s.stats.over33ms : null,
2337
+ heapPeakMB: s.heapPeakMB,
2338
+ errors,
2339
+ forbidden: reg.forbidden,
2340
+ refusedInPage: s.refusedInPage,
2341
+ overlapped: reg.overlapped,
2342
+ valid: !invalid,
2343
+ ...invalid ? { invalidReason: invalid } : {},
2344
+ ...s.cut !== void 0 ? { cut: s.cut } : {},
2345
+ ...reg.restarted ? { restarted: true } : {},
2346
+ ...s.bakesPending ? { bakesPending: true } : {}
2347
+ };
2348
+ }
2349
+ /** One run of script 1: the warm-up, the measured load and its three gestures, the line (A3.8 #20). */
2350
+ async function runOnce(o) {
2351
+ const T = runT();
2352
+ const id = randomBytes(8).toString("hex");
2353
+ const reg = runs.register(o.board, id);
2354
+ if (anyLingering()) reg.overlapped = true;
2355
+ const me = {};
2356
+ const seen = {
2357
+ id,
2358
+ board: o.board,
2359
+ slow: o.slow,
2360
+ startedAt: reg.startedAt,
2361
+ inputs: null,
2362
+ inputsEnd: null,
2363
+ chrome: "unknown",
2364
+ renderer: null,
2365
+ machine: "unknown",
2366
+ host: basicHost(),
2367
+ power: "unknown",
2368
+ bakes: "cold",
2369
+ cancelled: false,
2370
+ crashed: false,
2371
+ bakesMissed: false,
2372
+ gestures: 0,
2373
+ gesturesOk: false,
2374
+ stats: null,
2375
+ heapPeakMB: null,
2376
+ landed: false,
2377
+ postersSkipped: 0,
2378
+ refusedInPage: 0
2379
+ };
2380
+ const set = { paths: null };
2381
+ const fp = async (urls) => {
2382
+ const paths = o.watch ? await inputPaths(o.root, o.watch, urls) : null;
2383
+ if (!paths) return;
2384
+ set.paths = paths;
2385
+ seen.inputs = await hashInputs(o.root, paths);
2386
+ };
2387
+ const requested = /* @__PURE__ */ new Set();
2388
+ let offRequests = () => {};
2389
+ let b = null;
2390
+ let page = null;
2391
+ const stop = new AbortController();
2392
+ const onAbort = () => stop.abort("cancelled");
2393
+ if (o.signal.aborted) onAbort();
2394
+ else o.signal.addEventListener("abort", onAbort, { once: true });
2395
+ const cap = setTimeout(() => stop.abort("overrun"), T.runMs);
2396
+ stop.signal.addEventListener("abort", () => {
2397
+ endRunBakes(id);
2398
+ b?.abort(me, String(stop.signal.reason));
2399
+ }, { once: true });
2400
+ /** Throws when the run must stop: halted, or (with a page) that page stalled. */
2401
+ const halt = (p) => () => {
2402
+ if (stop.signal.aborted) throw new Halt(stop.signal.reason);
2403
+ if (p?.stalled) throw new Halt("unresponsive");
2404
+ };
2405
+ const check = halt();
2406
+ try {
2407
+ o.progress({
2408
+ phase: "warm",
2409
+ run: id
2410
+ });
2411
+ const [, profile] = await Promise.all([fp([]), writeHeadlessProfile(marverHome())]);
2412
+ seen.machine = profile.hash;
2413
+ seen.host = profile.profile.host;
2414
+ seen.power = profile.profile.power;
2415
+ check();
2416
+ b = await Browser.launch();
2417
+ if (stop.signal.aborted) b.abort(me, String(stop.signal.reason));
2418
+ check();
2419
+ const version = await within(b.send("Browser.getVersion", {}, void 0, me), T.callMs, "Browser.getVersion");
2420
+ seen.chrome = String(version?.product ?? "unknown").replace(/^[^/]*\//, "");
2421
+ const sys = await within(b.send("SystemInfo.getInfo", {}, void 0, me), T.callMs, "SystemInfo.getInfo").catch(() => null);
2422
+ const fs = sys?.gpu?.featureStatus, dev = sys?.gpu?.devices?.[0];
2423
+ seen.renderer = sys ? {
2424
+ gpuCompositing: fs?.gpu_compositing,
2425
+ rasterization: fs?.rasterization,
2426
+ vendor: dev?.vendorString,
2427
+ device: dev?.deviceString
2428
+ } : null;
2429
+ page = await openPage(b, {
2430
+ cache: true,
2431
+ slow: false,
2432
+ halt: stop.signal
2433
+ });
2434
+ const warmSession = page.session;
2435
+ offRequests = b.on((m) => {
2436
+ const url = m.sessionId === warmSession && m.method === "Network.requestWillBeSent" ? m.params?.request?.url : void 0;
2437
+ if (typeof url === "string" && url.startsWith(`${o.origin}/`)) requested.add(url);
2438
+ });
2439
+ await page.send("Page.navigate", { url: runUrl(o.origin, o.board, id, true) });
2440
+ const warm = await until(page, (s) => loadEnded(s) && bakeIdle(id)(s), T.warmMs, halt(page));
2441
+ seen.bakes = warm.ok ? "warm" : "cold";
2442
+ seen.refusedInPage += warm.status?.refused ?? 0;
2443
+ seen.crashed ||= page.crashed;
2444
+ await closePage(b, page);
2445
+ page = null;
2446
+ offRequests();
2447
+ check();
2448
+ await fp([...requested]);
2449
+ if (set.paths) {
2450
+ runPaths.set(id, set.paths);
2451
+ while (runPaths.size > RUN_PATHS_MAX) runPaths.delete(runPaths.keys().next().value);
2452
+ }
2453
+ check();
2454
+ reg.phase = "measured";
2455
+ o.progress({
2456
+ phase: "measured",
2457
+ run: id
2458
+ });
2459
+ page = await openPage(b, {
2460
+ cache: false,
2461
+ slow: o.slow,
2462
+ halt: stop.signal
2463
+ });
2464
+ const p = page;
2465
+ const hp = halt(p);
2466
+ let heap = 0, sampling = false;
2467
+ const sampleHeap = () => {
2468
+ if (sampling || p.stalled || stop.signal.aborted) return;
2469
+ sampling = true;
2470
+ p.send("Runtime.getHeapUsage").then((h) => {
2471
+ if (typeof h?.usedSize === "number") heap = Math.max(heap, h.usedSize);
2472
+ }, () => {}).finally(() => {
2473
+ sampling = false;
2474
+ });
2475
+ };
2476
+ const heapTimer = setInterval(sampleHeap, T.heapMs);
2477
+ try {
2478
+ await p.send("Page.navigate", { url: runUrl(o.origin, o.board, id, false) });
2479
+ sampleHeap();
2480
+ const loaded = await until(p, loadEnded, T.settleMs, hp);
2481
+ if (!loaded.ok || loaded.status?.load?.state === "cut") seen.cut = loaded.status?.load?.reason ?? (p.crashed ? "crash" : "timeout");
2482
+ else {
2483
+ const idle = await until(p, bakeIdle(id), T.bakeIdleMs, hp);
2484
+ seen.bakesMissed = !idle.ok;
2485
+ if (idle.ok) Object.assign(seen, await measureGestures(p, hp));
2486
+ }
2487
+ seen.landed = await p.eval("window.__mvPerfRun ? window.__mvPerfRun.flush() : false", true, FLUSH_MS + T.callMs).catch((e) => {
2488
+ if (p.stalled) throw e;
2489
+ return false;
2490
+ }) === true;
2491
+ const last = await status(p);
2492
+ seen.postersSkipped = last?.postersSkipped ?? 0;
2493
+ seen.refusedInPage += last?.refused ?? 0;
2494
+ } finally {
2495
+ clearInterval(heapTimer);
2496
+ seen.heapPeakMB = heap ? Math.round(heap / 1048576 * 10) / 10 : null;
2497
+ }
2498
+ } catch (e) {
2499
+ const f = failureOf(e, {
2500
+ clientGone: o.signal.aborted,
2501
+ halted: stop.signal.aborted ? stop.signal.reason : null,
2502
+ stalled: !!page?.stalled,
2503
+ browser: !b ? "none" : b.dead ? "dead" : "alive",
2504
+ pageCrashed: !!page?.crashed
2505
+ });
2506
+ if (!f) {
2507
+ clearTimeout(cap);
2508
+ runs.end(id);
2509
+ throw e;
2510
+ }
2511
+ if ("cancelled" in f) seen.cancelled = true;
2512
+ else if ("cut" in f) seen.cut ??= f.cut;
2513
+ else seen.crashed = true;
2514
+ } finally {
2515
+ endRunBakes(id);
2516
+ offRequests();
2517
+ clearTimeout(cap);
2518
+ o.signal.removeEventListener("abort", onAbort);
2519
+ reg.phase = "closing";
2520
+ try {
2521
+ o.progress({
2522
+ phase: "closing",
2523
+ run: id
2524
+ });
2525
+ } catch {}
2526
+ if (page && b) {
2527
+ seen.crashed ||= page.crashed;
2528
+ await closePage(b, page);
2529
+ }
2530
+ if (b) await b.close();
2531
+ }
2532
+ if (!await jobsIdle(id, 5e4)) {
2533
+ seen.bakesPending = true;
2534
+ lingering.add(id);
2535
+ }
2536
+ await sleep(T.watcherLagMs);
2537
+ seen.inputsEnd = set.paths ? (await hashInputs(o.root, set.paths)).hash : null;
2538
+ const done = runs.end(id) ?? reg;
2539
+ seen.cancelled ||= o.signal.aborted;
2540
+ const line = runLine(done, seen);
2541
+ appendRun(o.root, line);
2542
+ return line;
2543
+ }
2544
+ /** The whole body, or null: too large, unreadable, or cut short - a request whose body never completes starts nothing. */
2545
+ function readWhole(req, limit = 4096) {
2546
+ return new Promise((done) => {
2547
+ let size = 0, over = false;
2548
+ const chunks = [];
2549
+ req.on("data", (c) => {
2550
+ size += c.length;
2551
+ if (size > limit) {
2552
+ over = true;
2553
+ done(null);
2554
+ req.destroy();
2555
+ } else chunks.push(c);
2556
+ });
2557
+ req.on("end", () => {
2558
+ if (!over) done(Buffer.concat(chunks).toString("utf8"));
2559
+ });
2560
+ req.on("error", () => done(null));
2561
+ req.on("close", () => {
2562
+ if (!req.complete) done(null);
2563
+ });
2564
+ });
2565
+ }
2566
+ /** A run request's body, checked: the board must be one of `boards`; `repeat` 1-5 (1); `slow` a boolean. */
2567
+ function readRunRequest(raw, boards) {
2568
+ if (raw === null) return {
2569
+ ok: false,
2570
+ error: "body too large, unreadable or cut short"
2571
+ };
2572
+ let b;
2573
+ try {
2574
+ b = JSON.parse(raw);
2575
+ } catch {
2576
+ return {
2577
+ ok: false,
2578
+ error: "malformed JSON"
2579
+ };
2580
+ }
2581
+ if (!b || typeof b !== "object" || Array.isArray(b)) return {
2582
+ ok: false,
2583
+ error: "expected { board, slow?, repeat? }"
2584
+ };
2585
+ if (typeof b.board !== "string" || !boards.includes(b.board)) return {
2586
+ ok: false,
2587
+ error: `no board "${String(b.board ?? "")}" - the boards: ${boards.join(", ") || "none"}`
2588
+ };
2589
+ if (b.slow !== void 0 && typeof b.slow !== "boolean") return {
2590
+ ok: false,
2591
+ error: "slow must be true or false"
2592
+ };
2593
+ const repeat = b.repeat === void 0 ? 1 : b.repeat;
2594
+ if (!(Number.isInteger(repeat) && repeat >= 1 && repeat <= 5)) return {
2595
+ ok: false,
2596
+ error: "repeat must be 1-5"
2597
+ };
2598
+ return {
2599
+ ok: true,
2600
+ req: {
2601
+ board: b.board,
2602
+ slow: b.slow === true,
2603
+ repeat
2604
+ }
2605
+ };
2606
+ }
2607
+ /**
2608
+ * `POST /api/perf/run` (A3.8 #22), its gate checked by the caller: the body read whole before any run registers, then
2609
+ * NDJSON - headers at once, a phase as each starts, a heartbeat every 10 s (Node's fetch cuts a body silent for 300 s),
2610
+ * one `{ line }` per run, `{ done }`. **The client going away cancels, and nothing else does** (A3.8 r2 #3): the
2611
+ * response closing before it finished, never the request's `close` (which fires once its body is read).
2612
+ */
2613
+ async function serveRun(req, res, o) {
2614
+ const asked = readRunRequest(await readWhole(req), o.boards());
2615
+ if (!asked.ok) {
2616
+ if (res.destroyed) return;
2617
+ res.statusCode = 400;
2618
+ res.setHeader("content-type", "application/json");
2619
+ res.end(JSON.stringify({ error: asked.error }));
2620
+ return;
2621
+ }
2622
+ if (res.destroyed) return;
2623
+ const T = runT();
2624
+ const ac = new AbortController();
2625
+ res.on("close", () => {
2626
+ if (!res.writableFinished) ac.abort();
2627
+ });
2628
+ res.writeHead(200, {
2629
+ "content-type": "application/x-ndjson",
2630
+ "cache-control": "no-store",
2631
+ "x-accel-buffering": "no"
2632
+ });
2633
+ res.flushHeaders();
2634
+ const write = (l) => {
2635
+ if (!res.destroyed && !res.writableEnded) res.write(JSON.stringify(l) + "\n");
2636
+ };
2637
+ const beat = setInterval(() => write({ heartbeat: Date.now() }), T.heartbeatMs);
2638
+ try {
2639
+ const drive = runOnce;
2640
+ for (let i = 0; i < asked.req.repeat && !ac.signal.aborted; i++) write({ line: await drive({
2641
+ root: o.root,
2642
+ origin: o.origin,
2643
+ board: asked.req.board,
2644
+ slow: asked.req.slow,
2645
+ signal: ac.signal,
2646
+ progress: write,
2647
+ watch: o.watch
2648
+ }) });
2649
+ write({ done: true });
2650
+ } catch (e) {
2651
+ write({ error: e.message });
2652
+ } finally {
2653
+ clearInterval(beat);
2654
+ if (!res.destroyed) res.end();
2655
+ }
2656
+ }
2657
+ //#endregion
424
2658
  //#region src/server/api.ts
425
2659
  const BODY_LIMIT = 1e6;
426
2660
  const CSRF_MAX_AGE = 2592e3;
@@ -772,7 +3006,7 @@ function apiMiddleware(root, opts = {}) {
772
3006
  const str = (v) => typeof v === "string" ? v.slice(0, 200) : void 0;
773
3007
  const num = (v) => typeof v === "number" && Number.isFinite(v) ? Math.round(v) : void 0;
774
3008
  if (!str(b?.kind)) return json(res, 400, { error: "kind required" });
775
- (await import("./perf-BWzQwZqj.mjs").then((n) => n.i)).logReload(root, {
3009
+ (await import("./perf-jam-BaH3Lg0m.mjs").then((n) => n.c)).logReload(root, {
776
3010
  kind: str(b.kind),
777
3011
  tab: str(b.tab),
778
3012
  node: str(b.node),
@@ -794,11 +3028,13 @@ function apiMiddleware(root, opts = {}) {
794
3028
  return json(res, 400, { error: "malformed JSON" });
795
3029
  }
796
3030
  if (!b || b.kind !== "capture" && b.kind !== "upload") return json(res, 400, { error: "kind must be capture or upload" });
797
- (await import("./perf-jam-D55U3FZK.mjs").then((n) => n.n)).logJam(root, b);
3031
+ (await import("./perf-jam-BaH3Lg0m.mjs").then((n) => n.n)).logJam(root, b);
798
3032
  return json(res, 200, { ok: true });
799
3033
  }
800
3034
  if (path === "perf/page" && req.method === "POST") {
801
3035
  if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
3036
+ const run = runIdOf(req);
3037
+ if (run && !runs.get(run)) return json(res, 409, { error: "run ended" });
802
3038
  const raw = await readBody(req, PAGE_BODY_MAX);
803
3039
  if (raw == null) return json(res, 400, { error: "body too large or unreadable" });
804
3040
  let b;
@@ -810,7 +3046,42 @@ function apiMiddleware(root, opts = {}) {
810
3046
  if (!Array.isArray(b?.records)) return json(res, 400, { error: "expected { records: [...] }" });
811
3047
  return json(res, 200, {
812
3048
  ok: true,
813
- accepted: logPage(root, b.records)
3049
+ accepted: logPage(root, b.records, run ? {
3050
+ run,
3051
+ kept: (recs) => runs.records(run, recs)
3052
+ } : {})
3053
+ });
3054
+ }
3055
+ if (path === "perf/run" && req.method === "POST" || path === "perf/inputs" && req.method === "GET") {
3056
+ const { readDevInfo } = await import("./work-CNhFF9pU.mjs").then((n) => n.o);
3057
+ const token = readDevInfo(root)?.token;
3058
+ if (!ownerGated(req) && !(token && req.headers["x-mv-work"] === token)) return json(res, 403, { error: "forbidden" });
3059
+ if (path === "perf/inputs") {
3060
+ if (!opts.inputs) return json(res, 200, { inputs: null });
3061
+ const { fingerprint, hashInputs } = await Promise.resolve().then(() => perf_inputs_exports);
3062
+ const run = url.searchParams.get("run");
3063
+ if (run !== null) {
3064
+ const { runInputPaths } = await Promise.resolve().then(() => perf_run_exports);
3065
+ const paths = runInputPaths(run);
3066
+ if (!paths) return json(res, 404, {
3067
+ inputs: null,
3068
+ error: `run ${run} is not one of the last 32 this dev server ran`
3069
+ });
3070
+ return json(res, 200, {
3071
+ run,
3072
+ inputs: await hashInputs(root, paths)
3073
+ });
3074
+ }
3075
+ return json(res, 200, { inputs: await fingerprint(root, opts.inputs) });
3076
+ }
3077
+ const origin = opts.origin?.() ?? `http://${req.headers.host ?? "localhost"}`;
3078
+ const { serveRun } = await Promise.resolve().then(() => perf_run_exports);
3079
+ const boards = () => checkBoardsDir(root, boardsDir) ? [] : listBoardFiles(boardsDir).boards.filter((x) => !x.error).map((x) => x.name);
3080
+ return await serveRun(req, res, {
3081
+ root,
3082
+ origin,
3083
+ boards,
3084
+ watch: opts.inputs
814
3085
  });
815
3086
  }
816
3087
  if (path === "sizes" && req.method === "GET") {
@@ -1204,7 +3475,7 @@ function apiMiddleware(root, opts = {}) {
1204
3475
  }
1205
3476
  }
1206
3477
  if (path === "shot" && req.method === "GET") {
1207
- const { readDevInfo } = await import("./work-Bp1p39kq.mjs").then((n) => n.o);
3478
+ const { readDevInfo } = await import("./work-CNhFF9pU.mjs").then((n) => n.o);
1208
3479
  const token = readDevInfo(root)?.token;
1209
3480
  if (!ownerGated(req) && !(token && req.headers["x-mv-work"] === token)) return json(res, 403, { error: "forbidden" });
1210
3481
  const frameId = url.searchParams.get("frame") ?? "";
@@ -1220,7 +3491,7 @@ function apiMiddleware(root, opts = {}) {
1220
3491
  };
1221
3492
  const asPng = url.searchParams.get("format") === "png";
1222
3493
  const origin = opts.origin?.() ?? `http://${req.headers.host ?? "localhost"}`;
1223
- const { shootFrame } = await import("./shot-LFhC-WYD.mjs");
3494
+ const { shootFrame } = await import("./shot-Ch24tiMO.mjs").then((n) => n.u);
1224
3495
  const r = await shootFrame({
1225
3496
  root,
1226
3497
  viewports: opts.viewports ?? {},
@@ -1254,7 +3525,7 @@ function apiMiddleware(root, opts = {}) {
1254
3525
  return res.end(png);
1255
3526
  }
1256
3527
  if (path === "shots" && req.method === "POST") {
1257
- const { readDevInfo } = await import("./work-Bp1p39kq.mjs").then((n) => n.o);
3528
+ const { readDevInfo } = await import("./work-CNhFF9pU.mjs").then((n) => n.o);
1258
3529
  const token = readDevInfo(root)?.token;
1259
3530
  if (!ownerGated(req) && !(token && req.headers["x-mv-work"] === token)) return json(res, 403, { error: "forbidden" });
1260
3531
  const raw = await readBody(req);
@@ -1271,7 +3542,7 @@ function apiMiddleware(root, opts = {}) {
1271
3542
  if (typeof theme !== "string" || !/^[a-z0-9-]+$/i.test(theme)) return json(res, 400, { error: "invalid theme" });
1272
3543
  const scale = body.scale === void 0 ? void 0 : body.scale;
1273
3544
  if (scale !== void 0 && !(Number.isInteger(scale) && scale >= 1 && scale <= 4)) return json(res, 400, { error: "invalid scale" });
1274
- const { resolveFrames, shootBatch } = await import("./shot-LFhC-WYD.mjs");
3545
+ const { resolveFrames, shootBatch } = await import("./shot-Ch24tiMO.mjs").then((n) => n.u);
1275
3546
  const sel = resolveFrames(root, body);
1276
3547
  if (!sel.ok) return json(res, sel.status, { error: sel.error });
1277
3548
  const origin = opts.origin?.() ?? `http://${req.headers.host ?? "localhost"}`;
@@ -1289,7 +3560,7 @@ function apiMiddleware(root, opts = {}) {
1289
3560
  }
1290
3561
  }
1291
3562
  if (path === "anchor" && req.method === "POST") {
1292
- const { readDevInfo } = await import("./work-Bp1p39kq.mjs").then((n) => n.o);
3563
+ const { readDevInfo } = await import("./work-CNhFF9pU.mjs").then((n) => n.o);
1293
3564
  const token = readDevInfo(root)?.token;
1294
3565
  if (!ownerGated(req) && !(token && req.headers["x-mv-work"] === token)) return json(res, 403, { error: "forbidden" });
1295
3566
  const raw = await readBody(req);
@@ -1305,7 +3576,7 @@ function apiMiddleware(root, opts = {}) {
1305
3576
  if (typeof target === "string") return json(res, 400, { error: target });
1306
3577
  const others = Array.isArray(b.others) ? b.others.filter((o) => typeof o?.key === "string").slice(0, 200) : [];
1307
3578
  const origin = opts.origin?.() ?? `http://${req.headers.host ?? "localhost"}`;
1308
- const { checkAnchor, CheckInputError } = await import("./anchor-check-ChdDqL5z.mjs");
3579
+ const { checkAnchor, CheckInputError } = await import("./anchor-check-gkxkPAIv.mjs");
1309
3580
  try {
1310
3581
  return json(res, 200, await checkAnchor({
1311
3582
  root,
@@ -1333,7 +3604,8 @@ function apiMiddleware(root, opts = {}) {
1333
3604
  return json(res, 400, { error: "malformed JSON" });
1334
3605
  }
1335
3606
  if (!body || typeof body !== "object" || !Array.isArray(body.asks) || !body.asks.length || body.asks.length > 200) return json(res, 400, { error: "asks must list 1-200 frames" });
1336
- const { bakeBatch, ASK_MAX } = await import("./bake-DM_uWgAA.mjs");
3607
+ const { bakeBatch, ASK_MAX, NORMAL_OWNER, RUN_ENDED } = await Promise.resolve().then(() => bake_exports);
3608
+ const run = runIdOf(req);
1337
3609
  let manifest = {};
1338
3610
  try {
1339
3611
  manifest = JSON.parse(readFileSync(join(root, "design", "manifest.json"), "utf8"));
@@ -1354,25 +3626,32 @@ function apiMiddleware(root, opts = {}) {
1354
3626
  });
1355
3627
  docs.push(typeof a?.doc === "string" ? a.doc : void 0);
1356
3628
  }
1357
- const { docRev } = await import("./marks-CKgzucHZ.mjs").then((n) => n.i);
3629
+ const { docRev } = await import("./marks-CnCCfAbD.mjs").then((n) => n.i);
1358
3630
  const all = devManifest().frames;
1359
3631
  const pending = opts.settled ? !opts.settled() : false;
1360
3632
  const behind = docs.map((d, i) => d !== void 0 && (pending || d !== docRev(root, all, asks[i].frame)));
1361
3633
  const origin = opts.origin?.() ?? `http://${req.headers.host ?? "localhost"}`;
1362
3634
  const { ROUTE } = await import("./cli.mjs").then((n) => n.t);
1363
3635
  const gen = opts.bakeGen?.() ?? 0;
1364
- const baked = await bakeBatch({
3636
+ const current = asks.filter((_, i) => !behind[i]);
3637
+ const named = (u) => run ? `${u}&${RUN_PARAM}=${run}` : u;
3638
+ const baked = run && !runs.get(run) ? current.map((a) => ({
3639
+ ...a,
3640
+ ok: false,
3641
+ error: RUN_ENDED
3642
+ })) : await bakeBatch({
1365
3643
  root,
1366
3644
  gen,
1367
- asks: asks.filter((_, i) => !behind[i]),
3645
+ asks: current,
1368
3646
  live: () => opts.bakeGen?.() ?? 0,
3647
+ owner: run ?? NORMAL_OWNER,
1369
3648
  log: (a) => {
1370
3649
  if (a.ok) console.log(` bake: ${a.frame} ${a.theme} ${a.w}x${a.h} - ${a.targets.length} effects, ${a.rejected} stay live, ${a.ms} ms`);
1371
3650
  else console.log(` bake: ${a.frame} ${a.theme} ${a.w}x${a.h} - stays live: ${a.error}`);
1372
3651
  },
1373
3652
  urlFor: (ask) => {
1374
3653
  const f = frames.get(ask.frame);
1375
- return f.kind === "html" ? `${origin}/${f.file}?theme=${encodeURIComponent(ask.theme)}` : `${origin}${ROUTE}/frame/?id=${encodeURIComponent(ask.frame)}&theme=${encodeURIComponent(ask.theme)}`;
3654
+ return named(f.kind === "html" ? `${origin}/${f.file}?theme=${encodeURIComponent(ask.theme)}` : `${origin}${ROUTE}/frame/?id=${encodeURIComponent(ask.frame)}&theme=${encodeURIComponent(ask.theme)}`);
1376
3655
  },
1377
3656
  urlBase: `${ROUTE}/bakes`,
1378
3657
  waitMs: 2500
@@ -1405,8 +3684,8 @@ function apiMiddleware(root, opts = {}) {
1405
3684
  return json(res, 400, { error: "malformed JSON" });
1406
3685
  }
1407
3686
  const src = typeof b?.src === "string" ? b.src : "";
1408
- const { ensurePoster, isLocalClip } = await import("./poster-Bx83ZYVK.mjs");
1409
- const { isLocalAssetRef } = await import("./build-DZnFysGU.mjs");
3687
+ const { ensurePoster, isLocalClip } = await import("./poster-BNgafWMK.mjs");
3688
+ const { isLocalAssetRef } = await import("./build-VgNg4rr8.mjs");
1410
3689
  if (!isLocalAssetRef(src) || !isLocalClip(src)) return json(res, 400, { error: "src must be a clip under design/assets/" });
1411
3690
  const r = await ensurePoster(join(root, "design", "assets"), src);
1412
3691
  if (!r.ok) return json(res, r.error.includes("does not exist") ? 404 : 503, { error: r.error });
@@ -1433,7 +3712,7 @@ function apiMiddleware(root, opts = {}) {
1433
3712
  }
1434
3713
  const dir = join(root, "design", ".local");
1435
3714
  mkdirSync(dir, { recursive: true });
1436
- const { validAvatar } = await import("./collab-Dxg2trOK.mjs");
3715
+ const { validAvatar } = await import("./collab-BEAcXrBb.mjs");
1437
3716
  let cur = {};
1438
3717
  try {
1439
3718
  cur = JSON.parse(readFileSync(join(dir, "profile.json"), "utf8"));
@@ -1449,7 +3728,7 @@ function apiMiddleware(root, opts = {}) {
1449
3728
  }
1450
3729
  if (path === "marks" || path === "marks/seen") {
1451
3730
  if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
1452
- const { readMarks, markSeen } = await import("./marks-CKgzucHZ.mjs").then((n) => n.i);
3731
+ const { readMarks, markSeen } = await import("./marks-CnCCfAbD.mjs").then((n) => n.i);
1453
3732
  const manifest = devManifest();
1454
3733
  if (path === "marks" && req.method === "GET") return json(res, 200, readMarks(root, manifest));
1455
3734
  if (path === "marks/seen" && req.method === "POST") {
@@ -1469,14 +3748,14 @@ function apiMiddleware(root, opts = {}) {
1469
3748
  return json(res, 405, { error: "method not allowed" });
1470
3749
  }
1471
3750
  if (path === "work") {
1472
- const { workActivity, readDevInfo, WORK_TTL_DEFAULT, WORK_TTL_MAX } = await import("./work-Bp1p39kq.mjs").then((n) => n.o);
3751
+ const { workActivity, readDevInfo, WORK_TTL_DEFAULT, WORK_TTL_MAX } = await import("./work-CNhFF9pU.mjs").then((n) => n.o);
1473
3752
  const tokenOk = () => {
1474
3753
  const t = readDevInfo(root)?.token;
1475
3754
  return !!t && req.headers["x-mv-work"] === t;
1476
3755
  };
1477
3756
  if (req.method === "GET") {
1478
3757
  if (!ownerGated(req) && !tokenOk()) return json(res, 403, { error: "forbidden" });
1479
- const { boardsShowing, activityClock } = await import("./work-Bp1p39kq.mjs").then((n) => n.o);
3758
+ const { boardsShowing, activityClock } = await import("./work-CNhFF9pU.mjs").then((n) => n.o);
1480
3759
  const frames = workActivity.active();
1481
3760
  return json(res, 200, {
1482
3761
  frames,
@@ -1499,7 +3778,7 @@ function apiMiddleware(root, opts = {}) {
1499
3778
  if (!on && b.all === true) {
1500
3779
  const done = workActivity.active().filter((f) => workActivity.has(f, "cli"));
1501
3780
  if (done.length) {
1502
- (await import("./marks-CKgzucHZ.mjs").then((n) => n.i)).recordChanged(root, devFrames(), done, { doc: false });
3781
+ (await import("./marks-CnCCfAbD.mjs").then((n) => n.i)).recordChanged(root, devFrames(), done, { doc: false });
1503
3782
  opts.notify?.("sh:marks");
1504
3783
  }
1505
3784
  workActivity.clearAll("cli");
@@ -1519,7 +3798,7 @@ function apiMiddleware(root, opts = {}) {
1519
3798
  for (const f of frames) on ? workActivity.mark(f, ttl, "cli") : workActivity.clear(f, "cli");
1520
3799
  saveHolds(root, workActivity);
1521
3800
  if (!on) {
1522
- (await import("./marks-CKgzucHZ.mjs").then((n) => n.i)).recordChanged(root, devFrames(), frames, { doc: false });
3801
+ (await import("./marks-CnCCfAbD.mjs").then((n) => n.i)).recordChanged(root, devFrames(), frames, { doc: false });
1523
3802
  opts.notify?.("sh:marks");
1524
3803
  return json(res, 200, { frames: workActivity.active() });
1525
3804
  }
@@ -1735,7 +4014,7 @@ function apiMiddleware(root, opts = {}) {
1735
4014
  if (!b || typeof b.capture !== "string" || !CAPTURE_ID.test(b.capture) || typeof b.frame !== "string") return json(res, 400, { error: "expected { capture, frame, theme?, viewport? }" });
1736
4015
  if (readCapture(root, b.capture)) return json(res, 409, { error: "that capture is sealed" });
1737
4016
  const theme = typeof b.theme === "string" && /^[a-z0-9-]+$/i.test(b.theme) ? b.theme : "light";
1738
- const { shootFrame } = await import("./shot-LFhC-WYD.mjs");
4017
+ const { shootFrame } = await import("./shot-Ch24tiMO.mjs").then((n) => n.u);
1739
4018
  const origin = opts.origin?.() ?? `http://${req.headers.host ?? "localhost"}`;
1740
4019
  const vp = typeof b.viewport === "string" ? opts.viewports?.[b.viewport] : void 0;
1741
4020
  const dim = (v) => typeof v === "number" && Number.isFinite(v) ? Math.round(v) : void 0;
@@ -1826,7 +4105,7 @@ function apiMiddleware(root, opts = {}) {
1826
4105
  }
1827
4106
  }
1828
4107
  if (path === "sync" && req.method === "POST") {
1829
- const { loadCollab, syncOnce } = await import("./sync-BQVlHZpx.mjs").then((n) => n.o);
4108
+ const { loadCollab, syncOnce } = await import("./sync-CQdGARJ9.mjs").then((n) => n.o);
1830
4109
  const collab = loadCollab(root);
1831
4110
  if (!collab) return json(res, 200, { connected: false });
1832
4111
  try {
@@ -1855,7 +4134,7 @@ function backgroundPush(root) {
1855
4134
  pushTimer = setTimeout(async () => {
1856
4135
  pushTimer = null;
1857
4136
  try {
1858
- const { loadCollab, syncOnce } = await import("./sync-BQVlHZpx.mjs").then((n) => n.o);
4137
+ const { loadCollab, syncOnce } = await import("./sync-CQdGARJ9.mjs").then((n) => n.o);
1859
4138
  const collab = loadCollab(root);
1860
4139
  if (collab) await syncOnce(root, collab);
1861
4140
  } catch {}
@@ -1872,18 +4151,22 @@ function backgroundPush(root) {
1872
4151
  *
1873
4152
  * Pinned exactly, so the app (A2.3 `proof.ts`) computes the same: the key is the slot file's 32 bytes
1874
4153
  * (base64url there), HMAC-SHA256 over UTF-8 `doc|<nonce>|<port>` (port in decimal), base64url without
1875
- * padding. Requests from the app itself carry `app|<port>` the same way.
4154
+ * padding. Requests from the app itself carry `app|<port>` the same way, and the logo the app fetches
4155
+ * (`GET /__mv/logo`, spec 28 A2.4) `logo|<nonce>|<port>`: a listener that took the port after the tab was
4156
+ * verified can never hand it a logo.
1876
4157
  */
1877
4158
  /** 16-64 base64url characters - anything else is not a nonce, and is ignored. */
1878
4159
  const NONCE = /^[A-Za-z0-9_-]{16,64}$/;
1879
4160
  const sign$1 = (key, msg) => createHmac("sha256", key).update(msg, "utf8").digest("base64url");
1880
4161
  const docProof = (key, nonce, port) => sign$1(key, `doc|${nonce}|${port}`);
1881
- /** The two headers for a request carrying a well-formed `x-mv-nonce`, else null. */
1882
- function proofHeaders(p, nonce) {
4162
+ const logoProof = (key, nonce, port) => sign$1(key, `logo|${nonce}|${port}`);
4163
+ /** The two headers for a request carrying a well-formed `x-mv-nonce`, else null: over the shell's document
4164
+ * (`doc`), or over the logo (`logo`). */
4165
+ function proofHeaders(p, nonce, kind = "doc") {
1883
4166
  if (!p || typeof nonce !== "string" || !NONCE.test(nonce)) return null;
1884
4167
  return {
1885
4168
  "x-mv-instance": p.instance,
1886
- "x-mv-proof": docProof(p.key, nonce, p.port)
4169
+ "x-mv-proof": (kind === "logo" ? logoProof : docProof)(p.key, nonce, p.port)
1887
4170
  };
1888
4171
  }
1889
4172
  //#endregion
@@ -1955,6 +4238,229 @@ function routesMiddleware(server, clientDir, stamps, proof) {
1955
4238
  }
1956
4239
  };
1957
4240
  }
4241
+ /** The type each sniffed logo is served with. */
4242
+ const LOGO_MIME = {
4243
+ png: "image/png",
4244
+ ico: "image/x-icon",
4245
+ svg: "image/svg+xml"
4246
+ };
4247
+ const PNG = [
4248
+ 137,
4249
+ 80,
4250
+ 78,
4251
+ 71,
4252
+ 13,
4253
+ 10,
4254
+ 26,
4255
+ 10
4256
+ ];
4257
+ /** The logo type these bytes are, or null when they are none of the three. */
4258
+ function sniffLogo(b) {
4259
+ if (b.length >= PNG.length && PNG.every((x, i) => b[i] === x)) return "png";
4260
+ if (b.length >= 4 && b[0] === 0 && b[1] === 0 && b[2] === 1 && b[3] === 0) return "ico";
4261
+ return svgRoot(b) ? "svg" : null;
4262
+ }
4263
+ /** Is this UTF-8 text an SVG document: its root element `<svg`, with only the prolog A2.14 #24 allows before it? */
4264
+ function svgRoot(b) {
4265
+ let s;
4266
+ try {
4267
+ s = new TextDecoder("utf-8", { fatal: true }).decode(b);
4268
+ } catch {
4269
+ return false;
4270
+ }
4271
+ let i = s.charCodeAt(0) === 65279 ? 1 : 0;
4272
+ const space = () => {
4273
+ while (i < s.length && /\s/.test(s[i])) i++;
4274
+ };
4275
+ space();
4276
+ if (s.startsWith("<?xml", i) && /[\s?]/.test(s[i + 5] ?? "")) {
4277
+ const end = s.indexOf("?>", i);
4278
+ if (end < 0) return false;
4279
+ i = end + 2;
4280
+ }
4281
+ let doctype = false;
4282
+ for (;;) {
4283
+ space();
4284
+ if (s.startsWith("<!--", i)) {
4285
+ const end = s.indexOf("-->", i + 4);
4286
+ if (end < 0) return false;
4287
+ i = end + 3;
4288
+ continue;
4289
+ }
4290
+ if (s.startsWith("<!DOCTYPE", i)) {
4291
+ if (doctype) return false;
4292
+ doctype = true;
4293
+ const end = doctypeEnd(s, i + 9);
4294
+ if (end < 0) return false;
4295
+ i = end;
4296
+ continue;
4297
+ }
4298
+ break;
4299
+ }
4300
+ return s.startsWith("<svg", i) && /[\s>/]/.test(s[i + 4] ?? "");
4301
+ }
4302
+ /** Just past the `>` that closes a `<!DOCTYPE svg ...>` whose body starts at `i`, or -1: another root name, an
4303
+ * internal subset (`[` outside quotes) or no end. Quoted public and system ids may hold anything but their quote. */
4304
+ function doctypeEnd(s, i) {
4305
+ if (!/\s/.test(s[i] ?? "")) return -1;
4306
+ while (i < s.length && /\s/.test(s[i])) i++;
4307
+ if (!s.startsWith("svg", i) || !/[\s>]/.test(s[i + 3] ?? "")) return -1;
4308
+ i += 3;
4309
+ while (i < s.length) {
4310
+ const c = s[i];
4311
+ if (c === ">") return i + 1;
4312
+ if (c === "[") return -1;
4313
+ if (c === "\"" || c === "'") {
4314
+ const close = s.indexOf(c, i + 1);
4315
+ if (close < 0) return -1;
4316
+ i = close + 1;
4317
+ continue;
4318
+ }
4319
+ i++;
4320
+ }
4321
+ return -1;
4322
+ }
4323
+ //#endregion
4324
+ //#region src/server/logo.ts
4325
+ const LOGO_LADDER = [
4326
+ "design/logo.svg",
4327
+ "design/logo.png",
4328
+ "public/logo.svg",
4329
+ "public/logo.png",
4330
+ "public/favicon.svg",
4331
+ "public/favicon.png",
4332
+ "public/favicon.ico"
4333
+ ];
4334
+ /** The first candidate that passes every check, read whole; null when none does. `warn` hears why a `share.logo`
4335
+ * was ignored (the ladder's own entries are tried quietly: most repos have none of them). */
4336
+ function findLogo(root, shareLogo, warn) {
4337
+ let realRoot;
4338
+ try {
4339
+ realRoot = realpathSync(root);
4340
+ } catch {
4341
+ return null;
4342
+ }
4343
+ const own = typeof shareLogo === "string" && shareLogo !== "" ? shareLogo : null;
4344
+ for (const cand of new Set(own ? [own, ...LOGO_LADDER] : LOGO_LADDER)) {
4345
+ const r = readLogo(realRoot, resolve(realRoot, cand));
4346
+ if (typeof r !== "string") return {
4347
+ ...r,
4348
+ from: cand
4349
+ };
4350
+ if (cand === own) warn?.(`share.logo ${own} is ignored: ${r}`);
4351
+ }
4352
+ return null;
4353
+ }
4354
+ /** One candidate: its bytes and type, or why it does not count. */
4355
+ function readLogo(realRoot, file) {
4356
+ let st;
4357
+ try {
4358
+ st = lstatSync(file);
4359
+ } catch (e) {
4360
+ return e.code === "ENOENT" || e.code === "ENOTDIR" ? "no such file" : "unreadable";
4361
+ }
4362
+ if (st.isSymbolicLink()) return "a symlink";
4363
+ if (!st.isFile()) return "not a file";
4364
+ if (!/\.(svg|png|ico)$/i.test(file)) return "not .svg, .png or .ico";
4365
+ if (st.size > 262144) return "over 256 KB";
4366
+ let real;
4367
+ try {
4368
+ real = realpathSync(file);
4369
+ } catch {
4370
+ return "unreadable";
4371
+ }
4372
+ if (!real.startsWith(realRoot + sep)) return "outside the repo";
4373
+ let fd;
4374
+ try {
4375
+ fd = openSync(real, constants.O_RDONLY | constants.O_NOFOLLOW);
4376
+ } catch {
4377
+ return "unreadable";
4378
+ }
4379
+ try {
4380
+ const f = fstatSync(fd);
4381
+ if (!f.isFile() || f.ino !== st.ino || f.dev !== st.dev) return "changed while it was read";
4382
+ const buf = Buffer.alloc(262145);
4383
+ let n = 0;
4384
+ for (let k = 1; k > 0 && n < buf.length; n += k) k = readSync(fd, buf, n, buf.length - n, null);
4385
+ if (n > 262144) return "over 256 KB";
4386
+ const bytes = Buffer.from(buf.subarray(0, n));
4387
+ const type = sniffLogo(bytes);
4388
+ return type ? {
4389
+ type,
4390
+ bytes
4391
+ } : "not an image (PNG, ICO or SVG)";
4392
+ } catch {
4393
+ return "unreadable";
4394
+ } finally {
4395
+ closeSync(fd);
4396
+ }
4397
+ }
4398
+ /** `marver build`: the logo into `<outDir>/__mv/logo.<type>` (an `.ico` as `logo.ico`), by its bytes - never a copy
4399
+ * that follows a link. Its published path, or undefined when the repo has none. */
4400
+ function publishLogo(root, shareLogo, outDir, warn) {
4401
+ const logo = findLogo(root, shareLogo, warn);
4402
+ if (!logo) return void 0;
4403
+ const dir = join(outDir, ROUTE.slice(1));
4404
+ mkdirSync(dir, { recursive: true });
4405
+ writeFileSync(join(dir, `logo.${logo.type}`), logo.bytes);
4406
+ return `${ROUTE}/logo.${logo.type}`;
4407
+ }
4408
+ /** A strong `ETag` for these bytes. */
4409
+ const logoTag = (bytes) => `"${createHash("sha256").update(bytes).digest("base64url").slice(0, 22)}"`;
4410
+ /** Does an `If-None-Match` name this tag (a list, a weak tag, or `*`)? */
4411
+ function matches(header, tag) {
4412
+ if (typeof header !== "string") return false;
4413
+ return header.split(",").map((t) => t.trim().replace(/^W\//, "")).some((t) => t === "*" || t === tag);
4414
+ }
4415
+ /**
4416
+ * `marver dev`'s `GET|HEAD /__mv/logo`. Read once per request (256 KB at most), checked, and answered with its sniffed
4417
+ * type, an `ETag` and `Cache-Control: no-cache`; `x-content-type-options: nosniff` and a CSP that runs nothing, so an
4418
+ * SVG opened as a page is a picture. A request carrying a well-formed `x-mv-nonce` gets the logo proof
4419
+ * (`x-mv-instance`, `x-mv-proof` over `logo|<nonce>|<port>`), on a 200 and a 304 alike. 404 when the repo has none.
4420
+ */
4421
+ function logoRoute(root, shareLogo, proof) {
4422
+ const warned = /* @__PURE__ */ new Set();
4423
+ const warn = (m) => {
4424
+ if (warned.has(m)) return;
4425
+ warned.add(m);
4426
+ console.warn(` marver: ${m}`);
4427
+ };
4428
+ return (req, res, next) => {
4429
+ let path;
4430
+ try {
4431
+ path = new URL(req.url ?? "/", "http://x").pathname;
4432
+ } catch {
4433
+ return next();
4434
+ }
4435
+ if (path !== `/__mv/logo`) return next();
4436
+ if (req.method !== "GET" && req.method !== "HEAD") {
4437
+ res.statusCode = 405;
4438
+ res.setHeader("allow", "GET, HEAD");
4439
+ return res.end();
4440
+ }
4441
+ const logo = findLogo(root, shareLogo(), warn);
4442
+ if (!logo) {
4443
+ res.statusCode = 404;
4444
+ res.setHeader("cache-control", "no-store");
4445
+ return res.end();
4446
+ }
4447
+ const tag = logoTag(logo.bytes);
4448
+ res.setHeader("content-type", LOGO_MIME[logo.type]);
4449
+ res.setHeader("etag", tag);
4450
+ res.setHeader("cache-control", "no-cache");
4451
+ res.setHeader("vary", "x-mv-nonce");
4452
+ res.setHeader("x-content-type-options", "nosniff");
4453
+ res.setHeader("content-security-policy", "default-src 'none'; style-src 'unsafe-inline'");
4454
+ const signed = proofHeaders(proof, req.headers["x-mv-nonce"], "logo");
4455
+ if (signed) for (const [k, v] of Object.entries(signed)) res.setHeader(k, v);
4456
+ if (matches(req.headers["if-none-match"], tag)) {
4457
+ res.statusCode = 304;
4458
+ return res.end();
4459
+ }
4460
+ res.setHeader("content-length", String(logo.bytes.length));
4461
+ res.end(req.method === "HEAD" ? void 0 : logo.bytes);
4462
+ };
4463
+ }
1958
4464
  //#endregion
1959
4465
  //#region src/server/guard.ts
1960
4466
  /** A workspace key as marver writes it: 16 hex. A frame's own `ws` query in another shape is the
@@ -2039,73 +4545,6 @@ function elsewhere(res) {
2039
4545
  res.end(JSON.stringify({ error: "another workspace" }));
2040
4546
  }
2041
4547
  //#endregion
2042
- //#region src/server/update.ts
2043
- /**
2044
- * Update discovery - dev only, and deliberately boring about privacy: one anonymous
2045
- * registry metadata GET per day (the same request `npm view` makes), cached in
2046
- * design/.local/, nothing sent beyond the request itself. Offline, slow, or
2047
- * firewalled registries degrade to silence. MARVER_NO_UPDATE_CHECK=1 disables it.
2048
- * Published bundles never check anything - viewers are not the owner.
2049
- */
2050
- const TTL = 864e5;
2051
- /** Installed version: walk up from this module to the package's own package.json
2052
- * (one level from dist/, two from src/server/ - the walk covers both). */
2053
- function installedVersion() {
2054
- let dir = dirname(fileURLToPath(import.meta.url));
2055
- for (let i = 0; i < 4; i++) {
2056
- try {
2057
- const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
2058
- if (pkg.name === "@marver-design/marver") return pkg.version;
2059
- } catch {}
2060
- dir = dirname(dir);
2061
- }
2062
- return null;
2063
- }
2064
- /** Strictly-newer numeric compare; anything non-numeric (prerelease tags) compares false. */
2065
- const newer = (a, b) => {
2066
- const pa = a.split(".").map((n) => parseInt(n, 10));
2067
- const pb = b.split(".").map((n) => parseInt(n, 10));
2068
- for (let i = 0; i < 3; i++) {
2069
- const x = pa[i] ?? 0, y = pb[i] ?? 0;
2070
- if (!Number.isFinite(x) || !Number.isFinite(y)) return false;
2071
- if (x !== y) return x > y;
2072
- }
2073
- return false;
2074
- };
2075
- /** The latest published version when strictly newer than installed, else null. Never throws. */
2076
- async function checkUpdate(root) {
2077
- if (process.env.MARVER_NO_UPDATE_CHECK) return null;
2078
- const current = installedVersion();
2079
- if (!current) return null;
2080
- const latest = await latestVersion(root);
2081
- return latest && newer(latest, current) ? latest : null;
2082
- }
2083
- async function latestVersion(root) {
2084
- const cacheFile = join(root, "design", ".local", "update-check.json");
2085
- const wellFormed = (v) => typeof v === "string" && /^\d+\.\d+\.\d+$/.test(v);
2086
- try {
2087
- const c = JSON.parse(readFileSync(cacheFile, "utf8"));
2088
- const age = Date.now() - c.checkedAt;
2089
- if (typeof c.checkedAt === "number" && age >= 0 && age < TTL) return wellFormed(c.latest) ? c.latest : null;
2090
- } catch {}
2091
- let latest = null;
2092
- try {
2093
- const res = await fetch(`https://registry.npmjs.org/${encodeURIComponent(PKG)}/latest`, { signal: AbortSignal.timeout(3e3) });
2094
- if (res.ok) {
2095
- const v = (await res.json())?.version;
2096
- if (wellFormed(v)) latest = v;
2097
- }
2098
- } catch {}
2099
- try {
2100
- mkdirSync(join(root, "design", ".local"), { recursive: true });
2101
- writeFileSync(cacheFile, JSON.stringify({
2102
- checkedAt: Date.now(),
2103
- latest
2104
- }) + "\n");
2105
- } catch {}
2106
- return latest;
2107
- }
2108
- //#endregion
2109
4548
  //#region src/server/plugin.ts
2110
4549
  const VIRTUAL_THEME = "virtual:sh-theme";
2111
4550
  const VIRTUAL_CONFIG = "virtual:sh-config";
@@ -2123,6 +4562,30 @@ function marverPlugin(ctx) {
2123
4562
  let manifest = scanFrames(root, projectInfo());
2124
4563
  let devServer = null;
2125
4564
  let served = 0;
4565
+ const watching = {
4566
+ server: null,
4567
+ watcher: null,
4568
+ ready: false,
4569
+ waiters: /* @__PURE__ */ new Set()
4570
+ };
4571
+ const inputs = {
4572
+ ready: () => watching.ready ? Promise.resolve(true) : new Promise((resolve) => {
4573
+ const done = () => {
4574
+ clearTimeout(t);
4575
+ resolve(true);
4576
+ };
4577
+ const t = setTimeout(() => {
4578
+ watching.waiters.delete(done);
4579
+ resolve(watching.ready);
4580
+ }, runT().watcherReadyMs);
4581
+ watching.waiters.add(done);
4582
+ }),
4583
+ watched: () => watching.watcher?.getWatched() ?? {},
4584
+ loaded: (urls) => {
4585
+ const s = watching.server;
4586
+ return s ? loadedFiles(urls, s.config.root, s.environments?.client?.moduleGraph ?? null, s.config.base) : [];
4587
+ }
4588
+ };
2126
4589
  const bootId = String(process.hrtime.bigint());
2127
4590
  let invRev = 0;
2128
4591
  const pendingInv = /* @__PURE__ */ new Set();
@@ -2280,7 +4743,8 @@ function marverPlugin(ctx) {
2280
4743
  capture: config.jam.capture,
2281
4744
  names: config.jam.names && config.jam.agent === "claude"
2282
4745
  } : null,
2283
- workspace: ws
4746
+ workspace: ws,
4747
+ version: installedVersion() ?? "0.0.0"
2284
4748
  })}`;
2285
4749
  }
2286
4750
  if (id === "\0virtual:sh-data") return "export default null";
@@ -2343,8 +4807,21 @@ function marverPlugin(ctx) {
2343
4807
  if (served++) {
2344
4808
  manifest = scanFrames(root, projectInfo());
2345
4809
  observeLater();
4810
+ runs.restarted();
2346
4811
  }
2347
4812
  server.middlewares.use(guardMiddleware(ws));
4813
+ server.middlewares.use(perfRunBarrier());
4814
+ const viteWatcher = server.watcher;
4815
+ watching.server = server;
4816
+ watching.watcher = viteWatcher;
4817
+ watching.ready = viteWatcher._readyEmitted === true;
4818
+ viteWatcher.once("ready", () => {
4819
+ if (watching.watcher !== viteWatcher) return;
4820
+ watching.ready = true;
4821
+ for (const w of watching.waiters) w();
4822
+ watching.waiters.clear();
4823
+ });
4824
+ viteWatcher.on("all", (_event, file) => runs.changed(file));
2348
4825
  let bakeGen = Date.now();
2349
4826
  server.middlewares.use((req, res, next) => {
2350
4827
  if (req.url && req.url.includes("/frame-host/registry.ts")) {
@@ -2378,8 +4855,10 @@ function marverPlugin(ctx) {
2378
4855
  notify: (event) => server.ws.send(event, {}),
2379
4856
  manifest: () => manifest,
2380
4857
  settled,
2381
- workspace: ws
4858
+ workspace: ws,
4859
+ inputs
2382
4860
  }));
4861
+ server.middlewares.use(logoRoute(root, () => config.share.logo, ctx.proof));
2383
4862
  server.middlewares.use(routesMiddleware(server, clientDir, {
2384
4863
  doc: (id) => docRev(root, manifest.frames, id),
2385
4864
  docs: () => docRevs(root, manifest.frames)
@@ -2447,7 +4926,7 @@ function marverPlugin(ctx) {
2447
4926
  const t = setTimeout(async () => {
2448
4927
  pruning.delete(t);
2449
4928
  try {
2450
- (await import("./bake-DM_uWgAA.mjs")).pruneBakes(root, bakeGen);
4929
+ (await Promise.resolve().then(() => bake_exports)).pruneBakes(root, bakeGen);
2451
4930
  } catch {}
2452
4931
  }, 500);
2453
4932
  pruning.add(t);
@@ -2523,6 +5002,7 @@ function marverPlugin(ctx) {
2523
5002
  if (nodeExists(join(boardsDir, `all-scenes.json`))) console.log(`[${NAME}] design/boards/${ALL_SCENES}.json is left over from the All Scenes board, gone since 0.25 - nothing reads it any more; delete it when you like (its threads stay in design/comments/)`);
2524
5003
  let listTimer;
2525
5004
  const watcher = guarded(watch(boardsDir, (_event, file) => {
5005
+ if (file?.endsWith(".json")) runs.changed(join(boardsDir, file));
2526
5006
  if (!file || !file.endsWith(".json") || file === "_sizes.json" || file === `all-scenes.json`) return;
2527
5007
  clearTimeout(listTimer);
2528
5008
  listTimer = setTimeout(() => {
@@ -2638,7 +5118,7 @@ function marverPlugin(ctx) {
2638
5118
  });
2639
5119
  return;
2640
5120
  }
2641
- const { shootFrame, shootBatch, resolveFrames } = await import("./shot-LFhC-WYD.mjs");
5121
+ const { shootFrame, shootBatch, resolveFrames } = await import("./shot-Ch24tiMO.mjs").then((n) => n.u);
2642
5122
  if (ways[0] === "frame") {
2643
5123
  if (typeof spec.frame !== "string") {
2644
5124
  write({
@@ -2759,4 +5239,4 @@ async function tailwind3Css(root) {
2759
5239
  return null;
2760
5240
  }
2761
5241
  //#endregion
2762
- export { autoWidthOf as a, readSizes as c, installedVersion as i, loadConfig as l, tailwind3Css as n, keptSizes as o, tailwind4Plugin as r, measuringFrames as s, marverPlugin as t };
5242
+ export { installedVersion as a, autoWidthOf as c, readSizes as d, loadConfig as f, publishLogo as i, keptSizes as l, tailwind3Css as n, ASK_MAX as o, tailwind4Plugin as r, bakeBatch as s, marverPlugin as t, measuringFrames as u };