@dioramajs/assets 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1211 @@
1
+ import { a as noop, i as linked, n as DEV, r as isAbort, t as AssetError } from "./errors-DgHytoOg.js";
2
+ import { withDocs } from "@dioramajs/core/dev";
3
+ import { definePlugin, isCancel, signal } from "@dioramajs/core";
4
+ // src/queue.ts
5
+ const RANK = {
6
+ low: 0,
7
+ normal: 1,
8
+ high: 2
9
+ };
10
+ /** Parallel decodes: createImageBitmap, glTF parsing. */
11
+ const DECODES = 2;
12
+ /** Low requests at once, and only while no high one waits. */
13
+ const LOW = 2;
14
+ const abortError = () => new DOMException("aborted", "AbortError");
15
+ /**
16
+ * Request and decode slots. Priorities are read at every step, so a lease that raises an entry's
17
+ * priority moves it up in its lane. Low-only work doesn't start while a pause is held.
18
+ */
19
+ var Queue = class {
20
+ concurrency;
21
+ #waiting = [];
22
+ #active = {
23
+ request: 0,
24
+ decode: 0,
25
+ low: 0
26
+ };
27
+ #pauses = 0;
28
+ #seq = 0;
29
+ /** Once stopped, every slot is granted at once and detached entries finish on their own. */
30
+ #open = false;
31
+ constructor(concurrency) {
32
+ this.concurrency = concurrency;
33
+ }
34
+ /** Resolves with the slot's release once granted. Rejects with AbortError on abort. */
35
+ slot(lane, priority, signal) {
36
+ return new Promise((resolve, reject) => {
37
+ if (signal.aborted) return reject(abortError());
38
+ const abort = () => {
39
+ const index = this.#waiting.indexOf(ticket);
40
+ if (index >= 0) this.#waiting.splice(index, 1);
41
+ reject(abortError());
42
+ };
43
+ const ticket = {
44
+ lane,
45
+ priority,
46
+ seq: this.#seq++,
47
+ grant: () => {
48
+ signal.removeEventListener("abort", abort);
49
+ const low = lane === "request" && priority() === "low";
50
+ this.#active[lane]++;
51
+ if (low) this.#active.low++;
52
+ let done = false;
53
+ resolve(() => {
54
+ if (done) return;
55
+ done = true;
56
+ this.#active[lane]--;
57
+ if (low) this.#active.low--;
58
+ this.pump();
59
+ });
60
+ }
61
+ };
62
+ signal.addEventListener("abort", abort, { once: true });
63
+ this.#waiting.push(ticket);
64
+ this.pump();
65
+ });
66
+ }
67
+ pause() {
68
+ this.#pauses++;
69
+ let done = false;
70
+ return () => {
71
+ if (done) return;
72
+ done = true;
73
+ this.#pauses--;
74
+ this.pump();
75
+ };
76
+ }
77
+ open() {
78
+ this.#open = true;
79
+ this.pump();
80
+ }
81
+ /** Grants every ticket the rules allow, highest priority first, then in arrival order. */
82
+ pump() {
83
+ for (let next = this.#next(); next; next = this.#next()) {
84
+ this.#waiting.splice(this.#waiting.indexOf(next), 1);
85
+ next.grant();
86
+ }
87
+ }
88
+ #next() {
89
+ const ranked = this.#waiting.map((ticket) => ({
90
+ ticket,
91
+ priority: ticket.priority()
92
+ })).sort((a, b) => RANK[b.priority] - RANK[a.priority] || a.ticket.seq - b.ticket.seq);
93
+ if (this.#open) return ranked[0]?.ticket;
94
+ const high = ranked.some((t) => t.ticket.lane === "request" && t.priority === "high");
95
+ const active = this.#active;
96
+ for (const { ticket, priority } of ranked) {
97
+ if (priority === "low" && this.#pauses > 0) continue;
98
+ if (ticket.lane === "decode") {
99
+ if (active.decode < DECODES) return ticket;
100
+ } else if (active.request < this.concurrency) {
101
+ if (priority !== "low" || active.low < LOW && !high) return ticket;
102
+ }
103
+ }
104
+ }
105
+ };
106
+ var Entry = class {
107
+ spec;
108
+ /** Cleared once run, since the loader may hold its source (an <img> of a page that is gone). */
109
+ make;
110
+ leases = /* @__PURE__ */ new Set();
111
+ abort = new AbortController();
112
+ state = "loading";
113
+ result;
114
+ value;
115
+ /** What the loader threw, and the same wrapped as AssetError. */
116
+ cause;
117
+ error;
118
+ bytes = 0;
119
+ total;
120
+ loaded = 0;
121
+ waved = false;
122
+ /** Out of the cache because the plugin stopped. Freed with its last lease. */
123
+ detached = false;
124
+ /** Its renderer stopped (KTX2). Freed with its last lease, never retained. */
125
+ stale = false;
126
+ constructor({ make, ...spec }) {
127
+ this.spec = spec;
128
+ this.make = make;
129
+ this.total = spec.weight ?? 1e5;
130
+ }
131
+ priority() {
132
+ let best = "low";
133
+ for (const lease of this.leases) if (RANK[lease.priority] > RANK[best]) best = lease.priority;
134
+ return best;
135
+ }
136
+ };
137
+ /** Unknown sizes weigh ESTIMATE. At 0 bytes `retain` would keep them forever. */
138
+ const estimate = (value) => {
139
+ const sized = value;
140
+ return sized?.byteLength || (sized?.width ?? 0) * (sized?.height ?? 0) * 4 || 1e5;
141
+ };
142
+ const failure = (lease) => lease.wrap ? lease.entry.error : lease.entry.cause;
143
+ /**
144
+ * Entries by key with leases. An entry lives while any lease does, then it is aborted, retained
145
+ * (LRU by bytes, no timers) or disposed once.
146
+ */
147
+ var Cache = class {
148
+ #host;
149
+ #entries = /* @__PURE__ */ new Map();
150
+ /** Ready entries without leases, oldest first. */
151
+ #retained = /* @__PURE__ */ new Set();
152
+ /** Stale entries out of the map that still have leases. Counted until their last lease. */
153
+ #stale = /* @__PURE__ */ new Set();
154
+ constructor(host) {
155
+ this.#host = host;
156
+ }
157
+ get(spec, priority, report, signal) {
158
+ let entry = this.#entries.get(spec.key);
159
+ const created = !entry;
160
+ if (!entry) {
161
+ entry = new Entry(spec);
162
+ this.#entries.set(spec.key, entry);
163
+ }
164
+ this.#retained.delete(entry);
165
+ const lease = this.#lease(entry, priority, report, spec.wrap);
166
+ if (created) this.#run(entry);
167
+ this.#changed(entry);
168
+ const asset = this.#asset(lease);
169
+ if (signal?.aborted) asset.release();
170
+ else if (signal) {
171
+ signal.addEventListener("abort", asset.release, { once: true });
172
+ lease.off = () => signal.removeEventListener("abort", asset.release);
173
+ }
174
+ return asset;
175
+ }
176
+ release(lease) {
177
+ if (lease.released) return;
178
+ lease.released = true;
179
+ lease.off?.();
180
+ const { entry } = lease;
181
+ entry.leases.delete(lease);
182
+ if (lease.status.peek() === "loading") lease.reject(linked(new AssetError("ASSET_ABORTED", "released before ready", { url: entry.spec.url })));
183
+ lease.status.value = "released";
184
+ if (entry.leases.size) {
185
+ this.#changed(entry);
186
+ return;
187
+ }
188
+ const { retain } = this.#host;
189
+ if (entry.state === "ready" && !entry.detached && !entry.stale && entry.bytes <= retain) {
190
+ this.#retained.add(entry);
191
+ let bytes = this.#bytes();
192
+ for (const old of this.#retained) {
193
+ if (bytes <= retain) break;
194
+ bytes -= old.bytes;
195
+ this.#drop(old);
196
+ }
197
+ } else this.#drop(entry);
198
+ }
199
+ /** Whether the key has an entry, loading, ready or retained. */
200
+ has(key) {
201
+ return this.#entries.has(key);
202
+ }
203
+ stats() {
204
+ const all = [...this.#entries.values(), ...this.#stale];
205
+ return {
206
+ entries: all.length,
207
+ used: all.filter((entry) => entry.leases.size > 0).length,
208
+ retained: this.#bytes(),
209
+ pending: all.filter((entry) => entry.state === "loading").length
210
+ };
211
+ }
212
+ /** `render` stopped. Renderer-bound entries go at once or with their last lease. */
213
+ rebind() {
214
+ for (const entry of [...this.#entries.values()]) {
215
+ if (!entry.result?.renderBound) continue;
216
+ if (!entry.leases.size) this.#drop(entry);
217
+ else {
218
+ entry.stale = true;
219
+ this.#entries.delete(entry.spec.key);
220
+ this.#stale.add(entry);
221
+ }
222
+ }
223
+ }
224
+ /**
225
+ * The plugin stops. `remove('assets')` keeps entries with leases until their last one, since an
226
+ * effect's texture may still show the bitmap. `destroy` releases everything at once.
227
+ */
228
+ close(hard) {
229
+ this.#host.queue.open();
230
+ for (const entry of [...this.#entries.values(), ...this.#stale]) {
231
+ this.#entries.delete(entry.spec.key);
232
+ entry.detached = true;
233
+ if (!entry.leases.size) this.#drop(entry);
234
+ else if (hard) for (const lease of [...entry.leases]) this.release(lease);
235
+ }
236
+ this.#host.wave.close();
237
+ }
238
+ #bytes() {
239
+ let bytes = 0;
240
+ for (const entry of this.#retained) bytes += entry.bytes;
241
+ return bytes;
242
+ }
243
+ #drop(entry) {
244
+ if (this.#entries.get(entry.spec.key) === entry) this.#entries.delete(entry.spec.key);
245
+ this.#retained.delete(entry);
246
+ this.#stale.delete(entry);
247
+ this.#unwave(entry);
248
+ if (entry.state === "loading") entry.abort.abort();
249
+ const { result } = entry;
250
+ entry.result = entry.value = void 0;
251
+ result?.dispose?.();
252
+ }
253
+ /** A lease came or went. The queue re-reads priorities and low-only work leaves the wave. */
254
+ #changed(entry) {
255
+ if (entry.state === "loading" && !entry.detached) {
256
+ if (entry.priority() !== "low") {
257
+ if (!entry.waved) this.#host.wave.add(entry);
258
+ entry.waved = true;
259
+ } else this.#unwave(entry);
260
+ }
261
+ this.#host.queue.pump();
262
+ }
263
+ #unwave(entry) {
264
+ if (!entry.waved) return;
265
+ entry.waved = false;
266
+ this.#host.wave.done(entry);
267
+ }
268
+ #lease(entry, priority, report, wrap) {
269
+ let resolve;
270
+ let reject;
271
+ const ready = new Promise((res, rej) => {
272
+ resolve = res;
273
+ reject = rej;
274
+ });
275
+ ready.catch(noop);
276
+ const initial = entry.state === "ready" ? "ready" : entry.state === "failed" ? "failed" : "loading";
277
+ const lease = {
278
+ entry,
279
+ priority,
280
+ report,
281
+ wrap,
282
+ status: signal(initial),
283
+ ready,
284
+ resolve,
285
+ reject,
286
+ released: false
287
+ };
288
+ entry.leases.add(lease);
289
+ if (entry.state === "ready") resolve(entry.value);
290
+ else if (entry.state === "failed") reject(failure(lease));
291
+ return lease;
292
+ }
293
+ #asset(lease) {
294
+ const { entry } = lease;
295
+ const release = () => this.release(lease);
296
+ const asset = Object.assign(release, {
297
+ release,
298
+ dispose: release,
299
+ key: entry.spec.key,
300
+ url: entry.spec.url,
301
+ status: lease.status,
302
+ ready: lease.ready
303
+ });
304
+ return Object.defineProperties(asset, {
305
+ value: { get: () => lease.status.peek() === "ready" ? entry.value : void 0 },
306
+ error: { get: () => lease.status.peek() === "failed" ? failure(lease) : void 0 }
307
+ });
308
+ }
309
+ /** Loads the entry once its loader resolves and a request slot is free. */
310
+ async #run(entry) {
311
+ const { spec } = entry;
312
+ const { signal } = entry.abort;
313
+ const host = this.#host;
314
+ let free;
315
+ const resolve = entry.make;
316
+ entry.make = void 0;
317
+ try {
318
+ const make = await resolve();
319
+ if (signal.aborted) throw abortError();
320
+ free = await host.queue.slot("request", () => entry.priority(), signal);
321
+ const result = await make(this.#context(entry, () => free?.()));
322
+ free();
323
+ if (signal.aborted) {
324
+ result.dispose?.();
325
+ return;
326
+ }
327
+ const value = entry.detached ? result.value : host.transform(result.value, spec.type, spec.url);
328
+ entry.result = result;
329
+ entry.value = value;
330
+ entry.bytes = result.bytes ?? estimate(value);
331
+ entry.state = "ready";
332
+ this.#unwave(entry);
333
+ for (const lease of entry.leases) {
334
+ lease.status.value = "ready";
335
+ lease.resolve(value);
336
+ }
337
+ } catch (cause) {
338
+ free?.();
339
+ if (signal.aborted || entry.leases.size === 0) return;
340
+ const error = linked(cause instanceof AssetError ? cause : new AssetError(isAbort(cause) ? "ASSET_ABORTED" : "ASSET_PARSE", String(cause), {
341
+ url: spec.url,
342
+ cause
343
+ }));
344
+ entry.cause = cause;
345
+ entry.error = error;
346
+ entry.state = "failed";
347
+ this.#unwave(entry);
348
+ const leases = [...entry.leases];
349
+ for (const lease of leases) {
350
+ lease.status.value = "failed";
351
+ lease.reject(failure(lease));
352
+ }
353
+ if (!entry.detached && leases.some((lease) => lease.report)) host.report(error, spec.url);
354
+ }
355
+ }
356
+ #context(entry, free) {
357
+ const { spec } = entry;
358
+ const { url, crossOrigin } = spec;
359
+ const { signal } = entry.abort;
360
+ const host = this.#host;
361
+ const wave = host.wave;
362
+ return {
363
+ url,
364
+ key: spec.key,
365
+ get priority() {
366
+ return entry.priority();
367
+ },
368
+ crossOrigin,
369
+ options: spec.options,
370
+ signal,
371
+ async fetch(init) {
372
+ const priority = entry.priority();
373
+ let response;
374
+ try {
375
+ response = await fetch(url, {
376
+ signal,
377
+ priority: priority === "normal" ? "auto" : priority,
378
+ credentials: crossOrigin === "use-credentials" ? "include" : "same-origin",
379
+ ...init
380
+ });
381
+ } catch (cause) {
382
+ if (signal.aborted) throw abortError();
383
+ throw new AssetError("ASSET_LOAD", `cannot fetch ${url}`, {
384
+ url,
385
+ cause
386
+ });
387
+ }
388
+ if (!response.ok) throw new AssetError("ASSET_LOAD", `${response.status} ${url}`, { url });
389
+ return response;
390
+ },
391
+ async bytes(response) {
392
+ const length = Number(response.headers.get("content-length"));
393
+ if (length > 0 && !response.headers.has("content-encoding")) entry.total = length;
394
+ const reader = response.body?.getReader();
395
+ if (!reader) {
396
+ const buffer = await response.arrayBuffer();
397
+ entry.loaded = entry.total;
398
+ wave.changed();
399
+ return buffer;
400
+ }
401
+ const chunks = [];
402
+ let size = 0;
403
+ for (;;) {
404
+ const { done, value } = await reader.read();
405
+ if (done) break;
406
+ chunks.push(value);
407
+ size += value.byteLength;
408
+ entry.loaded = Math.min(size, entry.total);
409
+ wave.changed();
410
+ }
411
+ const body = new Uint8Array(size);
412
+ let offset = 0;
413
+ for (const chunk of chunks) {
414
+ body.set(chunk, offset);
415
+ offset += chunk.byteLength;
416
+ }
417
+ return body.buffer;
418
+ },
419
+ async decode(work) {
420
+ free();
421
+ const done = await host.queue.slot("decode", () => entry.priority(), signal);
422
+ try {
423
+ return await work();
424
+ } finally {
425
+ done();
426
+ }
427
+ },
428
+ load(dependency, options) {
429
+ free();
430
+ return host.load(dependency, {
431
+ ...options,
432
+ signal
433
+ });
434
+ },
435
+ render() {
436
+ free();
437
+ return host.render(signal);
438
+ },
439
+ decoders: host.decoders
440
+ };
441
+ }
442
+ };
443
+ // src/keys.ts
444
+ /** Asset type by file extension, for loads without an explicit type. */
445
+ const BY_EXTENSION = {
446
+ glb: "gltf",
447
+ gltf: "gltf",
448
+ ktx2: "ktx2",
449
+ jpg: "texture",
450
+ jpeg: "texture",
451
+ png: "texture",
452
+ webp: "texture",
453
+ avif: "texture",
454
+ gif: "texture"
455
+ };
456
+ /** Absolute URL without the fragment, which never reaches the request. */
457
+ function absolute(url, base) {
458
+ const parsed = new URL(url, base ?? document.baseURI);
459
+ parsed.hash = "";
460
+ return parsed.href;
461
+ }
462
+ /**
463
+ * CORS mode of a texture load. Pixels of another origin fetched without CORS are tainted and the
464
+ * GPU upload throws SecurityError on every draw, so such a texture is always asked in CORS mode.
465
+ */
466
+ function textureCors(url, crossOrigin) {
467
+ if (crossOrigin) return crossOrigin;
468
+ const page = globalThis.location?.origin;
469
+ const target = new URL(url);
470
+ return page && /^https?:$/.test(target.protocol) && target.origin !== page ? "anonymous" : "";
471
+ }
472
+ /** Lower-case extension of an absolute URL's path, without the dot. '' for none. */
473
+ const extensionOf = (url) => /\.([a-z0-9]+)$/i.exec(new URL(url).pathname)?.[1]?.toLowerCase() ?? "";
474
+ /**
475
+ * Cache key `type url[ crossOrigin][ options]`. The CORS mode is part of it, as in the browser's
476
+ * image cache. The effects pool builds `image <currentSrc>[ crossOrigin]` keys the same way.
477
+ */
478
+ function keyOf(type, url, crossOrigin, options) {
479
+ const entries = Object.entries(options).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
480
+ let key = `${type} ${url}`;
481
+ if (crossOrigin) key += ` ${crossOrigin}`;
482
+ if (entries.length) key += ` ${JSON.stringify(entries)}`;
483
+ return key;
484
+ }
485
+ /** URL and type of a `keyOf` key. A key without a space stands for both. */
486
+ const parseKey = (key) => ({
487
+ url: key.split(" ")[1] ?? key,
488
+ type: key.split(" ")[0] ?? key
489
+ });
490
+ const CANDIDATE = /[\s,]*(\S+)/y;
491
+ /**
492
+ * A srcset with absolute candidate URLs. A URL is a run of non-spaces, so commas inside stay
493
+ * (CDN transforms like `w_400,c_fill`). Per the HTML spec, one ending in commas has no descriptors.
494
+ */
495
+ function srcset(value, base) {
496
+ const out = [];
497
+ for (let i = 0;;) {
498
+ CANDIDATE.lastIndex = i;
499
+ const match = CANDIDATE.exec(value);
500
+ if (!match) break;
501
+ let url = match[1];
502
+ i = CANDIDATE.lastIndex;
503
+ let descriptor = "";
504
+ if (url.endsWith(",")) url = url.replace(/,+$/, "");
505
+ else {
506
+ const end = value.indexOf(",", i);
507
+ descriptor = value.slice(i, end < 0 ? void 0 : end).trim();
508
+ i = end < 0 ? value.length : end + 1;
509
+ }
510
+ const href = new URL(url, base).href;
511
+ out.push(descriptor ? `${href} ${descriptor}` : href);
512
+ }
513
+ return out.join(", ");
514
+ }
515
+ // src/loaders.ts
516
+ /** Resolves once the image has loaded, or rejects with ASSET_LOAD. Aborting stops the request. */
517
+ function loaded(img, url, signal) {
518
+ return new Promise((resolve, reject) => {
519
+ if (signal.aborted) return reject(abortError());
520
+ if (img.complete && (img.currentSrc || img.src)) return resolve();
521
+ const done = () => {
522
+ img.removeEventListener("load", ok);
523
+ img.removeEventListener("error", fail);
524
+ signal.removeEventListener("abort", abort);
525
+ };
526
+ const ok = () => {
527
+ done();
528
+ resolve();
529
+ };
530
+ const fail = () => {
531
+ done();
532
+ const hint = new URL(url, location.href).origin !== location.origin && img.crossOrigin !== null ? ": is it served with Access-Control-Allow-Origin?" : "";
533
+ reject(new AssetError("ASSET_LOAD", `cannot load ${url}${hint}`, { url }));
534
+ };
535
+ const abort = () => {
536
+ done();
537
+ img.removeAttribute("srcset");
538
+ img.removeAttribute("src");
539
+ reject(abortError());
540
+ };
541
+ img.addEventListener("load", ok);
542
+ img.addEventListener("error", fail);
543
+ signal.addEventListener("abort", abort);
544
+ });
545
+ }
546
+ const FLIP = { imageOrientation: "flipY" };
547
+ /**
548
+ * The image's bytes decoded, or `undefined` when they cannot be read. Chrome decodes a Blob off
549
+ * the main thread, but an <img> on it: about 60 ms for 1920×1080. The bytes come from the HTTP
550
+ * cache, where the image left them. Mirrors `fromBytes` of the effects pool.
551
+ */
552
+ async function fromBytes(img) {
553
+ try {
554
+ const mode = img.crossOrigin;
555
+ const target = new URL(img.currentSrc || img.src, location.href);
556
+ if (mode === null && target.origin !== location.origin && target.protocol !== "data:") return;
557
+ const response = await fetch(target, {
558
+ credentials: mode === "use-credentials" ? "include" : "same-origin",
559
+ cache: "force-cache"
560
+ });
561
+ if (!response.ok) return;
562
+ return await createImageBitmap(await response.blob(), FLIP);
563
+ } catch {
564
+ return;
565
+ }
566
+ }
567
+ /** Shared with the effects pool. Decodes, then flips the pixels like effects textures. */
568
+ async function bitmap(img, url) {
569
+ try {
570
+ let pixels = await fromBytes(img);
571
+ if (!pixels) {
572
+ await img.decode();
573
+ pixels = await createImageBitmap(img, FLIP);
574
+ }
575
+ return {
576
+ value: pixels,
577
+ bytes: pixels.width * pixels.height * 4,
578
+ dispose: () => pixels.close()
579
+ };
580
+ } catch (cause) {
581
+ throw new AssetError("ASSET_PARSE", `cannot decode ${url}`, {
582
+ url,
583
+ cause
584
+ });
585
+ }
586
+ }
587
+ /** A detached image. The browser makes the request, then it takes a decode slot. */
588
+ const image = { async load(context) {
589
+ const img = new Image();
590
+ if (context.crossOrigin) img.crossOrigin = context.crossOrigin;
591
+ if (context.priority !== "normal") img.setAttribute("fetchpriority", context.priority);
592
+ img.src = context.url;
593
+ await loaded(img, context.url, context.signal);
594
+ return context.decode(() => bitmap(img, context.url));
595
+ } };
596
+ async function body(context) {
597
+ return context.bytes(await context.fetch());
598
+ }
599
+ const buffer = { async load(context) {
600
+ const value = await body(context);
601
+ return {
602
+ value,
603
+ bytes: value.byteLength
604
+ };
605
+ } };
606
+ const json = { async load(context) {
607
+ const bytes = await body(context);
608
+ try {
609
+ return {
610
+ value: JSON.parse(new TextDecoder().decode(bytes)),
611
+ bytes: bytes.byteLength
612
+ };
613
+ } catch (cause) {
614
+ throw new AssetError("ASSET_PARSE", `${context.url} is not JSON`, {
615
+ url: context.url,
616
+ cause
617
+ });
618
+ }
619
+ } };
620
+ // src/preload.ts
621
+ /** Hover longer than this is an intent to follow the link. */
622
+ const INTENT_MS = 65;
623
+ const IMAGES = "img[data-dio], img[data-dio-key]";
624
+ const MARKUP = "[data-dio-preload]";
625
+ /** Nothing is preloaded under Save-Data or on a 2g connection. */
626
+ function frugal() {
627
+ const connection = globalThis.navigator?.connection;
628
+ return connection?.saveData === true || /(^|-)2g$/.test(connection?.effectiveType ?? "");
629
+ }
630
+ /** The CORS mode of an element as a key part. No attribute gives '' (no CORS). */
631
+ function corsOf(el) {
632
+ const value = el.getAttribute("crossorigin");
633
+ if (value === null) return "";
634
+ return value.toLowerCase() === "use-credentials" ? "use-credentials" : "anonymous";
635
+ }
636
+ /**
637
+ * A detached image that picks the candidate the element would. Same `crossorigin`, `sizes` and
638
+ * absolute `srcset`, inside a copy of its <picture>.
639
+ */
640
+ function copy(source, base, priority) {
641
+ const src = source.getAttribute("src");
642
+ const set = source.getAttribute("srcset");
643
+ if (!src && !set) return void 0;
644
+ const img = new Image();
645
+ const cors = source.getAttribute("crossorigin");
646
+ if (cors !== null) img.setAttribute("crossorigin", cors);
647
+ const sizes = source.getAttribute("sizes");
648
+ if (sizes) img.setAttribute("sizes", sizes);
649
+ if (priority !== "normal") img.setAttribute("fetchpriority", priority);
650
+ let holder;
651
+ const picture = source.parentElement;
652
+ if (picture?.localName === "picture") {
653
+ holder = document.createElement("picture");
654
+ for (const child of picture.children) {
655
+ if (child.localName !== "source") continue;
656
+ const item = document.createElement("source");
657
+ for (const { name, value } of child.attributes) item.setAttribute(name, name === "srcset" ? srcset(value, base) : value);
658
+ holder.append(item);
659
+ }
660
+ }
661
+ return {
662
+ img,
663
+ start() {
664
+ holder?.append(img);
665
+ if (set) img.setAttribute("srcset", srcset(set, base));
666
+ if (src) img.src = new URL(src, base).href;
667
+ }
668
+ };
669
+ }
670
+ const words = (el) => (el.getAttribute("data-dio-preload") ?? "").split(/\s+/);
671
+ var PreloadImpl = class {
672
+ leases = [];
673
+ abort = new AbortController();
674
+ settled = Promise.resolve();
675
+ release = () => {
676
+ this.abort.abort();
677
+ for (const lease of this.leases.splice(0)) lease.release();
678
+ };
679
+ dispose = this.release;
680
+ then = (fulfilled, rejected) => this.settled.then(fulfilled, rejected);
681
+ };
682
+ /** API and markup preloads. Only the last of each kind holds its leases. */
683
+ var Preloads = class {
684
+ #host;
685
+ #last = /* @__PURE__ */ new Map();
686
+ /** A broken link warns once in development, not on every intent. */
687
+ #warned = /* @__PURE__ */ new Set();
688
+ constructor(host) {
689
+ this.#host = host;
690
+ }
691
+ preload(source, options = {}, kind = "api") {
692
+ const preload = new PreloadImpl();
693
+ if (frugal()) return preload;
694
+ const priority = options.priority ?? "low";
695
+ const base = this.#base(source, options.base);
696
+ const jobs = [];
697
+ const url = (href, cors) => {
698
+ if (href) jobs.push(this.#url(preload, href, base, priority, cors));
699
+ };
700
+ const cors = options.crossOrigin ?? "";
701
+ if (typeof source === "string") url(source, cors);
702
+ else if (Array.isArray(source)) for (const href of source) url(href, cors);
703
+ else if (typeof source === "object") {
704
+ const root = source;
705
+ const own = root instanceof Element ? [root] : [];
706
+ for (const el of [...own, ...root.querySelectorAll(IMAGES)]) if (el.matches(IMAGES)) jobs.push(this.#image(preload, el, base, priority));
707
+ for (const el of [...own, ...root.querySelectorAll(MARKUP)]) if (el.matches(MARKUP)) for (const href of words(el)) url(href, corsOf(el));
708
+ }
709
+ preload.settled = Promise.all(jobs).then(noop);
710
+ if (priority !== "low") this.#host.track(preload.settled, priority);
711
+ this.#last.get(kind)?.release();
712
+ this.#last.set(kind, preload);
713
+ return preload;
714
+ }
715
+ /** `data-dio-preload` on intent: hover (65 ms), focus or touch. */
716
+ listen(signal) {
717
+ let hovered;
718
+ let timer;
719
+ const target = (event) => event.target?.closest?.(MARKUP) ?? null;
720
+ const intent = (el) => {
721
+ if (!el) return;
722
+ const urls = words(el);
723
+ const crossOrigin = corsOf(el);
724
+ const lost = (url) => {
725
+ const wanted = this.#target(url, document.baseURI, crossOrigin);
726
+ return typeof wanted === "string" || !this.#host.has(wanted.key);
727
+ };
728
+ if (urls.some((url) => url && lost(url))) this.preload(urls, { crossOrigin }, "markup");
729
+ };
730
+ const options = {
731
+ signal,
732
+ passive: true
733
+ };
734
+ document.addEventListener("pointerover", (event) => {
735
+ const el = target(event);
736
+ if (!el || el === hovered) return;
737
+ clearTimeout(timer);
738
+ hovered = el;
739
+ timer = setTimeout(() => intent(el), INTENT_MS);
740
+ }, options);
741
+ document.addEventListener("pointerout", (event) => {
742
+ const el = target(event);
743
+ if (!el || el !== hovered || el.contains(event.relatedTarget)) return;
744
+ clearTimeout(timer);
745
+ hovered = void 0;
746
+ }, options);
747
+ document.addEventListener("focusin", (event) => intent(target(event)), options);
748
+ document.addEventListener("touchstart", (event) => intent(target(event)), options);
749
+ signal.addEventListener("abort", () => clearTimeout(timer), { once: true });
750
+ }
751
+ close() {
752
+ for (const preload of this.#last.values()) preload.release();
753
+ this.#last.clear();
754
+ }
755
+ #base(source, base) {
756
+ if (base !== void 0) return new URL(base, document.baseURI).href;
757
+ const href = (source.nodeType === 9 ? source : void 0)?.querySelector("base[href]")?.getAttribute("href");
758
+ return href ? new URL(href, document.baseURI).href : document.baseURI;
759
+ }
760
+ /** The entry a preload of the URL takes, or the reason there is none. */
761
+ #target(url, base, cors) {
762
+ let href;
763
+ try {
764
+ href = absolute(url, base);
765
+ } catch {
766
+ return `${url} is not a URL`;
767
+ }
768
+ const found = this.#host.typeOf(href);
769
+ if (!found) return withDocs(`ASSET_TYPE: ${href} has no asset type: preload takes asset URLs or a Document`, "ASSET_TYPE");
770
+ const type = found === "texture" ? "image" : found;
771
+ const crossOrigin = type === "image" ? cors : "";
772
+ return {
773
+ href,
774
+ type,
775
+ crossOrigin,
776
+ key: keyOf(type, href, crossOrigin, {})
777
+ };
778
+ }
779
+ #url(preload, url, base, priority, cors) {
780
+ const target = this.#target(url, base, cors);
781
+ if (typeof target === "string") return this.#failed(target);
782
+ const { href, type, crossOrigin } = target;
783
+ const { signal } = preload.abort;
784
+ return this.#hold(preload, this.#host.load(href, {
785
+ type,
786
+ priority,
787
+ crossOrigin,
788
+ signal
789
+ }), href);
790
+ }
791
+ /**
792
+ * A failed lease goes at once, so the entry leaves the cache and the page's own load is a new
793
+ * attempt, reported if it fails too.
794
+ */
795
+ async #hold(preload, lease, url) {
796
+ preload.leases.push(lease);
797
+ try {
798
+ await lease.ready;
799
+ } catch (error) {
800
+ const at = preload.leases.indexOf(lease);
801
+ if (at >= 0) preload.leases.splice(at, 1);
802
+ lease.release();
803
+ return this.#failed(error, url);
804
+ }
805
+ }
806
+ async #image(preload, source, base, priority) {
807
+ const { signal } = preload.abort;
808
+ let made;
809
+ try {
810
+ made = copy(source, base, priority);
811
+ } catch {
812
+ return;
813
+ }
814
+ if (!made) return;
815
+ const { img } = made;
816
+ const url = source.getAttribute("src") ?? source.getAttribute("srcset") ?? "";
817
+ try {
818
+ const free = await this.#host.slot(priority, signal);
819
+ try {
820
+ made.start();
821
+ await loaded(img, url, signal);
822
+ } finally {
823
+ free();
824
+ }
825
+ } catch (error) {
826
+ return this.#failed(error, url);
827
+ }
828
+ if (signal.aborted) return;
829
+ const src = absolute(img.currentSrc || img.src);
830
+ const key = keyOf("image", src, corsOf(img), {});
831
+ const target = img;
832
+ const lease = this.#host.acquire(key, (context) => context.decode(() => bitmap(target, src)), priority);
833
+ return this.#hold(preload, lease, src);
834
+ }
835
+ #failed(error, url) {
836
+ if (DEV && !isAbort(error)) {
837
+ const message = typeof error === "string" ? error : `preload of ${url} failed: ${String(error)}`;
838
+ if (!this.#warned.has(message)) this.#host.warn(message);
839
+ this.#warned.add(message);
840
+ }
841
+ return Promise.resolve();
842
+ }
843
+ };
844
+ // src/wave.ts
845
+ /** Progress stops here until the wave is done. 1 means `ready()` resolved. */
846
+ const BEFORE_END = .99;
847
+ /**
848
+ * The current wave of high and normal work. It starts when pending items appear, only grows,
849
+ * and stays at 1 until the next wave starts from 0. Work of no weight (a decode the next frame
850
+ * waits for) holds `ready()` but starts no wave of its own: the bar stays where it is.
851
+ * `data-dio-progress` elements follow the first wave and the waves that start during a page
852
+ * transition only: a texture loading as its section nears does not pull a bar back mid-scroll.
853
+ */
854
+ var Wave = class {
855
+ #progress = signal(0);
856
+ progress = this.#progress;
857
+ #pending = /* @__PURE__ */ new Set();
858
+ #done = 0;
859
+ /** The wave has weighed work, so progress moves. */
860
+ #shown = false;
861
+ /** No weighed wave has ended yet: the page is still loading. */
862
+ #first = true;
863
+ /** `data-dio-progress` elements follow this wave. */
864
+ #bar = true;
865
+ #waiters = [];
866
+ #elements = [];
867
+ #find;
868
+ constructor(find) {
869
+ this.#find = find;
870
+ this.#elements = find();
871
+ this.#write();
872
+ }
873
+ add(item) {
874
+ if (this.#pending.has(item)) return;
875
+ if (!this.#pending.size) {
876
+ this.#done = 0;
877
+ this.#shown = false;
878
+ }
879
+ this.#pending.add(item);
880
+ if (!this.#shown && item.total > 0) {
881
+ this.#shown = true;
882
+ this.#bar = this.#first || typeof document !== "undefined" && document.documentElement.hasAttribute("data-dio-transition");
883
+ if (this.#bar) this.#elements = this.#find();
884
+ this.#set(0);
885
+ }
886
+ this.changed();
887
+ }
888
+ /** A page change: the bar follows the wave under way, or else the next one. */
889
+ page() {
890
+ this.#first = true;
891
+ if (!this.#shown || this.#bar || !this.#pending.size) return;
892
+ this.#bar = true;
893
+ this.#elements = this.#find();
894
+ this.#write();
895
+ }
896
+ /** The item settled, failed or became low and left the wave. Counted as done. */
897
+ done(item) {
898
+ if (!this.#pending.delete(item)) return;
899
+ this.#done += item.total;
900
+ if (this.#pending.size) {
901
+ this.changed();
902
+ return;
903
+ }
904
+ if (this.#shown || this.#progress.peek() < 1) this.#set(1);
905
+ if (this.#shown) this.#first = false;
906
+ for (const resolve of this.#waiters.splice(0)) resolve();
907
+ }
908
+ changed() {
909
+ if (!this.#pending.size || !this.#shown) return;
910
+ let loaded = this.#done;
911
+ let total = this.#done;
912
+ for (const item of this.#pending) {
913
+ loaded += Math.min(item.loaded, item.total);
914
+ total += item.total;
915
+ }
916
+ const ratio = total > 0 ? Math.min(loaded / total, BEFORE_END) : 0;
917
+ if (ratio > this.#progress.peek()) this.#set(ratio);
918
+ }
919
+ ready() {
920
+ return this.#pending.size ? new Promise((resolve) => this.#waiters.push(resolve)) : Promise.resolve();
921
+ }
922
+ /** Ends the wave and settles waiters. */
923
+ close() {
924
+ this.#pending.clear();
925
+ for (const resolve of this.#waiters.splice(0)) resolve();
926
+ }
927
+ #set(value) {
928
+ this.#progress.value = value;
929
+ if (this.#bar) this.#write();
930
+ }
931
+ #write() {
932
+ const value = String(this.#progress.peek());
933
+ for (const el of this.#elements) el.style.setProperty("--dio-progress", value);
934
+ }
935
+ };
936
+ // src/plugin.ts
937
+ const BUILT_IN = {
938
+ image,
939
+ buffer,
940
+ json
941
+ };
942
+ const THREE_TYPES = [
943
+ "texture",
944
+ "gltf",
945
+ "ktx2"
946
+ ];
947
+ /** KTX2 waits for `render`. Show a development hint after this long. */
948
+ const RENDER_WAIT_MS = 5e3;
949
+ const defaults = {
950
+ loaders: {},
951
+ decoders: {},
952
+ concurrency: 6,
953
+ retain: 33554432,
954
+ preload: true
955
+ };
956
+ const isThree = (type) => THREE_TYPES.includes(type);
957
+ /** A lease that failed before it began, for SSR or a URL that doesn't parse. */
958
+ function failed(url, error) {
959
+ linked(error);
960
+ const ready = Promise.reject(error);
961
+ ready.catch(noop);
962
+ const release = () => {};
963
+ return Object.assign(release, {
964
+ release,
965
+ dispose: release,
966
+ key: url,
967
+ url,
968
+ status: signal("failed"),
969
+ ready,
970
+ value: void 0,
971
+ error
972
+ });
973
+ }
974
+ const settled = Object.freeze({
975
+ release: noop,
976
+ dispose: noop,
977
+ then: (fulfilled, rejected) => Promise.resolve().then(fulfilled, rejected)
978
+ });
979
+ /** Without a DOM (SSR) loads fail silently and nothing waits. */
980
+ function inert() {
981
+ const none = (url) => failed(url, new AssetError("ASSET_LOAD", "no DOM to load in", { url }));
982
+ return {
983
+ load: none,
984
+ acquire: none,
985
+ preload: () => settled,
986
+ track: noop,
987
+ pause: () => noop,
988
+ progress: signal(0),
989
+ ready: () => Promise.resolve(),
990
+ stats: () => ({
991
+ entries: 0,
992
+ used: 0,
993
+ retained: 0,
994
+ pending: 0
995
+ })
996
+ };
997
+ }
998
+ /** One cache, queue, wave and preloads per app. */
999
+ var Assets = class {
1000
+ api;
1001
+ #app;
1002
+ #options;
1003
+ #queue;
1004
+ #wave;
1005
+ #cache;
1006
+ #preloads;
1007
+ #three;
1008
+ #module;
1009
+ #leave;
1010
+ #renderer;
1011
+ #destroying = false;
1012
+ constructor(app, options) {
1013
+ this.#app = app;
1014
+ this.#options = options;
1015
+ this.#queue = new Queue(options.concurrency);
1016
+ this.#wave = new Wave(() => [...document.querySelectorAll("[data-dio-progress]")]);
1017
+ const decoders = {
1018
+ meshopt: true,
1019
+ workers: void 0,
1020
+ ...options.decoders
1021
+ };
1022
+ this.#cache = new Cache({
1023
+ queue: this.#queue,
1024
+ wave: this.#wave,
1025
+ retain: options.retain,
1026
+ decoders,
1027
+ report: (error, url) => app.report(error, `asset:${url}`),
1028
+ transform: (value, type, url) => {
1029
+ const result = app.callHook("assets:transform", value, {
1030
+ type,
1031
+ url
1032
+ });
1033
+ return isCancel(result) ? value : result;
1034
+ },
1035
+ render: (abort) => this.#render(abort),
1036
+ load: (url, options) => this.#load(url, options, false)
1037
+ });
1038
+ this.#preloads = new Preloads({
1039
+ load: (url, options) => this.#load(url, options, false),
1040
+ acquire: (key, make, priority) => this.api.acquire(key, make, { priority }),
1041
+ has: (key) => this.#cache.has(key),
1042
+ slot: (priority, abort) => this.#queue.slot("request", () => priority, abort),
1043
+ typeOf: (url) => this.#typeOf(url),
1044
+ track: (work, priority) => this.api.track(work, { priority }),
1045
+ warn: (message) => app.log.warn(message)
1046
+ });
1047
+ if (options.preload && !frugal()) this.#preloads.listen(app.abortSignal);
1048
+ app.on("app:destroy", () => {
1049
+ this.#destroying = true;
1050
+ });
1051
+ app.on("page:leave", () => this.#wave.page());
1052
+ app.on("plugin:status", ({ name, status }) => {
1053
+ if (name !== "render" || status !== "stopping") return;
1054
+ if (this.#renderer) this.#module?.forget(this.#renderer);
1055
+ this.#renderer = void 0;
1056
+ this.#cache.rebind();
1057
+ });
1058
+ app.onDispose(() => {
1059
+ this.#preloads.close();
1060
+ this.#cache.close(this.#destroying);
1061
+ this.#leave?.();
1062
+ });
1063
+ const wave = this.#wave;
1064
+ this.api = {
1065
+ load: (url, options) => this.#load(url, options ?? {}, true),
1066
+ acquire: (key, make, { priority, weight } = {}) => this.#cache.get({
1067
+ key,
1068
+ ...parseKey(key),
1069
+ crossOrigin: "",
1070
+ options: {},
1071
+ make: () => make,
1072
+ wrap: false,
1073
+ weight
1074
+ }, priority ?? "normal", false),
1075
+ preload: (source, preload) => this.#preloads.preload(source, preload),
1076
+ track(work, { priority, weight } = {}) {
1077
+ if (priority === "low") return;
1078
+ const item = {
1079
+ total: weight ?? 1e5,
1080
+ loaded: 0
1081
+ };
1082
+ wave.add(item);
1083
+ const done = () => wave.done(item);
1084
+ Promise.resolve(work).then(done, done);
1085
+ },
1086
+ pause: () => this.#queue.pause(),
1087
+ progress: wave.progress,
1088
+ ready: () => wave.ready(),
1089
+ stats: () => this.#cache.stats()
1090
+ };
1091
+ }
1092
+ #load(url, options, report) {
1093
+ let href;
1094
+ try {
1095
+ href = absolute(url);
1096
+ } catch (cause) {
1097
+ const error = linked(new AssetError("ASSET_LOAD", `${url} is not a URL`, {
1098
+ url,
1099
+ cause
1100
+ }));
1101
+ if (report) this.#app.report(error, `asset:${url}`);
1102
+ return failed(url, error);
1103
+ }
1104
+ const type = options.type ?? this.#typeOf(href);
1105
+ const name = type ?? "?";
1106
+ const crossOrigin = name === "texture" ? textureCors(href, options.crossOrigin ?? "") : options.crossOrigin ?? "";
1107
+ const params = options.options ?? {};
1108
+ const spec = {
1109
+ key: keyOf(name, href, crossOrigin, params),
1110
+ url: href,
1111
+ type: name,
1112
+ crossOrigin,
1113
+ options: params,
1114
+ make: () => this.#loader(type, href).then((loader) => (context) => loader.load(context)),
1115
+ wrap: true
1116
+ };
1117
+ return this.#cache.get(spec, options.priority ?? "normal", report, options.signal);
1118
+ }
1119
+ /** Own loaders' extensions first, then the built-in table. */
1120
+ #typeOf(url) {
1121
+ const extension = extensionOf(url);
1122
+ if (!extension) return void 0;
1123
+ for (const [type, entry] of Object.entries(this.#options.loaders)) if ((typeof entry === "function" ? void 0 : entry.extensions)?.some((e) => e.replace(/^\./, "").toLowerCase() === extension)) return type;
1124
+ return BY_EXTENSION[extension];
1125
+ }
1126
+ async #loader(type, url) {
1127
+ const known = [.../* @__PURE__ */ new Set([
1128
+ ...Object.keys(this.#options.loaders),
1129
+ ...Object.keys(BUILT_IN),
1130
+ ...THREE_TYPES
1131
+ ])];
1132
+ if (type === void 0) {
1133
+ const message = `no type for ${url}: pass { type } (known: ${known.join(", ")}); a page address is not an asset`;
1134
+ throw new AssetError("ASSET_TYPE", message, { url });
1135
+ }
1136
+ const own = this.#options.loaders[type];
1137
+ try {
1138
+ if (own) {
1139
+ const found = typeof own === "function" ? await own() : own;
1140
+ const loader = "default" in found ? found.default : found;
1141
+ if (typeof loader?.load === "function") return loader;
1142
+ } else if (BUILT_IN[type]) return BUILT_IN[type];
1143
+ else if (isThree(type)) return (await this.#import())[type];
1144
+ } catch (cause) {
1145
+ throw new AssetError("ASSET_TYPE", `the loader of "${type}" did not load`, {
1146
+ url,
1147
+ cause
1148
+ });
1149
+ }
1150
+ throw new AssetError("ASSET_TYPE", `no loader for "${type}" (known: ${known.join(", ")})`, { url });
1151
+ }
1152
+ /** The three loaders, once per app. The app joins the decoders shared by the page. */
1153
+ #import() {
1154
+ if (!this.#three) {
1155
+ const pending = import("./three/index.js").then((module) => {
1156
+ if (!this.#app.abortSignal.aborted && !this.#module) this.#leave = module.join();
1157
+ this.#module = module;
1158
+ return module;
1159
+ });
1160
+ this.#three = pending;
1161
+ pending.catch(() => {
1162
+ if (this.#three === pending) this.#three = void 0;
1163
+ });
1164
+ }
1165
+ return this.#three;
1166
+ }
1167
+ #render(abort) {
1168
+ const app = this.#app;
1169
+ const found = app.find("render");
1170
+ if (found) {
1171
+ this.#renderer = found.renderer;
1172
+ return Promise.resolve(found);
1173
+ }
1174
+ if (abort.aborted || app.abortSignal.aborted) return Promise.reject(abortError());
1175
+ return new Promise((resolve, reject) => {
1176
+ const timer = DEV ? setTimeout(() => app.log.warn("assets: a KTX2 load waits for render"), RENDER_WAIT_MS) : void 0;
1177
+ const done = () => {
1178
+ off();
1179
+ clearTimeout(timer);
1180
+ abort.removeEventListener("abort", stop);
1181
+ };
1182
+ const stop = () => {
1183
+ done();
1184
+ reject(abortError());
1185
+ };
1186
+ const off = app.on("plugin:status", ({ name, status }) => {
1187
+ const render = name === "render" && status === "running" ? app.find("render") : void 0;
1188
+ if (!render) return;
1189
+ done();
1190
+ this.#renderer = render.renderer;
1191
+ resolve(render);
1192
+ });
1193
+ abort.addEventListener("abort", stop, { once: true });
1194
+ });
1195
+ }
1196
+ };
1197
+ /**
1198
+ * `app.assets`. One cache with leases for media and models, a priority queue, preloading of
1199
+ * the next page and the progress wave of a preloader.
1200
+ */
1201
+ const assets = /*#__PURE__*/ definePlugin({
1202
+ name: "assets",
1203
+ optionalDependencies: ["render"],
1204
+ defaults,
1205
+ setup(app, options) {
1206
+ return typeof document === "undefined" ? inert() : new Assets(app, options).api;
1207
+ }
1208
+ });
1209
+ export { AssetError, assets };
1210
+
1211
+ //# sourceMappingURL=index.js.map