@ksp-gonogo/uplink-tools 1.0.0-rc.21 → 1.0.0-rc.25

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 (40) hide show
  1. package/README.md +46 -5
  2. package/dist/{chunk-UYSZ2JYT.js → chunk-3JUWBX63.js} +4 -3
  3. package/dist/chunk-3JUWBX63.js.map +1 -0
  4. package/dist/chunk-C7MB3JSB.js +82 -0
  5. package/dist/chunk-C7MB3JSB.js.map +1 -0
  6. package/dist/{chunk-IXYBXOZ5.js → chunk-NWZEKR6O.js} +22 -705
  7. package/dist/chunk-NWZEKR6O.js.map +1 -0
  8. package/dist/chunk-U5TALY37.js +6213 -0
  9. package/dist/chunk-U5TALY37.js.map +1 -0
  10. package/dist/chunk-UJPYZJLQ.js +679 -0
  11. package/dist/chunk-UJPYZJLQ.js.map +1 -0
  12. package/dist/chunk-V5EKSCEU.js +43 -0
  13. package/dist/chunk-V5EKSCEU.js.map +1 -0
  14. package/dist/{cli-3STJLZOV.js → cli-VWGWFVJG.js} +39 -51
  15. package/dist/cli-VWGWFVJG.js.map +1 -0
  16. package/dist/cli.d.ts +1 -1
  17. package/dist/cli.js +2 -1
  18. package/dist/index.d.ts +39 -75
  19. package/dist/index.js +16 -12
  20. package/dist/index.js.map +1 -1
  21. package/dist/page-check.js +11 -7
  22. package/dist/page-check.js.map +1 -1
  23. package/dist/render-probe.d.ts +43 -0
  24. package/dist/render-probe.js +22 -1
  25. package/dist/render-probe.js.map +1 -1
  26. package/dist/story-DZRIDPEZ.js +513 -0
  27. package/dist/story-DZRIDPEZ.js.map +1 -0
  28. package/dist/widget-facts.d.ts +58 -0
  29. package/dist/widget-facts.js +9 -0
  30. package/dist/widget-facts.js.map +1 -0
  31. package/dist/widgetRecord-DTd2xm53.d.ts +82 -0
  32. package/dist/widgets.js +20101 -17833
  33. package/dist/widgets.js.map +1 -1
  34. package/dist/widgets.json +2019 -1824
  35. package/package.json +11 -3
  36. package/dist/chunk-EUTWMXUS.js +0 -3306
  37. package/dist/chunk-EUTWMXUS.js.map +0 -1
  38. package/dist/chunk-IXYBXOZ5.js.map +0 -1
  39. package/dist/chunk-UYSZ2JYT.js.map +0 -1
  40. package/dist/cli-3STJLZOV.js.map +0 -1
package/README.md CHANGED
@@ -8,11 +8,12 @@ It is a **devDependency**. Nothing here ships in an Uplink's bundle.
8
8
 
9
9
  ## The command line
10
10
 
11
- One command, `uplink-tools`, and nothing to install before the first run:
11
+ One command, `uplink-tools`, and nothing to install before the first run. Until the first release, `latest` is a placeholder, so run the release candidate with `@rc`.
12
+
12
13
 
13
14
  ```sh
14
- npx @ksp-gonogo/uplink-tools new myuplink --repo you/myuplink # in an empty directory
15
- npx @ksp-gonogo/uplink-tools --help
15
+ npx @ksp-gonogo/uplink-tools@rc new myuplink --repo acme/myuplink # in an empty directory
16
+ npx @ksp-gonogo/uplink-tools@rc --help
16
17
  ```
17
18
 
18
19
  `new` asks what it was not told: the id, a display name, the author, the
@@ -35,14 +36,54 @@ Once it is in an Uplink's devDependencies the same commands answer to
35
36
  |---|---|
36
37
  | `new <id>` | scaffold an Uplink: contract slice, plugin, tests, one widget and its fixture, then generate its client types, install the client and write its page. In a repo with an `uplinks/` folder it goes to `uplinks/<id>/`; anywhere else the current directory becomes the Uplink |
37
38
  | `codegen` | generate `client/src/__generated__/` from the C# contract slice; `codegen --check` fails on drift |
39
+ | `check` | read the client with TypeScript (an optional peer, installed in every scaffold) and report what is unresolved or stale, with the command that heals each finding. Exits 0 clean, 1 when findings remain, 2 when it could not run; `--fix` writes the files it owns and is refused when `CI` is set; `--json`, `--only` and `--skip` take its groups. A read it cannot name takes a `// gonogo:reads <topic or family>` comment above the call. A frame whose built-in augment does all the reading keeps its `channels` and `fields` with a `// gonogo:augment-reads <augment id> <channel>...` comment above its `registerComponent`; `check` requires every channel named to appear in that augment's own `channels` |
38
40
  | `bundle` | build the client bundle the app loads, and the `gonogo-uplink.json` beside it; `--watch` rebuilds on every change and `--serve <port>` also serves it from this computer |
39
41
  | `bake` | write what the plugin tells the app about its client into C#: where the bundle lives, who wrote it, and the hash the mod vouches for |
40
42
  | `package` | lay the built plugin out as `GameData/<name>/` and zip it with that as the zip's one root, which is what a hand install and CKAN both expect; it refuses a netkan whose install stanza names a path the zip does not hold |
41
43
  | `release` | `bundle`, `bake`, compile the plugin, check the DLL carries what was baked, and `package`, in that order. It refuses when the Uplink's version is not the same in `client/package.json`, in `defineUplinkClient` and in the version folder of `client.url` |
42
44
  | `page` | write `README.md`, `gonogo-uplink.json` and `docs/widgets.json` from what the client registers, with no browser |
43
45
  | `render` | render every scene to `renders/` |
46
+ | `story <id>` | render one Storybook story to a PNG, or to a GIF when the story is tagged `playback`; see below |
44
47
  | `docs` | write `README.md`, `gonogo-uplink.json`, `docs/widgets.json` and `docs/assets/`; `docs --check` fails on drift |
45
48
 
49
+ ### Seeing a build in the app
50
+
51
+ With a checkout of the gonogo app, run `uplink-tools bundle --watch` in the
52
+ Uplink's `client/` and, from the app checkout, `pnpm dev --uplink <path>`, where
53
+ `<path>` is the directory holding `uplink.json`. Repeat the flag for several
54
+ Uplinks. The dev app loads each one's build output with no mod report, hash or
55
+ consent prompt, still checks its contract and the bytes it fetched, lists it in
56
+ Settings under Local builds, and reloads the page on every rebuild. An Uplink
57
+ without an `uplink.json` is refused. Without a checkout, `bundle --serve <port>`
58
+ with `bake --dev-path` serves a client to an app that is already running.
59
+
60
+ ### Rendering a Storybook story
61
+
62
+ `story` draws one story of any built Storybook, or a running one, and needs
63
+ nothing of the Uplink around it:
64
+
65
+ ```
66
+ uplink-tools story widgets-landing-status-descent-playback--crash-landing
67
+ uplink-tools story --list landing # the ids that contain "landing"
68
+ uplink-tools story <id> --png # the first settled frame of a playback story
69
+ uplink-tools story <id> --chrome # the whole story frame, controls and captions included
70
+ uplink-tools story <id> --seconds 8 --fps 15 --size 900x700 --out clip.gif
71
+ ```
72
+
73
+ It reads the build from `./storybook-static` (`--storybook <dir|url>` points
74
+ elsewhere) and writes `renders/<id>.png`. The picture is the widget alone, cropped to the element
75
+ the story marks `data-story-widget` (every marked element, when a story has
76
+ several); `--chrome` draws the whole story frame instead, and a story with no
77
+ marker is drawn whole. A story whose meta carries the tag
78
+ `playback` renders as a GIF instead: it clicks the story's Replay or Play
79
+ button, the one marked `data-story-start` or else named Replay or Play, once the
80
+ story has rendered even when it is outside the crop (`--start <name>` names another), records
81
+ for `--seconds` (default 6) at `--fps` (default 10), and is saved as
82
+ `renders/<id>.gif`. A story that starts on its own needs no button. A GIF
83
+ carries no sound, and Chromium is launched muted, so a Play control can be
84
+ pressed without noise. In the gonogo repository `pnpm render-story <id>`
85
+ does the same and builds the Storybook first when there is no build.
86
+
46
87
  The order inside `release` is the point of it. The app loads an installed
47
88
  Uplink's client only when the plugin says where the bundle lives and vouches for
48
89
  its hash, so the bundle has to be built and hashed before the plugin is
@@ -150,7 +191,7 @@ need the widget around it:
150
191
  A fixture can then name the widget it extends:
151
192
 
152
193
  ```json
153
- { "_scene": { "hostWidget": "strategies" } }
194
+ { "_scene": { "hostWidget": "admin-building" } }
154
195
  ```
155
196
 
156
197
  There is nothing to `import` from `/widgets`. It exports no symbols: importing it
@@ -170,7 +211,7 @@ and `Panel` draws every widget's `<id>.badges` itself, so a badge contribution
170
211
  lands there exactly as it lands in the real widget.
171
212
 
172
213
  Every **other** contribution slot is drawn by the host widget's own body, and a
173
- stand-in's body draws nothing. `strategies.screens`,
214
+ stand-in's body draws nothing. `admin-building.screens`,
174
215
  `space-center-status.facilities` and `astronaut-complex.readouts` are each read
175
216
  by a `useContributions(...)` inside the widget. Standing in for those produces a
176
217
  blank frame that reports success. A real widget's own body is the only thing that draws
@@ -7,7 +7,7 @@ import {
7
7
  jetbrainsMonoFace,
8
8
  payloadFor,
9
9
  themeTokensCss
10
- } from "./chunk-IXYBXOZ5.js";
10
+ } from "./chunk-NWZEKR6O.js";
11
11
 
12
12
  // ../../node_modules/.pnpm/gifenc@1.0.3/node_modules/gifenc/dist/gifenc.esm.js
13
13
  var X = { signature: "GIF", version: "89a", trailer: 59, extensionIntroducer: 33, applicationExtensionLabel: 255, graphicControlExtensionLabel: 249, imageSeparator: 44, signatureSize: 3, versionSize: 3, globalColorTableFlagMask: 128, colorResolutionMask: 112, sortFlagMask: 8, globalColorTableSizeMask: 7, applicationIdentifierSize: 8, applicationAuthCodeSize: 3, disposalMethodMask: 28, userInputFlagMask: 2, transparentColorFlagMask: 1, localColorTableFlagMask: 128, interlaceFlagMask: 64, idSortFlagMask: 32, localColorTableSizeMask: 7 };
@@ -1478,7 +1478,7 @@ function assertEveryEmitLanded(scene, report) {
1478
1478
  `${scene.name} (${scene.target.kind} ${scene.target.id}): nothing in the mounted tree subscribed to ${report.unsubscribedTopics.length} emitted topic(s), so they were dropped:
1479
1479
  ${report.unsubscribedTopics.join("\n ")}
1480
1480
  Topics the registration declares: ${scene.declaredTopics.join(", ") || "(none)"}
1481
- ` + (report.undeclaredTopics.length > 0 ? `Not declared at all: ${report.undeclaredTopics.join(", ")}. Add the topic to the target's \`channels\` / \`optionalChannels\` / \`dataRequirements\`, or drop it from the fixture.
1481
+ ` + (report.undeclaredTopics.length > 0 ? `Not declared at all: ${report.undeclaredTopics.join(", ")}. Add the topic to the target's \`channels\` / \`optionalChannels\` / \`channelFamilies\` / \`dataRequirements\`, or drop it from the fixture.
1482
1482
  ` : "Declared, and nothing read it: either the target does not consume the topic, or whatever gates the read never opened.\n")
1483
1483
  );
1484
1484
  }
@@ -1600,7 +1600,8 @@ export {
1600
1600
  writeShapeRecord,
1601
1601
  compareShapes,
1602
1602
  describeStale,
1603
+ engine,
1603
1604
  readUplinkScenes,
1604
1605
  renderUplink
1605
1606
  };
1606
- //# sourceMappingURL=chunk-UYSZ2JYT.js.map
1607
+ //# sourceMappingURL=chunk-3JUWBX63.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../node_modules/.pnpm/gifenc@1.0.3/node_modules/gifenc/src/constants.js","../../../node_modules/.pnpm/gifenc@1.0.3/node_modules/gifenc/src/stream.js","../../../node_modules/.pnpm/gifenc@1.0.3/node_modules/gifenc/src/lzwEncode.js","../../../node_modules/.pnpm/gifenc@1.0.3/node_modules/gifenc/src/rgb-packing.js","../../../node_modules/.pnpm/gifenc@1.0.3/node_modules/gifenc/src/pnnquant2.js","../../../node_modules/.pnpm/gifenc@1.0.3/node_modules/gifenc/src/color.js","../../../node_modules/.pnpm/gifenc@1.0.3/node_modules/gifenc/src/palettize.js","../../../node_modules/.pnpm/gifenc@1.0.3/node_modules/gifenc/src/index.js","../src/render/png.ts","../src/render/gif.ts","../src/render/page.ts","../src/render/shape.ts","../src/render/driver.ts","../src/render/grow.ts","../src/render/held.ts"],"sourcesContent":["export default {\n signature: \"GIF\",\n version: \"89a\",\n trailer: 0x3B,\n extensionIntroducer: 0x21,\n applicationExtensionLabel: 0xFF,\n graphicControlExtensionLabel: 0xF9,\n imageSeparator: 0x2C,\n // Header\n signatureSize: 3,\n versionSize: 3,\n globalColorTableFlagMask: 0b10000000,\n colorResolutionMask: 0b01110000,\n sortFlagMask: 0b00001000,\n globalColorTableSizeMask: 0b00000111,\n // Application extension\n applicationIdentifierSize: 8,\n applicationAuthCodeSize: 3,\n // Graphic control extension\n disposalMethodMask: 0b00011100,\n userInputFlagMask: 0b00000010,\n transparentColorFlagMask: 0b00000001,\n // Image descriptor\n localColorTableFlagMask: 0b10000000,\n interlaceFlagMask: 0b01000000,\n idSortFlagMask: 0b00100000,\n localColorTableSizeMask: 0b00000111\n}\n","export default function createStream(initialCapacity = 256) {\n let cursor = 0;\n let contents = new Uint8Array(initialCapacity);\n\n return {\n get buffer() {\n return contents.buffer;\n },\n reset() {\n cursor = 0;\n },\n bytesView() {\n return contents.subarray(0, cursor);\n },\n bytes() {\n return contents.slice(0, cursor);\n },\n writeByte(byte) {\n expand(cursor + 1);\n contents[cursor] = byte;\n cursor++;\n },\n writeBytes(data, offset = 0, byteLength = data.length) {\n expand(cursor + byteLength);\n for (let i = 0; i < byteLength; i++) {\n contents[cursor++] = data[i + offset];\n }\n },\n writeBytesView(data, offset = 0, byteLength = data.byteLength) {\n expand(cursor + byteLength);\n contents.set(data.subarray(offset, offset + byteLength), cursor);\n cursor += byteLength;\n },\n };\n\n function expand(newCapacity) {\n var prevCapacity = contents.length;\n if (prevCapacity >= newCapacity) return; // No need to expand, the storage was already large enough.\n // Don't expand strictly to the given requested limit if it's only a very small increase, but instead geometrically grow capacity.\n // For small filesizes (<1MB), perform size*2 geometric increase, but for large sizes, do a much more conservative size*1.125 increase to\n // avoid overshooting the allocation cap by a very large margin.\n var CAPACITY_DOUBLING_MAX = 1024 * 1024;\n newCapacity = Math.max(\n newCapacity,\n (prevCapacity * (prevCapacity < CAPACITY_DOUBLING_MAX ? 2.0 : 1.125)) >>>\n 0\n );\n if (prevCapacity != 0) newCapacity = Math.max(newCapacity, 256); // At minimum allocate 256b for each file when expanding.\n const oldContents = contents;\n contents = new Uint8Array(newCapacity); // Allocate new storage.\n if (cursor > 0) contents.set(oldContents.subarray(0, cursor), 0);\n }\n}\n","/*\n LZWEncoder.js\n Authors\n Kevin Weiner (original Java version - kweiner@fmsware.com)\n Thibault Imbert (AS3 version - bytearray.org)\n Johan Nordberg (JS version - code@johan-nordberg.com)\n Acknowledgements\n GIFCOMPR.C - GIF Image compression routines\n Lempel-Ziv compression based on 'compress'. GIF modifications by\n David Rowley (mgardi@watdcsu.waterloo.edu)\n GIF Image compression - modified 'compress'\n Based on: compress.c - File compression ala IEEE Computer, June 1984.\n By Authors: Spencer W. Thomas (decvax!harpo!utah-cs!utah-gr!thomas)\n Jim McKie (decvax!mcvax!jim)\n Steve Davies (decvax!vax135!petsd!peora!srd)\n Ken Turkowski (decvax!decwrl!turtlevax!ken)\n James A. Woods (decvax!ihnp4!ames!jaw)\n Joe Orost (decvax!vax135!petsd!joe)\n Matt DesLauriers (@mattdesl - V8/JS optimizations)\n Mathieu Henri (@p01 - JS optimization)\n*/\n\nimport createStream from \"./stream.js\";\n\nconst EOF = -1;\nconst BITS = 12;\nconst DEFAULT_HSIZE = 5003; // 80% occupancy\nconst MASKS = [\n 0x0000,\n 0x0001,\n 0x0003,\n 0x0007,\n 0x000f,\n 0x001f,\n 0x003f,\n 0x007f,\n 0x00ff,\n 0x01ff,\n 0x03ff,\n 0x07ff,\n 0x0fff,\n 0x1fff,\n 0x3fff,\n 0x7fff,\n 0xffff,\n];\n\nfunction lzwEncode(\n width,\n height,\n pixels,\n colorDepth,\n outStream = createStream(512),\n accum = new Uint8Array(256),\n htab = new Int32Array(DEFAULT_HSIZE),\n codetab = new Int32Array(DEFAULT_HSIZE)\n) {\n const hsize = htab.length;\n const initCodeSize = Math.max(2, colorDepth);\n\n accum.fill(0);\n codetab.fill(0);\n htab.fill(-1);\n\n let cur_accum = 0;\n let cur_bits = 0;\n\n // Algorithm: use open addressing double hashing (no chaining) on the\n // prefix code / next character combination. We do a variant of Knuth's\n // algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime\n // secondary probe. Here, the modular division first probe is gives way\n // to a faster exclusive-or manipulation. Also do block compression with\n // an adaptive reset, whereby the code table is cleared when the compression\n // ratio decreases, but after the table fills. The variable-length output\n // codes are re-sized at this point, and a special CLEAR code is generated\n // for the decompressor. Late addition: construct the table according to\n // file size for noticeable speed improvement on small files. Please direct\n // questions about this implementation to ames!jaw.\n\n // compress and write the pixel data\n const init_bits = initCodeSize + 1;\n\n // Set up the globals: g_init_bits - initial number of bits\n const g_init_bits = init_bits;\n\n // Set up the necessary values\n\n // block compression parameters -- after all codes are used up,\n // and compression rate changes, start over.\n let clear_flg = false;\n let n_bits = g_init_bits;\n let maxcode = (1 << n_bits) - 1;\n\n const ClearCode = 1 << (init_bits - 1);\n const EOFCode = ClearCode + 1;\n let free_ent = ClearCode + 2;\n let a_count = 0; // clear packet\n\n let ent = pixels[0];\n\n let hshift = 0;\n for (let fcode = hsize; fcode < 65536; fcode *= 2) {\n ++hshift;\n }\n hshift = 8 - hshift; // set hash code range bound\n\n outStream.writeByte(initCodeSize); // write \"initial code size\" byte\n\n output(ClearCode);\n\n const length = pixels.length;\n for (let idx = 1; idx < length; idx++) {\n next_block: {\n const c = pixels[idx];\n const fcode = (c << BITS) + ent;\n let i = (c << hshift) ^ ent; // xor hashing\n if (htab[i] === fcode) {\n ent = codetab[i];\n break next_block;\n }\n\n const disp = i === 0 ? 1 : hsize - i; // secondary hash (after G. Knott)\n while (htab[i] >= 0) {\n // non-empty slot\n i -= disp;\n if (i < 0) i += hsize;\n if (htab[i] === fcode) {\n ent = codetab[i];\n break next_block;\n }\n }\n output(ent);\n ent = c;\n if (free_ent < 1 << BITS) {\n codetab[i] = free_ent++; // code -> hashtable\n htab[i] = fcode;\n } else {\n // Clear out the hash table\n // table clear for block compress\n htab.fill(-1);\n free_ent = ClearCode + 2;\n clear_flg = true;\n output(ClearCode);\n }\n }\n }\n\n // Put out the final code.\n output(ent);\n output(EOFCode);\n\n outStream.writeByte(0); // write block terminator\n return outStream.bytesView();\n\n function output(code) {\n cur_accum &= MASKS[cur_bits];\n\n if (cur_bits > 0) cur_accum |= code << cur_bits;\n else cur_accum = code;\n\n cur_bits += n_bits;\n\n while (cur_bits >= 8) {\n // Add a character to the end of the current packet, and if it is 254\n // characters, flush the packet to disk.\n accum[a_count++] = cur_accum & 0xff;\n if (a_count >= 254) {\n outStream.writeByte(a_count);\n outStream.writeBytesView(accum, 0, a_count);\n a_count = 0;\n }\n cur_accum >>= 8;\n cur_bits -= 8;\n }\n\n // If the next entry is going to be too big for the code size,\n // then increase it, if possible.\n if (free_ent > maxcode || clear_flg) {\n if (clear_flg) {\n n_bits = g_init_bits;\n maxcode = (1 << n_bits) - 1;\n clear_flg = false;\n } else {\n ++n_bits;\n maxcode = n_bits === BITS ? (1 << n_bits) : (1 << n_bits) - 1;\n }\n }\n\n if (code == EOFCode) {\n // At EOF, write the rest of the buffer.\n while (cur_bits > 0) {\n // Add a character to the end of the current packet, and if it is 254\n // characters, flush the packet to disk.\n accum[a_count++] = cur_accum & 0xff;\n if (a_count >= 254) {\n outStream.writeByte(a_count);\n outStream.writeBytesView(accum, 0, a_count);\n a_count = 0;\n }\n cur_accum >>= 8;\n cur_bits -= 8;\n }\n // Flush the packet to disk, and reset the accumulator\n if (a_count > 0) {\n outStream.writeByte(a_count);\n outStream.writeBytesView(accum, 0, a_count);\n a_count = 0;\n }\n }\n }\n}\n\nexport default lzwEncode;\n","export function uint32_to_rgba(color) {\n var a = (color >> 24) & 0xff;\n var b = (color >> 16) & 0xff;\n var g = (color >> 8) & 0xff;\n var r = color & 0xff;\n return [r, g, b, a];\n}\n\nexport function rgba_to_uint32(r, g, b, a) {\n return (a << 24) | (b << 16) | (g << 8) | r;\n}\n\nexport function rgb888_to_rgb565(r, g, b) {\n return ((r << 8) & 0xf800) | ((g << 2) & 0x03e0) | (b >> 3);\n}\n\nexport function rgba8888_to_rgba4444(r, g, b, a) {\n return (r >> 4) | (g & 0xf0) | ((b & 0xf0) << 4) | ((a & 0xf0) << 8);\n}\n\nexport function rgb888_to_rgb444(r, g, b) {\n return ((r >> 4) << 8) | (g & 0xf0) | (b >> 4);\n}\n\n// Alternative 565 ?\n// return ((r & 0xf8) << 8) + ((g & 0xfc) << 3) + (b >> 3);\n\n// Alternative 4444 ?\n// ((a & 0xf0) << 8) | ((r & 0xf0) << 4) | (g & 0xf0) | (b >> 4);\n","// Modified from:\n// https://github.com/mcychan/PnnQuant.js/blob/master/src/pnnquant.js\n\n/* Fast pairwise nearest neighbor based algorithm for multilevel thresholding\nCopyright (C) 2004-2019 Mark Tyler and Dmitry Groshev\nCopyright (c) 2018-2021 Miller Cy Chan\n* error measure; time used is proportional to number of bins squared - WJ */\n\nimport {\n rgb888_to_rgb565,\n rgb888_to_rgb444,\n rgba8888_to_rgba4444,\n} from \"./rgb-packing.js\";\n\nfunction clamp(value, min, max) {\n return value < min ? min : value > max ? max : value;\n}\n\nfunction sqr(value) {\n return value * value;\n}\n\nfunction find_nn(bins, idx, hasAlpha) {\n var nn = 0;\n var err = 1e100;\n\n const bin1 = bins[idx];\n const n1 = bin1.cnt;\n const wa = bin1.ac;\n const wr = bin1.rc;\n const wg = bin1.gc;\n const wb = bin1.bc;\n for (var i = bin1.fw; i != 0; i = bins[i].fw) {\n const bin = bins[i];\n const n2 = bin.cnt;\n const nerr2 = (n1 * n2) / (n1 + n2);\n if (nerr2 >= err) continue;\n\n var nerr = 0;\n if (hasAlpha) {\n nerr += nerr2 * sqr(bin.ac - wa);\n if (nerr >= err) continue;\n }\n\n nerr += nerr2 * sqr(bin.rc - wr);\n if (nerr >= err) continue;\n\n nerr += nerr2 * sqr(bin.gc - wg);\n if (nerr >= err) continue;\n\n nerr += nerr2 * sqr(bin.bc - wb);\n if (nerr >= err) continue;\n err = nerr;\n nn = i;\n }\n bin1.err = err;\n bin1.nn = nn;\n}\n\nfunction create_bin() {\n return {\n ac: 0,\n rc: 0,\n gc: 0,\n bc: 0,\n cnt: 0,\n nn: 0,\n fw: 0,\n bk: 0,\n tm: 0,\n mtm: 0,\n err: 0,\n };\n}\n\nfunction bin_add_rgb(bin, r, g, b) {\n bin.rc += r;\n bin.gc += g;\n bin.bc += b;\n bin.cnt++;\n}\n\nfunction create_bin_list(data, format) {\n const bincount = format === \"rgb444\" ? 4096 : 65536;\n const bins = new Array(bincount);\n const size = data.length;\n\n /* Build histogram */\n // Note: Instead of introducing branching/conditions\n // within a very hot per-pixel iteration, we just duplicate the code\n // for each new condition\n if (format === \"rgba4444\") {\n for (let i = 0; i < size; ++i) {\n const color = data[i];\n const a = (color >> 24) & 0xff;\n const b = (color >> 16) & 0xff;\n const g = (color >> 8) & 0xff;\n const r = color & 0xff;\n\n // reduce to rgb4444 16-bit uint\n const index = rgba8888_to_rgba4444(r, g, b, a);\n let bin = index in bins ? bins[index] : (bins[index] = create_bin());\n bin.rc += r;\n bin.gc += g;\n bin.bc += b;\n bin.ac += a;\n bin.cnt++;\n }\n }\n \n else if (format === \"rgb444\") {\n for (let i = 0; i < size; ++i) {\n const color = data[i];\n const b = (color >> 16) & 0xff;\n const g = (color >> 8) & 0xff;\n const r = color & 0xff;\n\n // reduce to rgb444 12-bit uint\n const index = rgb888_to_rgb444(r, g, b);\n let bin = index in bins ? bins[index] : (bins[index] = create_bin());\n bin.rc += r;\n bin.gc += g;\n bin.bc += b;\n bin.cnt++;\n }\n } else {\n for (let i = 0; i < size; ++i) {\n const color = data[i];\n const b = (color >> 16) & 0xff;\n const g = (color >> 8) & 0xff;\n const r = color & 0xff;\n\n // reduce to rgb565 16-bit uint\n const index = rgb888_to_rgb565(r, g, b);\n let bin = index in bins ? bins[index] : (bins[index] = create_bin());\n bin.rc += r;\n bin.gc += g;\n bin.bc += b;\n bin.cnt++;\n }\n }\n return bins;\n}\n\nexport default function quantize(rgba, maxColors, opts = {}) {\n const {\n format = \"rgb565\",\n clearAlpha = true,\n clearAlphaColor = 0x00,\n clearAlphaThreshold = 0,\n oneBitAlpha = false,\n } = opts;\n\n if (!rgba || !rgba.buffer) {\n throw new Error('quantize() expected RGBA Uint8Array data');\n }\n if (!(rgba instanceof Uint8Array) && !(rgba instanceof Uint8ClampedArray)) {\n throw new Error('quantize() expected RGBA Uint8Array data');\n }\n \n const data = new Uint32Array(rgba.buffer);\n\n let useSqrt = opts.useSqrt !== false;\n\n // format can be:\n // rgb565 (default)\n // rgb444\n // rgba4444\n\n const hasAlpha = format === \"rgba4444\";\n const bins = create_bin_list(data, format);\n const bincount = bins.length;\n const bincountMinusOne = bincount - 1;\n const heap = new Uint32Array(bincount + 1);\n\n /* Cluster nonempty bins at one end of array */\n var maxbins = 0;\n for (var i = 0; i < bincount; ++i) {\n const bin = bins[i];\n if (bin != null) {\n var d = 1.0 / bin.cnt;\n if (hasAlpha) bin.ac *= d;\n bin.rc *= d;\n bin.gc *= d;\n bin.bc *= d;\n bins[maxbins++] = bin;\n }\n }\n\n if (sqr(maxColors) / maxbins < 0.022) {\n useSqrt = false;\n }\n\n var i = 0;\n for (; i < maxbins - 1; ++i) {\n bins[i].fw = i + 1;\n bins[i + 1].bk = i;\n if (useSqrt) bins[i].cnt = Math.sqrt(bins[i].cnt);\n }\n if (useSqrt) bins[i].cnt = Math.sqrt(bins[i].cnt);\n\n var h, l, l2;\n /* Initialize nearest neighbors and build heap of them */\n for (i = 0; i < maxbins; ++i) {\n find_nn(bins, i, false);\n /* Push slot on heap */\n var err = bins[i].err;\n for (l = ++heap[0]; l > 1; l = l2) {\n l2 = l >> 1;\n if (bins[(h = heap[l2])].err <= err) break;\n heap[l] = h;\n }\n heap[l] = i;\n }\n\n /* Merge bins which increase error the least */\n var extbins = maxbins - maxColors;\n for (i = 0; i < extbins; ) {\n var tb;\n /* Use heap to find which bins to merge */\n for (;;) {\n var b1 = heap[1];\n tb = bins[b1]; /* One with least error */\n /* Is stored error up to date? */\n if (tb.tm >= tb.mtm && bins[tb.nn].mtm <= tb.tm) break;\n if (tb.mtm == bincountMinusOne)\n /* Deleted node */ b1 = heap[1] = heap[heap[0]--];\n /* Too old error value */ else {\n find_nn(bins, b1, false);\n tb.tm = i;\n }\n /* Push slot down */\n var err = bins[b1].err;\n for (l = 1; (l2 = l + l) <= heap[0]; l = l2) {\n if (l2 < heap[0] && bins[heap[l2]].err > bins[heap[l2 + 1]].err) l2++;\n if (err <= bins[(h = heap[l2])].err) break;\n heap[l] = h;\n }\n heap[l] = b1;\n }\n\n /* Do a merge */\n var nb = bins[tb.nn];\n var n1 = tb.cnt;\n var n2 = nb.cnt;\n var d = 1.0 / (n1 + n2);\n if (hasAlpha) tb.ac = d * (n1 * tb.ac + n2 * nb.ac);\n tb.rc = d * (n1 * tb.rc + n2 * nb.rc);\n tb.gc = d * (n1 * tb.gc + n2 * nb.gc);\n tb.bc = d * (n1 * tb.bc + n2 * nb.bc);\n tb.cnt += nb.cnt;\n tb.mtm = ++i;\n\n /* Unchain deleted bin */\n bins[nb.bk].fw = nb.fw;\n bins[nb.fw].bk = nb.bk;\n nb.mtm = bincountMinusOne;\n }\n\n // let palette = new Uint32Array(maxColors);\n let palette = [];\n\n /* Fill palette */\n var k = 0;\n for (i = 0; ; ++k) {\n let r = clamp(Math.round(bins[i].rc), 0, 0xff);\n let g = clamp(Math.round(bins[i].gc), 0, 0xff);\n let b = clamp(Math.round(bins[i].bc), 0, 0xff);\n\n let a = 0xff;\n if (hasAlpha) {\n a = clamp(Math.round(bins[i].ac), 0, 0xff);\n if (oneBitAlpha) {\n const threshold = typeof oneBitAlpha === \"number\" ? oneBitAlpha : 127;\n a = a <= threshold ? 0x00 : 0xff;\n }\n if (clearAlpha && a <= clearAlphaThreshold) {\n r = g = b = clearAlphaColor;\n a = 0x00;\n }\n }\n\n const color = hasAlpha ? [r, g, b, a] : [r, g, b];\n const exists = existsInPalette(palette, color);\n if (!exists) palette.push(color);\n if ((i = bins[i].fw) == 0) break;\n }\n\n return palette;\n}\n\nfunction existsInPalette(palette, color) {\n for (let i = 0; i < palette.length; i++) {\n const p = palette[i];\n let matchesRGB =\n p[0] === color[0] && p[1] === color[1] && p[2] === color[2];\n let matchesAlpha =\n p.length >= 4 && color.length >= 4 ? p[3] === color[3] : true;\n if (matchesRGB && matchesAlpha) return true;\n }\n return false;\n}\n\n// TODO: Further 'clean' palette by merging nearly-identical colors?\n","function rgb2y(r, g, b) {\n return r * 0.29889531 + g * 0.58662247 + b * 0.11448223;\n}\nfunction rgb2i(r, g, b) {\n return r * 0.59597799 - g * 0.2741761 - b * 0.32180189;\n}\nfunction rgb2q(r, g, b) {\n return r * 0.21147017 - g * 0.52261711 + b * 0.31114694;\n}\n\nexport function colorDifferenceYIQSquared(yiqA, yiqB) {\n const y = yiqA[0] - yiqB[0];\n const i = yiqA[1] - yiqB[1];\n const q = yiqA[2] - yiqB[2];\n const a = alpha(yiqA) - alpha(yiqB);\n return y * y * 0.5053 + i * i * 0.299 + q * q * 0.1957 + a * a;\n}\n\nfunction alpha(array) {\n return array[3] != null ? array[3] : 0xff;\n}\n\nexport function colorDifferenceYIQ(yiqA, yiqB) {\n return Math.sqrt(colorDifferenceYIQSquared(yiqA, yiqB));\n}\n\nexport function colorDifferenceRGBToYIQSquared(rgb1, rgb2) {\n const [r1, g1, b1] = rgb1;\n const [r2, g2, b2] = rgb2;\n const y = rgb2y(r1, g1, b1) - rgb2y(r2, g2, b2),\n i = rgb2i(r1, g1, b1) - rgb2i(r2, g2, b2),\n q = rgb2q(r1, g1, b1) - rgb2q(r2, g2, b2);\n const a = alpha(rgb1) - alpha(rgb2);\n return y * y * 0.5053 + i * i * 0.299 + q * q * 0.1957 + a * a;\n}\n\nexport function colorDifferenceRGBToYIQ(rgb1, rgb2) {\n return Math.sqrt(colorDifferenceRGBToYIQSquared(rgb1, rgb2));\n}\n\nexport function euclideanDistanceSquared(a, b) {\n var sum = 0;\n var n;\n for (n = 0; n < a.length; n++) {\n const dx = a[n] - b[n];\n sum += dx * dx;\n }\n return sum;\n}\n\nexport function euclideanDistance(a, b) {\n return Math.sqrt(euclideanDistanceSquared(a, b));\n}\n","import {\n rgb888_to_rgb444,\n rgb888_to_rgb565,\n rgba8888_to_rgba4444,\n} from \"./rgb-packing.js\";\n\nimport { euclideanDistanceSquared } from \"./color.js\";\n\nfunction roundStep(byte, step) {\n return step > 1 ? Math.round(byte / step) * step : byte;\n}\n\nexport function prequantize(\n rgba,\n { roundRGB = 5, roundAlpha = 10, oneBitAlpha = null } = {}\n) {\n const data = new Uint32Array(rgba.buffer);\n for (let i = 0; i < data.length; i++) {\n const color = data[i];\n let a = (color >> 24) & 0xff;\n let b = (color >> 16) & 0xff;\n let g = (color >> 8) & 0xff;\n let r = color & 0xff;\n\n a = roundStep(a, roundAlpha);\n if (oneBitAlpha) {\n const threshold = typeof oneBitAlpha === \"number\" ? oneBitAlpha : 127;\n a = a <= threshold ? 0x00 : 0xff;\n }\n r = roundStep(r, roundRGB);\n g = roundStep(g, roundRGB);\n b = roundStep(b, roundRGB);\n\n data[i] = (a << 24) | (b << 16) | (g << 8) | (r << 0);\n }\n}\n\nexport function applyPalette(rgba, palette, format = \"rgb565\") {\n if (!rgba || !rgba.buffer) {\n throw new Error('quantize() expected RGBA Uint8Array data');\n }\n if (!(rgba instanceof Uint8Array) && !(rgba instanceof Uint8ClampedArray)) {\n throw new Error('quantize() expected RGBA Uint8Array data');\n }\n if (palette.length > 256) {\n throw new Error('applyPalette() only works with 256 colors or less');\n }\n\n const data = new Uint32Array(rgba.buffer);\n const length = data.length;\n const bincount = format === \"rgb444\" ? 4096 : 65536;\n const index = new Uint8Array(length);\n const cache = new Array(bincount);\n const hasAlpha = format === \"rgba4444\";\n\n // Some duplicate code below due to very hot code path\n // Introducing branching/conditions shows some significant impact\n if (format === \"rgba4444\") {\n for (let i = 0; i < length; i++) {\n const color = data[i];\n const a = (color >> 24) & 0xff;\n const b = (color >> 16) & 0xff;\n const g = (color >> 8) & 0xff;\n const r = color & 0xff;\n const key = rgba8888_to_rgba4444(r, g, b, a);\n const idx = key in cache ? cache[key] : (cache[key] = nearestColorIndexRGBA(r, g, b, a, palette));\n index[i] = idx;\n }\n } else {\n const rgb888_to_key = format === \"rgb444\" ? rgb888_to_rgb444 : rgb888_to_rgb565;\n for (let i = 0; i < length; i++) {\n const color = data[i];\n const b = (color >> 16) & 0xff;\n const g = (color >> 8) & 0xff;\n const r = color & 0xff;\n const key = rgb888_to_key(r, g, b);\n const idx = key in cache ? cache[key] : (cache[key] = nearestColorIndexRGB(r, g, b, palette));\n index[i] = idx;\n }\n }\n\n return index;\n}\n\nfunction nearestColorIndexRGBA(r, g, b, a, palette) {\n let k = 0;\n let mindist = 1e100;\n for (let i = 0; i < palette.length; i++) {\n const px2 = palette[i];\n const a2 = px2[3];\n let curdist = sqr(a2 - a);\n if (curdist > mindist) continue;\n const r2 = px2[0];\n curdist += sqr(r2 - r);\n if (curdist > mindist) continue;\n const g2 = px2[1];\n curdist += sqr(g2 - g);\n if (curdist > mindist) continue;\n const b2 = px2[2];\n curdist += sqr(b2 - b);\n if (curdist > mindist) continue;\n mindist = curdist;\n k = i;\n }\n return k;\n}\n\nfunction nearestColorIndexRGB(r, g, b, palette) {\n let k = 0;\n let mindist = 1e100;\n for (let i = 0; i < palette.length; i++) {\n const px2 = palette[i];\n const r2 = px2[0];\n let curdist = sqr(r2 - r);\n if (curdist > mindist) continue;\n const g2 = px2[1];\n curdist += sqr(g2 - g);\n if (curdist > mindist) continue;\n const b2 = px2[2];\n curdist += sqr(b2 - b);\n if (curdist > mindist) continue;\n mindist = curdist;\n k = i;\n }\n return k;\n}\n\nexport function snapColorsToPalette(palette, knownColors, threshold = 5) {\n if (!palette.length || !knownColors.length) return;\n\n const paletteRGB = palette.map((p) => p.slice(0, 3));\n const thresholdSq = threshold * threshold;\n const dim = palette[0].length;\n for (let i = 0; i < knownColors.length; i++) {\n let color = knownColors[i];\n if (color.length < dim) {\n // palette is RGBA, known is RGB\n color = [color[0], color[1], color[2], 0xff];\n } else if (color.length > dim) {\n // palette is RGB, known is RGBA\n color = color.slice(0, 3);\n } else {\n // make sure we always copy known colors\n color = color.slice();\n }\n const r = nearestColorIndexWithDistance(\n paletteRGB,\n color.slice(0, 3),\n euclideanDistanceSquared\n );\n const idx = r[0];\n const distanceSq = r[1];\n if (distanceSq > 0 && distanceSq <= thresholdSq) {\n palette[idx] = color;\n }\n }\n}\n\nfunction sqr(a) {\n return a * a;\n}\n\nexport function nearestColorIndex(\n colors,\n pixel,\n distanceFn = euclideanDistanceSquared\n) {\n let minDist = Infinity;\n let minDistIndex = -1;\n for (let j = 0; j < colors.length; j++) {\n const paletteColor = colors[j];\n const dist = distanceFn(pixel, paletteColor);\n if (dist < minDist) {\n minDist = dist;\n minDistIndex = j;\n }\n }\n return minDistIndex;\n}\n\nexport function nearestColorIndexWithDistance(\n colors,\n pixel,\n distanceFn = euclideanDistanceSquared\n) {\n let minDist = Infinity;\n let minDistIndex = -1;\n for (let j = 0; j < colors.length; j++) {\n const paletteColor = colors[j];\n const dist = distanceFn(pixel, paletteColor);\n if (dist < minDist) {\n minDist = dist;\n minDistIndex = j;\n }\n }\n return [minDistIndex, minDist];\n}\n\nexport function nearestColor(\n colors,\n pixel,\n distanceFn = euclideanDistanceSquared\n) {\n return colors[nearestColorIndex(colors, pixel, distanceFn)];\n}\n","import constants from \"./constants.js\";\nimport lzwEncode from \"./lzwEncode.js\";\nimport createStream from \"./stream.js\";\nimport quantize from \"./pnnquant2.js\";\n\nimport {\n prequantize,\n applyPalette,\n nearestColorIndex,\n nearestColor,\n nearestColorIndexWithDistance,\n snapColorsToPalette,\n} from \"./palettize.js\";\n\nfunction GIFEncoder(opt = {}) {\n const { initialCapacity = 4096, auto = true } = opt;\n\n // Stream all encoded data into this buffer\n const stream = createStream(initialCapacity);\n\n // Shared array data across all frames\n const HSIZE = 5003; // 80% occupancy\n const accum = new Uint8Array(256);\n const htab = new Int32Array(HSIZE);\n const codetab = new Int32Array(HSIZE);\n\n let hasInit = false;\n\n return {\n reset() {\n stream.reset();\n hasInit = false;\n },\n finish() {\n stream.writeByte(constants.trailer);\n },\n bytes() {\n return stream.bytes();\n },\n bytesView() {\n return stream.bytesView();\n },\n get buffer() {\n return stream.buffer;\n },\n get stream() {\n return stream;\n },\n writeHeader,\n writeFrame(index, width, height, opts = {}) {\n const {\n transparent = false,\n transparentIndex = 0x00,\n delay = 0,\n palette = null,\n repeat = 0, // -1=once, 0=forever, >0=count\n colorDepth = 8,\n dispose = -1,\n } = opts;\n\n let first = false;\n if (auto) {\n // In 'auto' mode, the first time we write a frame\n // we will write LSD/GCT/EXT\n if (!hasInit) {\n // have not yet init, we can consider this our first frame\n first = true;\n // in 'auto' mode, we also encode a header on first frame\n // this is different than manual mode where you must encode\n // header yoursef (or perhaps not write header altogether)\n writeHeader();\n hasInit = true;\n }\n } else {\n // in manual mode, the first frame is determined by the options only\n first = Boolean(opts.first);\n }\n\n width = Math.max(0, Math.floor(width));\n height = Math.max(0, Math.floor(height));\n\n // Write pre-frame details such as repeat count and global palette\n if (first) {\n if (!palette) {\n throw new Error(\"First frame must include a { palette } option\");\n }\n encodeLogicalScreenDescriptor(\n stream,\n width,\n height,\n palette,\n colorDepth\n );\n encodeColorTable(stream, palette);\n if (repeat >= 0) {\n encodeNetscapeExt(stream, repeat);\n }\n }\n\n const delayTime = Math.round(delay / 10);\n encodeGraphicControlExt(\n stream,\n dispose,\n delayTime,\n transparent,\n transparentIndex\n );\n\n const useLocalColorTable = Boolean(palette) && !first;\n encodeImageDescriptor(\n stream,\n width,\n height,\n useLocalColorTable ? palette : null\n );\n if (useLocalColorTable) encodeColorTable(stream, palette);\n encodePixels(\n stream,\n index,\n width,\n height,\n colorDepth,\n accum,\n htab,\n codetab\n );\n },\n };\n\n function writeHeader() {\n writeUTFBytes(stream, \"GIF89a\");\n }\n}\n\nfunction encodeGraphicControlExt(\n stream,\n dispose,\n delay,\n transparent,\n transparentIndex\n) {\n stream.writeByte(0x21); // extension introducer\n stream.writeByte(0xf9); // GCE label\n stream.writeByte(4); // data block size\n\n if (transparentIndex < 0) {\n transparentIndex = 0x00;\n transparent = false;\n }\n\n var transp, disp;\n if (!transparent) {\n transp = 0;\n disp = 0; // dispose = no action\n } else {\n transp = 1;\n disp = 2; // force clear if using transparent color\n }\n\n if (dispose >= 0) {\n disp = dispose & 7; // user override\n }\n\n disp <<= 2;\n\n const userInput = 0;\n\n // packed fields\n stream.writeByte(\n 0 | // 1:3 reserved\n disp | // 4:6 disposal\n userInput | // 7 user input - 0 = none\n transp // 8 transparency flag\n );\n\n writeUInt16(stream, delay); // delay x 1/100 sec\n stream.writeByte(transparentIndex || 0x00); // transparent color index\n stream.writeByte(0); // block terminator\n}\n\nfunction encodeLogicalScreenDescriptor(\n stream,\n width,\n height,\n palette,\n colorDepth = 8\n) {\n const globalColorTableFlag = 1;\n const sortFlag = 0;\n const globalColorTableSize = colorTableSize(palette.length) - 1;\n const fields =\n (globalColorTableFlag << 7) |\n ((colorDepth - 1) << 4) |\n (sortFlag << 3) |\n globalColorTableSize;\n const backgroundColorIndex = 0;\n const pixelAspectRatio = 0;\n writeUInt16(stream, width);\n writeUInt16(stream, height);\n stream.writeBytes([fields, backgroundColorIndex, pixelAspectRatio]);\n}\n\nfunction encodeNetscapeExt(stream, repeat) {\n stream.writeByte(0x21); // extension introducer\n stream.writeByte(0xff); // app extension label\n stream.writeByte(11); // block size\n writeUTFBytes(stream, \"NETSCAPE2.0\"); // app id + auth code\n stream.writeByte(3); // sub-block size\n stream.writeByte(1); // loop sub-block id\n writeUInt16(stream, repeat); // loop count (extra iterations, 0=repeat forever)\n stream.writeByte(0); // block terminator\n}\n\nfunction encodeColorTable(stream, palette) {\n const colorTableLength = 1 << colorTableSize(palette.length);\n for (let i = 0; i < colorTableLength; i++) {\n let color = [0, 0, 0];\n if (i < palette.length) {\n color = palette[i];\n }\n stream.writeByte(color[0]);\n stream.writeByte(color[1]);\n stream.writeByte(color[2]);\n }\n}\n\nfunction encodeImageDescriptor(stream, width, height, localPalette) {\n stream.writeByte(0x2c); // image separator\n\n writeUInt16(stream, 0); // x position\n writeUInt16(stream, 0); // y position\n writeUInt16(stream, width); // image size\n writeUInt16(stream, height);\n\n if (localPalette) {\n const interlace = 0;\n const sorted = 0;\n const palSize = colorTableSize(localPalette.length) - 1;\n // local palette\n stream.writeByte(\n 0x80 | // 1 local color table 1=yes\n interlace | // 2 interlace - 0=no\n sorted | // 3 sorted - 0=no\n 0 | // 4-5 reserved\n palSize // 6-8 size of color table\n );\n } else {\n // global palette\n stream.writeByte(0);\n }\n}\n\nfunction encodePixels(\n stream,\n index,\n width,\n height,\n colorDepth = 8,\n accum,\n htab,\n codetab\n) {\n lzwEncode(width, height, index, colorDepth, stream, accum, htab, codetab);\n}\n\n// Utilities\n\nfunction writeUInt16(stream, short) {\n stream.writeByte(short & 0xff);\n stream.writeByte((short >> 8) & 0xff);\n}\n\nfunction writeUTFBytes(stream, text) {\n for (var i = 0; i < text.length; i++) {\n stream.writeByte(text.charCodeAt(i));\n }\n}\n\nfunction colorTableSize(length) {\n return Math.max(Math.ceil(Math.log2(length)), 1);\n}\n\nexport {\n GIFEncoder,\n quantize,\n prequantize,\n applyPalette,\n nearestColorIndex,\n nearestColor,\n nearestColorIndexWithDistance,\n snapColorsToPalette,\n};\n\nexport default GIFEncoder;\n","import { inflateSync } from \"node:zlib\";\n\n/**\n * A PNG reader, in about sixty lines, because the alternative was a dependency.\n *\n * The GIF encoder needs RGBA pixels and Playwright hands back PNG bytes, so\n * something has to decode them. `pngjs` is CJS and reaches for `util` through a\n * `require`, which an ESM bundle answers with \"Dynamic require of util is not\n * supported\" on its first frame; making it a real dependency would put the first\n * runtime dependency on a design-system package whose whole manifest premise is\n * that it has none. `zlib` is a Node builtin and the rest is arithmetic.\n *\n * Deliberately narrow: 8-bit, non-interlaced, colour type 2 (RGB) or 6 (RGBA),\n * which is what every engine's screenshot is. Anything else throws by name\n * rather than being decoded wrongly into a plausible picture.\n */\n\nexport interface DecodedPng {\n width: number;\n height: number;\n /** RGBA, four bytes per pixel, row-major. */\n data: Uint8Array;\n}\n\nconst SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];\n\n/**\n * Width and height alone, without inflating a single `IDAT` byte.\n *\n * `IHDR` is always the first chunk after the signature, at a fixed offset, so\n * this is four field reads rather than a decode. For a caller that only wants\n * to know a picture's shape (an aspect-ratio check on a fresh screenshot), that\n * is the whole job: `decodePng` earns its cost by handing back pixels, and\n * nothing here needs any.\n */\nexport function pngSize(bytes: Buffer): { width: number; height: number } {\n for (const [i, expected] of SIGNATURE.entries()) {\n if (bytes[i] !== expected) throw new Error(\"pngSize: not a PNG\");\n }\n return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20) };\n}\n\nexport function decodePng(bytes: Buffer): DecodedPng {\n for (const [i, expected] of SIGNATURE.entries()) {\n if (bytes[i] !== expected) throw new Error(\"decodePng: not a PNG\");\n }\n let offset = 8;\n let width = 0;\n let height = 0;\n let channels = 0;\n const idat: Buffer[] = [];\n while (offset < bytes.length) {\n const length = bytes.readUInt32BE(offset);\n const type = bytes.toString(\"ascii\", offset + 4, offset + 8);\n const body = bytes.subarray(offset + 8, offset + 8 + length);\n offset += 12 + length;\n if (type === \"IHDR\") {\n width = body.readUInt32BE(0);\n height = body.readUInt32BE(4);\n const depth = body[8];\n const colourType = body[9];\n const interlace = body[12];\n if (\n depth !== 8 ||\n interlace !== 0 ||\n (colourType !== 6 && colourType !== 2)\n ) {\n throw new Error(\n `decodePng: only 8-bit non-interlaced RGB/RGBA is supported, got ` +\n `depth ${depth}, colour type ${colourType}, interlace ${interlace}`,\n );\n }\n channels = colourType === 6 ? 4 : 3;\n }\n if (type === \"IDAT\") {\n idat.push(body);\n }\n if (type === \"IEND\") {\n break;\n }\n }\n if (width === 0 || height === 0 || channels === 0) {\n throw new Error(\"decodePng: no IHDR\");\n }\n const raw = inflateSync(Buffer.concat(idat));\n const stride = width * channels;\n const out = new Uint8Array(width * height * 4);\n const line = new Uint8Array(stride);\n const previous = new Uint8Array(stride);\n let cursor = 0;\n for (let y = 0; y < height; y++) {\n const filter = raw[cursor++];\n for (let x = 0; x < stride; x++) {\n const value = raw[cursor + x];\n const left = x >= channels ? line[x - channels] : 0;\n const up = previous[x];\n const upLeft = x >= channels ? previous[x - channels] : 0;\n line[x] = unfilter(filter, value, left, up, upLeft);\n }\n cursor += stride;\n for (let x = 0; x < width; x++) {\n const src = x * channels;\n const dst = (y * width + x) * 4;\n out[dst] = line[src];\n out[dst + 1] = line[src + 1];\n out[dst + 2] = line[src + 2];\n out[dst + 3] = channels === 4 ? line[src + 3] : 255;\n }\n previous.set(line);\n }\n return { width, height, data: out };\n}\n\n/** The five PNG line filters (RFC 2083 section 6). */\nfunction unfilter(\n filter: number,\n value: number,\n left: number,\n up: number,\n upLeft: number,\n): number {\n switch (filter) {\n case 0:\n return value;\n case 1:\n return (value + left) & 0xff;\n case 2:\n return (value + up) & 0xff;\n case 3:\n return (value + ((left + up) >> 1)) & 0xff;\n case 4:\n return (value + paeth(left, up, upLeft)) & 0xff;\n default:\n throw new Error(`decodePng: unknown line filter ${filter}`);\n }\n}\n\nfunction paeth(a: number, b: number, c: number): number {\n const p = a + b - c;\n const pa = Math.abs(p - a);\n const pb = Math.abs(p - b);\n const pc = Math.abs(p - c);\n if (pa <= pb && pa <= pc) return a;\n return pb <= pc ? b : c;\n}\n","import { applyPalette, GIFEncoder, quantize } from \"gifenc\";\nimport { decodePng } from \"./png\";\n\n/**\n * Stitches PNG frames into a GIF at `fps`, in plain JavaScript with no system\n * tools needed. With `pingPong` the frames play forward and then back. Throws\n * on an empty list.\n *\n * A GIF, because an Uplink's README is read on GitHub and SpaceDock, where a\n * GIF embeds and a video does not. `--frames` keeps the numbered PNGs for\n * anything else.\n *\n * @category Rendering scenes\n */\nexport function encodeGif(\n frames: readonly Buffer[],\n opts: { fps: number; pingPong: boolean },\n): Buffer {\n if (frames.length === 0) {\n throw new Error(\"encodeGif: no frames\");\n }\n const ordered = opts.pingPong\n ? [...frames, ...[...frames].slice(1, -1).reverse()]\n : frames;\n const delay = Math.max(2, Math.round(1000 / opts.fps));\n const encoder = GIFEncoder();\n let size: { width: number; height: number } | undefined;\n for (const frame of ordered) {\n const png = decodePng(frame);\n if (!size) size = { width: png.width, height: png.height };\n if (png.width !== size.width || png.height !== size.height) {\n throw new Error(\n `encodeGif: frame sizes differ (${png.width}x${png.height} after ` +\n `${size.width}x${size.height}). Every frame of one scene has to be ` +\n \"the same box, or the animation is a slideshow of crops.\",\n );\n }\n const palette = quantize(png.data, 256);\n const index = applyPalette(png.data, palette);\n encoder.writeFrame(index, png.width, png.height, { palette, delay });\n }\n encoder.finish();\n return Buffer.from(encoder.bytes());\n}\n","import { existsSync } from \"node:fs\";\nimport { mkdtemp, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { build, type Plugin } from \"esbuild\";\nimport {\n type FontFace,\n jetbrainsMonoFace,\n themeTokensCss,\n type UplinkPackage,\n} from \"./context\";\n\nconst require = createRequire(import.meta.url);\nconst HERE = dirname(fileURLToPath(import.meta.url));\n\n/**\n * The page a scene is rendered in, built once per run.\n *\n * The browser entry is GENERATED rather than owned by each Uplink, and that is\n * load-bearing rather than tidy. The sdk's author surface is host-injected shims,\n * so a widget's module-load `registerComponent` throws against an uninstalled\n * host; static ES imports are hoisted above every statement, so an entry that\n * installs the host and then side-effect-imports the client is correct only by\n * import ORDER, which an import sorter is free to change. Generating the entry\n * moves that footgun out of every author's file into one place with no lines for\n * a sorter to move.\n */\n\n/** The one `<style id=\"probe-theme\">` slot and the one script slot. */\nconst PAGE_TEMPLATE = `<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <title>Uplink render probe</title>\n <style id=\"probe-theme\"></style>\n <style>\n html, body {\n margin: 0;\n padding: 0;\n background: var(--color-surface-app);\n color: var(--color-text-primary);\n font-family: var(--font-family-mono);\n }\n /* The app's document size (global.css), by the same token, so inherited text is not drawn at the browser's 16px. */\n body {\n font-size: var(--font-size-compact);\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100vh;\n }\n </style>\n </head>\n <body>\n <div id=\"root\"></div>\n <script id=\"probe-entry\" type=\"module\"></script>\n </body>\n</html>\n`;\n\n/**\n * A widget's own bare `import \"some.css\"` has to land in the page as a `<style>`\n * tag. `loader: \"text\"` alone makes an inert string module that esbuild then\n * tree-shakes away whenever the importing package declares `sideEffects: false`,\n * producing an ignored-bare-import warning and a fully unstyled render. Resolution\n * goes through Node's resolver rather than `pluginBuild.resolve()`, which\n * re-enters this same `onResolve` filter and hung the esbuild service.\n */\nconst cssSideEffectPlugin: Plugin = {\n name: \"css-side-effect\",\n setup(pluginBuild) {\n pluginBuild.onResolve({ filter: /\\.css$/ }, (args) => ({\n path: require.resolve(args.path, { paths: [args.resolveDir] }),\n sideEffects: true,\n }));\n pluginBuild.onLoad({ filter: /\\.css$/ }, async (args) => {\n const css = await readFile(args.path, \"utf8\");\n return {\n loader: \"js\",\n contents:\n 'const __style = document.createElement(\"style\");\\n' +\n `__style.textContent = ${JSON.stringify(css)};\\n` +\n \"document.head.appendChild(__style);\",\n };\n });\n },\n};\n\nfunction posix(path: string): string {\n return path.split(\"\\\\\").join(\"/\");\n}\n\n/**\n * One copy of the kit in the page, pinned to the file a consumer would get.\n *\n * `render-probe` reaches the kit by its own package NAME so the built file stays\n * a consumer of it, and this package's `tsconfig.json` maps that self-reference\n * back to `src/` for typechecking. esbuild honours the tsconfig nearest the\n * importing file, so bundling `dist/render-probe.js` pulled in the SOURCE kit\n * while every other importer got `dist/`: two augment registries, `registerAugment`\n * writing to a Map `<AugmentSlot>` never reads, which is the exact failure this\n * harness's header says having one probe was meant to prevent. It cost nothing\n * while an augment was only ever mounted in a stand-in host built from the same\n * copy; a scene naming a REAL host in another package is the first thing that\n * puts the two halves on opposite sides.\n *\n * Pinned to `dist` rather than `src` because that is what a third-party author\n * resolves, and a harness that renders something nobody else can run is not the\n * harness.\n *\n * ## The two halves resolve from DIFFERENT places, and that is the whole care\n *\n * This used to be one loop over three siblings, correct only because all three\n * shipped from `@ksp-gonogo/ui-kit`. They no longer do:\n *\n * - `render-probe` is a sibling of THIS file, in `@ksp-gonogo/uplink-tools`\n * - the kit and its `/testing` subpath are a different package entirely, and\n * must be the copy the AUTHOR installed, for the same reason `react` is\n *\n * Left as `join(HERE, ...)`, the kit's two entries would simply not be found,\n * `existsSync` would skip them, and the page would silently carry two kits.\n * That is the failure the paragraph above is about, and it reports nothing.\n * `page.test.ts` fails if either pin goes missing.\n */\nfunction oneKitPerPage(dir: string): Record<string, string> {\n const alias: Record<string, string> = {};\n\n // Ours: a sibling of this file, whether that dist sits in this repo or in a third party's `node_modules`.\n const probe = join(HERE, \"render-probe.js\");\n // Absent means this is running from source, where the caller's own resolution is the only one in play and is already a single copy.\n if (existsSync(probe)) {\n alias[\"@ksp-gonogo/uplink-tools/render-probe\"] = probe;\n }\n\n // Theirs. `require.resolve` cannot answer this: the kit's `exports` declares\n // only the `import` condition, and no `./package.json` at all, so a CJS\n // resolver refuses outright and the throw would be swallowed into \"no pin\".\n // Walking `node_modules` up from the Uplink is what a bundler does and is the\n // one layout pnpm's symlink farm and npm's flat tree agree on.\n const kit = nearestPackageDir(dir, \"@ksp-gonogo/ui-kit\");\n if (kit) {\n for (const [specifier, file] of [\n [\"@ksp-gonogo/ui-kit\", \"dist/index.js\"],\n [\"@ksp-gonogo/ui-kit/testing\", \"dist/testing.js\"],\n [\"@ksp-gonogo/ui-kit/grid\", \"dist/gridUnits.js\"],\n ]) {\n const built = join(kit, file);\n if (existsSync(built)) alias[specifier] = built;\n }\n }\n return alias;\n}\n\n/** The nearest installed copy of `pkg`, walking up from `dir`. */\nfunction nearestPackageDir(dir: string, pkg: string): string | undefined {\n let at = resolve(dir);\n for (;;) {\n const candidate = join(at, \"node_modules\", pkg);\n if (existsSync(join(candidate, \"package.json\"))) return candidate;\n const up = dirname(at);\n if (up === at) return undefined;\n at = up;\n }\n}\n\n/**\n * Everything else that must be ONE copy in the page, pinned to the Uplink's\n * own resolution of it.\n *\n * The kit was not the only package that can arrive twice, only the first one\n * noticed. A `--with` module lives OUTSIDE the Uplink's package, so esbuild\n * resolves its imports from that module's own `node_modules` rather than the\n * Uplink's, and when the two are separate installs (a published Uplink beside a\n * checkout of this repo, which is the case `--with` exists for) every shared\n * package is bundled twice.\n *\n * React is the one that bites, and it bites in a way that reads as a bug in the\n * widget: an augment mounted inside a cross-package host threw \"Cannot read\n * properties of null (reading 'useEffect')\" from its first hook, because the\n * copy it called had no current dispatcher, the copy RENDERING it did. A\n * CONTRIBUTION scene survives this, which is why it went unnoticed: a\n * contribution is data its host draws, so no module from the Uplink ever\n * renders and no second React is ever entered. An augment supplies a COMPONENT,\n * and is the first thing to run hooks from both sides at once.\n *\n * styled-components duplicates into two theme contexts and two stylesheets, so\n * one side of the page renders unthemed.\n *\n * The sdk is deliberately NOT on this list. Its registries live on `globalThis`\n * and are already shared, which is what makes a cross-package host resolvable\n * at all; its `createContext` spine is not, so a second copy would read no\n * telemetry. Pinning it needs a resolver that honours an `import`-only exports\n * map, which the one here is not, and nothing has yet been seen to break for\n * want of it. It belongs on this list the day something does.\n *\n * Pinned to the UPLINK's copy, for the same reason the kit is pinned to `dist`:\n * an Uplink is what the render is of, so its resolution is the honest one. With\n * one install in play every entry resolves to what esbuild would have chosen\n * anyway and the whole map is inert.\n *\n * Each value is the package DIRECTORY, never the entry file, and both halves of\n * that were measured. esbuild substitutes an alias at the START of the import\n * path, so a file value turns `react-dom/test-utils` into\n * `.../react-dom/index.js/test-utils` and fails the build; and a file value\n * picked by a CJS resolver is the package's CJS half, which for\n * styled-components pulled in Node's `stream` and failed the build a second\n * way. A directory leaves the subpath and the export CONDITION to esbuild,\n * which is the half of resolution that was never the problem.\n */\nexport function oneCopyPerPage(dir: string): Record<string, string> {\n const from = createRequire(join(dir, \"noop.js\"));\n const alias: Record<string, string> = {};\n for (const specifier of [\"react\", \"react-dom\", \"styled-components\"]) {\n try {\n // Through `package.json` because that is the one path inside a package whose location IS the directory, whatever the entry points are called.\n alias[specifier] = dirname(from.resolve(`${specifier}/package.json`));\n } catch {\n // Not reachable from the Uplink, so there is no copy of it here to be the\n // one copy. Leave esbuild to it rather than guess.\n }\n }\n return alias;\n}\n\n/**\n * The generated browser entry. Awaited imports, never static ones.\n *\n * @category Rendering scenes\n */\nexport function generateEntry(\n pkg: UplinkPackage,\n extraModules: readonly string[] = [],\n): string {\n const lines = [\n \"// GENERATED by @ksp-gonogo/uplink-tools. Never committed, never edited.\",\n 'import { installRenderProbe } from \"@ksp-gonogo/uplink-tools/render-probe\";',\n \"\",\n \"// Before anything the Uplink registers: the host has to exist first, and a\",\n \"// static import of the client would be hoisted above this line.\",\n \"await installRenderProbe();\",\n ];\n for (const module of extraModules) {\n lines.push(\n \"// --with: registrations from outside this package, so a scene naming a\",\n \"// host widget has a real host to mount the augment inside.\",\n `await import(\"${posix(module)}\");`,\n );\n }\n lines.push(`await import(\"${posix(pkg.entry)}\");`);\n if (pkg.setup) {\n lines.push(\n \"// The author's own browser-side glue, when they wrote any.\",\n `await import(\"${posix(pkg.setup)}\");`,\n );\n }\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nexport interface ProbePage {\n file: string;\n font: FontFace;\n /** Removes the page from disk. Each page is tens of megabytes, so a caller disposes it once the tab has it. */\n dispose(): Promise<void>;\n}\n\n/**\n * Bundles the Uplink's client, its render setup and the render probe into one\n * page on disk, ready for a browser to open.\n *\n * @category Rendering scenes\n */\nexport async function buildProbePage(\n pkg: UplinkPackage,\n extraModules: readonly string[] = [],\n): Promise<ProbePage> {\n const result = await build({\n stdin: {\n contents: generateEntry(pkg, extraModules),\n resolveDir: pkg.dir,\n sourcefile: \"gonogo-render-entry.tsx\",\n loader: \"tsx\",\n },\n bundle: true,\n format: \"esm\",\n target: \"es2022\",\n platform: \"browser\",\n jsx: \"automatic\",\n write: false,\n sourcemap: \"inline\",\n define: { \"process.env.NODE_ENV\": '\"production\"' },\n plugins: [cssSideEffectPlugin],\n // The kit's pins go LAST: it resolves itself to its own sibling files, and an Uplink's copy of the kit is not the one running this bundle.\n alias: { ...oneCopyPerPage(pkg.dir), ...oneKitPerPage(pkg.dir) },\n absWorkingDir: pkg.dir,\n });\n const bundle = result.outputFiles[0].text;\n const font = jetbrainsMonoFace();\n // Function-form replacements throughout: a React bundle contains `$&`, and String.replace's string form reads it as a backreference and corrupts it.\n const escaped = bundle.replace(/<\\/script/gi, \"<\\\\/script\");\n const html = PAGE_TEMPLATE.replace(\n '<style id=\"probe-theme\"></style>',\n () => `<style id=\"probe-theme\">${font.css}\\n${themeTokensCss()}</style>`,\n ).replace(\n '<script id=\"probe-entry\" type=\"module\"></script>',\n () => `<script id=\"probe-entry\" type=\"module\">${escaped}</script>`,\n );\n const dir = await mkdtemp(join(tmpdir(), \"gonogo-uplink-probe-\"));\n const file = join(dir, \"probe.html\");\n await writeFile(file, html, \"utf8\");\n return {\n file,\n font,\n dispose: () => rm(dir, { recursive: true, force: true }),\n };\n}\n","import { createHash } from \"node:crypto\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\n/**\n * What a rendered asset IS, in a form two machines can compare.\n *\n * A docs page whose content is pictures had a gate that read the prose. `docs\n * --check` compared the README, the manifest and the asset FILENAMES, and said\n * nothing about whether the images were rendered from today's code: Vehicle\n * Assembly's page showed a layout the code had stopped producing for five\n * commits, green throughout, and a re-render then changed thirty assets nobody\n * had touched.\n *\n * The obvious answer, comparing the pixels, cannot work. Rasterisation is\n * per-engine and per-OS, which is why the visual baselines are generated on\n * Linux and never accepted from a developer's machine. The obvious fallback,\n * requiring the assets to be newer than any commit touching the kit, is\n * OS-independent and useless: it fires on every kit change whether the picture\n * moved or not, so it is red forever and gets muted.\n *\n * ## The split this file is built on\n *\n * A shape carries the things the CSS cascade **computes** and excludes the things\n * a glyph rasteriser **measures**.\n *\n * Admissible, because a browser derives them from the stylesheet and the DOM:\n * element order, the attributes below, text content, and the computed properties\n * in `ADMISSIBLE_PROPERTIES`. `padding: 8px` computes to `8px` everywhere;\n * `flex-shrink: 0` computes to `0`; `font-family` computes to the SPECIFIED\n * stack rather than the face that won, so it is a fact about the stylesheet.\n *\n * Inadmissible, because a browser derives them from glyph advances and hinting:\n * `getBoundingClientRect`, `offsetWidth`/`offsetHeight`, `scrollHeight`, any\n * length authored in `ch` or `em` (`min-width: 12ch` computed to `120.938px` in\n * chromium, `121px` in firefox and `117.1875px` in webkit), the px `line-height:\n * normal` resolves to, and the resolved track widths of a grid whose tracks are\n * content-sized.\n *\n * Measured against representative kit markup in all three engines on one\n * machine: every admissible field identical, every inadmissible one different.\n * Three layout engines and three font stacks is a harder test than one engine\n * across two operating systems, so agreement there is the evidence this rests\n * on. `scripts/uplink-shape-engines.mjs` is that measurement, kept runnable.\n *\n * Note `render-probe.tsx` already computes a `signature`, and this is a sibling\n * rather than a reuse: that one hashes `Math.round(box.width)` per element,\n * which is exactly the inadmissible half. It is right for its own job, comparing\n * a fed render against a starved one inside a single run, where both sides come\n * out of the same browser.\n *\n * ## The second consumer, which is the point\n *\n * A regeneration used to be committed back by a workflow that discarded every\n * MODIFIED asset, keeping only additions and deletions, so it had never once\n * healed a stale asset. The reasoning was sound and the rule was under-informed:\n * a motion scene's GIF re-encodes to different bytes from an unchanged tree, so\n * committing byte changes would push a churn commit on every run forever. It had\n * no way to tell that from a real one. The shape is that predicate. Shape\n * changed, it is stale; shape identical and bytes moved, it is not.\n */\n\n/**\n * Computed properties whose value is a fact about the stylesheet.\n *\n * Add to this list freely and only after `uplink-shape-engines.mjs` agrees\n * across all three engines. Anything whose value can be traced back to the width\n * of a glyph belongs in the doc comment above as an exclusion, not here.\n */\nexport const ADMISSIBLE_PROPERTIES = [\n \"color\",\n \"background-color\",\n \"background-image\",\n \"display\",\n \"position\",\n \"visibility\",\n \"opacity\",\n \"overflow\",\n \"overflow-x\",\n \"overflow-y\",\n \"z-index\",\n \"flex-direction\",\n \"flex-wrap\",\n \"flex-grow\",\n \"flex-shrink\",\n \"flex-basis\",\n \"align-items\",\n \"justify-content\",\n \"gap\",\n \"row-gap\",\n \"column-gap\",\n \"padding-top\",\n \"padding-right\",\n \"padding-bottom\",\n \"padding-left\",\n \"margin-top\",\n \"margin-right\",\n \"margin-bottom\",\n \"margin-left\",\n \"border-top-width\",\n \"border-right-width\",\n \"border-bottom-width\",\n \"border-left-width\",\n \"border-top-style\",\n \"border-top-color\",\n \"border-right-color\",\n \"border-bottom-color\",\n \"border-left-color\",\n \"border-top-left-radius\",\n \"border-top-right-radius\",\n \"font-family\",\n \"font-size\",\n \"font-weight\",\n \"font-style\",\n \"letter-spacing\",\n \"text-align\",\n \"text-transform\",\n \"text-overflow\",\n \"text-decoration-line\",\n \"white-space\",\n \"box-shadow\",\n] as const;\n\n/**\n * Attributes worth recording, as a regex source so it survives the trip into the\n * page.\n *\n * `style` and the SVG geometry attributes are here because that is where a\n * widget puts the numbers it means: a coverage bar's length is\n * `style=\"width: 42%\"` and a gauge needle is a `d` or a `transform`, and both are\n * silent in `textContent`. They are AUTHORED numbers, which is what makes them\n * admissible where a measured box is not.\n *\n * The `aria-`/`data-` prefixes are a SECOND alternative with its own anchor, and\n * that is not tidiness. Inside the first group they sat in front of a `$`, so\n * only an attribute named exactly `data-` matched and every real `data-x` and\n * `aria-x` was silently dropped: `data-section-full`, which is how a panel marks\n * a section spanning every column, and `aria-expanded`, which flips with the\n * layout decision the shape is trying to see. A unit test on `data-x=1` found it;\n * the cross-engine harness could not, because both engines dropped it equally and\n * agreed.\n *\n * `title` is here because a kit primitive reaches for it whenever text can be\n * truncated, so it appears and disappears with a layout decision: `RowName` and\n * `Panel`'s compacted title both carry the full string in one when the visible\n * text is an ellipsis. A change that alters what fits therefore shows up in this\n * attribute before it shows up anywhere else that is admissible.\n */\nexport const RECORDED_ATTRIBUTES =\n \"^(style|title|role|type|disabled|hidden|open|checked|d|points|cx|cy|r|x|y|x1|y1|x2|y2|rx|ry|transform|viewBox|fill|stroke|stroke-width|stroke-dasharray|offset|stop-color)$|^(aria|data)-\";\n\n/**\n * Committed beside the assets it describes.\n *\n * @category Shape records\n */\nexport const SHAPE_RECORD_FILE = \"render-shape.json\";\n\n/** One reading of the mounted widget. A still folds one, a film folds one per\n * frame. */\nexport interface ShapeCapture {\n text: string;\n elements: number;\n visibleText: string;\n}\n\n/**\n * What one asset's render reduces to.\n *\n * @category Shape records\n */\nexport interface AssetShape {\n /** sha256 of the shape text, first 16 hex. */\n hash: string;\n /** Elements walked. Named so a mismatch can say the tree grew. */\n elements: number;\n /** sha256 of the visible text alone, first 8 hex. Splits a content change\n * from a styling change without keeping the text itself. */\n text: string;\n}\n\n/**\n * The committed shape of every rendered asset, which the page check compares a\n * fresh render against.\n *\n * @category Shape records\n * @categoryDescription Shape records\n * The recorded shape of every rendered picture, which lets the page check tell\n * a page that no longer matches the code without comparing pixels.\n */\nexport interface ShapeRecord {\n /** Bumped when the admissible set changes, so an old record is not compared\n * against a new walk and reported as staleness that is really a schema\n * change. */\n version: number;\n /** The engine the shapes were taken in. A record from another engine is not\n * comparable and the check refuses rather than failing. */\n engine: string;\n assets: Record<string, AssetShape>;\n}\n\n/**\n * The version of the `ShapeRecord` format this package writes.\n *\n * @category Shape records\n */\nexport const SHAPE_RECORD_VERSION = 1;\n\n/**\n * Read the mounted widget, in the page.\n *\n * Passed to `tab.evaluate` and so must close over nothing: the whitelists arrive\n * as arguments. It returns the shape TEXT rather than a hash, because hashing in\n * the page would mean a mismatch could only ever say \"different\", and the caller\n * derives the counts a message can act on.\n *\n * `#root` itself is walked past rather than included. `growToFullContent` writes\n * a measured `height` into its inline style before the shot, so recording the\n * host's own attributes would carry a content measurement into the one place\n * that must not have one.\n */\nexport const readShapeText = (args: {\n properties: readonly string[];\n attributes: string;\n}): ShapeCapture => {\n const host = document.getElementById(\"root\");\n if (!host) throw new Error(\"render shape: no #root in the page\");\n const attrRe = new RegExp(args.attributes);\n // Engines serialise a wide-gamut colour to different last digits: the same\n // theme token came out `color(srgb 0.636078 ...)` in chromium and\n // `color(srgb 0.636079 ...)` in firefox, and that one digit alone made every\n // asset's shape differ between the two. It is the same colour, and no change\n // anybody could see in a picture lives in the fourth decimal place, so the\n // text is normalised to three before it is hashed.\n const round = (text: string): string =>\n text.replace(/\\d+\\.\\d{4,}/g, (n) => String(Math.round(+n * 1000) / 1000));\n /**\n * A React `useId` is a page-wide mount counter, and every scene renders in\n * one page, so the raw value depends on how many components mounted in the\n * scenes before this one. Each distinct id is renamed `:id<n>:` by first\n * appearance in this capture, which keeps a pair that references one id\n * linked. React 18 writes `:r<n>:` on the client and `:R<tree>H<n>:` when\n * hydrating, both in base 32.\n */\n const reactIds = new Map<string, string>();\n const canonicalIds = (text: string): string =>\n text.replace(/:(?:r[0-9a-v]+|R[0-9a-v]+(?:H[0-9a-v]+)?):/g, (id) => {\n const seen = reactIds.get(id);\n if (seen !== undefined) return seen;\n const named = `:id${reactIds.size}:`;\n reactIds.set(id, named);\n return named;\n });\n const lines: string[] = [];\n const texts: string[] = [];\n let elements = 0;\n\n const skip = new Set([\"STYLE\", \"SCRIPT\"]);\n const walk = (el: Element, path: string): void => {\n // xterm injects its own stylesheet into the widget, so a naive walk records a page of CSS selectors as text.\n if (\n skip.has(el.tagName) ||\n el.hasAttribute(\"data-unit-word\") ||\n el.hasAttribute(\"data-unit-currency\")\n ) {\n return;\n }\n elements++;\n const attrs = Array.from(el.attributes)\n .filter((a) => attrRe.test(a.name))\n .map((a) => `${a.name}=${a.value}`)\n .sort()\n .map(canonicalIds);\n const style = getComputedStyle(el);\n lines.push(\n round(\n `${path} ${el.tagName.toLowerCase()}` +\n (attrs.length > 0 ? ` [${attrs.join(\";\")}]` : \"\") +\n ` {${args.properties.map((p) => `${p}:${style.getPropertyValue(p)}`).join(\";\")}}`,\n ),\n );\n for (const node of Array.from(el.childNodes)) {\n if (node.nodeType !== 3) continue;\n const t = (node.textContent ?? \"\").replace(/\\s+/g, \" \").trim();\n if (t.length > 0) {\n lines.push(`${path} \"${t}\"`);\n texts.push(t);\n }\n }\n const kids = Array.from(el.children);\n for (let i = 0; i < kids.length; i++) {\n walk(kids[i] as Element, `${path}/${i}`);\n }\n };\n\n const roots = Array.from(host.children);\n for (let i = 0; i < roots.length; i++) {\n walk(roots[i] as Element, `${i}`);\n }\n return { text: lines.join(\"\\n\"), elements, visibleText: texts.join(\" \") };\n};\n\n/**\n * Stop the tree moving, so a computed style is a fact about the stylesheet\n * rather than a reading off a clock.\n *\n * The shape read was the ONE capture in a render taken while animations were\n * still running. The picture beside it is not: `shoot` passes playwright's\n * `animations: \"disabled\"`, which fast-forwards a finite animation to its end\n * before the shutter. Nothing did the same for the walk, and\n * `getComputedStyle` on an element mid-transition returns the INTERPOLATED\n * value, which depends on how many milliseconds elapsed between the act that\n * started it and the read.\n *\n * That is not theoretical. `_scene.before` presses a control with\n * `locator.click()`, which parks the pointer on it, and the kit's `Button`\n * transitions `color` and `border-color` over 120ms on `:hover`. Seventeen of\n * one Uplink's 105 assets hashed differently on two runs of identical source,\n * every one of them a button the scene had pressed, every difference a few\n * units of grey: `rgb(150, 150, 150)` against `rgb(153, 153, 153)`, the same\n * colour caught at two points on the same ramp. A hash that moves on unchanged\n * source cannot tell a stale page from noise, which is the whole job.\n *\n * Finite animations are finished rather than cancelled, to match what the\n * screenshot does: the settled value is the one the picture shows. An animation\n * with no end cannot be finished and is REPORTED instead, because a silent skip\n * here is how the next version of this defect would arrive.\n *\n * Passed to `tab.evaluate` and so closes over nothing.\n */\nexport const settleAnimations = (): { finished: number; endless: string[] } => {\n // `transitionProperty` is on CSSTransition, `animationName` on CSSAnimation\n // and `target` on KeyframeEffect, none of which the base types declare. Read\n // rather than asserted, because a stand-in in a test has neither prototype.\n const read = (host: object, key: string): unknown => Reflect.get(host, key);\n const word = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.length > 0 ? value : undefined;\n\n const describe = (animation: Animation): string => {\n const what =\n word(read(animation, \"transitionProperty\")) ??\n word(read(animation, \"animationName\")) ??\n \"an animation\";\n const effect = animation.effect;\n const target = effect === null ? undefined : read(effect, \"target\");\n const tag =\n typeof target === \"object\" && target !== null\n ? word(read(target, \"tagName\"))\n : undefined;\n return tag === undefined ? what : `${tag.toLowerCase()} ${what}`;\n };\n\n const endless: string[] = [];\n let finished = 0;\n for (const animation of document.getAnimations()) {\n const timing = animation.effect?.getComputedTiming();\n const ends =\n timing !== undefined &&\n timing.iterations !== Number.POSITIVE_INFINITY &&\n Number.isFinite(Number(timing.endTime ?? Number.POSITIVE_INFINITY));\n if (!ends) {\n endless.push(describe(animation));\n continue;\n }\n try {\n animation.finish();\n finished++;\n } catch {\n // An animation can refuse to finish (an unresolved effect end), and one that refuses is one still moving, so it belongs in the same bucket.\n endless.push(describe(animation));\n }\n }\n return { finished, endless };\n};\n\nconst digest = (input: string, chars: number): string =>\n createHash(\"sha256\").update(input).digest(\"hex\").slice(0, chars);\n\n/** Fold one or more captures into the shape of a single asset. A still has one\n * capture; a motion scene has one per frame, and the film's shape is the\n * sequence, so a step that stopped firing changes it. */\nexport function foldShape(captures: readonly ShapeCapture[]): AssetShape {\n return {\n hash: digest(captures.map((c) => c.text).join(\"\\n--frame--\\n\"), 16),\n elements: captures[0]?.elements ?? 0,\n text: digest(captures.map((c) => c.visibleText).join(\" | \"), 8),\n };\n}\n\n/**\n * The shape record in `assetDir`, or `undefined` when there is none.\n *\n * @category Shape records\n */\nexport function readShapeRecord(assetDir: string): ShapeRecord | undefined {\n const file = join(assetDir, SHAPE_RECORD_FILE);\n if (!existsSync(file)) return undefined;\n const parsed: unknown = JSON.parse(readFileSync(file, \"utf8\"));\n if (\n typeof parsed !== \"object\" ||\n parsed === null ||\n typeof Reflect.get(parsed, \"version\") !== \"number\" ||\n typeof Reflect.get(parsed, \"assets\") !== \"object\"\n ) {\n throw new Error(`${file} is not a shape record`);\n }\n return parsed as ShapeRecord;\n}\n\nexport async function writeShapeRecord(\n assetDir: string,\n record: ShapeRecord,\n): Promise<void> {\n // Keys sorted so a regeneration that changes nothing produces no diff.\n const assets: Record<string, AssetShape> = {};\n for (const name of Object.keys(record.assets).sort()) {\n assets[name] = record.assets[name] as AssetShape;\n }\n await writeFile(\n join(assetDir, SHAPE_RECORD_FILE),\n `${JSON.stringify({ ...record, assets }, null, 2)}\\n`,\n \"utf8\",\n );\n}\n\n/**\n * What `compareShapes` found: the assets that changed, and the ones with no\n * recorded shape.\n *\n * @category Shape records\n */\nexport interface ShapeVerdict {\n /** Assets whose render no longer matches what was committed. */\n stale: { file: string; was: AssetShape; now: AssetShape }[];\n /** Assets with no recorded shape, so nothing can be said about them. */\n unrecorded: string[];\n /** Set when the record cannot be compared at all, with the reason. */\n incomparable?: string;\n}\n\n/**\n * Compares today's render against the committed shape record. An asset with no\n * recorded shape is listed as `unrecorded`, never as `stale`.\n *\n * @category Shape records\n */\nexport function compareShapes(\n record: ShapeRecord | undefined,\n rendered: ReadonlyMap<string, AssetShape>,\n engine: string,\n): ShapeVerdict {\n if (!record) {\n return { stale: [], unrecorded: [...rendered.keys()].sort() };\n }\n if (record.version !== SHAPE_RECORD_VERSION) {\n return {\n stale: [],\n unrecorded: [],\n incomparable:\n `the record is version ${record.version} and this build writes ` +\n `${SHAPE_RECORD_VERSION}, so the two walks are not the same walk. ` +\n \"Regenerate with `uplink-tools docs`, on Linux.\",\n };\n }\n if (record.engine !== engine) {\n return {\n stale: [],\n unrecorded: [],\n incomparable:\n `the record was taken in ${record.engine} and this run used ${engine}. ` +\n \"Shapes agree across engines by design, but a mismatch here means one \" +\n \"of the two is not the engine the page's images were rendered in, so \" +\n \"the comparison is not the one anybody wants.\",\n };\n }\n const stale: ShapeVerdict[\"stale\"] = [];\n const unrecorded: string[] = [];\n for (const file of [...rendered.keys()].sort()) {\n const was = record.assets[file];\n const now = rendered.get(file) as AssetShape;\n if (!was) {\n unrecorded.push(file);\n continue;\n }\n if (was.hash !== now.hash) stale.push({ file, was, now });\n }\n return { stale, unrecorded };\n}\n\n/**\n * Why one asset's render no longer matches its recorded shape, in terms a\n * person can act on.\n *\n * @category Shape records\n */\nexport function describeStale(entry: {\n file: string;\n was: AssetShape;\n now: AssetShape;\n}): string {\n const { file, was, now } = entry;\n const why: string[] = [];\n if (was.elements !== now.elements) {\n why.push(`${was.elements} elements became ${now.elements}`);\n }\n if (was.text !== now.text) why.push(\"the visible text changed\");\n if (why.length === 0) why.push(\"styling changed, the tree and text did not\");\n return (\n `${file}: the committed picture is not what this code renders ` +\n `(${why.join(\"; \")}; shape ${was.hash} became ${now.hash})`\n );\n}\n","import { mkdir, readdir, rm, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { Locator, Page } from \"playwright\";\nimport type {\n RenderProbeApi,\n ScenePayload,\n SceneReport,\n SceneStep,\n SceneTarget,\n UnreadTopics,\n UplinkInventory,\n} from \"../render-probe\";\nimport type { UplinkPackage } from \"./context\";\nimport { encodeGif } from \"./gif\";\nimport { growRootToContent } from \"./grow\";\nimport {\n type HeldStage,\n type HeldVerdict,\n judgeHeld,\n mountForHeld,\n} from \"./held\";\nimport { buildProbePage, type ProbePage } from \"./page\";\nimport { pngSize } from \"./png\";\nimport { PROBE_CHROME_ATTR, RENDER_PROBE_GLOBAL } from \"./probe-global\";\nimport { payloadFor } from \"./sceneModel\";\nimport {\n assertEveryWidgetCovered,\n buildScenes,\n type Scene,\n type SceneAct,\n} from \"./scenes\";\nimport {\n ADMISSIBLE_PROPERTIES,\n type AssetShape,\n foldShape,\n RECORDED_ATTRIBUTES,\n readShapeText,\n type ShapeCapture,\n settleAnimations,\n} from \"./shape\";\n\n/*\n * The Playwright half: one browser, one page, every scene.\n * One init script pins `Date.now`, `new Date()`, `performance.now`, `Math.random` and `crypto.randomUUID` before any module runs; when callbacks run belongs to a motion scene's own clock (`./sceneClock`).\n */\n\n/**\n * The browser engine a render runs in.\n *\n * @category Rendering scenes\n */\nexport type Engine = \"chromium\" | \"firefox\" | \"webkit\";\n\n/**\n * playwright, imported when an engine is actually launched.\n *\n * It is an OPTIONAL peer of this package and this module's own header promises\n * that \"a missing one fails with a named message rather than a resolution error\".\n * That promise was false while the import sat at module scope: Node threw\n * ERR_MODULE_NOT_FOUND out of `dist/render.js` before a line of ours ran, which\n * is what an author copying the template met when they ran `npm run docs`, naming\n * a package they had never heard of and a file inside somebody else's dist.\n *\n * Only the VALUES move. `Page` and `Locator` stay type-only imports, which erase,\n * so the signatures throughout this file keep their real types.\n */\nexport async function engine(name: Engine) {\n let playwright: typeof import(\"playwright\");\n try {\n playwright = await import(\"playwright\");\n } catch (err) {\n if (\n err instanceof Error &&\n /Cannot find (module|package)|ERR_MODULE_NOT_FOUND/.test(err.message)\n ) {\n throw new Error(\n \"rendering needs playwright, which is not installed. It is your \" +\n \"dependency rather than ui-kit's, so an author who pins a version \" +\n \"gets the one they pinned:\\n\" +\n \" npm i -D playwright && npx playwright install chromium\\n\" +\n \"Both halves are needed: the package drives a browser and the second \" +\n \"command downloads one.\",\n );\n }\n throw err;\n }\n return playwright[name];\n}\n\n/** Arbitrary, stable: 2023-11-14T22:13:20Z. Only its fixedness matters. */\nconst FIXED_EPOCH_MS = 1_700_000_000_000;\n\nasync function pinTheClock(page: Page): Promise<void> {\n await page.addInitScript((fixed) => {\n const RealDate = Date;\n // A widget deriving layout from `new Date()` rather than `Date.now()` is\n // the gap this closes. Only the NO-ARGUMENT form is the nondeterministic\n // one, so every other overload is forwarded untouched.\n //\n // A function DECLARATION rather than an arrow function: an arrow has no\n // [[Construct]], so `new Date(x)` throws \"Date is not a constructor\" and\n // takes the whole page down before a single module runs. Nothing in the\n // page constructs a date until a first-party widget is mounted in it, so\n // the stand-in-host renders never reach the line. A declaration also\n // keeps its own name without the `__name` helper an anonymous function\n // assigned to a const picks up, which does not exist in the serialised\n // page context.\n function PinnedDate(this: unknown, ...args: unknown[]) {\n if (!new.target) return RealDate();\n return Reflect.construct(\n RealDate,\n args.length === 0 ? [fixed] : args,\n new.target,\n );\n }\n PinnedDate.prototype = RealDate.prototype;\n PinnedDate.now = () => fixed;\n PinnedDate.parse = RealDate.parse;\n PinnedDate.UTC = RealDate.UTC;\n Object.defineProperty(globalThis, \"Date\", { value: PinnedDate });\n performance.now = () => 0;\n let seed = 0x2545f491;\n Math.random = () => {\n seed = (seed * 1103515245 + 12345) & 0x7fffffff;\n return seed / 0x7fffffff;\n };\n let uuidCounter = 0;\n Object.defineProperty(globalThis.crypto, \"randomUUID\", {\n configurable: true,\n value: () => {\n uuidCounter++;\n const tail = uuidCounter.toString(16).padStart(12, \"0\");\n return `00000000-0000-4000-8000-${tail}`;\n },\n });\n }, FIXED_EPOCH_MS);\n}\n\n/**\n * Options for `renderUplink`.\n *\n * @category Rendering scenes\n */\nexport interface RenderOptions {\n engine: Engine;\n outDir: string;\n /** Only scenes whose name matches. */\n scene?: string;\n /** Keep the numbered PNG frames of a motion scene beside its GIF. */\n frames: boolean;\n uplinkId?: string;\n /** Extra modules bundled into the page ON TOP of the package's own\n * `gonogo.renderWith`, so a one-off run can name a host the package does not\n * declare. See `ScenePayload.host`. */\n withModules?: readonly string[];\n /**\n * Write each asset's raw shape text beside it as `<asset>.shape.txt`.\n *\n * A shape is a hash, so a mismatch can otherwise only ever say \"different\",\n * and a gate that reports a change without a way to see the change is one\n * people mute. This is what `uplink-shape-engines.mjs` diffs when two engines\n * disagree, and what an author dumps when `docs --check` names an asset they\n * did not expect.\n */\n dumpShapes?: boolean;\n}\n\n/**\n * One image or animation `renderUplink` wrote.\n *\n * @category Rendering scenes\n */\nexport interface RenderedAsset {\n scene: Scene;\n mode: string;\n /** Path relative to `outDir`. */\n file: string;\n kind: \"still\" | \"motion\";\n /** What this render IS, comparable across machines. See `./shape`. */\n shape: AssetShape;\n}\n\n/**\n * What `renderUplink` returns: what the Uplink registered, its scenes, and every\n * asset written.\n *\n * @category Rendering scenes\n */\nexport interface RenderResult extends UplinkScenes {\n assets: RenderedAsset[];\n}\n\n/** What a probe page knows before any scene is mounted. */\nexport interface UplinkScenes {\n inventory: UplinkInventory;\n scenes: Scene[];\n /** `augment:<id>` / `contribution:<id>` with no scene. Named on the page. */\n unpreviewed: string[];\n fontMode: \"locked\" | \"fallback\";\n fontAdvice?: string;\n}\n\ntype ProbeOptions = Pick<RenderOptions, \"engine\" | \"uplinkId\" | \"withModules\">;\n\n/*\n * The probe's handle, declared on `globalThis` so the `tab.evaluate` bodies\n * below reach it by name. They are compiled here and run in the page, where\n * `installRenderProbe` has already put it there.\n */\ndeclare global {\n var __gonogoRenderProbe: RenderProbeApi;\n}\n\n/**\n * Load the Uplink into a probe page, read what it registers, and hand the open\n * tab to `body`. Every scene is built and coverage asserted before `body` runs.\n */\nasync function withProbe<Result>(\n pkg: UplinkPackage,\n opts: ProbeOptions,\n body: (\n tab: Page,\n read: UplinkScenes,\n pageErrors: string[],\n ) => Promise<Result>,\n): Promise<Result> {\n const browser = await (await engine(opts.engine)).launch();\n const pageErrors: string[] = [];\n let page: ProbePage | undefined;\n try {\n page = await buildProbePage(pkg, [\n ...pkg.renderWith,\n ...(opts.withModules ?? []),\n ]);\n const context = await browser.newContext({\n viewport: { width: 900, height: 900 },\n deviceScaleFactor: 2,\n // Context level, so `prefers-reduced-motion`-guarded infinite pulses\n // collapse. `animations: \"disabled\"` covers the rest of the PICTURE and\n // only the picture. The shape read is a capture too, and settling that\n // one is `captureShape`'s job.\n reducedMotion: \"reduce\",\n });\n const tab = await context.newPage();\n tab.on(\"pageerror\", (err) => {\n if (isUnmountPlayAbort(err.message)) return;\n console.error(` [page error] ${err.message}`);\n pageErrors.push(err.message);\n });\n tab.on(\"console\", (msg) => {\n if (msg.type() === \"error\") console.error(` [console] ${msg.text()}`);\n });\n await pinTheClock(tab);\n await tab.goto(pathToFileURL(page.file).toString(), {\n waitUntil: \"domcontentloaded\",\n });\n await tab.waitForFunction(\n (key) =>\n typeof (globalThis as Record<string, unknown>)[key as string] ===\n \"object\",\n RENDER_PROBE_GLOBAL,\n { timeout: 20_000 },\n );\n\n const inventory = await tab.evaluate(\n ([key, uplinkId]) =>\n globalThis[key as typeof RENDER_PROBE_GLOBAL].readInventory(\n uplinkId as string | undefined,\n ),\n [RENDER_PROBE_GLOBAL, opts.uplinkId] as const,\n );\n\n const scenes = buildScenes(pkg, inventory);\n const { unpreviewed } = assertEveryWidgetCovered(scenes, inventory);\n return await body(\n tab,\n {\n inventory,\n scenes,\n unpreviewed,\n fontMode: page.font.mode,\n fontAdvice: page.font.advice,\n },\n pageErrors,\n );\n } finally {\n await browser.close();\n await page?.dispose();\n }\n}\n\n/**\n * Everything the page's prose is built from, with no scene mounted and no file\n * written. The registrations only exist once the client has run, which is why\n * this still opens a browser, but it renders nothing.\n */\nexport async function readUplinkScenes(\n pkg: UplinkPackage,\n opts: ProbeOptions,\n): Promise<UplinkScenes> {\n return withProbe(pkg, opts, async (_tab, read) => read);\n}\n\n/**\n * Renders every scene of an Uplink in a real browser and writes a PNG for each\n * still scene and a GIF for each animated one.\n *\n * @category Rendering scenes\n */\nexport async function renderUplink(\n pkg: UplinkPackage,\n opts: RenderOptions,\n): Promise<RenderResult> {\n return withProbe(pkg, opts, async (tab, read, pageErrors) => {\n const all = read.scenes;\n const scenes = opts.scene ? all.filter((s) => s.name === opts.scene) : all;\n if (scenes.length === 0) {\n throw new Error(\n `uplink-tools: no scene named \"${opts.scene}\". Known scenes: ` +\n `${all.map((s) => s.name).join(\", \")}`,\n );\n }\n\n await mkdir(opts.outDir, { recursive: true });\n await cleanPngsAndGifs(opts.outDir);\n\n const assets: RenderedAsset[] = [];\n const ledger = guestLedger(read.inventory);\n for (const scene of scenes) {\n await renderOneScene(tab, scene, opts, assets, ledger);\n }\n reportUnjudgedGuests(ledger, opts.scene !== undefined);\n\n if (pageErrors.length > 0) {\n // A crashed widget still writes a PNG, and on a dark widget a blank frame\n // reads as font hinting. A render error must never be something a reviewer\n // catches by eye.\n const unique = [...new Set(pageErrors)];\n throw new Error(\n `${pageErrors.length} uncaught page error(s); no render from this run ` +\n `is trustworthy:\\n ${unique.join(\"\\n \")}`,\n );\n }\n return { ...read, assets };\n });\n}\n\n/**\n * Name the guests no scene drew, which the held check therefore never\n * judged. Said rather than failed: a guest can legitimately draw nothing in\n * every scene this Uplink has, and the fix is a scene, which is the author's\n * call. Silent on a one-scene run, where most guests are simply not in view.\n */\nfunction reportUnjudgedGuests(ledger: GuestLedger, oneScene: boolean): void {\n if (oneScene) return;\n const unjudged = ledger.guests.filter((g) => !ledger.judged.has(g.id));\n if (unjudged.length === 0) return;\n console.log(\n `\\n ! held: ${unjudged.length} guest(s) no scene draws, so nothing ` +\n \"has checked what they show when the link drops: \" +\n unjudged.map((g) => `${g.kind} ${g.id}`).join(\", \"),\n );\n}\n\n/**\n * The one page error a render is allowed to survive.\n *\n * A `<video>` element unmounted while a `play()` promise is still pending\n * rejects, and every scene after the first unmounts one. It says nothing about\n * the render: the frame that was captured was captured before the unmount, and\n * the element being torn down is the harness moving on. Nothing else is\n * forgiven, because a page error is otherwise a widget that threw and a PNG\n * that looks like a widget that did not.\n *\n * Matched on both halves of the sentence rather than on \"play\", so a genuine\n * playback failure still fails the run.\n */\nfunction isUnmountPlayAbort(message: string): boolean {\n return (\n message.includes(\"play() request was interrupted\") &&\n message.includes(\"new load request\")\n );\n}\n\nasync function renderOneScene(\n tab: Page,\n scene: Scene,\n opts: RenderOptions,\n assets: RenderedAsset[],\n ledger: GuestLedger,\n): Promise<void> {\n console.log(`\\n── ${scene.target.kind} ${scene.target.id} / ${scene.name}`);\n const first = scene.modes[0];\n\n // The starved run, once per scene rather than once per mode: the question is about the FIXTURE, and a tile size cannot answer it.\n const starved = await mount(tab, payloadFor(scene, first, true));\n const heldPair = await heldRenders(tab, scene, first);\n if (heldPair) {\n await assertHeldShows(tab, scene, first, heldPair, ledger);\n }\n for (const [index, mode] of scene.modes.entries()) {\n const fed = await mount(tab, payloadFor(scene, mode, false));\n if (index === 0) assertFedRenderMeansSomething(scene, fed, starved);\n const control = index === 0 ? heldPair?.control : undefined;\n\n if (scene.steps && scene.steps.length > 0 && index === 0) {\n await captureMotion(tab, scene, mode, opts, assets, control);\n assertEveryEmitLanded(scene, await refeed(tab));\n continue;\n }\n const file = `${scene.name}--${mode.name}.png`;\n await reportFit(tab, scene, mode.name);\n await performActs(tab, scene);\n // After the presses, never before them. A tab's content is not mounted\n // until its tab is selected, so a topic only that content reads had no\n // subscriber while the fixture was emitting; production replays the last\n // value on subscribe and this is where the harness does the same. What is\n // still unread once the presses have run is the real finding.\n assertEveryEmitLanded(scene, await refeed(tab));\n if (control) assertRendersRepeat(scene, control, await readScene(tab));\n // Read BEFORE the grow, which writes a measured height into `#root`'s inline\n // style and lets every ResizeObserver in the tree settle against it. The\n // shape is meant to be the same on any machine, and the state after that\n // step is the one place in the run where it would not be.\n const capture = await captureShape(tab);\n if (opts.dumpShapes) {\n await writeFile(join(opts.outDir, `${file}.shape.txt`), capture.text);\n }\n const shape = foldShape([capture]);\n await growToFullContent(tab);\n await assertEveryPaintVisible(tab, scene, mode.name);\n const png = await shoot(tab, join(opts.outDir, file));\n if (scene.hero && index === 0) warnOnExtremeAspectRatio(scene, file, png);\n assets.push({ scene, mode: mode.name, file, kind: \"still\", shape });\n // The visible text is printed because a picture is the one output a\n // terminal cannot show you, and this is the cheapest way for an author to\n // see that the render carries the words they expected.\n console.log(` ${file} ${fed.visibleText.slice(0, 110)}`);\n }\n}\n\n/**\n * One reading of the mounted widget, taken once it has stopped moving.\n *\n * The whitelists travel as an argument so the page function closes over\n * nothing. `settleAnimations` is why this is not a single `evaluate`: see its\n * doc comment for the defect, which is that a transition still running at read\n * time puts a stopwatch inside the hash.\n *\n * Then it reads TWICE and requires the two to agree, which is the part that\n * makes this checkable rather than hopeful. Settling covers the cause we found;\n * a second reading covers the ones we have not, because anything still moving\n * for any other reason (an animation with no end that touches an admissible\n * property, a pending `ResizeObserver`, a live clock that escaped pinning)\n * shows up as two readings that differ. A shape gate whose own reading drifts\n * is a random number generator, and this repo has now spent a day proving that\n * from the outside. It fails here instead, at the moment the render is taken,\n * naming the line.\n */\nasync function captureShape(tab: Page): Promise<ShapeCapture> {\n const read = (): Promise<ShapeCapture> =>\n tab.evaluate(readShapeText, {\n properties: ADMISSIBLE_PROPERTIES as readonly string[],\n attributes: RECORDED_ATTRIBUTES,\n });\n\n let previous: ShapeCapture | undefined;\n let capture: ShapeCapture | undefined;\n let endless: string[] = [];\n for (let attempt = 0; attempt < 3; attempt++) {\n endless = (await tab.evaluate(settleAnimations)).endless;\n previous = capture;\n capture = await read();\n if (previous !== undefined && previous.text === capture.text) {\n return capture;\n }\n await settle(tab);\n }\n\n // The two readings that actually disagreed, rather than a fresh pair: a fourth read could agree by luck and print a message with no difference in it.\n const before = (previous as ShapeCapture).text.split(\"\\n\");\n const after = (capture as ShapeCapture).text.split(\"\\n\");\n const differs = before.findIndex((row, i) => row !== after[i]);\n const line = differs === -1 ? before.length : differs;\n throw new Error(\n \"render shape: the widget is still changing after three settles, so its \" +\n \"shape is a reading off a clock rather than a fact about the code.\\n\" +\n ` line ${line + 1}\\n` +\n ` ${before[line] ?? \"(end)\"}\\n` +\n ` ${after[line] ?? \"(end)\"}\\n` +\n (endless.length > 0\n ? ` animations with no end, running during the read: ${[...new Set(endless)].join(\", \")}`\n : \" no endless animation was running, so something outside CSS is moving.\"),\n );\n}\n\n/**\n * Say, under each render, what the operator cannot read at that size.\n *\n * Printed rather than thrown, and that is the only thing about it worth\n * arguing over. It is an author's own render run, not a gate: failing it would\n * stop the pictures being produced, which is the one thing the author came here\n * for, and a check that blocks the tool it rides in is a check people stop\n * running. The repo's own gate over every widget at once fails; this tells the\n * author, at the moment they are looking at the widget, which of their own\n * sizes is unreadable.\n *\n * Taken BEFORE `growToFullContent`, which lifts the vertical crop so the\n * picture shows the whole widget: an audit after that has measured a tile\n * nobody runs.\n */\nasync function reportFit(tab: Page, scene: Scene, mode: string): Promise<void> {\n const findings = await tab.evaluate(\n (key) => globalThis[key as typeof RENDER_PROBE_GLOBAL].auditMinFit(),\n RENDER_PROBE_GLOBAL,\n );\n if (findings.length === 0) return;\n console.log(\n ` ! ${scene.name} @ ${mode}: ${findings.length} thing(s) an operator ` +\n `cannot read at this size`,\n );\n for (const f of findings.slice(0, 4)) {\n console.log(` ${f.kind} ${f.px}px [${f.axis}] \"${f.text}\"`);\n }\n if (findings.length > 4) {\n console.log(` ... and ${findings.length - 4} more`);\n }\n console.log(\n \" A heading that will not fit wants <Panel compactTitle>; content \" +\n \"that overflows wants a scroller. If neither is honest, raise the \" +\n \"widget's minSize.\",\n );\n}\n\nasync function mount(tab: Page, payload: ScenePayload): Promise<SceneReport> {\n const report = await tab.evaluate(\n ([key, scene]) =>\n globalThis[key as typeof RENDER_PROBE_GLOBAL].renderScene(\n scene as ScenePayload,\n ),\n [RENDER_PROBE_GLOBAL, payload] as const,\n );\n return report;\n}\n\n/** Feed whatever `_scene.before` has just mounted, and read back what is still\n * unread. See the probe's `refeedScene`. */\nfunction refeed(tab: Page): Promise<UnreadTopics> {\n return tab.evaluate(\n (key) => globalThis[key as typeof RENDER_PROBE_GLOBAL].refeedScene(),\n RENDER_PROBE_GLOBAL,\n );\n}\n\nfunction readScene(tab: Page): Promise<SceneReport> {\n return tab.evaluate(\n (key) => globalThis[key as typeof RENDER_PROBE_GLOBAL].readScene(),\n RENDER_PROBE_GLOBAL,\n );\n}\n\n/**\n * Every string `_scene.paints` names is on screen and READABLE.\n *\n * Measured through the real layout, which is the whole point: a jsdom suite\n * computes none, so text squeezed to zero width by a neighbour that wrapped\n * satisfies every `toBeInTheDocument` while being unreadable in a browser.\n *\n * Two ways a label loses. Zero width is the one that motivated the check: a\n * launch complex's own name rendered at nothing beside a detail sentence that\n * took the whole row. CLIPPING is the other, and it is the one a bounding box\n * alone cannot see, because `text-overflow: ellipsis` leaves a box of perfectly\n * respectable size showing \"V...\". Both are the same failure to a reader, so both\n * fail here.\n *\n * Collected across the whole list before throwing, so an author fixing a scene\n * sees all of it rather than one label per run. Grown to full content first, so\n * a label below the tile's fold is a visible label and not a failure.\n */\nasync function assertEveryPaintVisible(\n tab: Page,\n scene: Scene,\n mode: string,\n): Promise<void> {\n const failures: string[] = [];\n for (const text of scene.paints) {\n const matches = tab.locator(\"#root\").getByText(text, { exact: false });\n const found = await matches.count().catch(() => 0);\n // Harness chrome does not count. A stand-in host's title is inside `#root`\n // like everything else, and `paints: [\"FUEL\"]` was passing against\n // \"FUEL STATUS (stand-in host)\" on a scene whose augment drew nothing.\n const subject: Locator[] = [];\n for (let i = 0; i < found; i++) {\n const one = matches.nth(i);\n const chrome = await one\n .evaluate(\n (el, attr) => el.closest(`[${attr}]`) !== null,\n PROBE_CHROME_ATTR,\n )\n .catch(() => false);\n if (!chrome) subject.push(one);\n }\n const count = subject.length;\n if (count === 0) {\n failures.push(\n found === 0\n ? `\"${text}\" is not on the page at all`\n : `\"${text}\" is on the page ONLY in the harness's stand-in host ` +\n `title, never in the ${scene.target.kind} itself`,\n );\n continue;\n }\n // ANY readable instance passes, rather than the first. A hosted scene mounts\n // every augment registered on the host's slot, so a common label like\n // \"Funds\" legitimately appears several times, and asking only the first\n // whether it survived is asking about an arbitrary one of them.\n const verdicts: string[] = [];\n for (const one of subject) {\n const verdict = await readable(one);\n if (verdict === null) {\n verdicts.length = 0;\n break;\n }\n verdicts.push(verdict);\n }\n if (verdicts.length > 0) {\n failures.push(\n `\"${text}\" appears ${count === 1 ? \"once\" : `${count} times`} and is ` +\n `readable nowhere: ${[...new Set(verdicts)].join(\"; \")}`,\n );\n }\n }\n if (failures.length === 0) return;\n throw new Error(\n `${scene.name} (${scene.target.kind} ${scene.target.id}) at ${mode}: ` +\n `${failures.length} of ${scene.paints.length} \"_scene.paints\" ` +\n `entries did not survive the layout:\\n ${failures.join(\"\\n \")}\\n` +\n \"Either the render is wrong, or this shape genuinely cannot carry the \" +\n 'text, in which case narrow the scene with \"_scene\": { \"modes\": [...] }.',\n );\n}\n\n/**\n * `_scene.before`, through real input events.\n *\n * A press goes through the accessible NAME rather than a selector, because that\n * is the handle an operator has and a class name is not: a control renamed out\n * from under a scene should fail here rather than quietly photograph the state\n * before the press.\n */\nasync function performActs(\n tab: Page,\n scene: Scene,\n missing: \"throw\" | \"skip\" = \"throw\",\n): Promise<void> {\n const performAct = async (act: SceneAct): Promise<void> => {\n if (act.press !== undefined) {\n const control = await pressable(tab, act.press);\n if (control === null && missing === \"skip\") return;\n if (control === null) {\n throw new Error(\n `${scene.name}: \"_scene.before\" presses \"${act.press}\", which is ` +\n \"not a button or a tab on screen at that point. Presses run in \" +\n \"order, so a control that only appears after an earlier press has \" +\n \"to come after it.\",\n );\n }\n await control.click();\n return;\n }\n if (act.hover !== undefined) {\n const target = tab.locator(act.hover).first();\n await target.scrollIntoViewIfNeeded().catch(() => {});\n const box = await target.boundingBox().catch(() => null);\n if (box === null && missing === \"skip\") return;\n if (box === null) {\n throw new Error(\n `${scene.name}: \"_scene.before\" hovers \"${act.hover}\", which matched ` +\n \"nothing that is laid out.\",\n );\n }\n // A plain pointer move, not `locator.hover()`. That one refuses when\n // something is painted over the target, which is the normal case for a\n // hover-gated overlay: the chrome sits on top of the video it is gating.\n // What a hover-gate reads is where the pointer IS, so that is what this\n // sets.\n await tab.mouse.move(box.x + box.width / 2, box.y + box.height / 2);\n return;\n }\n await restPointer(tab);\n };\n\n for (const act of scene.before) {\n await performAct(act);\n await settle(tab);\n }\n}\n\n/**\n * The control an accessible name reaches, or null when nothing does.\n *\n * <p>A tab is tried after a button because a tab IS a press an operator makes\n * and `role=\"tab\"` is not `role=\"button\"`. Without it every augment hosted\n * inside a tabbed widget was unreachable: the host renders its first tab, the\n * scene can never open the one the augment is in, and the only fixture that\n * could be written was one photographing a panel the augment is not on. Three\n * of the app's own hosts tab their content.</p>\n */\nasync function pressable(tab: Page, name: string): Promise<Locator | null> {\n for (const role of [\"button\", \"tab\"] as const) {\n const found = tab.getByRole(role, { name }).first();\n if ((await found.count()) > 0) return found;\n }\n return null;\n}\n\n/**\n * Put the pointer somewhere the widget is not.\n *\n * Past the tile's own bottom-right corner rather than at negative coordinates:\n * the browser clamps those back into the viewport, whose origin is INSIDE the\n * tile, so a hover-gated control asked to rest was hovered instead and both\n * halves of a resting/hovered pair came out identical.\n */\nasync function restPointer(tab: Page): Promise<void> {\n const viewport = tab.viewportSize() ?? { width: 900, height: 900 };\n const rect = await tab.evaluate(() => {\n const el = document.getElementById(\"root\");\n if (!el) return null;\n const box = el.getBoundingClientRect();\n return { right: box.right, bottom: box.bottom };\n });\n await tab.mouse.move(\n Math.min(viewport.width - 1, (rect?.right ?? 0) + 20),\n Math.min(viewport.height - 1, (rect?.bottom ?? 0) + 20),\n );\n}\n\n/** Two frames, which is what a React state change plus its layout costs. */\nasync function settle(tab: Page): Promise<void> {\n await tab.evaluate(\n () =>\n new Promise<void>((resolve) => {\n requestAnimationFrame(() => requestAnimationFrame(() => resolve()));\n }),\n );\n}\n\n/** `null` when this element carries the text readably, otherwise why it does not. */\nasync function readable(at: Locator): Promise<string | null> {\n const box = await at.boundingBox().catch(() => null);\n if (box === null) return \"not laid out at all\";\n if (box.width <= 0 || box.height <= 0) {\n return `painted at ${box.width}x${box.height}`;\n }\n // Its own overflow, not an ancestor's: `text-overflow: ellipsis` needs the\n // clip on the element carrying the text, so this is where the idiom lives. An\n // element overflowing VISIBLY is still readable and is not a failure.\n return at\n .evaluate((el) => {\n if (getComputedStyle(el).overflowX === \"visible\") return null;\n const over = el.scrollWidth - el.clientWidth;\n return over > 1\n ? `clipped, ${over}px of it outside the ${el.clientWidth}px it is given`\n : null;\n })\n .catch(() => null);\n}\n\nasync function shoot(tab: Page, path: string): Promise<Buffer> {\n await fitViewportToRoot(tab);\n const root = await tab.$(\"#root\");\n if (!root) throw new Error(\"render: #root vanished after mount\");\n return root.screenshot({ path, animations: \"disabled\" });\n}\n\n/**\n * Make the viewport tall enough to hold the whole widget in one go.\n *\n * An element screenshot taller than the viewport is captured by SCROLLING and\n * stitching, and scrolling the page also scrolls anything under it that still\n * has an overflow of its own. A `Panel` whose body did not quite grow to fit\n * therefore scrolled between two captures and the stitched image showed the\n * same rows twice, which reads as a widget that renders its contents twice.\n * Fitting the viewport first means nothing ever scrolls.\n */\nasync function fitViewportToRoot(tab: Page): Promise<void> {\n const height = await tab.evaluate(\n () => document.getElementById(\"root\")?.getBoundingClientRect().height ?? 0,\n );\n const wanted = Math.ceil(height) + VIEWPORT_MARGIN_PX;\n const current = tab.viewportSize();\n if (!current || wanted <= current.height) return;\n await tab.setViewportSize({ width: current.width, height: wanted });\n await settle(tab);\n}\n\n/** Room for the tile's own outer inset, so nothing sits on the viewport edge. */\nconst VIEWPORT_MARGIN_PX = 64;\n\n/**\n * Grow `#root` so the image shows the WHOLE widget, then let it settle.\n *\n * The mount already laid out at the real tile WIDTH, so responsive breakpoints\n * stay honest; only the vertical crop is lifted. See `growRootToContent` for\n * which overflow counts.\n *\n * On by default here, unlike the first-party visual gate: a per-tile baseline\n * wants the crop, and a reader of a docs page wants the widget.\n */\nasync function growToFullContent(tab: Page): Promise<void> {\n await tab.evaluate(growRootToContent);\n // ResizeObserver-driven bits (gauges, tapes, scroll glow) settle at the final height before the shot.\n await tab.evaluate(\n () =>\n new Promise<void>((resolve) => {\n requestAnimationFrame(() => requestAnimationFrame(() => resolve()));\n }),\n );\n}\n\n/**\n * The check the operator asked for, and it is exact rather than textual.\n *\n * An empty widget renders the same whether it works or not, so a render of an\n * unfed scene is a picture that looks like a working widget with no data. Two\n * widgets in this repo once carried 96 committed baselines between them that were\n * renders of nothing, and a textual detector found one and missed the other,\n * because one empty state is a sentence and the other is punctuation.\n *\n * So the comparison is between the SAME scene fed and starved. If they match, the\n * render does not depend on the fixture, whatever the scenario is called. The only\n * escape is `_scene.expectsEmpty`, which takes a written reason, and which still\n * has to render something.\n */\nfunction assertFedRenderMeansSomething(\n scene: Scene,\n fed: SceneReport,\n starved: SceneReport,\n): void {\n if (fed.boxCount === 0) {\n throw new Error(\n `${scene.name} (${scene.target.kind} ${scene.target.id}): the render is ` +\n \"BLANK, not one painted element. Nothing mounted, or the mount threw \" +\n \"before painting.\",\n );\n }\n if (scene.expectsEmpty) {\n if (fed.visibleText.length === 0) {\n throw new Error(\n `${scene.name}: \"_scene.expectsEmpty\" says this scene is an empty ` +\n `state (\"${scene.expectsEmpty}\"), but the render carries no visible ` +\n \"text of its own. An empty state a reader can see is a render; a \" +\n \"blank frame is not, and expectsEmpty is not a way to wave one \" +\n \"through. A stand-in host's title does not count towards this: it is \" +\n \"the harness talking, and it reads the same whether the scene \" +\n \"rendered anything or not.\",\n );\n }\n return;\n }\n if (fed.signature === starved.signature) {\n throw new Error(\n `${scene.name} (${scene.target.kind} ${scene.target.id}): this scene ` +\n \"renders IDENTICALLY with its fixture suppressed, so the picture \" +\n \"contains none of the data the fixture feeds.\\n\" +\n ` what a reader sees: ${JSON.stringify(fed.visibleText.slice(0, 160))}\\n` +\n ` topics the fixture emits: ${scene.emits.map((e) => e.topic).join(\", \") || \"(none)\"}\\n` +\n ` legacy keys: ${Object.values(scene.dataSources).flatMap(Object.keys).join(\", \") || \"(none)\"}\\n` +\n \"Either the fixture feeds something this target does not read, or the \" +\n \"scene genuinely is an empty state, in which case say so with \" +\n '\"_scene\": { \"expectsEmpty\": \"<why>\" }.',\n );\n }\n}\n\n/**\n * Whether a scene can be asked what it does when the link drops: it feeds the\n * stream, and it is not an empty state, which draws no figure to hold.\n */\nfunction heldApplies(scene: Scene): boolean {\n return scene.emits.length > 0 && !scene.expectsEmpty;\n}\n\n/** The scene's whole render in both states, at the first mode. */\ninterface HeldPair {\n live: SceneReport;\n held: SceneReport;\n}\n\n/** An augment or contribution, and the slot it fills. */\ntype Guest = SceneTarget & { slot: string };\n\n/**\n * This Uplink's augments and contributions, which the held check judges\n * wherever a scene draws them, the ids it has judged at least once in this\n * run, and every widget's declared slots, for a guest filling a global one.\n */\ninterface GuestLedger {\n guests: Guest[];\n judged: Set<string>;\n hostSlots: Map<string, Set<string>>;\n}\n\nfunction guestLedger(inventory: UplinkInventory): GuestLedger {\n return {\n hostSlots: new Map(\n [...inventory.widgets, ...inventory.hosts].map((w) => [\n w.id,\n new Set([...w.augmentSlots, ...w.contributionSlots]),\n ]),\n ),\n guests: [\n ...inventory.augments.map((a) => ({\n kind: \"augment\" as const,\n id: a.id,\n slot: a.augments,\n })),\n ...inventory.contributions.map((c) => ({\n kind: \"contribution\" as const,\n id: c.id,\n slot: c.contributes,\n })),\n ],\n judged: new Set(),\n };\n}\n\n/**\n * Everything the held gate reads for one scene, mounted before the fed\n * render because that has to be the last mount: everything after it reads the\n * page as it was left.\n *\n * <p>The fed state is mounted once more as a CONTROL. Two renders of one state\n * that differ would make every comparison read as a change, so the check\n * proves it can see \"the same\" before it trusts \"different\".</p>\n */\nasync function heldRenders(\n tab: Page,\n scene: Scene,\n mode: Scene[\"modes\"][number],\n): Promise<(HeldPair & { control: SceneReport }) | undefined> {\n if (!heldApplies(scene)) return undefined;\n const staged = scene.stopsArriving === true;\n const control = await mountAs(tab, scene, mode, staged);\n const twin = await mountAs(tab, scene, mode, !staged);\n return staged\n ? { live: twin, held: control, control }\n : { live: control, held: twin, control };\n}\n\nfunction mountAs(\n tab: Page,\n scene: Scene,\n mode: Scene[\"modes\"][number],\n stopsArriving: boolean,\n withhold?: SceneTarget,\n): Promise<SceneReport> {\n return mountForHeld(heldStage(tab), scene, {\n ...payloadFor(scene, mode, false),\n stopsArriving,\n withhold,\n });\n}\n\nfunction heldStage(tab: Page): HeldStage {\n return {\n mount: (payload) => mount(tab, payload),\n act: (scene, missing) => performActs(tab, scene, missing),\n refeed: async () => {\n await refeed(tab);\n },\n finish: () =>\n tab.evaluate(\n (key) => globalThis[key as typeof RENDER_PROBE_GLOBAL].finishScene(),\n RENDER_PROBE_GLOBAL,\n ),\n read: () => readScene(tab),\n };\n}\n\n/** The widget a scene's guests are drawn inside, if the scene has a real one. */\nfunction hostOf(scene: Scene): string | undefined {\n return (\n scene.host ?? (scene.target.kind === \"widget\" ? scene.target.id : undefined)\n );\n}\n\n/**\n * The held gate for one scene. Fails a subject that draws the same thing\n * whether its figures are arriving or not, and one that marks a figure held\n * without saying so. Every stream-fed scene is checked, so nothing escapes it\n * for want of a held fixture.\n *\n * <p>A widget is judged on its whole render. A guest (an augment or a\n * contribution) is judged on what is left once the render without it is taken\n * away, in both states: the host around it may mark its own held readings, and\n * a render that changed only because the host did is exactly a correctly marked\n * panel carrying a figure nobody marked. The scene's own subject is judged,\n * and so is every other guest of this Uplink the scene's host draws: a guest\n * with no scene of its own is still on screen wherever its host is.</p>\n */\nasync function assertHeldShows(\n tab: Page,\n scene: Scene,\n mode: Scene[\"modes\"][number],\n pair: HeldPair & { control: SceneReport },\n ledger: GuestLedger,\n): Promise<void> {\n const staged = scene.stopsArriving === true;\n const host = hostOf(scene);\n const withoutGuest = async (guest: SceneTarget) => ({\n live: (await mountAs(tab, scene, mode, false, guest)).elements,\n held: (await mountAs(tab, scene, mode, true, guest)).elements,\n });\n\n const subjectIsGuest = scene.target.kind !== \"widget\" && scene.host;\n const verdict = judgeHeld({\n live: pair.live.elements,\n held: pair.held.elements,\n hostOnly: subjectIsGuest ? await withoutGuest(scene.target) : undefined,\n });\n ledger.judged.add(scene.target.id);\n reportHeld(scene, scene.target, verdict, {\n staged,\n excuse: scene.unchangedWhenHeld,\n hosted: Boolean(subjectIsGuest),\n });\n\n if (!host) return;\n for (const guest of ledger.guests) {\n if (guest.id === scene.target.id) continue;\n const fills =\n guest.slot.startsWith(`${host}.`) ||\n ledger.hostSlots.get(host)?.has(guest.slot) === true;\n if (!fills) continue;\n const guestVerdict = judgeHeld({\n live: pair.live.elements,\n held: pair.held.elements,\n hostOnly: await withoutGuest(guest),\n });\n // Not drawn in this scene at all.\n if (guestVerdict.drawn.live === 0 && guestVerdict.drawn.held === 0)\n continue;\n ledger.judged.add(guest.id);\n reportHeld(scene, guest, guestVerdict, {\n staged,\n excuse: undefined,\n hosted: true,\n });\n }\n}\n\nfunction reportHeld(\n scene: Scene,\n subject: SceneTarget,\n verdict: HeldVerdict,\n how: { staged: boolean; excuse: string | undefined; hosted: boolean },\n): void {\n const who = `${scene.name}: ${subject.kind} ${subject.id}`;\n if (how.excuse !== undefined && !verdict.unchanged) {\n throw new Error(\n `${who}: \"_scene.unchangedWhenHeld\" says this scene draws the same ` +\n `with the link dropped (\"${how.excuse}\"), and it no longer does: ` +\n `${verdict.changed} element(s) differ. Remove the field.`,\n );\n }\n if (verdict.unchanged && how.excuse === undefined) {\n throw new Error(\n `${who} draws exactly the same whether its figures are arriving or ` +\n `not${how.hosted ? \", once what its host draws for itself is taken out\" : \"\"}` +\n `${how.staged ? \"\" : ' (compared against this scene rendered again with \"_stream\": { \"stopsArriving\": true })'}. ` +\n `It draws ${verdict.drawn.live} element(s) live and ${verdict.drawn.held} with the link dropped, and they match. ` +\n \"An operator has no way to tell a held figure from a current one.\\n\" +\n \"Mark what is held the way the kit does: read the value as a Reading \" +\n \"and draw it through `Unit` (or a `Meter`/readout fed the reading), so \" +\n \"it carries the held dot and says when it was read, or say it \" +\n 'in words (\"held\", \"at last contact\"). A guest in a host that marks ' +\n \"itself is not covered by the host's mark: it reads its own data, so \" +\n \"it owns saying that data is held.\\n\" +\n \"If the subject draws no figure an operator could take for current (a \" +\n \"vocabulary, a control, a label), say so on its scene with \" +\n '\"_scene\": { \"unchangedWhenHeld\": \"<why>\" }.',\n );\n }\n if (verdict.unannounced.length > 0) {\n throw new Error(\n `${who}: with the link dropped it draws ${verdict.unannounced.length} ` +\n \"held mark(s) with no caption saying so, so the dot is on screen and a \" +\n \"screen reader is told nothing:\\n \" +\n `${verdict.unannounced.slice(0, 6).join(\"\\n \")}\\n` +\n \"Draw the figure through `Unit` or hand the kit instrument the reading, \" +\n \"each of which says its mark, rather than setting `data-held` by hand.\",\n );\n }\n if (verdict.unchanged) {\n console.log(\n ` held ${subject.id}: unchanged with the link dropped, excused: ${how.excuse}`,\n );\n return;\n }\n console.log(\n ` held ${subject.id}: ${verdict.changed} of ` +\n `${verdict.drawn.live}/${verdict.drawn.held} element(s) differ with the link dropped` +\n `${how.staged ? \"\" : \" (derived twin)\"}`,\n );\n for (const line of verdict.differences.slice(0, 2)) {\n console.log(\n ` ${line.length > 150 ? `${line.slice(0, 147)}...` : line}`,\n );\n }\n}\n\n/** Fails when two renders of one state differ, naming the first element that does. */\nfunction assertRendersRepeat(\n scene: Scene,\n control: SceneReport,\n fed: SceneReport,\n): void {\n const a = control.elements;\n const b = fed.elements;\n const at = a.findIndex((line, i) => line !== b[i]);\n if (at === -1 && a.length === b.length) return;\n const i = at === -1 ? Math.min(a.length, b.length) : at;\n throw new Error(\n `${scene.name} (${scene.target.kind} ${scene.target.id}): two renders of ` +\n \"the same state differ, so whether it changes when the link drops \" +\n \"cannot be read off a comparison.\\n\" +\n ` element ${i + 1}: ${a[i] ?? \"(none)\"} vs ${b[i] ?? \"(none)\"}\\n` +\n \"Something in the render is not pinned: a counter, a random id, a \" +\n \"clock the scene clock does not own.\",\n );\n}\n\n/**\n * A `StubTransport` is subscription-gated exactly as production is, so an emit\n * to a topic nothing subscribed to is dropped in silence and the render is of no\n * data. This turns that whole class of bug into a named error.\n */\nfunction assertEveryEmitLanded(scene: Scene, report: UnreadTopics): void {\n if (report.unsubscribedTopics.length === 0) return;\n throw new Error(\n `${scene.name} (${scene.target.kind} ${scene.target.id}): nothing in the ` +\n \"mounted tree subscribed to \" +\n `${report.unsubscribedTopics.length} emitted topic(s), so they were ` +\n \"dropped:\\n \" +\n `${report.unsubscribedTopics.join(\"\\n \")}\\n` +\n `Topics the registration declares: ${scene.declaredTopics.join(\", \") || \"(none)\"}\\n` +\n (report.undeclaredTopics.length > 0\n ? `Not declared at all: ${report.undeclaredTopics.join(\", \")}. ` +\n \"Add the topic to the target's `channels` / `optionalChannels` / \" +\n \"`channelFamilies` / `dataRequirements`, or drop it from the fixture.\\n\"\n : \"Declared, and nothing read it: either the target does not consume \" +\n \"the topic, or whatever gates the read never opened.\\n\"),\n );\n}\n\n/**\n * A motion scene, frame by frame off the PINNED clock.\n *\n * That is the whole difference between this and a screen recording: the clock is\n * an input, so the same fixture produces the same frames on any machine. A still\n * already answers \"what does this look like\"; motion earns its place only where\n * the thing the widget exists to show IS a change.\n */\nasync function captureMotion(\n tab: Page,\n scene: Scene,\n mode: { name: string; w: number; h: number; pxW: number; pxH: number },\n opts: RenderOptions,\n assets: RenderedAsset[],\n control?: SceneReport,\n): Promise<void> {\n const frames: Buffer[] = [];\n const framesDir = join(opts.outDir, `${scene.name}.frames`);\n if (opts.frames) await mkdir(framesDir, { recursive: true });\n await performActs(tab, scene);\n if (control) assertRendersRepeat(scene, control, await readScene(tab));\n // Before the first frame, and once: a step that drives a control has to be\n // able to REACH it, and `page.mouse` works in viewport coordinates. A control\n // below the fold of a scrolling tile is at a y nothing is under, so the press\n // landed on the page and the film came out thirty-four identical frames.\n // Doing it here rather than per frame also keeps the framing fixed, which a\n // scroll between two frames would not.\n await growToFullContent(tab);\n await fitViewportToRoot(tab);\n // The state before the first step is a frame in its own right: the reader has to see what changed FROM.\n frames.push(await shootFrame(tab, opts, framesDir, frames.length));\n // One shape per frame, so the film's shape is the SEQUENCE and a step that\n // stopped firing changes it. A GIF is the asset that most needs this: its\n // bytes differ between two encodes of an unchanged tree, so bytes cannot say\n // whether the film moved and the shape can.\n const captures: ShapeCapture[] = [await captureShape(tab)];\n let holding = false;\n for (const step of scene.steps ?? []) {\n const count = Math.max(1, step.frames ?? 1);\n const delta = (step.advanceUt ?? 0) / count;\n const wait = (step.waitMs ?? 0) / count;\n for (let i = 0; i < count; i++) {\n // The emit, the click and the pointer belong to the step's FIRST frame\n // only; repeating them would re-emit once per frame and mean something\n // else. `waitMs` is the exception, being an amount rather than an event.\n if (i === 0 && step.hold) {\n await holdPointer(tab, scene, step.hold);\n holding = true;\n }\n if (i === 0 && step.release) {\n await tab.mouse.up();\n holding = false;\n }\n // `waitMs` is divided, not repeated: the probe moves the scene clock that much per frame, the way `advanceUt` is divided.\n const perFrame: SceneStep =\n i === 0\n ? { ...step, frames: 1, waitMs: wait }\n : { frames: 1, waitMs: wait };\n await tab.evaluate(\n ([key, s, d]) =>\n globalThis[key as typeof RENDER_PROBE_GLOBAL].stepScene(\n s as SceneStep,\n d as number,\n ),\n [RENDER_PROBE_GLOBAL, perFrame, delta] as const,\n );\n frames.push(await shootFrame(tab, opts, framesDir, frames.length));\n captures.push(await captureShape(tab));\n }\n }\n // A pointer left down outlives the scene and lands on whatever mounts next.\n if (holding) await tab.mouse.up();\n assertMotionMoved(scene, frames);\n const gif = encodeGif(frames, scene.motion);\n const file = `${scene.name}--${mode.name}.gif`;\n if (scene.hero) warnOnExtremeAspectRatio(scene, file, frames[0]);\n await writeFile(join(opts.outDir, file), gif);\n assets.push({\n scene,\n mode: mode.name,\n file,\n kind: \"motion\",\n shape: foldShape(captures),\n });\n console.log(` ${file} (${frames.length} frames @ ${scene.motion.fps}fps)`);\n}\n\n/**\n * A motion scene whose frames are all the same byte-for-byte is a film of\n * nothing.\n *\n * The still path has the fed-versus-starved comparison and a motion scene had\n * no equivalent, so a GIF announcing thirty-four frames was indistinguishable\n * from one where every step missed. That is not hypothetical: it is how a\n * `hold` step reaching a control the page had scrolled past was found, having\n * produced a perfectly well-formed film of a widget sitting still.\n */\nfunction assertMotionMoved(scene: Scene, frames: readonly Buffer[]): void {\n const first = frames[0];\n if (!first || frames.every((frame) => frame.equals(first))) {\n throw new Error(\n `${scene.name} (${scene.target.kind} ${scene.target.id}): all ` +\n `${frames.length} frames of this motion scene are IDENTICAL, so the ` +\n \"film shows nothing happening. Either the steps did not reach what \" +\n \"they name, or this scene has no motion in it and wants to be a still.\",\n );\n }\n}\n\n/**\n * A picture stretched past 4:1 either way is impractical in a README: too\n * wide to read without a horizontal scroll, or too tall to see in one\n * screenful. A WARNING rather than a failure, since a genuinely thin strip (an\n * action-group row) or a genuinely tall one (a terminal) is still a real,\n * honest shape for that widget, just one worth a human glancing at before it\n * ships.\n *\n * Callers gate this on `scene.hero` (and, for a still, on it being the first\n * mode): those are the only renders `docs.ts` ever puts in the page, so a\n * warning about every other render would be about a picture nobody will see.\n */\nconst MAX_ASPECT_RATIO = 4;\n\nfunction warnOnExtremeAspectRatio(\n scene: Scene,\n file: string,\n png: Buffer,\n): void {\n const { width, height } = pngSize(png);\n const ratio = Math.max(width, height) / Math.min(width, height);\n if (ratio <= MAX_ASPECT_RATIO) return;\n const shape = width > height ? \"wide\" : \"tall\";\n console.warn(\n `\\n warning: ${file} is ${width}×${height}px, ${ratio.toFixed(1)}:1 and ` +\n `very ${shape}. That is impractical to read inline in a README; worth a ` +\n `look before it ships as ${scene.target.kind} ${scene.target.id}'s picture.`,\n );\n}\n\n/** Presses the pointer on a named control and drags it, without letting go. */\nasync function holdPointer(\n tab: Page,\n scene: Scene,\n hold: NonNullable<SceneStep[\"hold\"]>,\n): Promise<void> {\n const control = tab\n .getByRole((hold.role ?? \"slider\") as Parameters<Page[\"getByRole\"]>[0], {\n name: hold.name,\n })\n .first();\n await control.scrollIntoViewIfNeeded().catch(() => {});\n const box = await control.boundingBox().catch(() => null);\n if (box === null) {\n throw new Error(\n `${scene.name}: a \"hold\" step names \"${hold.name}\", which is not laid ` +\n \"out. A control that is not on screen cannot be dragged, and the frames \" +\n \"after this step would be a film of nothing happening.\",\n );\n }\n const x = box.x + box.width / 2;\n const y = box.y + box.height / 2;\n await tab.mouse.move(x, y);\n await tab.mouse.down();\n // Stepped rather than jumped: a drag handler reading movement per event sees one enormous delta from a teleport and nothing resembling a drag.\n await tab.mouse.move(x + (hold.dx ?? 0), y + (hold.dy ?? 0), { steps: 8 });\n}\n\nasync function shootFrame(\n tab: Page,\n opts: RenderOptions,\n framesDir: string,\n index: number,\n): Promise<Buffer> {\n const path = opts.frames\n ? join(framesDir, `${String(index).padStart(3, \"0\")}.png`)\n : undefined;\n const root = await tab.$(\"#root\");\n if (!root) throw new Error(\"render: #root vanished mid-motion\");\n return root.screenshot({ path, animations: \"disabled\" });\n}\n\n/** Wipe this tool's own artifacts so a removed scene leaves no orphan. Only the\n * two extensions it writes, so a sibling directory is never destroyed. */\nasync function cleanPngsAndGifs(dir: string): Promise<void> {\n let entries: string[] = [];\n try {\n entries = await readdir(dir);\n } catch {\n return;\n }\n for (const entry of entries) {\n if (entry.endsWith(\".png\") || entry.endsWith(\".gif\")) {\n await rm(join(dir, entry));\n }\n }\n}\n","/**\n * Grow `#root` until nothing it can reveal is clipped, and no further.\n *\n * Passed to `tab.evaluate`, so it closes over nothing and declares no named\n * function inside: tsx's `keepNames` wraps one in a `__name(...)` helper that\n * exists in the module scope and not the serialised page context.\n *\n * Every clipping box under the root is measured, found rather than listed: a\n * `Panel`'s body is the scroller in this kit and carries no marker, so a\n * hand-kept list of the ways content hides goes stale silently. The root grows\n * by the largest overflow and the tree is measured again, because growing can\n * reveal a little more.\n *\n * Only an overflow the root's height governs is worth growing for. A box of a\n * fixed height clips the same amount at any root height: a screen-reader-only\n * label clipped to 1px, or a list with its own `max-height`. After each growth\n * a box whose overflow did not shrink is set aside for good, and a growth made\n * on behalf of such a box is undone, so the root grows no taller than the\n * content it reveals.\n */\nexport const growRootToContent = (): void => {\n const el = document.getElementById(\"root\");\n if (!el) return;\n el.style.overflow = \"visible\";\n const fixed = new Set<Element>();\n let measured = new Map<Element, number>();\n let driver: Element | undefined;\n let heightBefore = el.style.height;\n let grew = false;\n for (let i = 0; i < 16; i++) {\n const overflows = new Map<Element, number>();\n const boxes: Element[] = [el, ...el.querySelectorAll(\"*\")];\n for (const node of boxes) {\n const over = node.scrollHeight - node.clientHeight;\n if (over <= 1) continue;\n if (node !== el && getComputedStyle(node).overflowY === \"visible\") {\n continue;\n }\n overflows.set(node, over);\n }\n if (grew) {\n for (const [node, over] of measured) {\n if ((overflows.get(node) ?? 0) >= over) fixed.add(node);\n }\n grew = false;\n if (driver && fixed.has(driver)) {\n el.style.height = heightBefore;\n void el.offsetHeight;\n continue;\n }\n }\n let need = 0;\n driver = undefined;\n for (const [node, over] of overflows) {\n if (fixed.has(node) || over <= need) continue;\n need = over;\n driver = node;\n }\n if (!driver) break;\n measured = overflows;\n heightBefore = el.style.height;\n el.style.height = `${el.clientHeight + need}px`;\n void el.offsetHeight;\n grew = true;\n }\n};\n","import type { ScenePayload, SceneReport } from \"../render-probe\";\nimport { UNANNOUNCED_MARK } from \"./probe-global\";\nimport type { Scene } from \"./scenes\";\n\n/**\n * Whether a subject says the link has gone, judged from two renders of one\n * scene: live, and with the link dropped.\n *\n * <p>Every render the harness takes of a stream-fed scene gets a twin with the\n * other `stopsArriving` value, so an Uplink needs no held fixture for its\n * widgets to be held to this. A scene that already stages the drop is compared\n * with itself fed live; one that does not is compared with itself dropped.</p>\n *\n * <p>Two ways to fail. UNCHANGED: the subject draws exactly the same elements\n * both ways, so an operator has nothing to tell a figure from twenty minutes ago\n * from one that just arrived. UNANNOUNCED: the subject draws a held mark with\n * no caption, so the dot is there and a screen reader is told nothing.</p>\n *\n * <p>A guest drawn inside a real host is judged on what IT draws. The host may\n * mark its own readings, and a render that changed only because the host did is\n * the case this exists for: a correctly marked panel carrying a figure nobody\n * marked. So a hosted scene is also rendered with its guest withheld, in both\n * states, and the guest's elements are what is left after the host's are taken\n * away.</p>\n */\nexport interface HeldRenders {\n live: readonly string[];\n held: readonly string[];\n /** The same two renders with the guest withheld, for a hosted scene. */\n hostOnly?: { live: readonly string[]; held: readonly string[] };\n}\n\nexport interface HeldVerdict {\n /** The subject drew the same elements live and with the link dropped. */\n unchanged: boolean;\n /** How many of the subject's elements differ between the two, counted both ways. */\n changed: number;\n /** The differing elements, `-` drawn only live and `+` only with the link dropped. */\n differences: string[];\n /** How many elements the subject drew live, and with the link dropped, bare wrappers not counted. */\n drawn: { live: number; held: number };\n /** Elements the subject drew held with no caption saying so. */\n unannounced: string[];\n}\n\n/** What `from` has that `take` does not, counting repeats. */\nexport function multisetMinus(\n from: readonly string[],\n take: readonly string[],\n): string[] {\n const left = new Map<string, number>();\n for (const line of take) left.set(line, (left.get(line) ?? 0) + 1);\n const out: string[] = [];\n for (const line of from) {\n const n = left.get(line) ?? 0;\n if (n > 0) left.set(line, n - 1);\n else out.push(line);\n }\n return out;\n}\n\n/**\n * An element with no text of its own and nothing but a class: a layout wrapper.\n * See {@link judgeHeld} for when one is not counted.\n */\nfunction isBareWrapper(line: string): boolean {\n return /^<[a-z0-9-]+ (class=\"[^\"]*\")?> $/.test(line);\n}\n\nfunction tagOf(line: string): string {\n return line.slice(1, line.indexOf(\" \"));\n}\n\n/**\n * Drop a bare wrapper that appears on one side only with no bare wrapper of its\n * tag on the other. A layout box a host adds or removes around its guest says\n * nothing to an operator; the same box restyled (a dimmed class in place of a\n * lit one) appears on both sides and is kept.\n */\nfunction withoutLoneWrappers(\n gone: readonly string[],\n added: readonly string[],\n): { gone: string[]; added: string[] } {\n const bareTags = (lines: readonly string[]) =>\n new Set(lines.filter(isBareWrapper).map(tagOf));\n const goneTags = bareTags(gone);\n const addedTags = bareTags(added);\n return {\n gone: gone.filter((l) => !isBareWrapper(l) || addedTags.has(tagOf(l))),\n added: added.filter((l) => !isBareWrapper(l) || goneTags.has(tagOf(l))),\n };\n}\n\nexport function judgeHeld(renders: HeldRenders): HeldVerdict {\n const subjectLive = renders.hostOnly\n ? multisetMinus(renders.live, renders.hostOnly.live)\n : renders.live;\n const subjectHeld = renders.hostOnly\n ? multisetMinus(renders.held, renders.hostOnly.held)\n : renders.held;\n const { gone, added } = withoutLoneWrappers(\n multisetMinus(subjectLive, subjectHeld),\n multisetMinus(subjectHeld, subjectLive),\n );\n const differences = [\n ...gone.map((line) => `- ${line}`),\n ...added.map((line) => `+ ${line}`),\n ];\n const changed = differences.length;\n const unchanged = changed === 0;\n return {\n unchanged,\n changed,\n differences,\n drawn: {\n live: subjectLive.filter((l) => !isBareWrapper(l)).length,\n held: subjectHeld.filter((l) => !isBareWrapper(l)).length,\n },\n unannounced: subjectHeld.filter((line) => line.endsWith(UNANNOUNCED_MARK)),\n };\n}\n\n/** The page calls one held render is made of. */\nexport interface HeldStage {\n /** Mount the scene with the drop held back. */\n mount(payload: ScenePayload): Promise<SceneReport>;\n act(scene: Scene, missing: \"throw\" | \"skip\"): Promise<void>;\n refeed(): Promise<void>;\n /** Drop the link if the payload stops arriving, then read the render. */\n finish(): Promise<SceneReport>;\n read(): Promise<SceneReport>;\n}\n\n/**\n * One render of a scene for the held comparison, live or dropped as the\n * payload says, in the state the scene pictures.\n *\n * <p>The render in the scene's own state is the fed render again, so it drops\n * the link where the fed render does, before the presses. The twin with the\n * other state holds its drop until the presses have run: a scene driven by\n * presses is judged pressed, and a link that goes after them is the order an\n * operator meets it.</p>\n *\n * <p>A still is refed after the presses, as its picture is; a motion scene is\n * not, because its first frame is taken before the refeed. With a guest\n * withheld, a press that finds no control is skipped: the control was the\n * guest's, and the host without it is in the state the press leaves it.</p>\n */\nexport async function mountForHeld(\n stage: HeldStage,\n scene: Scene,\n payload: ScenePayload,\n): Promise<SceneReport> {\n const twin =\n (payload.stopsArriving === true) !== (scene.stopsArriving === true);\n await stage.mount({ ...payload, holdDrop: true });\n if (!twin) await stage.finish();\n await stage.act(scene, payload.withhold ? \"skip\" : \"throw\");\n if (!(scene.steps && scene.steps.length > 0)) await stage.refeed();\n return twin ? stage.finish() : stage.read();\n}\n"],"mappings":";;;;;;;;;;;;AAAA,IAAO,IAAQ,EACb,WAAW,OACX,SAAS,OACT,SAAS,IACT,qBAAqB,IACrB,2BAA2B,KAC3B,8BAA8B,KAC9B,gBAAgB,IAEhB,eAAe,GACf,aAAa,GACb,0BAA0B,KAC1B,qBAAqB,KACrB,cAAc,GACd,0BAA0B,GAE1B,2BAA2B,GAC3B,yBAAyB,GAEzB,oBAAoB,IACpB,mBAAmB,GACnB,0BAA0B,GAE1B,yBAAyB,KACzB,mBAAmB,IACnB,gBAAgB,IAChB,yBAAyB,EAAA;AC1BZ,SAAA,EAAsB,IAAkB,KAAK;AAC1D,MAAI,IAAS,GACT,IAAW,IAAI,WAAW,CAAA;AAE9B,SAAO,EAAA,IACD,SAAS;AACX,WAAO,EAAS;EAAA,GAElB,QAAQ;AACN,QAAS;EAAA,GAEX,YAAY;AACV,WAAO,EAAS,SAAS,GAAG,CAAA;EAAA,GAE9B,QAAQ;AACN,WAAO,EAAS,MAAM,GAAG,CAAA;EAAA,GAE3B,UAAU,GAAM;AACd,MAAO,IAAS,CAAA,GAChB,EAAS,CAAA,IAAU,GACnB;EAAA,GAEF,WAAW,GAAM,IAAS,GAAG,IAAa,EAAK,QAAQ;AACrD,MAAO,IAAS,CAAA;AAChB,aAAS,IAAI,GAAG,IAAI,GAAY,IAC9B,GAAS,GAAA,IAAY,EAAK,IAAI,CAAA;EAAA,GAGlC,eAAe,GAAM,IAAS,GAAG,IAAa,EAAK,YAAY;AAC7D,MAAO,IAAS,CAAA,GAChB,EAAS,IAAI,EAAK,SAAS,GAAQ,IAAS,CAAA,GAAa,CAAA,GACzD,KAAU;EAAA,EAAA;AAId,WAAA,EAAgB,GAAa;AAC3B,QAAI,IAAe,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M,IAAI,IAAI,IAAI,IAAI,QAAQ;AAC9B,QAAM,IAAI,IAAI,IAAI,IAAI,SAAS;AAC/B,QAAM,IAAI,MAAM,KAAK,GAAG,CAAC;AACzB,QAAM,IAAI,MAAM,KAAK;AAErB,QAAM,IAAI,MAAM,KAAK,KAAK,KAAK,MAAM,IAAI,KAAK,KAAK,MAAM,IAAI,EAAE,OAAO,EAAE,CAAC;AAC3E;AAEA,eAAe,WACb,KACA,MACA,WACA,OACiB;AACjB,QAAM,OAAO,KAAK,SACdA,MAAK,WAAW,GAAG,OAAO,KAAK,EAAE,SAAS,GAAG,GAAG,CAAC,MAAM,IACvD;AACJ,QAAM,OAAO,MAAM,IAAI,EAAE,OAAO;AAChC,MAAI,CAAC,KAAM,OAAM,IAAI,MAAM,mCAAmC;AAC9D,SAAO,KAAK,WAAW,EAAE,MAAM,YAAY,WAAW,CAAC;AACzD;AAIA,eAAe,iBAAiB,KAA4B;AAC1D,MAAI,UAAoB,CAAC;AACzB,MAAI;AACF,cAAU,MAAM,QAAQ,GAAG;AAAA,EAC7B,QAAQ;AACN;AAAA,EACF;AACA,aAAW,SAAS,SAAS;AAC3B,QAAI,MAAM,SAAS,MAAM,KAAK,MAAM,SAAS,MAAM,GAAG;AACpD,YAAMI,IAAGJ,MAAK,KAAK,KAAK,CAAC;AAAA,IAC3B;AAAA,EACF;AACF;","names":["require","at","existsSync","writeFile","join","engine","rm","writeFile","join","writeFile","join","resolve","at","i","rm"]}