@occluze/umber 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/README.md +93 -47
  2. package/THIRD-PARTY-NOTICES.md +33 -0
  3. package/dist/chunks/badge.js +2 -2
  4. package/dist/chunks/basis.js +2 -2
  5. package/dist/chunks/batches.js +2 -0
  6. package/dist/chunks/capture.js +2 -2
  7. package/dist/chunks/covers.js +2 -2
  8. package/dist/chunks/curves.js +2 -2
  9. package/dist/chunks/flip.js +2 -2
  10. package/dist/chunks/fx.js +2 -2
  11. package/dist/chunks/gl.js +2 -2
  12. package/dist/chunks/glsl.js +2 -2
  13. package/dist/chunks/glyphs.js +2 -0
  14. package/dist/chunks/inspect.js +2 -2
  15. package/dist/chunks/instances.js +2 -2
  16. package/dist/chunks/layers.js +2 -2
  17. package/dist/chunks/licence.js +2 -2
  18. package/dist/chunks/morph.js +2 -2
  19. package/dist/chunks/pace.js +2 -0
  20. package/dist/chunks/patch.js +2 -2
  21. package/dist/chunks/prepared.js +2 -2
  22. package/dist/chunks/profiler.js +2 -2
  23. package/dist/chunks/recheck.js +2 -0
  24. package/dist/chunks/resize.js +2 -0
  25. package/dist/chunks/restore.js +2 -2
  26. package/dist/chunks/shapes.js +2 -2
  27. package/dist/chunks/sim.js +2 -2
  28. package/dist/chunks/text.js +2 -2
  29. package/dist/chunks/video.js +2 -2
  30. package/dist/chunks/vocabulary.js +2 -2
  31. package/dist/chunks/warm.js +2 -2
  32. package/dist/modules/debug.js +2 -2
  33. package/dist/modules/debug.mjs +2 -2
  34. package/dist/modules/handoff.js +2 -2
  35. package/dist/modules/handoff.mjs +2 -2
  36. package/dist/modules/input.js +2 -2
  37. package/dist/modules/input.mjs +2 -2
  38. package/dist/modules/scrollfx.js +2 -2
  39. package/dist/modules/scrollfx.mjs +2 -2
  40. package/dist/modules/scrub.js +2 -2
  41. package/dist/modules/scrub.mjs +2 -2
  42. package/dist/modules/three.js +2 -2
  43. package/dist/modules/three.mjs +2 -2
  44. package/dist/node/assets.mjs +4 -2
  45. package/dist/node/astro.mjs +26 -18
  46. package/dist/node/cli.mjs +63 -10
  47. package/dist/node/shared-P6KINBNR.mjs +2113 -0
  48. package/dist/node/{shared-4FIU6DYP.mjs → shared-VQKZUUXF.mjs} +106 -17
  49. package/dist/node/vite.mjs +7 -3
  50. package/dist/prepared.mjs +2 -0
  51. package/dist/umber.css +1 -1
  52. package/dist/umber.js +2 -2
  53. package/dist/umber.mjs +2 -2
  54. package/docs/AI-quick.md +43 -87
  55. package/docs/AI.md +1965 -1828
  56. package/docs/npm.md +13 -16
  57. package/package.json +31 -48
  58. package/types/assets.d.ts +109 -4
  59. package/types/astro.d.ts +20 -23
  60. package/types/debug.d.ts +1 -1
  61. package/types/esm.d.ts +2 -6
  62. package/types/input.d.ts +3 -3
  63. package/types/loop.d.ts +21 -9
  64. package/types/module.d.ts +0 -2
  65. package/types/scrollfx.d.ts +5 -41
  66. package/types/scrub.d.ts +2 -2
  67. package/types/three.d.ts +26 -1
  68. package/types/umber.d.ts +152 -155
  69. package/types/vite.d.ts +3 -3
  70. package/dist/chunks/views.js +0 -2
  71. package/dist/frameworks/astro.mjs +0 -2
  72. package/dist/frameworks/react.mjs +0 -2
  73. package/dist/frameworks/svelte.mjs +0 -2
  74. package/dist/frameworks/vue.mjs +0 -2
  75. package/dist/modules/router-swap.js +0 -2
  76. package/dist/modules/router.js +0 -2
  77. package/dist/modules/router.mjs +0 -2
  78. package/dist/modules/scroll-more.js +0 -2
  79. package/dist/modules/scroll-touch.js +0 -2
  80. package/dist/modules/scroll.js +0 -2
  81. package/dist/modules/scroll.mjs +0 -2
  82. package/dist/node/shared-3Q24RNIF.mjs +0 -602
  83. package/types/react.d.ts +0 -15
  84. package/types/router.d.ts +0 -223
  85. package/types/scroll.d.ts +0 -190
  86. package/types/svelte.d.ts +0 -16
  87. package/types/vue.d.ts +0 -14
@@ -0,0 +1,2113 @@
1
+ /*! Umber v0.4.0 asset tool | (c) Ravi Klaassens | UNLICENSED */
2
+
3
+ // src/gl/glsl/names.ts
4
+ var GLSL_CALL = /\b(?:(?:quad|cubic|quart|quint|sine|expo|circ)(?:In|Out|B)|stagger|[sp]noise|cellular|sd[A-Z]|op[A-Z]|aa|blend[A-Z]|bayer|blueNoise|dither|srgbTo|linearTo|oklabTo|mixOklab|noise|fbm|rotate2d|screen[UP]|samplePrev|flowSmooth|textureSmooth|umber[A-Z])\w*\s*\(|\buScreen\b/;
5
+
6
+ // src/gl/effect-needs.ts
7
+ var SWAPS = /\bu(Prev|Swap)\b/;
8
+ var GLYPH_CALL = /\bglyph\s*\(/;
9
+ var effectNeeds = (glsl, options2 = {}) => ({
10
+ glsl: glsl.includes("#include" /* include */) || GLSL_CALL.test(glsl) || "perspective" /* perspective */ in options2,
11
+ backdrop: glsl.includes("uBackdrop" /* backdrop */),
12
+ flow: glsl.includes("uFlow" /* flow */),
13
+ swap: SWAPS.test(glsl) || /\bsamplePrev\s*\(/.test(glsl),
14
+ glyph: GLYPH_CALL.test(glsl)
15
+ });
16
+
17
+ // tools/assets/html.ts
18
+ var VOID = /* @__PURE__ */ new Set([
19
+ "area",
20
+ "base",
21
+ "br",
22
+ "col",
23
+ "embed",
24
+ "hr",
25
+ "img",
26
+ "input",
27
+ "link",
28
+ "meta",
29
+ "param",
30
+ "source",
31
+ "track",
32
+ "wbr"
33
+ ]);
34
+ var RAW = /* @__PURE__ */ new Set(["script", "style", "template", "textarea", "title"]);
35
+ var ATTRIBUTE = /([^\s"'=<>/`]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
36
+ function attributes(body) {
37
+ const found = /* @__PURE__ */ new Map();
38
+ for (const match of body.matchAll(ATTRIBUTE)) {
39
+ const name = match[1]?.toLowerCase();
40
+ if (!name || found.has(name)) continue;
41
+ found.set(name, decode(match[2] ?? match[3] ?? match[4] ?? ""));
42
+ }
43
+ return found;
44
+ }
45
+ function decode(value) {
46
+ return value.replace(/&(amp|quot|apos|lt|gt|#39|#x27);/g, (_, entity) => {
47
+ const words = { amp: "&", quot: '"', apos: "'", lt: "<", gt: ">", "#39": "'", "#x27": "'" };
48
+ return words[entity] ?? "";
49
+ });
50
+ }
51
+ var SPACE = /\s/;
52
+ function skip(text, i, test) {
53
+ while (i < text.length && test(text.charAt(i))) i++;
54
+ return i;
55
+ }
56
+ function srcsetUrls(srcset) {
57
+ const urls = [];
58
+ let i = 0;
59
+ while (i < srcset.length) {
60
+ const start = skip(srcset, i, (char) => SPACE.test(char) || char === ",");
61
+ i = skip(srcset, start, (char) => !SPACE.test(char));
62
+ const url = srcset.slice(start, i);
63
+ if (!url.endsWith(",")) i = skip(srcset, i, (char) => char !== ",");
64
+ const clean = url.replace(/,+$/, "");
65
+ if (clean) urls.push(clean);
66
+ }
67
+ return urls;
68
+ }
69
+ function close(stack, name) {
70
+ const at = stack.map((open) => open.name).lastIndexOf(name);
71
+ if (at >= 0) stack.length = at;
72
+ }
73
+ function pictureOf(parent, name, attrs) {
74
+ const picture = parent?.name === "picture" ? parent.picture : void 0;
75
+ if (picture && name === "source" && (attrs.has("media") || attrs.has("type"))) picture.chooses = true;
76
+ return picture;
77
+ }
78
+ var PLANE_KINDS = /* @__PURE__ */ new Set(["image", "video", "text", "shader", "layer", "model", "group"]);
79
+ var drawsGl = (words) => !!words && words.split(/\s+/).some((word) => PLANE_KINDS.has(word));
80
+ var opened = (name, gl, end) => name === "picture" ? { name, gl, picture: { end, chooses: false } } : { name, gl };
81
+ function glTags(html) {
82
+ const tags = [];
83
+ const stack = [];
84
+ const lower = html.toLowerCase();
85
+ const tag = /<!--[\s\S]*?-->|<(\/?)([a-zA-Z][\w:-]*)([^>]*)>/g;
86
+ for (let match = tag.exec(html); match; match = tag.exec(html)) {
87
+ const [, closing, rawName, body = ""] = match;
88
+ const name = rawName?.toLowerCase();
89
+ if (!name) continue;
90
+ if (closing) {
91
+ close(stack, name);
92
+ continue;
93
+ }
94
+ const attrs = attributes(body);
95
+ const parent = stack.at(-1);
96
+ const picture = pictureOf(parent, name, attrs);
97
+ const gl = drawsGl(attrs.get("data-umber")) || parent?.gl === true;
98
+ if (gl) tags.push({ name, attrs, start: match.index, end: tag.lastIndex, picture });
99
+ if (RAW.has(name)) {
100
+ const end = lower.indexOf(`</${name}`, tag.lastIndex);
101
+ tag.lastIndex = end < 0 ? html.length : end;
102
+ } else if (!VOID.has(name) && !body.trimEnd().endsWith("/")) stack.push(opened(name, gl, tag.lastIndex));
103
+ }
104
+ return tags;
105
+ }
106
+ function drawnPictures(html) {
107
+ const found = /* @__PURE__ */ new Set();
108
+ for (const { name, attrs } of glTags(html)) collect(name, attrs, found);
109
+ return [...found];
110
+ }
111
+ function collect(name, attrs, found) {
112
+ const add = (url) => {
113
+ if (url && !url.startsWith("data:") && !url.startsWith("blob:")) found.add(url);
114
+ };
115
+ add(attrs.get("data-umber-src"));
116
+ if (name === "img") add(attrs.get("src"));
117
+ if (name === "img" || name === "source" && attrs.get("type") !== "image/avif")
118
+ for (const url of srcsetUrls(attrs.get("srcset") ?? "")) add(url);
119
+ }
120
+ var escape = (value) => value.replace(/&/g, "&amp;").replace(/"/g, "&quot;");
121
+ function avifSrcset(attrs, replace) {
122
+ const src = attrs.get("src") ?? "";
123
+ const srcset = attrs.get("srcset") ?? "";
124
+ let changed = srcset;
125
+ for (const url of srcsetUrls(srcset)) changed = changed.replace(url, replace(url) ?? url);
126
+ const implicit = src && !/\d\s*w\s*(,|$)|\s1x\s*(,|$)/.test(srcset);
127
+ const fromSrc = implicit ? replace(src) : null;
128
+ if (changed === srcset && !fromSrc) return null;
129
+ return implicit ? [`${fromSrc ?? src}${srcset ? " 1x" : ""}`, changed].filter(Boolean).join(", ") : changed;
130
+ }
131
+ function tinySource(attrs, tiny) {
132
+ const srcset = attrs.get("srcset") ?? "";
133
+ const urls = srcsetUrls(srcset);
134
+ const found = tiny([attrs.get("src"), urls.at(-1)].find(Boolean) ?? "");
135
+ if (!found) return "";
136
+ const widths = /\d\s*w\s*(,|$)/.test(srcset);
137
+ const density = Math.round(found.width / found.fullWidth * 1e5) / 1e5;
138
+ const sizes = attrs.get("sizes");
139
+ const candidate = `${found.url} ${widths ? `${found.width}w` : `${density}x`}`;
140
+ return `<source type="image/avif" media="(scripting: enabled)" srcset="${escape(candidate)}"${widths && sizes ? ` sizes="${escape(sizes)}"` : ""} data-umber-tiny>`;
141
+ }
142
+ function rewritePictures(html, replace, tiny) {
143
+ const edits = [];
144
+ for (const { name, attrs, start, end, picture } of glTags(html)) {
145
+ if (name !== "img" || picture?.chooses) continue;
146
+ const srcset = avifSrcset(attrs, replace);
147
+ if (!srcset) continue;
148
+ const sizes = attrs.get("sizes");
149
+ const source = `${tiny ? tinySource(attrs, tiny) : ""}<source type="image/avif" srcset="${escape(srcset)}"${sizes ? ` sizes="${escape(sizes)}"` : ""}>`;
150
+ if (picture) edits.push({ at: picture.end, end: picture.end, text: source });
151
+ else edits.push({ at: start, end, text: `<picture data-umber-avif>${source}${html.slice(start, end)}</picture>` });
152
+ }
153
+ let out = "";
154
+ let at = 0;
155
+ for (const edit of edits.sort((a, b) => a.at - b.at)) {
156
+ out += html.slice(at, edit.at) + edit.text;
157
+ at = edit.end;
158
+ }
159
+ return out + html.slice(at);
160
+ }
161
+ var FALLBACK = `(()=>{const f=()=>{if(!window.__umber)for(const s of document.querySelectorAll("source[data-umber-tiny]")){const n=s.nextElementSibling,d=()=>{s.remove()};if(n&&s.parentNode.querySelector("img")?.naturalWidth){const i=new Image;i.sizes=n.sizes;i.srcset=n.srcset;i.decode().then(d,d)}else d()}},t=()=>{setTimeout(f,3e3)};document.readyState==="complete"?t():addEventListener("load",t,{once:!0})})();
162
+ `;
163
+ function withFallback(html, url) {
164
+ const tag = `<script src="${url.replace(/"/g, "&quot;")}" defer data-umber-images></script>`;
165
+ const existing = /<script[^>]*\bdata-umber-images\b[^>]*><\/script>/i;
166
+ return existing.test(html) ? html.replace(existing, tag) : inHead(html, tag);
167
+ }
168
+ var DATA_FETCH = 'as="fetch"';
169
+ function withManifest(html, manifest) {
170
+ const url = manifest.replace(/"/g, "&quot;");
171
+ const tag = `<meta name="umber-assets" content="${url}"><link rel="preload" href="${url}" ${DATA_FETCH} data-umber-assets>`;
172
+ const existing = /<meta\s+name=["']?umber-assets["']?[^>]*>(<link[^>]*data-umber-assets[^>]*>)?/i;
173
+ return existing.test(html) ? html.replace(existing, tag) : inHead(html, tag);
174
+ }
175
+ function inHead(html, tag) {
176
+ const head = /<\/head\s*>/i.exec(html);
177
+ if (head) return `${html.slice(0, head.index)}${tag}${html.slice(head.index)}`;
178
+ const open = /<head[^>]*>/i.exec(html);
179
+ if (open) return `${html.slice(0, open.index + open[0].length)}${tag}${html.slice(open.index + open[0].length)}`;
180
+ return `${tag}${html}`;
181
+ }
182
+
183
+ // tools/assets/hints.ts
184
+ var CHECK = "https://umber.occluze.com";
185
+ var ADD_ONS = ["scrub", "debug", "input", "handoff", "scrollfx", "three"];
186
+ var BY_WORD = { text: "text", group: "fx", layer: "layers", model: "layers" };
187
+ var BY_ATTRIBUTE = [
188
+ ["data-umber-scrub", "video"],
189
+ ["data-umber-instances", "instances"],
190
+ ["data-umber-id", "morph"],
191
+ ["data-umber-placeholder", "warm"]
192
+ ];
193
+ function pageChunks(html) {
194
+ const tags = glTags(html);
195
+ if (!tags.length) return [];
196
+ const chunks = /* @__PURE__ */ new Set(["gl"]);
197
+ for (const { name, attrs } of tags) {
198
+ for (const word of (attrs.get("data-umber") ?? "").split(/\s+/)) {
199
+ const chunk = BY_WORD[word];
200
+ if (chunk) chunks.add(chunk);
201
+ }
202
+ if (name === "video") chunks.add("video");
203
+ for (const [attribute, chunk] of BY_ATTRIBUTE) if (attrs.has(attribute)) chunks.add(chunk);
204
+ }
205
+ if (/<[a-z][^>]*\sdata-umber-pass\b/i.test(html)) chunks.add("fx");
206
+ return [...chunks];
207
+ }
208
+ var PICTURE_VALUE = /\.(?:jpe?g|png|webp|gif|avif)(?:[?#]|$)/i;
209
+ function effectHints(definition) {
210
+ const blocks2 = [...Object.values(definition.vertex ?? {}), ...Object.values(definition.fragment ?? {})];
211
+ const glsl = blocks2.filter((block) => typeof block === "string").join("\n");
212
+ const needs = effectNeeds(glsl, definition.options);
213
+ const chunks = /* @__PURE__ */ new Set();
214
+ if (needs.glsl) chunks.add("glsl");
215
+ if (needs.backdrop) chunks.add("fx");
216
+ if (needs.flow) chunks.add("fx").add("sim");
217
+ if (needs.swap) chunks.add("flip");
218
+ if (needs.glyph) chunks.add("text").add("glyphs");
219
+ const pictures = Object.values(definition.options ?? {}).filter(
220
+ (value) => typeof value === "string" && PICTURE_VALUE.test(value)
221
+ );
222
+ return {
223
+ chunks: [...chunks],
224
+ head: [definition.vertex?.head, definition.fragment?.head].some(Boolean),
225
+ ...pictures.length ? { pictures } : {}
226
+ };
227
+ }
228
+ function effectChunks(html, effects, shaders = /* @__PURE__ */ new Map()) {
229
+ if (!effects.size && !shaders.size) return [];
230
+ const chunks = /* @__PURE__ */ new Set();
231
+ for (const { attrs } of glTags(html)) {
232
+ if (!drawsGl(attrs.get("data-umber"))) continue;
233
+ const named = namedHints(attrs, effects, shaders);
234
+ for (const needs of named) for (const chunk of needs.chunks) chunks.add(chunk);
235
+ if (named.filter((needs) => needs.head).length > 1) chunks.add("glsl");
236
+ }
237
+ return [...chunks];
238
+ }
239
+ function namedHints(attrs, effects, shaders) {
240
+ const named = (attrs.get("data-umber-effect") ?? "").split(/\s+/).flatMap((name) => effects.get(name) ?? []);
241
+ const shader = shaders.get(attrs.get("data-umber-shader") ?? "");
242
+ return shader ? [...named, shader] : named;
243
+ }
244
+ function uniformPictures(html, effects, shaders = /* @__PURE__ */ new Map()) {
245
+ const pictures = /* @__PURE__ */ new Set();
246
+ for (const { attrs } of glTags(html)) {
247
+ if (!drawsGl(attrs.get("data-umber"))) continue;
248
+ for (const needs of namedHints(attrs, effects, shaders)) for (const url of needs.pictures ?? []) pictures.add(url);
249
+ for (const [name, value] of attrs)
250
+ if (name.startsWith("data-umber-") && name !== "data-umber-src" && PICTURE_VALUE.test(value)) pictures.add(value);
251
+ }
252
+ return [...pictures];
253
+ }
254
+ var TURNS = /(?:^|[;{\s])(?:clip-path|mask(?:-image)?|rotate|perspective|offset-path|animation-timeline)\s*:\s*(?!none\b|auto\b|initial\b)|\b(?:rotate|skew|matrix|perspective)(?:3d|[XYZ])?\s*\(|\b(?:translate3d|translateZ|scale3d|scaleZ)\s*\(|\bscale[XY]?\s*\(\s*-/i;
255
+ var CLIPS = /(?:^|[;{\s])overflow(?:-[xy])?\s*:\s*(?:hidden|clip|auto|scroll|overlay)\b/i;
256
+ var ROOT = /^(?:\s*(?:html|body|:root)\s*,?)+$/i;
257
+ function styleShapes(css) {
258
+ const bare = css.replace(/\/\*[\s\S]*?\*\//g, "");
259
+ if (TURNS.test(bare)) return true;
260
+ for (const [, selector2 = "", body = ""] of bare.matchAll(/([^{}]*)\{([^{}]*)\}/g))
261
+ if (CLIPS.test(body) && !ROOT.test(selector2)) return true;
262
+ return false;
263
+ }
264
+ function styleChunks(html, styles) {
265
+ const chunks = [];
266
+ const inline = [...html.matchAll(/\sstyle\s*=\s*(?:"([^"]*)"|'([^']*)')/gi)].map(
267
+ (match) => `*{${match[1] ?? match[2] ?? ""}}`
268
+ );
269
+ if (/\sdata-umber-occlude\b/i.test(html) || [...styles, ...inline].some(styleShapes)) chunks.push("shapes");
270
+ if (/<script\b[^>]*\sdata-umber-patch\b/i.test(html)) chunks.push("patch");
271
+ return chunks;
272
+ }
273
+ var escape2 = (value) => value.replace(/&/g, "&amp;").replace(/"/g, "&quot;");
274
+ function scriptEngine(html) {
275
+ for (const match of html.matchAll(/<script\b([^>]*)>/gi)) {
276
+ const attrs = attributes(match[1] ?? "");
277
+ const src = /^(.*?)umber\.js(?:[?#].*)?$/.exec(attrs.get("src") ?? "");
278
+ if (!src || src[1] && !src[1].endsWith("/")) continue;
279
+ const folder = src[1] ?? "";
280
+ const version = /\/umber@([^/]+)\/$/.exec(folder);
281
+ if (version && !/^\d+\.\d+\.\d+(?:-[\w.]+)?$/.test(version[1] ?? "")) return null;
282
+ const modules = (attrs.get("data-umber-modules") ?? "").split(/[\s,]+/).filter((name) => ADD_ONS.includes(name));
283
+ const fetch = ["crossorigin", "integrity"].filter((name) => attrs.has(name)).map((name) => ` ${name}="${escape2(attrs.get(name) ?? "")}"`).join("");
284
+ return { folder, modules, nonce: attrs.get("nonce") ?? "", src: attrs.get("src") ?? "", fetch };
285
+ }
286
+ return null;
287
+ }
288
+ function hintLinks(engine, chunks) {
289
+ const nonce = engine.nonce ? ` nonce="${escape2(engine.nonce)}"` : "";
290
+ const link = (rest) => `<link ${rest}${nonce} data-umber-hint>`;
291
+ const links = [
292
+ ...engine.src ? [link(`rel="preload" as="script" href="${escape2(engine.src)}"${engine.fetch ?? ""}`)] : [],
293
+ ...(engine.modules ?? []).map(
294
+ (name) => link(`rel="preload" as="script" href="${escape2(engine.folder)}modules/${name}.js"`)
295
+ ),
296
+ ...chunks.map((name) => link(`rel="modulepreload" href="${escape2(engine.folder)}chunks/${name}.js"`))
297
+ ];
298
+ if (chunks.includes("licence") && !engine.folder.startsWith(CHECK))
299
+ links.push(`<link rel="preconnect" href="${CHECK}" crossorigin data-umber-hint>`);
300
+ return links.join("");
301
+ }
302
+ function fontLinks(manifest, files) {
303
+ const folder = manifest.slice(0, manifest.lastIndexOf("/") + 1);
304
+ return files.map((file) => `<link rel="preload" href="${folder}${file}.glyphs" ${DATA_FETCH} data-umber-hint>`).join("");
305
+ }
306
+ var DESKTOP = "(hover: hover) and (pointer: fine) and (min-width: 768px)";
307
+ function hintMedia(html) {
308
+ const tag = (name) => attributes(new RegExp(`<${name}\\b([^>]*)>`, "i").exec(html)?.[1] ?? "");
309
+ const body = tag("body");
310
+ const desktop = (body.get("data-umber-devices") ?? tag("html").get("data-umber-devices")) === "desktop";
311
+ const media = (body.get("data-umber-media") ?? "").trim();
312
+ if (!desktop) return media;
313
+ return media && !/,|^\s*(?:not|only)\b/i.test(media) ? `${DESKTOP} and ${media}` : DESKTOP;
314
+ }
315
+ var ALWAYS = /chunks\/(?:licence|patch)\.js"/;
316
+ function withHints(html, links) {
317
+ const bare = html.replace(/<link\b[^>]*\bdata-umber-hint\b[^>]*>/gi, "");
318
+ const media = links && hintMedia(bare);
319
+ const scoped = media ? links.replace(
320
+ /<link rel="(?:modulepreload|preload" href="[^"]*\.glyphs)"[^>]*>/g,
321
+ (link) => ALWAYS.test(link) ? link : link.replace(" data-umber-hint>", ` media="${escape2(media)}" data-umber-hint>`)
322
+ ) : links;
323
+ return scoped ? inHead(bare, scoped) : bare;
324
+ }
325
+
326
+ // tools/assets/calls.ts
327
+ var CALLS = {
328
+ view: ["layers"],
329
+ renderer: ["layers"],
330
+ target: ["fx"],
331
+ snapshot: ["fx"],
332
+ sim: ["fx", "sim"],
333
+ flow: ["fx", "sim"],
334
+ preload: ["warm"],
335
+ warm: ["warm"],
336
+ placeholder: ["warm"],
337
+ flip: ["flip"]
338
+ };
339
+ var isNode = (value) => typeof value === "object" && value !== null && typeof value.type === "string";
340
+ var nodes = (value) => Array.isArray(value) ? value.filter(isNode) : [];
341
+ var nameOf = (node) => isNode(node) && node.type === "Identifier" ? String(node.name) : "";
342
+ var FUNCTION = /^(?:Arrow)?Function(?:Expression|Declaration)$/;
343
+ function children(node) {
344
+ const out = [];
345
+ for (const value of Object.values(node))
346
+ if (Array.isArray(value)) out.push(...value.filter(isNode));
347
+ else if (isNode(value)) out.push(value);
348
+ return out;
349
+ }
350
+ function keyOf(property) {
351
+ if (property.computed || !isNode(property.key)) return "";
352
+ const key = property.key.type === "Identifier" ? property.key.name : property.key.value;
353
+ return typeof key === "string" ? key : "";
354
+ }
355
+ var push = (map, name, node) => {
356
+ if (name && isNode(node)) map.set(name, [...map.get(name) ?? [], node]);
357
+ };
358
+ function note(node, found) {
359
+ if (node.type === "VariableDeclarator") push(found.values, nameOf(node.id), node.init);
360
+ else if (node.type === "AssignmentExpression") {
361
+ push(found.values, nameOf(node.left), node.right);
362
+ if (isNode(node.left) && node.left.type === "MemberExpression") found.set.push(node);
363
+ } else if (node.type === "FunctionDeclaration") push(found.functions, nameOf(node.id), node);
364
+ else if (node.type === "CallExpression") found.calls.push(node);
365
+ else if (node.type === "ImportDeclaration" && isNode(node.source) && node.source.value === "@occluze/umber") {
366
+ for (const specifier of nodes(node.specifiers))
367
+ if (nameOf(specifier.imported) === "createUmber") found.makers.add(nameOf(specifier.local));
368
+ }
369
+ if (node.type === "ObjectExpression" || node.type === "Literal" || node.type === "TemplateLiteral")
370
+ found.written.push(node);
371
+ }
372
+ function declared(ast) {
373
+ const found = {
374
+ values: /* @__PURE__ */ new Map(),
375
+ functions: /* @__PURE__ */ new Map(),
376
+ makers: /* @__PURE__ */ new Set(),
377
+ calls: [],
378
+ set: [],
379
+ written: []
380
+ };
381
+ const visit = (node) => {
382
+ note(node, found);
383
+ children(node).forEach(visit);
384
+ };
385
+ visit(ast);
386
+ for (const [name, values] of found.values)
387
+ for (const value of values) if (FUNCTION.test(value.type)) push(found.functions, name, value);
388
+ return found;
389
+ }
390
+ function returned(fn) {
391
+ const body = fn.body;
392
+ if (!isNode(body)) return [];
393
+ if (body.type !== "BlockStatement") return [body];
394
+ const out = [];
395
+ const visit = (node) => {
396
+ if (node.type === "ReturnStatement" && isNode(node.argument)) out.push(node.argument);
397
+ else if (!FUNCTION.test(node.type)) children(node).forEach(visit);
398
+ };
399
+ children(body).forEach(visit);
400
+ return out;
401
+ }
402
+ var DEPTH = 12;
403
+ var Reader = class {
404
+ constructor(found) {
405
+ this.found = found;
406
+ /** Set when something that was followed could not be read. */
407
+ this.partial = false;
408
+ }
409
+ /** What `node` may be at run time, one step on: the values of a name, what a function of the module returns, each side of a choice. Null: read it as it is. */
410
+ next(node) {
411
+ if (node.type === "Identifier") return this.found.values.get(nameOf(node)) ?? [];
412
+ if (node.type === "ConditionalExpression") return nodes([node.consequent, node.alternate]);
413
+ if (node.type === "LogicalExpression") return nodes([node.left, node.right]);
414
+ if (node.type === "AwaitExpression" || node.type === "ParenthesizedExpression")
415
+ return nodes([node.argument ?? node.expression]);
416
+ if (node.type === "CallExpression" && nameOf(node.callee))
417
+ return (this.found.functions.get(nameOf(node.callee)) ?? []).flatMap(returned);
418
+ return null;
419
+ }
420
+ /**
421
+ * The object literals `node` may be, with the ones it spreads in. One that can't be followed sets `partial`.
422
+ * Each node is followed once a query (`seen`): a bundle's short names each have many values, and
423
+ * following them again at every step never ends.
424
+ */
425
+ objects(node, depth = 0, seen = /* @__PURE__ */ new Set()) {
426
+ if (seen.has(node)) return [];
427
+ seen.add(node);
428
+ if (node.type === "ObjectExpression") {
429
+ const spread = nodes(node.properties).filter((property) => property.type === "SpreadElement");
430
+ return [
431
+ node,
432
+ ...spread.flatMap(
433
+ (property) => isNode(property.argument) ? this.objects(property.argument, depth + 1, seen) : []
434
+ )
435
+ ];
436
+ }
437
+ const next = depth < DEPTH ? this.next(node) : null;
438
+ if (!next?.length) this.partial = true;
439
+ return (next ?? []).flatMap((value) => this.objects(value, depth + 1, seen));
440
+ }
441
+ /** The values of the properties named `key` in `objects`. */
442
+ values(objects, key) {
443
+ return objects.flatMap(
444
+ (object) => nodes(object.properties).filter((property) => property.type === "Property" && keyOf(property) === key).flatMap((property) => nodes([property.value]))
445
+ );
446
+ }
447
+ /**
448
+ * The pieces of text `node` is put together from, into `out`: a string, a template's own
449
+ * text (what it inserts is read too, and may be missing), strings joined with + or built
450
+ * by a method on them (join, map, replace), a name's values. False when no text was found.
451
+ * Each node is read once a query (`seen`), as in objects(): read again, it adds no piece.
452
+ */
453
+ strings(node, out, depth = 0, seen = /* @__PURE__ */ new Set()) {
454
+ if (depth > DEPTH || seen.has(node)) return false;
455
+ seen.add(node);
456
+ const read2 = (parts) => parts.map((part) => this.strings(part, out, depth + 1, seen)).some(Boolean);
457
+ if (node.type === "Literal") {
458
+ if (typeof node.value === "string") out.push(node.value);
459
+ return true;
460
+ }
461
+ if (node.type === "TemplateLiteral") {
462
+ for (const quasi of nodes(node.quasis)) out.push(quasi.value.cooked ?? "");
463
+ read2(nodes(node.expressions));
464
+ return true;
465
+ }
466
+ if (FUNCTION.test(node.type)) return read2(returned(node));
467
+ return read2(this.parts(node));
468
+ }
469
+ /** The nodes a value that is no literal is made of, for strings(). */
470
+ parts(node) {
471
+ if (node.type === "BinaryExpression") return nodes([node.left, node.right]);
472
+ if (node.type === "ArrayExpression") return nodes(node.elements);
473
+ if (node.type === "ObjectExpression") return nodes(node.properties).flatMap((property) => nodes([property.value]));
474
+ if (node.type === "CallExpression" && isNode(node.callee) && node.callee.type === "MemberExpression")
475
+ return [...nodes([node.callee.object]), ...nodes(node.arguments)];
476
+ return this.next(node) ?? [];
477
+ }
478
+ };
479
+ function literal(found, node) {
480
+ for (let depth = 0; depth < DEPTH; depth++) {
481
+ if (node.type === "Literal") return typeof node.value === "string" ? node.value : "";
482
+ const values = node.type === "Identifier" ? found.values.get(nameOf(node)) ?? [] : [];
483
+ const [value] = values;
484
+ if (values.length !== 1 || !value) return "";
485
+ node = value;
486
+ }
487
+ return "";
488
+ }
489
+ function partGlsl(reader, part, blocks2, out) {
490
+ const texts = blocks2 ? reader.objects(part).flatMap((object) => nodes(object.properties)) : [part];
491
+ for (const text of texts) {
492
+ const value = text.type === "Property" ? text.value : text;
493
+ if (isNode(value) && !reader.strings(value, out)) reader.partial = true;
494
+ }
495
+ }
496
+ function definitionHints(found, definition, shader, included) {
497
+ const reader = new Reader(found);
498
+ const objects = reader.objects(definition);
499
+ const glsl = [];
500
+ for (const key of shader ? ["fragment", "head"] : ["vertex", "fragment"])
501
+ for (const part of reader.values(objects, key)) partGlsl(reader, part, !shader, glsl);
502
+ const parts = shader ? objects : reader.values(objects, "vertex").concat(reader.values(objects, "fragment")).flatMap((part) => reader.objects(part));
503
+ const head = reader.values(parts, "head").length > 0;
504
+ const options2 = reader.values(objects, "options").flatMap((value) => reader.objects(value));
505
+ const perspective = reader.values(options2, "perspective").length > 0;
506
+ const given = [...options2, ...reader.values(objects, "uniforms").flatMap((value) => reader.objects(value))];
507
+ const pictures = given.flatMap((object) => nodes(object.properties)).flatMap(
508
+ (property) => property.type === "Property" && isNode(property.value) ? [literal(found, property.value)] : []
509
+ ).filter((value) => PICTURE_VALUE.test(value));
510
+ const text = glsl.join("\n");
511
+ const chunks = [...text.matchAll(/#include\s+"([^"]+)"/g)].map((match) => included.get(match[1] ?? "") ?? "");
512
+ const hints = effectHints({
513
+ fragment: { glsl: [text, ...chunks].join("\n"), head: head ? "head" : "" },
514
+ options: perspective ? { perspective: 0 } : {}
515
+ });
516
+ if (pictures.length) hints.pictures = [...new Set(pictures)];
517
+ return { hints, whole: !reader.partial && objects.length > 0 };
518
+ }
519
+ function method(call) {
520
+ const callee = isNode(call.callee) && call.callee.type === "ChainExpression" ? call.callee.expression : call.callee;
521
+ if (!isNode(callee) || callee.type !== "MemberExpression" || callee.computed) return null;
522
+ return { name: nameOf(callee.property), on: nameOf(callee.object) };
523
+ }
524
+ function engines(found) {
525
+ const made = /* @__PURE__ */ new Set();
526
+ for (const [name, values] of found.values)
527
+ for (const value of values) {
528
+ const call = value.type === "AwaitExpression" && isNode(value.argument) ? value.argument : value;
529
+ if (call.type === "CallExpression" && found.makers.has(nameOf(call.callee))) made.add(name);
530
+ }
531
+ return made;
532
+ }
533
+ function tagOf(reader, attributes2) {
534
+ const written = attributes2.filter(([name]) => name.startsWith("data-umber")).map(([name, value]) => {
535
+ const texts = [];
536
+ reader.strings(value, texts);
537
+ return `${name}="${texts.join(" ").replace(/"/g, "")}"`;
538
+ });
539
+ if (!written.length) return "";
540
+ const kind = written.some((attribute) => attribute.startsWith('data-umber="')) ? "" : ' data-umber="image"';
541
+ return `<i${kind} ${written.join(" ")}></i>`;
542
+ }
543
+ function markupOf(found) {
544
+ const reader = new Reader(found);
545
+ const tags = [];
546
+ for (const node of found.written) {
547
+ if (node.type === "ObjectExpression") {
548
+ const properties = nodes(node.properties).filter((property) => property.type === "Property");
549
+ tags.push(
550
+ tagOf(
551
+ reader,
552
+ properties.flatMap((property) => isNode(property.value) ? [[keyOf(property), property.value]] : [])
553
+ )
554
+ );
555
+ } else {
556
+ const texts = [];
557
+ reader.strings(node, texts);
558
+ const text = texts.join("");
559
+ if (/<[a-z][^>]*\sdata-umber/i.test(text)) tags.push(text);
560
+ }
561
+ }
562
+ for (const call of found.calls) {
563
+ const [name, value] = nodes(call.arguments);
564
+ if (method(call)?.name === "setAttribute" && name?.type === "Literal" && value)
565
+ tags.push(tagOf(reader, [[String(name.value), value]]));
566
+ }
567
+ return tags.filter(Boolean).join("");
568
+ }
569
+ function selectorOf(node) {
570
+ const called = node.type === "CallExpression" ? method(node) : null;
571
+ const [first] = nodes(node.arguments);
572
+ const text = first?.type === "Literal" && typeof first.value === "string" ? first.value : "";
573
+ if (called?.name === "querySelector" || called?.name === "querySelectorAll") return text;
574
+ return called?.name === "getElementById" && /^[\w-]+$/.test(text) ? `#${text}` : "";
575
+ }
576
+ function selectorsIn(found, node) {
577
+ const values = node.type === "Identifier" ? found.values.get(nameOf(node)) ?? [] : [node];
578
+ return values.map(selectorOf).filter(Boolean);
579
+ }
580
+ function isTextKind(reader, value) {
581
+ const texts = [];
582
+ return isNode(value) && reader.strings(value, texts) && /(?:^|\s)text(?:\s|$)/.test(texts.join(" "));
583
+ }
584
+ function textWriter(found, reader) {
585
+ const seen = [/* @__PURE__ */ new Map(), /* @__PURE__ */ new Map(), /* @__PURE__ */ new Map()];
586
+ const writes = (node, depth) => {
587
+ const known = seen[depth];
588
+ if (!known) return false;
589
+ let yes = known.get(node);
590
+ if (yes === void 0) {
591
+ const named = node.type === "Identifier" ? nameOf(node) : "";
592
+ yes = named ? [...found.values.get(named) ?? [], ...found.functions.get(named) ?? []].some(
593
+ (value) => writes(value, depth + 1)
594
+ ) : node.type === "ObjectExpression" && nodes(node.properties).some(
595
+ (property) => keyOf(property) === "data-umber" && isTextKind(reader, property.value)
596
+ ) || children(node).some((child) => writes(child, depth));
597
+ known.set(node, yes);
598
+ }
599
+ return yes;
600
+ };
601
+ return (node) => writes(node, 0);
602
+ }
603
+ function callTexts(found, reader, writesText, call) {
604
+ const args = nodes(call.arguments);
605
+ const [name, value] = args;
606
+ if (method(call)?.name === "setAttribute" && name?.type === "Literal" && name.value === "data-umber") {
607
+ const on = isNode(call.callee) && isNode(call.callee.object) ? call.callee.object : null;
608
+ return on && isTextKind(reader, value) ? selectorsIn(found, on) : [];
609
+ }
610
+ const elements = args.flatMap((arg) => selectorsIn(found, arg));
611
+ if (!elements.length) return [];
612
+ return args.some((arg) => !selectorsIn(found, arg).length && writesText(arg)) ? elements : [];
613
+ }
614
+ function assignedTexts(found, reader, assignment) {
615
+ const left = assignment.left;
616
+ const holder = isNode(left.object) && left.object.type === "MemberExpression" ? left.object : null;
617
+ const dataset = holder && nameOf(holder.property) === "dataset" && nameOf(left.property) === "umber";
618
+ return dataset && isNode(holder.object) && isTextKind(reader, assignment.right) ? selectorsIn(found, holder.object) : [];
619
+ }
620
+ function textsOf(found) {
621
+ const reader = new Reader(found);
622
+ const writesText = textWriter(found, reader);
623
+ const texts = [
624
+ ...found.calls.flatMap((call) => callTexts(found, reader, writesText, call)),
625
+ ...found.set.flatMap((assignment) => assignedTexts(found, reader, assignment))
626
+ ];
627
+ return [...new Set(texts)];
628
+ }
629
+ function definingCalls(found) {
630
+ return found.calls.flatMap((call) => {
631
+ const called = method(call);
632
+ const [name, definition] = nodes(call.arguments);
633
+ const defines = called && /^(?:effect|shader|chunk)$/.test(called.name);
634
+ return defines && name && definition ? [{ kind: called.name, name, definition }] : [];
635
+ });
636
+ }
637
+ function includedGlsl(found, defining) {
638
+ const included = /* @__PURE__ */ new Map();
639
+ for (const { name, definition } of defining.filter(({ kind }) => kind === "chunk")) {
640
+ const texts = [];
641
+ if (typeof name.value === "string" && new Reader(found).strings(definition, texts))
642
+ included.set(name.value, texts.join("\n"));
643
+ }
644
+ return included;
645
+ }
646
+ function definitions(found, needs) {
647
+ const defining = definingCalls(found);
648
+ const included = includedGlsl(found, defining);
649
+ for (const { kind, name: given, definition } of defining.filter((call) => call.kind !== "chunk")) {
650
+ const shader = kind === "shader";
651
+ const name = literal(found, given);
652
+ if (!name) {
653
+ const what2 = `${shader ? "a shader" : "an effect"} whose name is not written out where it is defined`;
654
+ needs.unknown.push({ what: what2, chunks: [] });
655
+ continue;
656
+ }
657
+ const { hints, whole } = definitionHints(found, definition, shader, included);
658
+ (shader ? needs.shaders : needs.effects)[name] = hints;
659
+ const what = `${shader ? "the shader" : "the effect"} "${name}"`;
660
+ if (!whole) needs.unknown.push({ what, chunks: [], name });
661
+ }
662
+ }
663
+ function patches(found, call) {
664
+ const [options2] = nodes(call.arguments);
665
+ const reader = new Reader(found);
666
+ const patch = options2 ? reader.values(reader.objects(options2), "patch") : [];
667
+ return patch.some((value) => value.type === "Literal" && value.value === true);
668
+ }
669
+ function engineCalls(found, needs) {
670
+ const made = engines(found);
671
+ const chunks = /* @__PURE__ */ new Set();
672
+ for (const call of found.calls) {
673
+ const called = method(call);
674
+ const brings = CALLS[called?.name ?? ""] ?? [];
675
+ if (found.makers.has(nameOf(call.callee)) && patches(found, call)) chunks.add("patch");
676
+ else if (called && made.has(called.on)) for (const chunk of brings) chunks.add(chunk);
677
+ else if (called && brings.length && /umber/i.test(called.on))
678
+ needs.unknown.push({ what: `${called.on}.${called.name}()`, chunks: brings });
679
+ }
680
+ needs.chunks = [...chunks];
681
+ }
682
+ var MAY_ASK = /\.(?:effect|shader)\s*\(|createUmber|data-umber|umber\s*\??\.\s*\w+\s*\(/i;
683
+ function scriptNeeds(ast) {
684
+ const found = declared(ast);
685
+ const needs = { chunks: [], effects: {}, shaders: {}, markup: "", texts: [], unknown: [] };
686
+ definitions(found, needs);
687
+ engineCalls(found, needs);
688
+ needs.markup = markupOf(found);
689
+ needs.texts = textsOf(found);
690
+ const any = needs.chunks.length || needs.markup || needs.texts.length || needs.unknown.length;
691
+ return any || Object.keys(needs.effects).length || Object.keys(needs.shaders).length ? needs : null;
692
+ }
693
+ function joinNeeds(all) {
694
+ const unknown = new Map(all.flatMap((needs) => needs.unknown).map((entry) => [entry.what, entry]));
695
+ return {
696
+ chunks: [...new Set(all.flatMap((needs) => needs.chunks))],
697
+ effects: Object.assign({}, ...all.map((needs) => needs.effects)),
698
+ shaders: Object.assign({}, ...all.map((needs) => needs.shaders)),
699
+ markup: all.map((needs) => needs.markup).join(""),
700
+ texts: [...new Set(all.flatMap((needs) => needs.texts))],
701
+ unknown: [...unknown.values()]
702
+ };
703
+ }
704
+
705
+ // tools/assets/native.ts
706
+ import { existsSync, readFileSync } from "node:fs";
707
+ import { createRequire } from "node:module";
708
+ import { fileURLToPath } from "node:url";
709
+ function libc() {
710
+ const report = process.report.getReport();
711
+ return report.header.glibcVersionRuntime ? "gnu" : "musl";
712
+ }
713
+ function triple(platform = process.platform, arch = process.arch, c = process.platform === "linux" ? libc() : "gnu") {
714
+ if (platform === "win32") return `win32-${arch}-msvc`;
715
+ if (platform === "linux") return `linux-${arch}-${c}`;
716
+ return `${platform}-${arch}`;
717
+ }
718
+ var PLATFORMS = [
719
+ "win32-x64-msvc",
720
+ "win32-arm64-msvc",
721
+ "darwin-x64",
722
+ "darwin-arm64",
723
+ "linux-x64-gnu",
724
+ "linux-arm64-gnu"
725
+ ];
726
+ var STAMP = "r8g2";
727
+ function pinned(name) {
728
+ try {
729
+ const file = fileURLToPath(new URL("../../package.json", import.meta.url));
730
+ const pkg = JSON.parse(readFileSync(file, "utf8"));
731
+ return `@occluze/umber-assets-${name}` in (pkg.optionalDependencies ?? {});
732
+ } catch {
733
+ return false;
734
+ }
735
+ }
736
+ function remedy(name, prebuilt) {
737
+ return prebuilt ? `Install @occluze/umber again without --no-optional / --omit=optional, so @occluze/umber-assets-${name} of the same version comes with it.` : `This copy of @occluze/umber (a snapshot or a checkout) comes with no prebuilt asset tool. In a checkout of Umber's repository: npm run build:native (it needs Rust and a C++ compiler). Otherwise use a published version of @occluze/umber, which installs one.`;
738
+ }
739
+ function matching(addon2, name, prebuilt = pinned(name)) {
740
+ const stamp = typeof addon2.stamp === "function" ? addon2.stamp() : "none (an older build)";
741
+ if (stamp !== STAMP)
742
+ throw new Error(
743
+ `Umber's asset tool addon for ${name} is another version's (its stamp is ${stamp}, this tool needs ${STAMP}). ${remedy(name, prebuilt)}`
744
+ );
745
+ return addon2;
746
+ }
747
+ var loaded = null;
748
+ function loadNative() {
749
+ if (loaded) return loaded;
750
+ const require2 = createRequire(import.meta.url);
751
+ const name = triple();
752
+ const local = fileURLToPath(new URL(`../../crates/umber-assets-node/umber-assets.${name}.node`, import.meta.url));
753
+ const found = existsSync(local) ? local : `@occluze/umber-assets-${name}`;
754
+ let addon2;
755
+ try {
756
+ addon2 = require2(found);
757
+ } catch (err) {
758
+ const known = PLATFORMS.includes(name);
759
+ throw new Error(
760
+ known ? `Umber's asset tool for ${name} is not installed (@occluze/umber-assets-${name}). ${remedy(name, pinned(name))}` : `Umber's asset tool has no build for ${name}. It runs on ${PLATFORMS.join(", ")}.`,
761
+ { cause: err }
762
+ );
763
+ }
764
+ loaded = matching(addon2, name);
765
+ return loaded;
766
+ }
767
+
768
+ // tools/assets/site.ts
769
+ import { createHash as createHash2 } from "node:crypto";
770
+ import { existsSync as existsSync3 } from "node:fs";
771
+ import { copyFile, mkdir as mkdir2, readdir, readFile as readFile2, rm, stat, writeFile as writeFile2 } from "node:fs/promises";
772
+ import { availableParallelism } from "node:os";
773
+ import { join as join2, relative, resolve, sep } from "node:path";
774
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
775
+
776
+ // tools/assets/data.ts
777
+ import { createHash } from "node:crypto";
778
+ import { deflateSync } from "node:zlib";
779
+ var DATA_TYPES = {
780
+ raw: [1, false],
781
+ u8: [1, true],
782
+ i8: [1, true],
783
+ u16: [2, true],
784
+ i16: [2, true],
785
+ u32: [4, true],
786
+ i32: [4, true],
787
+ f32: [4, false],
788
+ f64: [8, false]
789
+ };
790
+ function planes(bytes, type) {
791
+ const [size, delta] = DATA_TYPES[type];
792
+ if (bytes.length % size) throw new Error(`${bytes.length} bytes is no whole number of ${type} elements`);
793
+ if (size === 1 && !delta) return bytes;
794
+ const count = bytes.length / size;
795
+ const out = new Uint8Array(bytes.length);
796
+ for (let i = 0; i < count; i++) {
797
+ let borrow = 0;
798
+ for (let b = 0; b < size; b++) {
799
+ let value = bytes[i * size + b] ?? 0;
800
+ if (delta && i > 0) {
801
+ const difference = value - (bytes[(i - 1) * size + b] ?? 0) - borrow;
802
+ borrow = difference < 0 ? 1 : 0;
803
+ value = difference & 255;
804
+ }
805
+ out[b * count + i] = value;
806
+ }
807
+ }
808
+ return out;
809
+ }
810
+ function pack(bytes, type) {
811
+ const key = createHash("sha256").update(type).update(bytes).digest("hex").slice(0, 20);
812
+ return { key, bytes: deflateSync(planes(bytes, type), { level: 9 }), size: bytes.length };
813
+ }
814
+
815
+ // tools/assets/fonts.ts
816
+ import { existsSync as existsSync2 } from "node:fs";
817
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
818
+ import { join } from "node:path";
819
+ import { deflateSync as deflateSync2 } from "node:zlib";
820
+ var FORMATS = /^(woff2|woff|truetype|opentype)$/;
821
+ var FILES = /\.(woff2?|ttf|otf)(?:[?#]|$)/i;
822
+ function fontFaces(css) {
823
+ const faces = [];
824
+ for (const [, body = ""] of css.matchAll(/@font-face\s*\{([^}]*)\}/g)) {
825
+ const read2 = (name) => new RegExp(`(?:^|;|\\s)${name}\\s*:\\s*([^;]+)`, "i").exec(body)?.[1]?.trim() ?? "";
826
+ const family = read2("font-family").replace(/^["']|["']$/g, "");
827
+ const sources = [
828
+ ...read2("src").matchAll(/url\(\s*["']?([^"')]+)["']?\s*\)(?:\s*format\(\s*["']?([\w-]+)["']?\s*\))?/g)
829
+ ];
830
+ const pick = sources.find(([, url = "", format]) => format ? FORMATS.test(format) : FILES.test(url));
831
+ const weightText = read2("font-weight") || "400";
832
+ if (!family || !pick?.[1]) continue;
833
+ const weight2 = weightText === "bold" ? 700 : Number.parseInt(weightText, 10) || 400;
834
+ const style = /italic|oblique/i.test(read2("font-style")) ? "italic" : "normal";
835
+ const range = /^(\d+)\s+(\d+)$/.exec(weightText);
836
+ faces.push({
837
+ family,
838
+ weight: weight2,
839
+ style,
840
+ url: pick[1],
841
+ ...range ? { range: [Number(range[1]), Number(range[2])] } : {}
842
+ });
843
+ }
844
+ return faces;
845
+ }
846
+ var faceKey = (face) => `${face.family.toLowerCase()}|${face.weight}|${face.style}`;
847
+ function stylesOf(html) {
848
+ const blocks2 = [...html.matchAll(/<style[^>]*>([\s\S]*?)<\/style\s*>/gi)].map((match) => match[1] ?? "");
849
+ const links = [];
850
+ for (const [, body = ""] of html.matchAll(/<link\b([^>]*)>/gi)) {
851
+ const attrs = attributes(body);
852
+ if (/\bstylesheet\b/i.test(attrs.get("rel") ?? "") && attrs.get("href")) links.push(attrs.get("href") ?? "");
853
+ }
854
+ return { blocks: blocks2, links };
855
+ }
856
+ var VOID2 = /^(img|br|hr|meta|link|input|source|wbr|area|base|col|embed|param|track)$/i;
857
+ function glTextCharacters(html, into) {
858
+ const stack = [];
859
+ let inside = 0;
860
+ const open = (body) => {
861
+ const gl = (attributes(body).get("data-umber") ?? "").split(/\s+/).includes("text");
862
+ stack.push(gl);
863
+ if (gl) inside++;
864
+ };
865
+ const close2 = () => {
866
+ if (stack.pop() === true) inside--;
867
+ };
868
+ for (const [, closing, name = "", body = "", text] of html.matchAll(TOKENS)) {
869
+ if (text !== void 0) addText(inside ? text : "", into);
870
+ else if (name && !VOID2.test(name)) {
871
+ if (closing) close2();
872
+ else open(body);
873
+ }
874
+ }
875
+ }
876
+ var TOKENS = /<!--[\s\S]*?-->|<(\/?)([a-zA-Z][\w:-]*)([^>]*)>|([^<]+)/g;
877
+ function addText(text, into) {
878
+ for (const char of decodeText(text)) into.add(char.codePointAt(0) ?? 32);
879
+ }
880
+ function decodeText(text) {
881
+ return text.replace(/&#x([0-9a-f]+);/gi, (_, hex) => String.fromCodePoint(Number.parseInt(hex, 16))).replace(/&#(\d+);/g, (_, dec) => String.fromCodePoint(Number(dec))).replace(/&nbsp;/g, "\xA0").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"');
882
+ }
883
+ function weightsIn(css, into) {
884
+ into.add(400).add(700);
885
+ for (const [, value = ""] of css.matchAll(/font-weight\s*:\s*([\w-]+)/gi)) {
886
+ if (value === "bold") into.add(700);
887
+ else if (/^\d+$/.test(value)) into.add(Number(value));
888
+ }
889
+ }
890
+ async function siteFonts(pages, local) {
891
+ const fonts = /* @__PURE__ */ new Map();
892
+ const weights = /* @__PURE__ */ new Set();
893
+ const variable = [];
894
+ const sheets = /* @__PURE__ */ new Map();
895
+ const read2 = (url) => {
896
+ const file = local(url);
897
+ if (!file) return Promise.resolve("");
898
+ let css = sheets.get(file);
899
+ if (!css) sheets.set(file, css = readFile(file, "utf8").catch(() => ""));
900
+ return css;
901
+ };
902
+ const take = (css, base) => {
903
+ weightsIn(css, weights);
904
+ for (const face of fontFaces(css)) {
905
+ const file = local(new URL(face.url, base));
906
+ if (!file) continue;
907
+ if (face.range) variable.push({ face, file });
908
+ else if (!fonts.has(faceKey(face))) fonts.set(faceKey(face), { file });
909
+ }
910
+ };
911
+ for (const { url, html } of pages) {
912
+ const { blocks: blocks2, links } = stylesOf(html);
913
+ weightsIn(html.match(/style\s*=\s*"[^"]*"/gi)?.join(";") ?? "", weights);
914
+ for (const block of blocks2) take(block, url);
915
+ for (const href of links) {
916
+ const sheet = new URL(href, url);
917
+ take(await read2(sheet), sheet);
918
+ }
919
+ }
920
+ for (const { face, file } of variable) {
921
+ const [low, high] = face.range ?? [0, 0];
922
+ for (const weight2 of weights) {
923
+ const key = faceKey({ ...face, weight: weight2 });
924
+ if (weight2 >= low && weight2 <= high && !fonts.has(key)) fonts.set(key, { file, weight: weight2 });
925
+ }
926
+ }
927
+ return fonts;
928
+ }
929
+ var ASCII = Array.from({ length: 95 }, (_, i) => 32 + i);
930
+ async function prepareFonts(fonts, chars, { native, folder, cache, skipped }) {
931
+ const keep = [.../* @__PURE__ */ new Set([...ASCII, ...chars])].sort((a, b) => a - b);
932
+ const out = {};
933
+ for (const [face, { file, weight: weight2 }] of fonts) {
934
+ try {
935
+ const bytes = await readFile(file);
936
+ const key = native.fontKey(bytes, keep, weight2);
937
+ const cached = cache ? join(cache, `${key}.glyphs`) : "";
938
+ const glyphs = cached && existsSync2(cached) ? await readFile(cached) : (await native.prepareFont(bytes, keep, weight2)).bytes;
939
+ if (cache && !existsSync2(cached)) {
940
+ await mkdir(cache, { recursive: true });
941
+ await writeFile(cached, glyphs);
942
+ }
943
+ await mkdir(folder, { recursive: true });
944
+ await writeFile(join(folder, `${key}.glyphs`), deflateSync2(glyphs, { level: 9 }));
945
+ out[face] = key;
946
+ } catch (err) {
947
+ skipped.push(`font ${face.replace(/\|/g, " ")}: ${err instanceof Error ? err.message : String(err)}`);
948
+ }
949
+ }
950
+ return out;
951
+ }
952
+
953
+ // tools/assets/text-fonts.ts
954
+ var NO = 0;
955
+ var MAYBE = 1;
956
+ var YES = 2;
957
+ var IDENT = String.raw`(?:[\w-]|[^\x00-\x7f]|\\.)+`;
958
+ var unescape = (name) => name.replace(/\\(.)/g, "$1");
959
+ var NEVER = /^(?:hover|active|focus|focus-visible|focus-within|visited|target|before|after|first-line|first-letter|selection|placeholder|marker|backdrop)$/;
960
+ var NO_RULES = /^(?:font-face|(?:-webkit-)?keyframes|property|counter-style|page|font-feature-values|font-palette-values|view-transition|position-try)$/;
961
+ var BOLD = /^(?:h[1-6]|b|strong|th)$/;
962
+ var ITALIC = /^(?:i|em|cite|var|dfn|address)$/;
963
+ function options(args) {
964
+ const texts = args.slice(1, -1).split(",");
965
+ const found = texts.map((text) => compound(text.trim()));
966
+ return texts.some((text) => /[\s>+~]/.test(text.trim())) ? null : found;
967
+ }
968
+ function compound(text) {
969
+ const found = {
970
+ tag: "",
971
+ id: "",
972
+ classes: [],
973
+ attrs: [],
974
+ root: false,
975
+ never: false,
976
+ unsure: false,
977
+ any: []
978
+ };
979
+ const part = new RegExp(
980
+ String.raw`^(?:(\*|${IDENT})|#(${IDENT})|\.(${IDENT})|\[\s*([\w-]+)\s*(?:([~^$*|]?=)\s*(?:"([^"]*)"|'([^']*)'|([^\s\]]+)))?\s*\]|(::?)([\w-]+)(\([^()]*(?:\([^()]*\)[^()]*)*\))?)`
981
+ );
982
+ let rest = text;
983
+ while (rest) {
984
+ const match = part.exec(rest);
985
+ if (!match) {
986
+ found.unsure = true;
987
+ break;
988
+ }
989
+ rest = rest.slice(match[0].length);
990
+ const [, tag, id, cls, attr, op = "", quoted, single, bare, colons = "", pseudo = "", args = ""] = match;
991
+ if (tag) found.tag = tag === "*" ? "" : unescape(tag).toLowerCase();
992
+ else if (id) found.id = unescape(id);
993
+ else if (cls) found.classes.push(unescape(cls));
994
+ else if (attr) found.attrs.push({ name: attr.toLowerCase(), op, value: quoted ?? single ?? bare ?? "" });
995
+ else pseudoOn(found, colons, pseudo, args);
996
+ }
997
+ return found;
998
+ }
999
+ function pseudoOn(found, colons, pseudo, args) {
1000
+ const chooses = /^(?:is|where)$/.test(pseudo) && args ? options(args) : null;
1001
+ if (colons === "::" || NEVER.test(pseudo)) found.never = true;
1002
+ else if (pseudo === "root") found.root = true;
1003
+ else if (chooses) found.any.push({ options: chooses, counts: pseudo === "is" });
1004
+ else found.unsure = true;
1005
+ }
1006
+ function weight(part) {
1007
+ const chosen = part.any.map(({ options: from, counts }) => counts ? Math.max(0, ...from.map(weight)) : 0);
1008
+ return (part.id ? 1e4 : 0) + (part.classes.length + part.attrs.length + (part.root ? 1 : 0)) * 100 + (part.tag ? 1 : 0) + chosen.reduce((sum, one) => sum + one, 0);
1009
+ }
1010
+ function selector(text) {
1011
+ const tokens = text.trim().replace(/\s*([>+~])\s*/g, " $1 ").split(/\s+(?![^[(]*[\])])/);
1012
+ let parts = [];
1013
+ let combinators = [];
1014
+ let unsure = false;
1015
+ let next = " ";
1016
+ for (const token of tokens) {
1017
+ if (token === ">") next = ">";
1018
+ else if (token === "+" || token === "~") {
1019
+ parts = [];
1020
+ combinators = [];
1021
+ unsure = true;
1022
+ next = " ";
1023
+ } else {
1024
+ if (parts.length) combinators.push(next);
1025
+ parts.push(compound(token));
1026
+ next = " ";
1027
+ }
1028
+ }
1029
+ const specificity = parts.reduce((sum, part) => sum + weight(part), 0);
1030
+ return { parts, combinators, specificity, unsure: unsure || !parts.length };
1031
+ }
1032
+ function attrMatches(node, { name, op, value }) {
1033
+ const has = node.attrs.get(name);
1034
+ if (has === void 0) return false;
1035
+ if (op === "=") return has === value;
1036
+ if (op === "~=") return has.split(/\s+/).includes(value);
1037
+ if (op === "^=") return has.startsWith(value);
1038
+ if (op === "$=") return has.endsWith(value);
1039
+ if (op === "*=") return has.includes(value);
1040
+ if (op === "|=") return has === value || has.startsWith(`${value}-`);
1041
+ return true;
1042
+ }
1043
+ function compoundMatches(node, part) {
1044
+ if (part.never) return NO;
1045
+ const holds = (!part.tag || part.tag === node.tag) && (!part.id || node.attrs.get("id") === part.id) && (!part.root || node.tag === "html") && part.classes.every((name) => node.classes.has(name)) && part.attrs.every((attr) => attrMatches(node, attr));
1046
+ if (!holds) return NO;
1047
+ const chosen = part.any.map(
1048
+ ({ options: from }) => Math.max(NO, ...from.map((option) => compoundMatches(node, option)))
1049
+ );
1050
+ return Math.min(part.unsure ? MAYBE : YES, ...chosen);
1051
+ }
1052
+ function matchesFrom(node, found, index) {
1053
+ const part = found.parts[index];
1054
+ const own = part ? compoundMatches(node, part) : NO;
1055
+ if (!own || index === 0) return own;
1056
+ let above = NO;
1057
+ if (found.combinators[index - 1] === ">") above = node.parent ? matchesFrom(node.parent, found, index - 1) : NO;
1058
+ else
1059
+ for (let up = node.parent; up && above < YES; up = up.parent)
1060
+ above = Math.max(above, matchesFrom(up, found, index - 1));
1061
+ return Math.min(own, above);
1062
+ }
1063
+ var matches = (node, found) => {
1064
+ if (!found.parts.length) return MAYBE;
1065
+ const answer = matchesFrom(node, found, found.parts.length - 1);
1066
+ return found.unsure ? Math.min(answer, MAYBE) : answer;
1067
+ };
1068
+ function declarations(body) {
1069
+ const kept = [];
1070
+ for (const text of body.split(";")) {
1071
+ const match = /^\s*([\w-]+)\s*:\s*([\s\S]*?)\s*(!\s*important)?\s*$/.exec(text);
1072
+ if (!match?.[1]) continue;
1073
+ const prop = match[1].startsWith("--") ? match[1] : match[1].toLowerCase();
1074
+ if (prop.startsWith("--") || /^font(?:-family|-weight|-style)?$/.test(prop))
1075
+ kept.push({ prop, value: match[2] ?? "", important: Boolean(match[3]) });
1076
+ }
1077
+ return kept;
1078
+ }
1079
+ function blocks(css) {
1080
+ const found = [];
1081
+ let depth = 0;
1082
+ let start = 0;
1083
+ let open = 0;
1084
+ for (let i = 0; i < css.length; i++) {
1085
+ const char = css[i];
1086
+ if (char === "{" && depth++ === 0) open = i;
1087
+ else if (char === "}" && depth > 0 && --depth === 0) {
1088
+ found.push({ prelude: css.slice(start, open).trim(), body: css.slice(open + 1, i) });
1089
+ start = i + 1;
1090
+ } else if (char === ";" && depth === 0) {
1091
+ found.push({ prelude: css.slice(start, i).trim(), body: null });
1092
+ start = i + 1;
1093
+ }
1094
+ }
1095
+ return found;
1096
+ }
1097
+ var ANYWHERE = { parts: [], combinators: [], specificity: 0, unsure: true };
1098
+ var read = /* @__PURE__ */ new Map();
1099
+ var UNLAYERED = 1e9;
1100
+ function rulesOf(sheets) {
1101
+ const found = sheets.map((sheet) => {
1102
+ let known = read.get(sheet.css);
1103
+ if (!known) read.set(sheet.css, known = sheetRules(sheet.css));
1104
+ return known;
1105
+ });
1106
+ const layers = [...new Set(found.flatMap((sheet) => sheet.layers))];
1107
+ const rules = [];
1108
+ for (const [i, sheet] of found.entries())
1109
+ for (const rule of sheet.rules)
1110
+ rules.push({
1111
+ ...rule,
1112
+ maybe: rule.maybe || sheets[i]?.maybe === true,
1113
+ order: rules.length,
1114
+ rank: rule.layer ? layers.indexOf(rule.layer) : UNLAYERED
1115
+ });
1116
+ return { rules, unread: found.some((sheet) => sheet.unread) };
1117
+ }
1118
+ function styleRule(prelude, body, rules, { maybe, layer }) {
1119
+ const nested = blocks(body).filter((block) => block.body !== null);
1120
+ const own = declarations(nested.length ? body.slice(0, body.indexOf("{")).replace(/[^;]*$/, "") : body);
1121
+ const selectors = prelude.split(/,(?![^(]*\))/).map(selector);
1122
+ const placed = { order: 0, rank: 0, layer };
1123
+ if (own.length) rules.push({ selectors, declarations: own, maybe, ...placed });
1124
+ if (!nested.length) return;
1125
+ const inner = nested.flatMap((block) => declarations((block.body ?? "").replace(/[{}]/g, ";")));
1126
+ inner.push(...declarations(body.slice(body.lastIndexOf("}") + 1)));
1127
+ if (inner.length) rules.push({ selectors: [ANYWHERE], declarations: inner, maybe: true, ...placed });
1128
+ }
1129
+ function sheetRules(text) {
1130
+ const rules = [];
1131
+ const layers = [];
1132
+ let unread = false;
1133
+ const named = (prelude) => prelude.replace(/^@layer\s*/i, "").split(",").map((name) => name.trim()).filter(Boolean);
1134
+ const atRule = (at, prelude, body, within) => {
1135
+ if (NO_RULES.test(at)) return;
1136
+ const [name = ""] = named(prelude);
1137
+ if (at === "layer" && name && !within.layer && !name.includes(".")) {
1138
+ layers.push(name);
1139
+ walk2(body, { maybe: within.maybe, layer: name });
1140
+ } else {
1141
+ const sure = at === "media" && /^@media\s+(?:all|screen)\s*$/i.test(prelude);
1142
+ walk2(body, { maybe: within.maybe || !sure, layer: within.layer });
1143
+ }
1144
+ };
1145
+ const walk2 = (css, within) => {
1146
+ for (const { prelude, body } of blocks(css)) {
1147
+ const at = /^@([\w-]+)/.exec(prelude)?.[1]?.toLowerCase();
1148
+ if (body === null) {
1149
+ unread ||= at === "import";
1150
+ if (at === "layer" && !within.layer) layers.push(...named(prelude));
1151
+ } else if (at) atRule(at, prelude, body, within);
1152
+ else styleRule(prelude, body, rules, within);
1153
+ }
1154
+ };
1155
+ walk2(text.replace(/\/\*[\s\S]*?\*\//g, ""), { maybe: false, layer: "" });
1156
+ return { rules, layers, unread };
1157
+ }
1158
+ var VOID3 = /^(?:img|br|hr|meta|link|input|source|wbr|area|base|col|embed|param|track)$/;
1159
+ var RAW2 = /^(?:script|style|textarea|title)$/;
1160
+ function nodeOf(tag, body, parent, made) {
1161
+ const attrs = attributes(body);
1162
+ const node = {
1163
+ tag,
1164
+ attrs,
1165
+ classes: new Set((attrs.get("class") ?? "").split(/\s+/).filter(Boolean)),
1166
+ parent: parent ?? null,
1167
+ style: declarations(attrs.get("style") ?? ""),
1168
+ text: false,
1169
+ gl: parent?.gl === true || (attrs.get("data-umber") ?? "").split(/\s+/).includes("text")
1170
+ };
1171
+ node.gl ||= made.some((found) => matches(node, found) === YES);
1172
+ return node;
1173
+ }
1174
+ function textNodes(html, made) {
1175
+ const found = [];
1176
+ const stack = [];
1177
+ const lower = html.toLowerCase();
1178
+ const token = /<!--[\s\S]*?-->|<(\/?)([a-zA-Z][\w:-]*)([^>]*)>|([^<]+)/g;
1179
+ const close2 = (tag) => {
1180
+ const at = stack.map((node) => node.tag).lastIndexOf(tag);
1181
+ if (at >= 0) stack.length = at;
1182
+ };
1183
+ const open = (tag, body) => {
1184
+ if (RAW2.test(tag)) {
1185
+ const end = lower.indexOf(`</${tag}`, token.lastIndex);
1186
+ token.lastIndex = end < 0 ? html.length : end;
1187
+ }
1188
+ if (!VOID3.test(tag) && !body.trimEnd().endsWith("/")) stack.push(nodeOf(tag, body, stack.at(-1), made));
1189
+ };
1190
+ for (let match = token.exec(html); match; match = token.exec(html)) {
1191
+ const [, closing, name = "", body = "", text] = match;
1192
+ const top = stack.at(-1);
1193
+ if (text === void 0) {
1194
+ if (closing) close2(name.toLowerCase());
1195
+ else if (name) open(name.toLowerCase(), body);
1196
+ } else if (top?.gl && !top.text && /\S/.test(text)) {
1197
+ top.text = true;
1198
+ found.push(top);
1199
+ }
1200
+ }
1201
+ return found;
1202
+ }
1203
+ var [OPEN, SPACE2, CLOSE] = ["\uE001", "\uE002", "\uE003"];
1204
+ var SIZE = new RegExp(
1205
+ String.raw`^(?:\d*\.?\d+(?:[a-z]+|%)|(?:xx?-|xxx-)?(?:small|large)|medium|smaller|larger|(?:calc|clamp|min|max)${OPEN})`,
1206
+ "i"
1207
+ );
1208
+ function shorthandWeight(head) {
1209
+ if (head.some((word) => /^(?:bolder|lighter)$/.test(word))) return void 0;
1210
+ return head.find((word) => /^\d+$/.test(word)) ?? (head.includes("bold") ? "700" : "400");
1211
+ }
1212
+ function fromShorthand(value, prop) {
1213
+ let flat = value;
1214
+ for (let last = ""; last !== flat; ) {
1215
+ last = flat;
1216
+ flat = flat.replace(/\(([^()]*)\)/g, (_, inner) => `${OPEN}${inner.replace(/\s+/g, SPACE2)}${CLOSE}`);
1217
+ }
1218
+ const words = flat.trim().split(/\s+/);
1219
+ const size = words.findIndex((word) => SIZE.test(word));
1220
+ if (size < 0) return void 0;
1221
+ const head = words.slice(0, size).map((word) => word.toLowerCase());
1222
+ if (prop === "font-style") return head.some((word) => /^(?:italic|oblique)/.test(word)) ? "italic" : "normal";
1223
+ if (prop === "font-weight") return shorthandWeight(head);
1224
+ let from = size + 1;
1225
+ if (words[from] === "/") from += 2;
1226
+ else if (words[from]?.startsWith("/") || words[size]?.endsWith("/")) from += 1;
1227
+ const family = words.slice(from).join(" ");
1228
+ return family ? family.replaceAll(OPEN, "(").replaceAll(SPACE2, " ").replaceAll(CLOSE, ")") : void 0;
1229
+ }
1230
+ function beats(weight2, held) {
1231
+ if (!held) return true;
1232
+ const differs = weight2.findIndex((part, i) => part !== held[i]);
1233
+ return differs < 0 || (weight2[differs] ?? 0) > (held[differs] ?? 0);
1234
+ }
1235
+ var Cascade = class {
1236
+ constructor(rules) {
1237
+ this.rules = rules;
1238
+ this.known = /* @__PURE__ */ new Map();
1239
+ }
1240
+ /** `prop` on `node`: its value, null where nothing sets it (the browser's own default), undefined where it is not sure. */
1241
+ value(node, prop, depth = 0) {
1242
+ let memo = this.known.get(node);
1243
+ if (!memo) this.known.set(node, memo = /* @__PURE__ */ new Map());
1244
+ if (!memo.has(prop)) memo.set(prop, depth > 20 ? void 0 : this.compute(node, prop, depth));
1245
+ return memo.get(prop);
1246
+ }
1247
+ /** How `rule` lands on `node`: NO, MAYBE or YES, and the specificity of its selectors that do. */
1248
+ lands(node, rule) {
1249
+ let best = NO;
1250
+ let specificity = 0;
1251
+ for (const found of rule.selectors) {
1252
+ const answer = matches(node, found);
1253
+ if (answer === YES) specificity = Math.max(specificity, found.specificity);
1254
+ best = Math.max(best, answer);
1255
+ }
1256
+ return { best: best && rule.maybe ? MAYBE : best, specificity };
1257
+ }
1258
+ /** The declaration that sets `prop` on `node` itself: null for none, undefined where a rule that might is not sure. */
1259
+ winner(node, prop) {
1260
+ const sets = (declaration) => declaration.prop === prop || declaration.prop === "font" && !prop.startsWith("--");
1261
+ let won = null;
1262
+ let held;
1263
+ const take = (declaration, rank, specificity, order) => {
1264
+ const weight2 = [declaration.important ? 1 : 0, declaration.important ? -rank : rank, specificity, order];
1265
+ if (!beats(weight2, held)) return;
1266
+ won = declaration;
1267
+ held = weight2;
1268
+ };
1269
+ for (const rule of this.rules) {
1270
+ const setting = rule.declarations.filter(sets);
1271
+ const { best, specificity } = setting.length ? this.lands(node, rule) : { best: NO, specificity: 0 };
1272
+ if (best === MAYBE) return void 0;
1273
+ if (best === YES) for (const declaration of setting) take(declaration, rule.rank, specificity, rule.order);
1274
+ }
1275
+ for (const declaration of node.style.filter(sets))
1276
+ take(declaration, declaration.important ? -Infinity : Infinity, 0, 0);
1277
+ return won;
1278
+ }
1279
+ compute(node, prop, depth) {
1280
+ const won = this.winner(node, prop);
1281
+ if (won === void 0) return void 0;
1282
+ const inherited = () => node.parent ? this.value(node.parent, prop, depth + 1) : null;
1283
+ if (!won) {
1284
+ if (prop === "font-weight" && BOLD.test(node.tag)) return "700";
1285
+ if (prop === "font-style" && ITALIC.test(node.tag)) return "italic";
1286
+ return inherited();
1287
+ }
1288
+ const whole = this.withVars(node, won.value, depth);
1289
+ const value = whole !== void 0 && won.prop === "font" ? fromShorthand(whole, prop) : whole?.trim();
1290
+ if (value === void 0 || /^revert/i.test(value)) return void 0;
1291
+ if (/^(?:inherit|unset)$/i.test(value)) return inherited();
1292
+ return /^initial$/i.test(value) ? null : value;
1293
+ }
1294
+ /** `value` with each var() as the custom property's value on `node` (its fallback where none is set); undefined where one is not sure. */
1295
+ withVars(node, value, depth) {
1296
+ const call = /var\(\s*(--[\w-]+)\s*(?:,([^()]*))?\)/;
1297
+ let out = value;
1298
+ for (let turn = 0; turn < 20; turn++) {
1299
+ const match = call.exec(out);
1300
+ if (!match) break;
1301
+ const found = this.value(node, match[1] ?? "", depth + 1);
1302
+ const set = found === null ? match[2] : found;
1303
+ if (set === void 0) return void 0;
1304
+ out = out.slice(0, match.index) + set + out.slice(match.index + match[0].length);
1305
+ }
1306
+ return out.includes("var(") ? void 0 : out;
1307
+ }
1308
+ };
1309
+ function hundred(weight2) {
1310
+ const named = { bold: "700", normal: "400" }[(weight2 ?? "normal").toLowerCase()] ?? weight2 ?? "";
1311
+ if (!/^\d+$/.test(named)) return void 0;
1312
+ return /^[1-9]00$/.test(named) ? named : "400";
1313
+ }
1314
+ function textFaces(html, sheets, made = []) {
1315
+ const { rules, unread } = rulesOf(sheets);
1316
+ const cascade = new Cascade(rules);
1317
+ const lists = made.flatMap((list) => list.split(/,(?![^(]*\))/));
1318
+ return textNodes(html, lists.map(selector)).map((node) => {
1319
+ const family = cascade.value(node, "font-family");
1320
+ const weight2 = cascade.value(node, "font-weight");
1321
+ const style = cascade.value(node, "font-style");
1322
+ const round = weight2 === void 0 ? void 0 : hundred(weight2);
1323
+ if (unread || family === void 0 || round === void 0 || style === void 0) return null;
1324
+ const slant = /italic|oblique/i.test(style ?? "") ? "italic" : "normal";
1325
+ return (family ?? "").split(",").map(
1326
+ (name) => name.trim().replace(/^["']|["']$/g, "").toLowerCase()
1327
+ ).filter(Boolean).map((name) => `${name}|${round}|${slant}`);
1328
+ });
1329
+ }
1330
+
1331
+ // tools/assets/encode.ts
1332
+ import { spawnSync } from "node:child_process";
1333
+ function findFfmpeg(given) {
1334
+ const ffmpeg = given ?? process.env.FFMPEG ?? "ffmpeg";
1335
+ const run2 = spawnSync(ffmpeg, ["-hide_banner", "-version"], { encoding: "utf8" });
1336
+ return run2.status === 0 && /^ffmpeg version/m.test(run2.stdout) ? ffmpeg : null;
1337
+ }
1338
+ function run(ffmpeg, input, args, output) {
1339
+ const done = spawnSync(ffmpeg, ["-hide_banner", "-loglevel", "error", "-y", "-i", input, ...args, output], {
1340
+ encoding: "utf8"
1341
+ });
1342
+ if (done.status !== 0)
1343
+ throw new Error(`ffmpeg failed: ${(done.stderr || String(done.error ?? "")).trim().slice(0, 300)}`);
1344
+ }
1345
+ function encodeScrub(ffmpeg, input, output, { width, crf = 23 }) {
1346
+ const scale = width ? `scale='min(${width},iw)':-2:flags=lanczos,` : "scale=trunc(iw/2)*2:trunc(ih/2)*2,";
1347
+ const filter = `${scale}setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709:range=tv,format=yuv420p`;
1348
+ const codec = ["-c:v", "libx264", "-profile:v", "main", "-pix_fmt", "yuv420p"];
1349
+ const frames = ["-g", "1", "-keyint_min", "1", "-sc_threshold", "0", "-bf", "0", "-refs", "1", "-tune", "fastdecode"];
1350
+ const quality = ["-crf", String(crf), "-preset", "slow", "-movflags", "+faststart", "-f", "mp4"];
1351
+ run(ffmpeg, input, ["-an", "-vf", filter, ...codec, ...frames, ...quality], output);
1352
+ }
1353
+ function encodePoster(ffmpeg, input, output) {
1354
+ run(ffmpeg, input, ["-frames:v", "1", "-q:v", "3", "-f", "image2"], output);
1355
+ }
1356
+ var escape3 = (value) => value.replace(/&/g, "&amp;").replace(/"/g, "&quot;");
1357
+ function withScrubAttributes(html, more) {
1358
+ return html.replace(/<([a-z][\w-]*)\b([^>]*\sdata-umber-scrub\b[^>]*)>/gi, (tag, name, body) => {
1359
+ const attrs = attributes(body);
1360
+ const added = Object.entries(more(name.toLowerCase(), attrs)).filter(([key]) => !attrs.has(key)).map(([key, value]) => ` ${key}="${escape3(value)}"`).join("");
1361
+ if (!added) return tag;
1362
+ const end = tag.endsWith("/>") ? tag.length - 2 : tag.length - 1;
1363
+ return `${tag.slice(0, end).trimEnd()}${added}${tag.slice(end)}`;
1364
+ });
1365
+ }
1366
+
1367
+ // tools/assets/video.ts
1368
+ function boxes(bytes, from, to) {
1369
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1370
+ const found = [];
1371
+ for (let at = from; at < to; ) {
1372
+ if (at + 8 > to) return [];
1373
+ let size = view.getUint32(at);
1374
+ let body = at + 8;
1375
+ if (size === 1) {
1376
+ if (at + 16 > to) return [];
1377
+ size = Number(view.getBigUint64(at + 8));
1378
+ body = at + 16;
1379
+ } else if (size === 0) size = to - at;
1380
+ if (size < body - at || at + size > to) return [];
1381
+ found.push({ type: String.fromCharCode(...bytes.subarray(at + 4, at + 8)), start: at, body, end: at + size });
1382
+ at += size;
1383
+ }
1384
+ return found;
1385
+ }
1386
+ var PARENTS = /* @__PURE__ */ new Set(["trak", "mdia", "minf", "stbl"]);
1387
+ function shiftOffsets(bytes, moov, shift, range) {
1388
+ const out = new Uint8Array(bytes.subarray(moov.start, moov.end));
1389
+ const view = new DataView(out.buffer);
1390
+ const moved = (offset) => offset >= range[0] && offset < range[1] ? offset + shift : offset;
1391
+ for (const table of offsetTables(bytes, moov.body, moov.end)) {
1392
+ const at = table.body - moov.start;
1393
+ const wide = table.type === "co64";
1394
+ const count = Math.min(view.getUint32(at + 4), Math.floor((table.end - table.body - 8) / (wide ? 8 : 4)));
1395
+ for (let i = 0; i < count; i++) if (!moveEntry(view, at + 8 + i * (wide ? 8 : 4), wide, moved)) return null;
1396
+ }
1397
+ return out;
1398
+ }
1399
+ function moveEntry(view, entry, wide, moved) {
1400
+ if (wide) {
1401
+ view.setBigUint64(entry, BigInt(moved(Number(view.getBigUint64(entry)))));
1402
+ return true;
1403
+ }
1404
+ const next = moved(view.getUint32(entry));
1405
+ if (next <= 4294967295) view.setUint32(entry, next);
1406
+ return next <= 4294967295;
1407
+ }
1408
+ function offsetTables(bytes, from, to) {
1409
+ return boxes(bytes, from, to).flatMap((box) => {
1410
+ if (PARENTS.has(box.type)) return offsetTables(bytes, box.body, box.end);
1411
+ return box.type === "stco" || box.type === "co64" ? [box] : [];
1412
+ });
1413
+ }
1414
+ function faststart(bytes) {
1415
+ const top = boxes(bytes, 0, bytes.length);
1416
+ const moov = top.find((box) => box.type === "moov");
1417
+ const mdat = top.find((box) => box.type === "mdat");
1418
+ if (!moov || !mdat || moov.start < mdat.start || top.some((box) => box.type === "moof")) return null;
1419
+ const index = shiftOffsets(bytes, moov, moov.end - moov.start, [mdat.start, moov.start]);
1420
+ if (!index) return null;
1421
+ const out = new Uint8Array(bytes.length);
1422
+ out.set(bytes.subarray(0, mdat.start));
1423
+ out.set(index, mdat.start);
1424
+ out.set(bytes.subarray(mdat.start, moov.start), mdat.start + index.length);
1425
+ out.set(bytes.subarray(moov.end), moov.end);
1426
+ return out;
1427
+ }
1428
+ function scrubbedVideos(html) {
1429
+ const found = /* @__PURE__ */ new Set();
1430
+ const add = (url) => {
1431
+ if (url && /\.(mp4|m4v|mov)(?:[?#]|$)/i.test(url)) found.add(url);
1432
+ };
1433
+ for (const match of html.matchAll(/<([a-z][\w-]*)\b([^>]*\sdata-umber-scrub\b[^>]*)>/gi)) {
1434
+ const attrs = attributes(match[2] ?? "");
1435
+ for (const name of ["src", "data-umber-scrub-src", "data-umber-scrub-src-mobile"]) add(attrs.get(name));
1436
+ if (match[1]?.toLowerCase() !== "video") continue;
1437
+ const from = match.index + match[0].length;
1438
+ const end = html.toLowerCase().indexOf("</video", from);
1439
+ for (const [, body = ""] of html.slice(from, end < 0 ? from : end).matchAll(/<source\b([^>]*)>/gi))
1440
+ add(attributes(body).get("src"));
1441
+ }
1442
+ return [...found];
1443
+ }
1444
+ function videoTrack(bytes) {
1445
+ const moov = boxes(bytes, 0, bytes.length).find((box) => box.type === "moov");
1446
+ for (const trak of moov ? boxes(bytes, moov.body, moov.end).filter((box) => box.type === "trak") : []) {
1447
+ const inside = boxes(bytes, trak.body, trak.end);
1448
+ const mdia = inside.find((box) => box.type === "mdia");
1449
+ const media = mdia ? boxes(bytes, mdia.body, mdia.end) : [];
1450
+ const handler = media.find((box) => box.type === "hdlr");
1451
+ if (!handler || String.fromCharCode(...bytes.subarray(handler.body + 8, handler.body + 12)) !== "vide") continue;
1452
+ const minf = media.find((box) => box.type === "minf");
1453
+ const stbl = minf ? boxes(bytes, minf.body, minf.end).find((box) => box.type === "stbl") : void 0;
1454
+ return { tkhd: inside.find((box) => box.type === "tkhd"), table: stbl ? boxes(bytes, stbl.body, stbl.end) : [] };
1455
+ }
1456
+ return null;
1457
+ }
1458
+ function videoShape(bytes) {
1459
+ const track = videoTrack(bytes);
1460
+ if (!track?.tkhd) return null;
1461
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1462
+ const width = view.getUint32(track.tkhd.end - 8) / 65536;
1463
+ const sizes = track.table.find((box) => box.type === "stsz");
1464
+ const keys = track.table.find((box) => box.type === "stss");
1465
+ if (!sizes || sizes.end - sizes.body < 12) return null;
1466
+ const samples = view.getUint32(sizes.body + 8);
1467
+ const everyFrameKey = !keys || keys.end - keys.body >= 8 && view.getUint32(keys.body + 4) >= samples;
1468
+ return { width, everyFrameKey, samples };
1469
+ }
1470
+
1471
+ // tools/assets/site.ts
1472
+ var PICTURE = /\.(jpe?g|png|webp|gif)$/i;
1473
+ var GL_TEXT = /\bdata-umber\s*=\s*["']?(?:[^"'>]*\s)?text\b/;
1474
+ var VECTOR = /\.svg(?:[?#]|$)/i;
1475
+ var FLAGS = { bc7: 2, bc1: 2 | 32, astc: 4, etc2: 8, avif: 16 };
1476
+ var extension = (kind) => kind === "avif" ? ".avif" : `.${kind}.ktx2`;
1477
+ async function walk(dir, skip2) {
1478
+ const files = [];
1479
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
1480
+ const path = join2(dir, entry.name);
1481
+ if (entry.isDirectory()) {
1482
+ if (path !== skip2 && entry.name !== "node_modules") files.push(...await walk(path, skip2));
1483
+ } else files.push(path);
1484
+ }
1485
+ return files;
1486
+ }
1487
+ var urlOf = (dir, file, baseUrl) => `${baseUrl}${relative(dir, file).split(sep).map(encodeURIComponent).join("/")}`;
1488
+ var localFile = (dir, baseUrl) => (url) => {
1489
+ const path = decodeURIComponent(url.pathname);
1490
+ if (url.origin !== "http://site" || !path.startsWith(baseUrl)) return null;
1491
+ const file = join2(dir, path.slice(baseUrl.length));
1492
+ return existsSync3(file) ? file : null;
1493
+ };
1494
+ var NAMED = 64;
1495
+ async function namedPictures(dir, folder, named) {
1496
+ const files = /* @__PURE__ */ new Map();
1497
+ for (const entry of named) {
1498
+ const name = typeof entry === "string" ? entry : entry.file;
1499
+ const path = resolve(dir, name);
1500
+ if (relative(dir, path).startsWith("..") || !existsSync3(path))
1501
+ throw new Error(`pictures: "${name}" is not a file or a folder inside ${dir}`);
1502
+ const found = (await stat(path)).isDirectory() ? await walk(path, folder) : [path];
1503
+ for (const file of found.filter((each) => PICTURE.test(each)))
1504
+ files.set(file, typeof entry === "string" ? void 0 : entry.quality);
1505
+ }
1506
+ return files;
1507
+ }
1508
+ async function findPictures(dir, folder, baseUrl, { all = false, pictures: named = [] }) {
1509
+ const files = await walk(dir, folder);
1510
+ const pictures = /* @__PURE__ */ new Map();
1511
+ const pages = [];
1512
+ const skipped = [];
1513
+ const text = [];
1514
+ const chars = /* @__PURE__ */ new Set();
1515
+ const namedFiles = await namedPictures(dir, folder, named);
1516
+ const readsNamed = (html) => namedFiles.size > 0 && glTags(html).length > 0;
1517
+ for (const file of files.filter((path) => path.endsWith(".html"))) {
1518
+ const page = new URL(urlOf(dir, file, baseUrl), "http://site");
1519
+ const html = await readFile2(file, "utf8");
1520
+ let shows = GL_TEXT.test(html);
1521
+ if (shows) {
1522
+ text.push({ url: page, html });
1523
+ glTextCharacters(html, chars);
1524
+ }
1525
+ for (const ref of drawnPictures(html).filter((name) => !VECTOR.test(name))) {
1526
+ const url = new URL(ref, page);
1527
+ const local = localFile(dir, baseUrl)(url);
1528
+ if (local && PICTURE.test(local)) pictures.set(url.pathname, local);
1529
+ else skipped.push(`${ref} (in ${relative(dir, file)}): not a JPEG, PNG, WebP or GIF in the site`);
1530
+ shows ||= Boolean(local && PICTURE.test(local));
1531
+ }
1532
+ if (shows || all || readsNamed(html)) pages.push(file);
1533
+ }
1534
+ for (const file of files.filter((path) => all && PICTURE.test(path))) pictures.set(urlOf(dir, file, baseUrl), file);
1535
+ const asked = /* @__PURE__ */ new Map();
1536
+ for (const [file, quality] of namedFiles) {
1537
+ pictures.set(urlOf(dir, file, baseUrl), file);
1538
+ asked.set(urlOf(dir, file, baseUrl), quality);
1539
+ }
1540
+ return { pictures, named: asked, pages, skipped: [...new Set(skipped)], text, chars };
1541
+ }
1542
+ async function fromCache(cache, key) {
1543
+ const meta = join2(cache, `${key}.json`);
1544
+ if (!existsSync3(meta)) return null;
1545
+ const image = JSON.parse(await readFile2(meta, "utf8"));
1546
+ if (!image.sizes) return null;
1547
+ const files = [];
1548
+ for (const [i, kind] of image.kinds.entries()) {
1549
+ const path = join2(cache, `${key}${extension(kind)}`);
1550
+ if (!existsSync3(path)) return null;
1551
+ files.push({ kind, bytes: await readFile2(path), sizes: image.sizes[i] ?? [] });
1552
+ }
1553
+ return { ...image, files };
1554
+ }
1555
+ async function toCache(cache, image) {
1556
+ await mkdir2(cache, { recursive: true });
1557
+ for (const file of image.files) await writeFile2(join2(cache, `${image.key}${extension(file.kind)}`), file.bytes);
1558
+ const { files, ...meta } = image;
1559
+ const kinds = files.map((file) => file.kind);
1560
+ await writeFile2(
1561
+ join2(cache, `${image.key}.json`),
1562
+ JSON.stringify({ ...meta, kinds, sizes: files.map((file) => file.sizes) })
1563
+ );
1564
+ }
1565
+ async function pool(items, limit, work) {
1566
+ let next = 0;
1567
+ const run2 = async () => {
1568
+ while (next < items.length) {
1569
+ const item = items[next++];
1570
+ if (item !== void 0) await work(item);
1571
+ }
1572
+ };
1573
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, run2));
1574
+ }
1575
+ function check(options2) {
1576
+ const formats = ["bc7", "astc", "etc2"];
1577
+ const bad = options2.formats?.find((format) => !formats.includes(format));
1578
+ if (bad !== void 0) throw new Error(`unknown format "${bad}" (${formats.join(", ")})`);
1579
+ if (options2.effort && !["fast", "normal", "best"].includes(options2.effort))
1580
+ throw new Error(`unknown effort "${options2.effort}" (fast, normal, best)`);
1581
+ if (options2.domImages && !["tiny", "avif", "source"].includes(options2.domImages))
1582
+ throw new Error(`unknown domImages "${options2.domImages}" (tiny, avif, source)`);
1583
+ const type = options2.data?.find((named) => typeof named !== "string" && !(named.type in DATA_TYPES));
1584
+ if (type && typeof type !== "string")
1585
+ throw new Error(`data: unknown type "${type.type}" for ${type.file} (${Object.keys(DATA_TYPES).join(", ")})`);
1586
+ const floor = options2.pictures?.find((named) => typeof named !== "string" && !(named.quality > 0));
1587
+ if (floor && typeof floor !== "string")
1588
+ throw new Error(`pictures: ${floor.file} needs a quality, dB ({ file: "${floor.file}", quality: 50 })`);
1589
+ const whole = (value, low, high) => value === void 0 || Number.isInteger(value) && value >= low && value <= high;
1590
+ const odd = options2.hints?.find((name) => !/^[a-z]+$/.test(name));
1591
+ if (odd !== void 0) throw new Error(`hints: "${odd}" is no chunk's name (shapes, glsl, sim, fx...)`);
1592
+ const effects = options2.effects ?? {};
1593
+ const plain = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1594
+ if (!plain(effects) || !Object.values(effects).every(plain))
1595
+ throw new Error("effects: an object of effect definitions by name ({ ripple: { fragment: { ... } } })");
1596
+ if (!whole(options2.tinySize, 16, 4096)) throw new Error(`tinySize ${options2.tinySize}: a whole number, 16 to 4096`);
1597
+ if (!whole(options2.tinyQuality, 1, 100))
1598
+ throw new Error(`tinyQuality ${options2.tinyQuality}: a whole number, 1 to 100`);
1599
+ }
1600
+ async function obtain(bytes, { native, settings, cache }, result) {
1601
+ const key = native.imageKey(bytes, settings);
1602
+ const kept = cache ? await fromCache(cache, key) : null;
1603
+ if (kept) {
1604
+ result.cached++;
1605
+ return kept;
1606
+ }
1607
+ const image = await native.prepareImage(bytes, settings);
1608
+ result.prepared++;
1609
+ if (cache) await toCache(cache, image);
1610
+ return image;
1611
+ }
1612
+ async function place(image, out, result, named) {
1613
+ let flags = (image.alpha ? 1 : 0) | (named ? NAMED : 0);
1614
+ for (const prepared of image.files) {
1615
+ flags |= FLAGS[prepared.kind];
1616
+ result.bytes[prepared.kind] = (result.bytes[prepared.kind] ?? 0) + prepared.bytes.length;
1617
+ const name = `${image.key}${extension(prepared.kind)}`;
1618
+ const cached = out.cache ? join2(out.cache, name) : "";
1619
+ if (cached && existsSync3(cached)) await copyFile(cached, join2(out.folder, name));
1620
+ else await writeFile2(join2(out.folder, name), prepared.bytes);
1621
+ }
1622
+ const sizes = [["bc7", "bc1"], ["astc"], ["etc2"]].map(
1623
+ (kinds) => image.files.find((made) => kinds.includes(made.kind))?.sizes ?? []
1624
+ );
1625
+ return [image.key, image.width, image.height, image.textureWidth, image.textureHeight, flags, image.astcBlock, sizes];
1626
+ }
1627
+ function pointPage(html, pageUrl, manifestUrl, { smaller, tiny, fallback, source }) {
1628
+ const shown = source ? html : rewritePictures(
1629
+ html,
1630
+ (ref) => smaller.get(new URL(ref, pageUrl).pathname) ?? null,
1631
+ tiny.size ? (ref) => tiny.get(new URL(ref, pageUrl).pathname) ?? null : void 0
1632
+ );
1633
+ const withTags = withManifest(shown, manifestUrl);
1634
+ return /<source[^>]*\bdata-umber-tiny\b/.test(withTags) ? withFallback(withTags, fallback) : withTags;
1635
+ }
1636
+ async function writePages(pages, options2, manifestUrl, shown) {
1637
+ const baseUrl = normalBase(options2.baseUrl);
1638
+ for (const page of pages) {
1639
+ const html = await readFile2(page, "utf8");
1640
+ const pageUrl = new URL(urlOf(options2.dir, page, baseUrl), "http://site");
1641
+ const next = pointPage(html, pageUrl, manifestUrl, shown);
1642
+ if (next !== html) await writeFile2(page, next);
1643
+ }
1644
+ }
1645
+ async function placeholder({ bytes, key }, native, options2, out) {
1646
+ const side = options2.tinySize ?? 512;
1647
+ const quality = options2.tinyQuality ?? 50;
1648
+ const name = `${key}.tiny${side}q${quality}.avif`;
1649
+ const kept = out.cache ? join2(out.cache, name) : "";
1650
+ const meta = `${kept}.json`;
1651
+ let made = null;
1652
+ if (kept && existsSync3(kept) && existsSync3(meta))
1653
+ made = {
1654
+ bytes: await readFile2(kept),
1655
+ width: JSON.parse(await readFile2(meta, "utf8")).width
1656
+ };
1657
+ if (!made) {
1658
+ const tiny = await native.tinyAvif(bytes, options2.maxSize ?? 4096, side, quality);
1659
+ made = tiny;
1660
+ if (out.cache) {
1661
+ await mkdir2(out.cache, { recursive: true });
1662
+ await writeFile2(kept, tiny.bytes);
1663
+ await writeFile2(meta, JSON.stringify({ width: tiny.width, height: tiny.height }));
1664
+ }
1665
+ }
1666
+ await writeFile2(join2(out.folder, name), made.bytes);
1667
+ return { name, width: made.width, bytes: made.bytes.length };
1668
+ }
1669
+ var normalBase = (baseUrl = "/") => baseUrl.replace(/\/?$/, "/").replace(/^\/?/, "/");
1670
+ var nothing = () => ({
1671
+ manifest: null,
1672
+ prepared: 0,
1673
+ cached: 0,
1674
+ pages: 0,
1675
+ fonts: 0,
1676
+ data: 0,
1677
+ videos: 0,
1678
+ encoded: 0,
1679
+ hinted: 0,
1680
+ skipped: [],
1681
+ bytes: { source: 0 }
1682
+ });
1683
+ function addon() {
1684
+ try {
1685
+ return loadNative();
1686
+ } catch (err) {
1687
+ return `all pictures: ${err instanceof Error ? err.message : String(err)} The site keeps its plain images, and its GL text is drawn from the glyph atlas.`;
1688
+ }
1689
+ }
1690
+ function hasLicence() {
1691
+ const chunk = new URL("../chunks/licence.js", import.meta.url);
1692
+ return chunk.protocol === "file:" && existsSync3(fileURLToPath2(chunk));
1693
+ }
1694
+ var needsOf = (effects) => new Map(Object.entries(effects ?? {}).map(([name, definition]) => [name, effectHints(definition)]));
1695
+ var EVERY_SCREEN = /^\s*(?:all|screen)?\s*$/i;
1696
+ function pageSources(dir, baseUrl) {
1697
+ const local = localFile(dir, baseUrl);
1698
+ const files = /* @__PURE__ */ new Map();
1699
+ const read2 = (file) => {
1700
+ let text = files.get(file);
1701
+ if (!text) files.set(file, text = readFile2(file, "utf8").catch(() => null));
1702
+ return text;
1703
+ };
1704
+ return async (html, page) => {
1705
+ const sheets = [];
1706
+ let whole = true;
1707
+ for (const [, block, css = "", link = ""] of html.matchAll(
1708
+ /<style\b([^>]*)>([\s\S]*?)<\/style\s*>|<link\b([^>]*)>/gi
1709
+ )) {
1710
+ const attrs = attributes(block ?? link);
1711
+ const maybe = !EVERY_SCREEN.test(attrs.get("media") ?? "") || attrs.has("disabled");
1712
+ if (block !== void 0) sheets.push({ css, maybe });
1713
+ else if (/\bstylesheet\b/i.test(attrs.get("rel") ?? "") && attrs.get("href")) {
1714
+ const file = local(new URL(attrs.get("href") ?? "", page));
1715
+ const text = file ? await read2(file) : null;
1716
+ if (text === null) whole = false;
1717
+ else sheets.push({ css: text, maybe: maybe || /\balternate\b/i.test(attrs.get("rel") ?? "") });
1718
+ }
1719
+ }
1720
+ return { sheets, whole };
1721
+ };
1722
+ }
1723
+ var FONT_HINTS = 4;
1724
+ function pageFonts(html, sheets, fonts, made) {
1725
+ const files = /* @__PURE__ */ new Set();
1726
+ for (const keys of textFaces(html, sheets, made)) {
1727
+ const file = keys?.map((key) => fonts[key]).find(Boolean);
1728
+ if (file) files.add(file);
1729
+ }
1730
+ return [...files].slice(0, FONT_HINTS);
1731
+ }
1732
+ var drawsPicture = (html) => drawnPictures(html).length > 0 || glTags(html).some(
1733
+ ({ attrs }) => [...attrs].some(([name, value]) => name.startsWith("data-umber-") && PICTURE_VALUE.test(value))
1734
+ );
1735
+ function pageScripts(html, page, scripts = {}) {
1736
+ const urls = [];
1737
+ for (const [, attrs = "", inline = ""] of html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi)) {
1738
+ const src = attributes(attrs).get("src");
1739
+ if (src) urls.push(src);
1740
+ else
1741
+ for (const [, , url = ""] of inline.matchAll(/\b(?:import|from)\s*\(?\s*(["'])([^"']+\.m?js)\1/g)) urls.push(url);
1742
+ }
1743
+ for (const [, attrs = ""] of html.matchAll(/<link\b([^>]*\bmodulepreload\b[^>]*)>/gi))
1744
+ urls.push(attributes(attrs).get("href") ?? "");
1745
+ const paths = urls.filter(Boolean).map((url) => new URL(url, page).pathname);
1746
+ const loaded2 = Object.entries(scripts).filter(([file]) => paths.some((path) => path.endsWith(`/${file}`)));
1747
+ return joinNeeds(loaded2.map(([, needs]) => needs));
1748
+ }
1749
+ function noteUnread(scripts, all, chunks, unread) {
1750
+ if (!unread || !scripts.unknown.length) return;
1751
+ const names = new Set(
1752
+ glTags(all).flatMap(
1753
+ ({ attrs }) => `${attrs.get("data-umber-effect") ?? ""} ${attrs.get("data-umber-shader") ?? ""}`.split(/\s+/)
1754
+ )
1755
+ );
1756
+ for (const { what, chunks: may, name } of scripts.unknown) {
1757
+ const left = may.filter((chunk) => !chunks.includes(chunk));
1758
+ if (name === void 0 ? may.length && !left.length : !names.has(name)) continue;
1759
+ unread.set(what, /* @__PURE__ */ new Set([...unread.get(what) ?? [], ...left]));
1760
+ }
1761
+ }
1762
+ function unreadNotice(unread) {
1763
+ if (!unread.size) return "";
1764
+ const chunks = [...new Set([...unread.values()].flatMap((left2) => [...left2]))];
1765
+ const effects = [...unread.values()].some((left2) => !left2.size);
1766
+ const left = [
1767
+ ...chunks.map((chunk) => `chunks/${chunk}.js`),
1768
+ ...effects ? ["what an effect that was not read needs (glsl, fx, sim, flip or glyphs)"] : []
1769
+ ];
1770
+ const example = JSON.stringify(chunks.length ? chunks : ["glsl"]).replace(/,/g, ", ");
1771
+ return `hints: the build could not read ${[...unread.keys()].join(", ")} in the site's scripts. Not hinted, so fetched only when the engine asks: ${left.join(", ")}. To fetch them with the page, name them in the plugin's options: hints: ${example}`;
1772
+ }
1773
+ async function pageHints(html, page, sources, hinting) {
1774
+ const { built, fonts, licence, more, effects } = hinting;
1775
+ const scripts = pageScripts(html, page, built?.scripts);
1776
+ const all = html + scripts.markup;
1777
+ const chunks = pageChunks(all);
1778
+ const engine = built?.engine ? { folder: built.engine } : scriptEngine(html);
1779
+ if (!chunks.length || !engine) return "";
1780
+ const { sheets, whole } = await sources(html, page);
1781
+ const styles = sheets.map((sheet) => sheet.css);
1782
+ const known = new Map([...Object.entries(scripts.effects), ...effects]);
1783
+ const shaders = new Map(Object.entries(scripts.shaders));
1784
+ const named = effectChunks(all, known, shaders);
1785
+ for (const chunk of [...named, ...scripts.chunks, ...styleChunks(html, styles), ...more])
1786
+ if (!chunks.includes(chunk)) chunks.push(chunk);
1787
+ noteUnread(scripts, all, chunks, hinting.unread);
1788
+ if (licence) chunks.push("licence");
1789
+ const manifest = /<meta\s+name=["']?umber-assets["']?\s+content="([^"]*)"/i.exec(html)?.[1];
1790
+ const text = chunks.includes("text") && Object.keys(fonts).length > 0;
1791
+ if (manifest && (drawsPicture(html) || uniformPictures(all, known, shaders).length > 0)) chunks.push("prepared");
1792
+ if (manifest && text) chunks.push("curves");
1793
+ const outlines = manifest && text && whole ? pageFonts(html, sheets, fonts, scripts.texts) : [];
1794
+ return hintLinks(engine, chunks) + fontLinks(manifest ?? "", outlines);
1795
+ }
1796
+ async function hintPages(options2, hinting) {
1797
+ const folder = join2(options2.dir, options2.folder ?? "_umber");
1798
+ const baseUrl = normalBase(options2.baseUrl);
1799
+ const sources = pageSources(options2.dir, baseUrl);
1800
+ let hinted = 0;
1801
+ for (const page of (await walk(options2.dir, folder)).filter((path) => path.endsWith(".html"))) {
1802
+ const html = await readFile2(page, "utf8");
1803
+ const url = new URL(urlOf(options2.dir, page, baseUrl), "http://site");
1804
+ const links = await pageHints(html, url, sources, hinting);
1805
+ if (links) hinted++;
1806
+ const next = withHints(html, links);
1807
+ if (next !== html) await writeFile2(page, next);
1808
+ }
1809
+ return hinted;
1810
+ }
1811
+ async function packData(options2, baseUrl, folder, result) {
1812
+ const packed = {};
1813
+ for (const named of options2.data ?? []) {
1814
+ const { file, type } = typeof named === "string" ? { file: named, type: "raw" } : named;
1815
+ const path = resolve(options2.dir, file);
1816
+ if (relative(options2.dir, path).startsWith("..") || !existsSync3(path))
1817
+ throw new Error(`data: "${file}" is not a file inside ${options2.dir}`);
1818
+ const made = pack(await readFile2(path), type);
1819
+ await writeFile2(join2(folder, `${made.key}.data`), made.bytes);
1820
+ packed[urlOf(options2.dir, path, baseUrl)] = [made.key, type, made.size];
1821
+ result.bytes.dataSource = (result.bytes.dataSource ?? 0) + made.size;
1822
+ result.bytes.data = (result.bytes.data ?? 0) + made.bytes.length;
1823
+ result.data++;
1824
+ }
1825
+ return packed;
1826
+ }
1827
+ async function moveIndexes(options2) {
1828
+ const baseUrl = normalBase(options2.baseUrl);
1829
+ const local = localFile(options2.dir, baseUrl);
1830
+ const files = /* @__PURE__ */ new Set();
1831
+ const folder = join2(options2.dir, options2.folder ?? "_umber");
1832
+ for (const page of (await walk(options2.dir, folder)).filter((path) => path.endsWith(".html"))) {
1833
+ const url = new URL(urlOf(options2.dir, page, baseUrl), "http://site");
1834
+ for (const ref of scrubbedVideos(await readFile2(page, "utf8"))) {
1835
+ const file = local(new URL(ref, url));
1836
+ if (file) files.add(file);
1837
+ }
1838
+ }
1839
+ let moved = 0;
1840
+ for (const file of files) {
1841
+ const next = faststart(await readFile2(file));
1842
+ if (!next) continue;
1843
+ await writeFile2(file, next);
1844
+ options2.log?.(
1845
+ `${relative(options2.dir, file)}: its index moved in front of its frames, so it scrubs while it downloads`
1846
+ );
1847
+ moved++;
1848
+ }
1849
+ return moved;
1850
+ }
1851
+ var scrubSource = (attrs) => attrs.get("data-umber-scrub-src") ?? attrs.get("src") ?? "";
1852
+ async function cachedFile(cache, name, out, make) {
1853
+ const kept = cache ? join2(cache, name) : "";
1854
+ if (kept && existsSync3(kept)) {
1855
+ await copyFile(kept, out);
1856
+ return;
1857
+ }
1858
+ make(out);
1859
+ if (cache) {
1860
+ await mkdir2(cache, { recursive: true });
1861
+ await copyFile(out, kept);
1862
+ }
1863
+ }
1864
+ async function encodeOne(video, ffmpeg, settings, out) {
1865
+ const bytes = await readFile2(video.file);
1866
+ const shape = videoShape(bytes);
1867
+ if (!shape) return 0;
1868
+ const key = createHash2("sha256").update(JSON.stringify(settings)).update(bytes).digest("hex").slice(0, 20);
1869
+ const source = join2(out.folder, `${key}.source`);
1870
+ let made = 0;
1871
+ const phone = settings.mobile ?? 720;
1872
+ await mkdir2(out.folder, { recursive: true });
1873
+ if (video.mobile && phone !== false && shape.width > phone) {
1874
+ const name = `${key}.mobile.mp4`;
1875
+ await cachedFile(out.cache, name, join2(out.folder, name), (to) => {
1876
+ encodeScrub(ffmpeg, video.file, to, { width: phone, crf: settings.crf });
1877
+ });
1878
+ video.made.mobile = `${out.folderUrl}${name}`;
1879
+ made++;
1880
+ }
1881
+ if (video.poster && settings.poster !== false) {
1882
+ const name = `${key}.poster.jpg`;
1883
+ await cachedFile(out.cache, name, join2(out.folder, name), (to) => {
1884
+ encodePoster(ffmpeg, video.file, to);
1885
+ });
1886
+ video.made.poster = `${out.folderUrl}${name}`;
1887
+ made++;
1888
+ }
1889
+ if (!shape.everyFrameKey || settings.width !== void 0 && shape.width > settings.width) {
1890
+ await cachedFile(out.cache, `${key}.scrub.mp4`, source, (to) => {
1891
+ encodeScrub(ffmpeg, video.file, to, settings);
1892
+ });
1893
+ await copyFile(source, video.file);
1894
+ made++;
1895
+ }
1896
+ await rm(source, { force: true });
1897
+ return made;
1898
+ }
1899
+ async function scrubbedFiles(options2, folder) {
1900
+ const baseUrl = normalBase(options2.baseUrl);
1901
+ const local = localFile(options2.dir, baseUrl);
1902
+ const videos = /* @__PURE__ */ new Map();
1903
+ const pages = [];
1904
+ for (const file of (await walk(options2.dir, folder)).filter((path) => path.endsWith(".html"))) {
1905
+ const url = new URL(urlOf(options2.dir, file, baseUrl), "http://site");
1906
+ const html = await readFile2(file, "utf8");
1907
+ pages.push({ file, url, html });
1908
+ withScrubAttributes(html, (name, attrs) => {
1909
+ const video = local(new URL(scrubSource(attrs), url));
1910
+ if (!video || !/\.(mp4|m4v|mov)$/i.test(video)) return {};
1911
+ const known = videos.get(video) ?? { file: video, mobile: false, poster: false, made: {} };
1912
+ known.mobile ||= !attrs.has("data-umber-scrub-src-mobile");
1913
+ known.poster ||= name === "video" && !attrs.has("poster");
1914
+ videos.set(video, known);
1915
+ return {};
1916
+ });
1917
+ }
1918
+ return { videos, pages, local };
1919
+ }
1920
+ async function encodeVideos(options2, result) {
1921
+ const settings = options2.encodeVideos === true ? {} : options2.encodeVideos;
1922
+ if (!settings) return;
1923
+ const ffmpeg = findFfmpeg(options2.ffmpeg);
1924
+ if (!ffmpeg) {
1925
+ result.skipped.push(
1926
+ "encodeVideos: no ffmpeg on this computer (looked at the ffmpeg option, $FFMPEG and the PATH), so the site's videos stay as they are. Install ffmpeg, or encode them yourself: npm run scrub"
1927
+ );
1928
+ return;
1929
+ }
1930
+ const folderName = options2.folder ?? "_umber";
1931
+ const folder = join2(options2.dir, folderName);
1932
+ const cache = options2.cache === false ? null : options2.cache ?? join2("node_modules", ".cache", "umber-assets");
1933
+ const out = { folder, folderUrl: `${normalBase(options2.baseUrl)}${folderName}/`, cache };
1934
+ const { videos, pages, local } = await scrubbedFiles(options2, folder);
1935
+ for (const video of videos.values()) {
1936
+ try {
1937
+ const made = await encodeOne(video, ffmpeg, settings, out);
1938
+ result.encoded += made;
1939
+ if (made) options2.log?.(`${relative(options2.dir, video.file)}: ${made} files encoded for scrubbing`);
1940
+ } catch (err) {
1941
+ result.skipped.push(`${relative(options2.dir, video.file)}: ${err instanceof Error ? err.message : String(err)}`);
1942
+ }
1943
+ }
1944
+ for (const { file, url, html } of pages) {
1945
+ const next = withScrubAttributes(html, (name, attrs) => {
1946
+ const made = videos.get(local(new URL(scrubSource(attrs), url)) ?? "")?.made;
1947
+ return {
1948
+ ...made?.mobile ? { "data-umber-scrub-src-mobile": made.mobile } : {},
1949
+ ...made?.poster && name === "video" ? { poster: made.poster } : {}
1950
+ };
1951
+ });
1952
+ if (next !== html) await writeFile2(file, next);
1953
+ }
1954
+ }
1955
+ function prepareSite(options2) {
1956
+ return prepareBuilt(options2);
1957
+ }
1958
+ async function prepareBuilt(options2, built, licence = hasLicence()) {
1959
+ const { result, shown, fonts = {} } = await preparePictures(options2);
1960
+ const hints = options2.hints ?? [];
1961
+ const effects = needsOf(options2.effects);
1962
+ const unread = /* @__PURE__ */ new Map();
1963
+ result.hinted = await hintPages(options2, { built, fonts, licence, more: hints, effects, unread });
1964
+ const notice = unreadNotice(unread);
1965
+ if (notice) options2.log?.(notice);
1966
+ await encodeVideos(options2, result);
1967
+ if (options2.videos !== false) result.videos = await moveIndexes(options2);
1968
+ if (result.manifest && shown) {
1969
+ const info = {
1970
+ v: 1,
1971
+ manifest: result.manifest,
1972
+ avif: Object.fromEntries(shown.smaller),
1973
+ tiny: Object.fromEntries(shown.tiny),
1974
+ fallback: shown.tiny.size ? shown.fallback : "",
1975
+ source: shown.source,
1976
+ all: result.data > 0,
1977
+ fonts: result.fonts > 0,
1978
+ engine: built?.engine ?? null,
1979
+ hints,
1980
+ effects: Object.fromEntries(effects),
1981
+ scripts: built?.scripts
1982
+ };
1983
+ await writeFile2(join2(options2.dir, options2.folder ?? "_umber", "pages.json"), JSON.stringify(info));
1984
+ }
1985
+ return result;
1986
+ }
1987
+ function writerHinting(info, fonts, licence) {
1988
+ return {
1989
+ built: info?.engine ? { engine: info.engine, scripts: info.scripts } : void 0,
1990
+ fonts,
1991
+ licence,
1992
+ more: info?.hints ?? [],
1993
+ effects: new Map(Object.entries(info?.effects ?? {}))
1994
+ };
1995
+ }
1996
+ async function pageWriter(options2, licence = hasLicence()) {
1997
+ const baseUrl = normalBase(options2.baseUrl);
1998
+ const folder = join2(options2.dir, options2.folder ?? "_umber");
1999
+ const file = join2(folder, "pages.json");
2000
+ const info = existsSync3(file) ? JSON.parse(await readFile2(file, "utf8")) : null;
2001
+ const shown = {
2002
+ smaller: new Map(Object.entries(info?.avif ?? {})),
2003
+ tiny: new Map(Object.entries(info?.tiny ?? {})),
2004
+ fallback: info?.fallback ?? "",
2005
+ source: info?.source ?? false
2006
+ };
2007
+ const prepared = /* @__PURE__ */ new Set();
2008
+ let fonts = {};
2009
+ let named = false;
2010
+ if (info) {
2011
+ const manifest = join2(folder, info.manifest.slice(info.manifest.lastIndexOf("/") + 1));
2012
+ const read2 = JSON.parse(await readFile2(manifest, "utf8"));
2013
+ for (const [url, entry] of Object.entries(read2.images)) {
2014
+ prepared.add(url);
2015
+ named ||= (entry[5] & NAMED) > 0;
2016
+ }
2017
+ fonts = read2.fonts ?? {};
2018
+ }
2019
+ const sources = pageSources(options2.dir, baseUrl);
2020
+ const hinting = writerHinting(info, fonts, licence);
2021
+ return async (html, url) => {
2022
+ const page = new URL(url, "http://site");
2023
+ const shows = info && (info.all || GL_TEXT.test(html) || named && glTags(html).length > 0 || drawnPictures(html).some((ref) => prepared.has(new URL(ref, page).pathname)));
2024
+ const pointed = shows ? pointPage(html, page, info.manifest, shown) : html;
2025
+ return withHints(pointed, await pageHints(pointed, page, sources, hinting));
2026
+ };
2027
+ }
2028
+ async function preparePictures(options2) {
2029
+ check(options2);
2030
+ const baseUrl = normalBase(options2.baseUrl);
2031
+ const folderName = options2.folder ?? "_umber";
2032
+ const folder = join2(options2.dir, folderName);
2033
+ const log = options2.log ?? (() => void 0);
2034
+ const cache = options2.cache === false ? null : options2.cache ?? join2("node_modules", ".cache", "umber-assets");
2035
+ const native = options2.native ?? addon();
2036
+ if (typeof native === "string") return { result: { ...nothing(), skipped: [native] } };
2037
+ const { quality, formats, avif, avifQuality, effort, maxSize } = options2;
2038
+ const settings = { quality, formats, avif, avifQuality, effort, maxSize };
2039
+ const found = await findPictures(options2.dir, folder, baseUrl, options2);
2040
+ const { pictures, pages, skipped } = found;
2041
+ const result = { ...nothing(), skipped };
2042
+ const fontFiles = options2.fonts === false ? /* @__PURE__ */ new Map() : await siteFonts(found.text, localFile(options2.dir, baseUrl));
2043
+ if (!pictures.size && !fontFiles.size && !options2.data?.length) return { result };
2044
+ await mkdir2(folder, { recursive: true });
2045
+ const images = {};
2046
+ const fonts = await prepareFonts(fontFiles, found.chars, { native, folder, cache, skipped });
2047
+ result.fonts = Object.keys(fonts).length;
2048
+ if (result.fonts)
2049
+ log(
2050
+ `${result.fonts} fonts' outlines written to ${folderName}/*.glyphs, files anyone can download: check that each font's licence allows a converted copy on your site (fonts: false leaves them out)`
2051
+ );
2052
+ const smaller = /* @__PURE__ */ new Map();
2053
+ const tiny = /* @__PURE__ */ new Map();
2054
+ const out = { folder, folderUrl: `${baseUrl}${folderName}/`, cache };
2055
+ const started = performance.now();
2056
+ await pool([...pictures], Math.max(1, Math.floor(availableParallelism() / 4)), async ([url, file]) => {
2057
+ const bytes = await readFile2(file);
2058
+ try {
2059
+ const own = { ...settings, quality: found.named.get(url) ?? quality };
2060
+ const image = await obtain(bytes, { native, settings: own, cache }, result);
2061
+ result.bytes.source = (result.bytes.source ?? 0) + bytes.length;
2062
+ const entry = images[url] = await place(image, out, result, found.named.has(url));
2063
+ const avifFile = image.files.find((made) => made.kind === "avif");
2064
+ if (avifFile && avifFile.bytes.length < bytes.length) {
2065
+ const avifUrl = `${out.folderUrl}${image.key}.avif`;
2066
+ images[avifUrl] = entry;
2067
+ smaller.set(url, avifUrl);
2068
+ if ((options2.domImages ?? "tiny") === "tiny") {
2069
+ try {
2070
+ const made = await placeholder({ bytes, key: image.key }, native, options2, out);
2071
+ const tinyUrl = `${out.folderUrl}${made.name}`;
2072
+ images[tinyUrl] = entry;
2073
+ result.bytes.tiny = (result.bytes.tiny ?? 0) + made.bytes;
2074
+ tiny.set(url, { url: tinyUrl, width: made.width, fullWidth: image.width });
2075
+ } catch (err) {
2076
+ log(`${url}: no placeholder (${err instanceof Error ? err.message : String(err)})`);
2077
+ }
2078
+ }
2079
+ }
2080
+ for (const note2 of image.notes) log(`${url}: ${note2}`);
2081
+ } catch (err) {
2082
+ result.skipped.push(`${url}: ${err instanceof Error ? err.message : String(err)}`);
2083
+ }
2084
+ });
2085
+ const manifest = { v: 1, images: Object.fromEntries(Object.entries(images).sort()) };
2086
+ if (result.fonts) manifest.fonts = fonts;
2087
+ const data = await packData(options2, baseUrl, folder, result);
2088
+ if (result.data) manifest.data = data;
2089
+ const text = JSON.stringify(manifest);
2090
+ const name = `assets.${createHash2("sha256").update(text).digest("hex").slice(0, 10)}.json`;
2091
+ await writeFile2(join2(folder, name), text);
2092
+ result.manifest = `${out.folderUrl}${name}`;
2093
+ const fallback = `images.${createHash2("sha256").update(FALLBACK).digest("hex").slice(0, 10)}.js`;
2094
+ if (tiny.size) await writeFile2(join2(folder, fallback), FALLBACK);
2095
+ const source = options2.domImages === "source";
2096
+ const shown = { smaller, tiny, fallback: `${out.folderUrl}${fallback}`, source };
2097
+ const pointed = result.data ? (await walk(options2.dir, folder)).filter((path) => path.endsWith(".html")) : pages;
2098
+ await writePages(pointed, options2, result.manifest, shown);
2099
+ result.pages = pointed.length;
2100
+ const seconds = ((performance.now() - started) / 1e3).toFixed(1);
2101
+ log(`${pictures.size} pictures (${result.prepared} prepared, ${result.cached} from the cache) in ${seconds} s`);
2102
+ return { result, shown, fonts };
2103
+ }
2104
+
2105
+ export {
2106
+ MAY_ASK,
2107
+ scriptNeeds,
2108
+ joinNeeds,
2109
+ loadNative,
2110
+ prepareSite,
2111
+ prepareBuilt,
2112
+ pageWriter
2113
+ };