@freedome/client 0.0.0-stage → 1.0.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.
@@ -0,0 +1,1608 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/codecs.ts
21
+ var codecs_exports = {};
22
+ __export(codecs_exports, {
23
+ CodecError: () => CodecError,
24
+ DEFAULT_ZIP_LIMITS: () => DEFAULT_ZIP_LIMITS,
25
+ DOME_MIME: () => DOME_MIME,
26
+ DOME_WRITER_VERSION: () => DOME_WRITER_VERSION,
27
+ DOS_DATE_1980_01_01: () => DOS_DATE_1980_01_01,
28
+ DomeCodec: () => DomeCodec,
29
+ FORMAT_MIME: () => FORMAT_MIME,
30
+ LeWriter: () => LeWriter,
31
+ addChecksums: () => addChecksums,
32
+ animKind: () => animKind,
33
+ badEntryName: () => badEntryName,
34
+ byteOrder: () => byteOrder,
35
+ bytesInput: () => bytesInput,
36
+ checkFdmesh: () => checkFdmesh,
37
+ concat: () => concat,
38
+ crc32: () => crc32,
39
+ decodeBoranko: () => decodeBoranko,
40
+ decodeComics: () => decodeComics,
41
+ decodeComicsData: () => decodeComicsData,
42
+ decodeText: () => decodeText,
43
+ decodeZelim: () => decodeZelim,
44
+ decodeZelimBinary: () => decodeZelimBinary,
45
+ decodeZelimJson: () => decodeZelimJson,
46
+ directoryInput: () => directoryInput,
47
+ equalBytes: () => equalBytes,
48
+ f32: () => f32,
49
+ f64: () => f64,
50
+ fromLatin1: () => fromLatin1,
51
+ fromUtf8: () => fromUtf8,
52
+ invalid: () => invalid,
53
+ isZip: () => isZip,
54
+ latin1: () => latin1,
55
+ manifestBytesFor: () => manifestBytesFor,
56
+ openZip: () => openZip,
57
+ parseJson: () => parseJson,
58
+ pemToDer: () => pemToDer,
59
+ sameDome: () => sameDome,
60
+ signDome: () => signDome,
61
+ signedEntryNames: () => signedEntryNames,
62
+ sniff: () => sniff,
63
+ tooLarge: () => tooLarge,
64
+ u16: () => u16,
65
+ u32: () => u32,
66
+ u64big: () => u64big,
67
+ unsupported: () => unsupported,
68
+ utf8: () => utf8,
69
+ webCryptoVerify: () => webCryptoVerify,
70
+ writeZip: () => writeZip
71
+ });
72
+ module.exports = __toCommonJS(codecs_exports);
73
+
74
+ // src/codecs/bytes.ts
75
+ var u16 = (b, o) => b[o] | b[o + 1] << 8;
76
+ var u32 = (b, o) => (b[o] | b[o + 1] << 8 | b[o + 2] << 16 | b[o + 3] << 24) >>> 0;
77
+ var u64big = (b, o) => BigInt(u32(b, o)) | BigInt(u32(b, o + 4)) << 32n;
78
+ var f64 = (b, o) => new DataView(b.buffer, b.byteOffset + o, 8).getFloat64(0, true);
79
+ var f32 = (b, o) => new DataView(b.buffer, b.byteOffset + o, 4).getFloat32(0, true);
80
+ var latin1 = (b) => {
81
+ let s = "";
82
+ for (const x of b) s += String.fromCharCode(x);
83
+ return s;
84
+ };
85
+ var fromLatin1 = (s) => Uint8Array.from(s, (c) => c.charCodeAt(0) & 255);
86
+ var utf8 = (s) => new TextEncoder().encode(s);
87
+ var fromUtf8 = (b) => new TextDecoder().decode(b);
88
+ function equalBytes(a, b) {
89
+ if (a.length !== b.length) return false;
90
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
91
+ return true;
92
+ }
93
+ function byteOrder(a, b) {
94
+ const x = utf8(a);
95
+ const y = utf8(b);
96
+ for (let i = 0; i < Math.min(x.length, y.length); i++) if (x[i] !== y[i]) return x[i] - y[i];
97
+ return x.length - y.length;
98
+ }
99
+ function concat(parts) {
100
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
101
+ let o = 0;
102
+ for (const p of parts) {
103
+ out.set(p, o);
104
+ o += p.length;
105
+ }
106
+ return out;
107
+ }
108
+ var table;
109
+ function crc32(b) {
110
+ if (!table) {
111
+ table = new Uint32Array(256);
112
+ for (let n = 0; n < 256; n++) {
113
+ let c2 = n;
114
+ for (let k = 0; k < 8; k++) c2 = c2 & 1 ? 3988292384 ^ c2 >>> 1 : c2 >>> 1;
115
+ table[n] = c2 >>> 0;
116
+ }
117
+ }
118
+ let c = 4294967295;
119
+ for (let i = 0; i < b.length; i++) c = table[(c ^ b[i]) & 255] ^ c >>> 8;
120
+ return (c ^ 4294967295) >>> 0;
121
+ }
122
+ var LeWriter = class {
123
+ bytes;
124
+ dv;
125
+ constructor(n) {
126
+ this.bytes = new Uint8Array(n);
127
+ this.dv = new DataView(this.bytes.buffer);
128
+ }
129
+ u16(o, v) {
130
+ this.dv.setUint16(o, v, true);
131
+ return this;
132
+ }
133
+ u32(o, v) {
134
+ this.dv.setUint32(o, v >>> 0, true);
135
+ return this;
136
+ }
137
+ u64(o, v) {
138
+ this.dv.setBigUint64(o, BigInt(v), true);
139
+ return this;
140
+ }
141
+ };
142
+
143
+ // src/codecs/dome.ts
144
+ var import_validate = require("@freedome/protocol/validate");
145
+
146
+ // src/sha256.ts
147
+ var K = new Uint32Array([
148
+ 1116352408,
149
+ 1899447441,
150
+ 3049323471,
151
+ 3921009573,
152
+ 961987163,
153
+ 1508970993,
154
+ 2453635748,
155
+ 2870763221,
156
+ 3624381080,
157
+ 310598401,
158
+ 607225278,
159
+ 1426881987,
160
+ 1925078388,
161
+ 2162078206,
162
+ 2614888103,
163
+ 3248222580,
164
+ 3835390401,
165
+ 4022224774,
166
+ 264347078,
167
+ 604807628,
168
+ 770255983,
169
+ 1249150122,
170
+ 1555081692,
171
+ 1996064986,
172
+ 2554220882,
173
+ 2821834349,
174
+ 2952996808,
175
+ 3210313671,
176
+ 3336571891,
177
+ 3584528711,
178
+ 113926993,
179
+ 338241895,
180
+ 666307205,
181
+ 773529912,
182
+ 1294757372,
183
+ 1396182291,
184
+ 1695183700,
185
+ 1986661051,
186
+ 2177026350,
187
+ 2456956037,
188
+ 2730485921,
189
+ 2820302411,
190
+ 3259730800,
191
+ 3345764771,
192
+ 3516065817,
193
+ 3600352804,
194
+ 4094571909,
195
+ 275423344,
196
+ 430227734,
197
+ 506948616,
198
+ 659060556,
199
+ 883997877,
200
+ 958139571,
201
+ 1322822218,
202
+ 1537002063,
203
+ 1747873779,
204
+ 1955562222,
205
+ 2024104815,
206
+ 2227730452,
207
+ 2361852424,
208
+ 2428436474,
209
+ 2756734187,
210
+ 3204031479,
211
+ 3329325298
212
+ ]);
213
+ var Sha256 = class {
214
+ h = new Uint32Array([
215
+ 1779033703,
216
+ 3144134277,
217
+ 1013904242,
218
+ 2773480762,
219
+ 1359893119,
220
+ 2600822924,
221
+ 528734635,
222
+ 1541459225
223
+ ]);
224
+ buf = new Uint8Array(64);
225
+ w = new Uint32Array(64);
226
+ bufLen = 0;
227
+ total = 0;
228
+ finished = false;
229
+ update(data) {
230
+ if (this.finished) throw new Error("sha256: already finished");
231
+ let i = 0;
232
+ this.total += data.length;
233
+ if (this.bufLen) {
234
+ const n = Math.min(64 - this.bufLen, data.length);
235
+ this.buf.set(data.subarray(0, n), this.bufLen);
236
+ this.bufLen += n;
237
+ i = n;
238
+ if (this.bufLen === 64) {
239
+ this.block(this.buf, 0);
240
+ this.bufLen = 0;
241
+ }
242
+ }
243
+ for (; i + 64 <= data.length; i += 64) this.block(data, i);
244
+ if (i < data.length) {
245
+ this.buf.set(data.subarray(i), 0);
246
+ this.bufLen = data.length - i;
247
+ }
248
+ return this;
249
+ }
250
+ digest() {
251
+ if (!this.finished) {
252
+ const bits = this.total * 8;
253
+ const pad = new Uint8Array((this.bufLen < 56 ? 56 : 120) - this.bufLen + 8);
254
+ pad[0] = 128;
255
+ const dv2 = new DataView(pad.buffer);
256
+ dv2.setUint32(pad.length - 8, Math.floor(bits / 2 ** 32));
257
+ dv2.setUint32(pad.length - 4, bits >>> 0);
258
+ const t = this.total;
259
+ this.update(pad);
260
+ this.total = t;
261
+ this.finished = true;
262
+ }
263
+ const out = new Uint8Array(32);
264
+ const dv = new DataView(out.buffer);
265
+ for (let j = 0; j < 8; j++) dv.setUint32(j * 4, this.h[j]);
266
+ return out;
267
+ }
268
+ hex() {
269
+ return Array.from(this.digest(), (b) => b.toString(16).padStart(2, "0")).join("");
270
+ }
271
+ block(d, o) {
272
+ const w = this.w;
273
+ for (let j = 0; j < 16; j++)
274
+ w[j] = d[o + j * 4] << 24 | d[o + j * 4 + 1] << 16 | d[o + j * 4 + 2] << 8 | d[o + j * 4 + 3];
275
+ for (let j = 16; j < 64; j++) {
276
+ const a2 = w[j - 15];
277
+ const b2 = w[j - 2];
278
+ const s0 = (a2 >>> 7 | a2 << 25) ^ (a2 >>> 18 | a2 << 14) ^ a2 >>> 3;
279
+ const s1 = (b2 >>> 17 | b2 << 15) ^ (b2 >>> 19 | b2 << 13) ^ b2 >>> 10;
280
+ w[j] = w[j - 16] + s0 + w[j - 7] + s1 | 0;
281
+ }
282
+ let [a, b, c, dd, e, f, g, h] = this.h;
283
+ for (let j = 0; j < 64; j++) {
284
+ const S1 = (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7);
285
+ const ch = e & f ^ ~e & g;
286
+ const t1 = h + S1 + ch + K[j] + w[j] | 0;
287
+ const S0 = (a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10);
288
+ const maj = a & b ^ a & c ^ b & c;
289
+ const t2 = S0 + maj | 0;
290
+ h = g;
291
+ g = f;
292
+ f = e;
293
+ e = dd + t1 | 0;
294
+ dd = c;
295
+ c = b;
296
+ b = a;
297
+ a = t1 + t2 | 0;
298
+ }
299
+ const H = this.h;
300
+ H[0] = H[0] + a | 0;
301
+ H[1] = H[1] + b | 0;
302
+ H[2] = H[2] + c | 0;
303
+ H[3] = H[3] + dd | 0;
304
+ H[4] = H[4] + e | 0;
305
+ H[5] = H[5] + f | 0;
306
+ H[6] = H[6] + g | 0;
307
+ H[7] = H[7] + h | 0;
308
+ }
309
+ };
310
+
311
+ // src/errors.ts
312
+ var FreedomeError = class extends Error {
313
+ code;
314
+ problem;
315
+ constructor(message, opts = {}) {
316
+ super(message, opts.cause === void 0 ? void 0 : { cause: opts.cause });
317
+ this.name = new.target.name;
318
+ this.code = opts.code;
319
+ this.problem = opts.problem;
320
+ }
321
+ };
322
+
323
+ // src/codecs/errors.ts
324
+ var STATUS = {
325
+ "validation-failed": 422,
326
+ "unsupported-format": 415,
327
+ "payload-too-large": 413
328
+ };
329
+ var CodecError = class extends FreedomeError {
330
+ constructor(codecCode, detail, errors = []) {
331
+ super(detail, { code: codecCode });
332
+ this.codecCode = codecCode;
333
+ this.status = STATUS[codecCode];
334
+ this.errors = errors;
335
+ }
336
+ codecCode;
337
+ status;
338
+ errors;
339
+ /** RFC 9457 problem object. */
340
+ toProblem() {
341
+ return {
342
+ type: `https://freedome.nativemind.us/problems/${this.codecCode}`,
343
+ title: this.codecCode,
344
+ status: this.status,
345
+ code: this.codecCode,
346
+ detail: this.message,
347
+ ...this.errors.length ? { errors: this.errors } : {}
348
+ };
349
+ }
350
+ };
351
+ var unsupported = (detail) => new CodecError("unsupported-format", detail);
352
+ var invalid = (detail, pointer) => new CodecError("validation-failed", detail, pointer !== void 0 ? [{ pointer, detail }] : []);
353
+ var tooLarge = (detail) => new CodecError("payload-too-large", detail);
354
+
355
+ // src/codecs/fdmesh.ts
356
+ function checkFdmesh(b) {
357
+ if (b.length < 24) return "shorter than the 24-byte header";
358
+ if (latin1(b.subarray(0, 8)) !== "FDMESH\0\0") return "bad magic";
359
+ const h = {
360
+ version: u16(b, 8),
361
+ flags: u16(b, 10),
362
+ cols: u32(b, 12),
363
+ rows: u32(b, 16),
364
+ channels: u32(b, 20)
365
+ };
366
+ if (h.version !== 1) return `version ${h.version}`;
367
+ if (h.cols < 2 || h.cols > 4097 || h.rows < 2 || h.rows > 4097)
368
+ return `grid ${h.cols}x${h.rows} outside 2..4097`;
369
+ if (h.channels !== 2 && h.channels !== 3) return `channels ${h.channels}`;
370
+ const want = 24 + 4 * h.cols * h.rows * h.channels;
371
+ if (b.length !== want) return `size ${b.length}, expected ${want}`;
372
+ for (let o = 24; o < b.length; o += 4)
373
+ if (!Number.isFinite(f32(b, o))) return `non-finite value at byte ${o}`;
374
+ return h;
375
+ }
376
+
377
+ // src/codecs/zip.ts
378
+ var import_fflate = require("fflate");
379
+ var DOS_DATE_1980_01_01 = 33;
380
+ var SIG_LOCAL = 67324752;
381
+ var SIG_CENTRAL = 33639248;
382
+ var SIG_EOCD = 101010256;
383
+ var SIG_ZIP64_EOCD = 101075792;
384
+ var SIG_ZIP64_LOCATOR = 117853008;
385
+ var U32 = 4294967295;
386
+ var U16 = 65535;
387
+ var DEFAULT_ZIP_LIMITS = {
388
+ maxEntries: 65536,
389
+ maxManifestBytes: 16 * 1024 * 1024,
390
+ maxTotalBytes: 256 * 1024 ** 3,
391
+ maxRatio: 200,
392
+ ratioMinBytes: 1024 * 1024
393
+ };
394
+ function badEntryName(name) {
395
+ if (name.length === 0) return "empty name";
396
+ if (name.includes("\0")) return "NUL in name";
397
+ if (name.includes("\\")) return "backslash in name";
398
+ if (name.startsWith("/")) return "absolute path";
399
+ if (/^[A-Za-z]:/.test(name)) return "drive letter";
400
+ const segs = name.split("/");
401
+ if (segs.some((s) => s === "..")) return "parent segment (..)";
402
+ if (segs.slice(0, -1).some((s) => s === "" || s === ".")) return 'empty or "." segment';
403
+ return null;
404
+ }
405
+ function u64(b, o) {
406
+ const v = u64big(b, o);
407
+ if (v > BigInt(Number.MAX_SAFE_INTEGER)) throw tooLarge("ZIP64 value beyond 2^53");
408
+ return Number(v);
409
+ }
410
+ var isZip = (b) => b.length >= 4 && u32(b, 0) === SIG_LOCAL;
411
+ function openZip(buf, limits = DEFAULT_ZIP_LIMITS) {
412
+ if (buf.length < 22 || u32(buf, 0) !== SIG_LOCAL) throw unsupported("not a ZIP archive");
413
+ let eocd = -1;
414
+ for (let i = buf.length - 22; i >= Math.max(0, buf.length - 22 - 65535); i--) {
415
+ if (u32(buf, i) === SIG_EOCD && i + 22 + u16(buf, i + 20) === buf.length) {
416
+ eocd = i;
417
+ break;
418
+ }
419
+ }
420
+ if (eocd < 0) throw invalid("ZIP end of central directory not found");
421
+ let count = u16(buf, eocd + 10);
422
+ let cdSize = u32(buf, eocd + 12);
423
+ let cdOffset = u32(buf, eocd + 16);
424
+ let zip64 = false;
425
+ const loc = eocd - 20;
426
+ if (loc >= 0 && u32(buf, loc) === SIG_ZIP64_LOCATOR) {
427
+ const z = u64(buf, loc + 8);
428
+ if (z + 56 > buf.length || u32(buf, z) !== SIG_ZIP64_EOCD)
429
+ throw invalid("bad ZIP64 end of central directory");
430
+ zip64 = true;
431
+ count = u64(buf, z + 32);
432
+ cdSize = u64(buf, z + 40);
433
+ cdOffset = u64(buf, z + 48);
434
+ } else if (count === U16 || cdSize === U32 || cdOffset === U32) {
435
+ throw invalid("ZIP64 values without a ZIP64 locator");
436
+ }
437
+ if (count > limits.maxEntries) throw tooLarge(`${count} entries (limit ${limits.maxEntries})`);
438
+ if (cdOffset + cdSize > buf.length) throw invalid("central directory outside the file");
439
+ const entries = [];
440
+ const seen = /* @__PURE__ */ new Set();
441
+ let p = cdOffset;
442
+ let total = 0;
443
+ for (let i = 0; i < count; i++) {
444
+ if (p + 46 > buf.length || u32(buf, p) !== SIG_CENTRAL)
445
+ throw invalid(`bad central directory record ${i}`);
446
+ const flags = u16(buf, p + 8);
447
+ const method = u16(buf, p + 10);
448
+ const crc = u32(buf, p + 16);
449
+ let compressedSize = u32(buf, p + 20);
450
+ let size = u32(buf, p + 24);
451
+ const nameLen = u16(buf, p + 28);
452
+ const extraLen = u16(buf, p + 30);
453
+ const commentLen = u16(buf, p + 32);
454
+ let localOffset = u32(buf, p + 42);
455
+ const nameBytes = buf.subarray(p + 46, p + 46 + nameLen);
456
+ const name = flags & 2048 ? fromUtf8(nameBytes) : latin1(nameBytes);
457
+ let e = p + 46 + nameLen;
458
+ const eEnd = e + extraLen;
459
+ let entryZip64 = false;
460
+ while (e + 4 <= eEnd) {
461
+ const id = u16(buf, e);
462
+ const len = u16(buf, e + 2);
463
+ if (id === 1) {
464
+ entryZip64 = true;
465
+ let q = e + 4;
466
+ if (size === U32) {
467
+ size = u64(buf, q);
468
+ q += 8;
469
+ }
470
+ if (compressedSize === U32) {
471
+ compressedSize = u64(buf, q);
472
+ q += 8;
473
+ }
474
+ if (localOffset === U32) {
475
+ localOffset = u64(buf, q);
476
+ q += 8;
477
+ }
478
+ }
479
+ e += 4 + len;
480
+ }
481
+ p = eEnd + commentLen;
482
+ const why = badEntryName(name);
483
+ if (why) throw invalid(`entry "${name}": ${why}`, `/entries/${i}`);
484
+ if (seen.has(name)) throw invalid(`duplicate entry "${name}"`, `/entries/${i}`);
485
+ seen.add(name);
486
+ if (flags & 1) throw unsupported(`entry "${name}" is encrypted`);
487
+ if (method !== 0 && method !== 8)
488
+ throw unsupported(`entry "${name}": compression method ${method}`);
489
+ if (name.endsWith("/")) {
490
+ if (size !== 0) throw invalid(`directory entry "${name}" with data`);
491
+ continue;
492
+ }
493
+ total += size;
494
+ if (total > limits.maxTotalBytes)
495
+ throw tooLarge(`total uncompressed size above ${limits.maxTotalBytes} bytes`);
496
+ if (name === "dome.json" && size > limits.maxManifestBytes)
497
+ throw tooLarge(`dome.json is ${size} bytes (limit ${limits.maxManifestBytes})`);
498
+ if (method === 8 && size > limits.ratioMinBytes && size / Math.max(1, compressedSize) > limits.maxRatio) {
499
+ throw tooLarge(
500
+ `entry "${name}": compression ratio ${(size / Math.max(1, compressedSize)).toFixed(0)} above ${limits.maxRatio}`
501
+ );
502
+ }
503
+ if (method === 0 && compressedSize !== size)
504
+ throw invalid(`stored entry "${name}" with different sizes`);
505
+ if (localOffset + 30 > buf.length || u32(buf, localOffset) !== SIG_LOCAL)
506
+ throw invalid(`entry "${name}": bad local header`);
507
+ const lNameLen = u16(buf, localOffset + 26);
508
+ const lExtraLen = u16(buf, localOffset + 28);
509
+ if (!equalBytes(buf.subarray(localOffset + 30, localOffset + 30 + lNameLen), nameBytes))
510
+ throw invalid(`entry "${name}": local / central names differ`);
511
+ const dataOffset = localOffset + 30 + lNameLen + lExtraLen;
512
+ if (dataOffset + compressedSize > buf.length)
513
+ throw invalid(`entry "${name}": data outside the file`);
514
+ entries.push({
515
+ name,
516
+ method,
517
+ flags,
518
+ crc,
519
+ compressedSize,
520
+ size,
521
+ localOffset,
522
+ dataOffset,
523
+ localExtraLength: lExtraLen,
524
+ centralExtraLength: extraLen,
525
+ zip64: entryZip64
526
+ });
527
+ }
528
+ const byName = new Map(entries.map((x) => [x.name, x]));
529
+ return {
530
+ entries,
531
+ zip64,
532
+ read(name) {
533
+ const x = byName.get(name);
534
+ if (!x) throw invalid(`no entry "${name}"`);
535
+ const raw = buf.subarray(x.dataOffset, x.dataOffset + x.compressedSize);
536
+ let data;
537
+ if (x.method === 0) data = raw.slice();
538
+ else {
539
+ try {
540
+ data = (0, import_fflate.inflateSync)(raw, { out: new Uint8Array(x.size + 1) });
541
+ } catch {
542
+ throw invalid(`entry "${name}": corrupt deflate data`);
543
+ }
544
+ }
545
+ if (data.length !== x.size) {
546
+ if (data.length > x.size)
547
+ throw tooLarge(`entry "${name}" inflates beyond its declared size ${x.size}`);
548
+ throw invalid(`entry "${name}": ${data.length} bytes, declared ${x.size}`);
549
+ }
550
+ if (crc32(data) !== x.crc) throw invalid(`entry "${name}": CRC-32 mismatch`);
551
+ return data;
552
+ }
553
+ };
554
+ }
555
+ function writeZip(entries, opts = {}) {
556
+ const parts = [];
557
+ const central = [];
558
+ let offset = 0;
559
+ for (const ent of entries) {
560
+ const why = badEntryName(ent.name);
561
+ if (why) throw invalid(`cannot write entry "${ent.name}": ${why}`);
562
+ const nameBytes = utf8(ent.name);
563
+ const utf8Flag = /[^\x20-\x7e]/.test(ent.name) ? 2048 : 0;
564
+ const body = ent.store ? ent.data : (0, import_fflate.deflateSync)(ent.data, { level: 9 });
565
+ const crc = crc32(ent.data);
566
+ const big = opts.forceZip64 === true || ent.data.length >= U32 || body.length >= U32 || offset >= U32;
567
+ const zip64Local = big && ent.name !== "mimetype";
568
+ const version = zip64Local ? 45 : 20;
569
+ const localExtra = new LeWriter(zip64Local ? 20 : 0);
570
+ if (zip64Local)
571
+ localExtra.u16(0, 1).u16(2, 16).u64(4, ent.data.length).u64(12, body.length);
572
+ const lh = new LeWriter(30).u32(0, SIG_LOCAL).u16(4, version).u16(6, utf8Flag).u16(8, ent.store ? 0 : 8).u16(10, 0).u16(12, DOS_DATE_1980_01_01).u32(14, crc).u32(18, zip64Local ? U32 : body.length).u32(22, zip64Local ? U32 : ent.data.length).u16(26, nameBytes.length).u16(28, localExtra.bytes.length);
573
+ parts.push(lh.bytes, nameBytes, localExtra.bytes, body);
574
+ const z64 = [];
575
+ if (zip64Local) z64.push(ent.data.length, body.length);
576
+ const offBig = offset >= U32 || opts.forceZip64 === true && ent.name !== "mimetype";
577
+ if (offBig) z64.push(offset);
578
+ const cExtra = new LeWriter(z64.length ? 4 + 8 * z64.length : 0);
579
+ if (z64.length) {
580
+ cExtra.u16(0, 1).u16(2, 8 * z64.length);
581
+ z64.forEach((v, i) => cExtra.u64(4 + 8 * i, v));
582
+ }
583
+ const ch = new LeWriter(46).u32(0, SIG_CENTRAL).u16(4, z64.length ? 45 : 20).u16(6, version).u16(8, utf8Flag).u16(10, ent.store ? 0 : 8).u16(12, 0).u16(14, DOS_DATE_1980_01_01).u32(16, crc).u32(20, zip64Local ? U32 : body.length).u32(24, zip64Local ? U32 : ent.data.length).u16(28, nameBytes.length).u16(30, cExtra.bytes.length).u32(42, offBig ? U32 : offset);
584
+ central.push(ch.bytes, nameBytes, cExtra.bytes);
585
+ offset += 30 + nameBytes.length + localExtra.bytes.length + body.length;
586
+ }
587
+ const cd = concat(central);
588
+ const cdOffset = offset;
589
+ const needZip64 = opts.forceZip64 === true || entries.length >= U16 || cdOffset >= U32 || cd.length >= U32;
590
+ const tail = [];
591
+ if (needZip64) {
592
+ tail.push(
593
+ new LeWriter(56).u32(0, SIG_ZIP64_EOCD).u64(4, 44).u16(12, 45).u16(14, 45).u64(24, entries.length).u64(32, entries.length).u64(40, cd.length).u64(48, cdOffset).bytes,
594
+ new LeWriter(20).u32(0, SIG_ZIP64_LOCATOR).u64(8, cdOffset + cd.length).u32(16, 1).bytes
595
+ );
596
+ }
597
+ tail.push(
598
+ new LeWriter(22).u32(0, SIG_EOCD).u16(8, needZip64 ? U16 : entries.length).u16(10, needZip64 ? U16 : entries.length).u32(12, needZip64 ? U32 : cd.length).u32(16, needZip64 ? U32 : cdOffset).bytes
599
+ );
600
+ return concat([...parts, cd, ...tail]);
601
+ }
602
+
603
+ // src/codecs/dome.ts
604
+ var DOME_MIME = "application/vnd.nativemind.freedome.dome+zip";
605
+ var DOME_WRITER_VERSION = "1.1.0";
606
+ var META_SIG = "META-INF/signature";
607
+ var META_SIG_JSON = "META-INF/signature.json";
608
+ var CHECKSUMS = "checksums.sha256";
609
+ var STORED_EXT = /\.(mp4|mov|mkv|webm|png|jpg|jpeg|webp|exr|wav|flac|ogg|mp3|m4a|zip|zelim)$/i;
610
+ var URI = /^[A-Za-z][A-Za-z0-9+.-]*:/;
611
+ var vf = (detail, errors = []) => new CodecError("validation-failed", detail, errors);
612
+ var sha256 = (b) => new Sha256().update(b).hex();
613
+ function pemToDer(pem) {
614
+ const b64 = pem.replace(/-----[^-]+-----/g, "").replace(/\s+/g, "");
615
+ return Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
616
+ }
617
+ var webCryptoVerify = async (spki, message, signature) => {
618
+ const subtle = globalThis.crypto?.subtle;
619
+ if (!subtle)
620
+ throw new CodecError("unsupported-format", "no WebCrypto: pass DomeReadOptions.verify");
621
+ const key = await subtle.importKey("spki", spki, { name: "Ed25519" }, false, [
622
+ "verify"
623
+ ]);
624
+ return subtle.verify(
625
+ { name: "Ed25519" },
626
+ key,
627
+ signature,
628
+ message
629
+ );
630
+ };
631
+ function manifestBytesFor(doc) {
632
+ if (doc.raw && doc.rawCanon === JSON.stringify(doc.manifest)) return doc.raw;
633
+ return utf8(`${JSON.stringify(doc.manifest, null, 2)}
634
+ `);
635
+ }
636
+ function signedEntryNames(doc) {
637
+ return [
638
+ "dome.json",
639
+ ...[...doc.entries.keys()].filter((n) => n !== META_SIG && n !== META_SIG_JSON).sort(byteOrder)
640
+ ];
641
+ }
642
+ function addChecksums(doc) {
643
+ doc.entries.delete(CHECKSUMS);
644
+ const names = [...doc.entries.keys()].filter((n) => n !== META_SIG && n !== META_SIG_JSON).sort(byteOrder);
645
+ const lines = ["dome.json", ...names].map(
646
+ (n) => `${sha256(n === "dome.json" ? manifestBytesFor(doc) : doc.entries.get(n))} ${n}
647
+ `
648
+ );
649
+ doc.entries.set(CHECKSUMS, utf8(lines.join("")));
650
+ }
651
+ async function signDome(doc, privateKey, keyId, created) {
652
+ doc.entries.delete(META_SIG);
653
+ doc.entries.delete(META_SIG_JSON);
654
+ const signedEntries = signedEntryNames(doc).map((path) => {
655
+ const data = path === "dome.json" ? manifestBytesFor(doc) : doc.entries.get(path);
656
+ return { path, sha256: sha256(data), size: data.length };
657
+ });
658
+ const sj = utf8(
659
+ `${JSON.stringify({ alg: "Ed25519", keyId, created, signedEntries }, null, 2)}
660
+ `
661
+ );
662
+ doc.entries.set(META_SIG_JSON, sj);
663
+ doc.entries.set(
664
+ META_SIG,
665
+ new Uint8Array(
666
+ await globalThis.crypto.subtle.sign({ name: "Ed25519" }, privateKey, sj)
667
+ )
668
+ );
669
+ }
670
+ var DomeCodec = {
671
+ /** Reads a packed `.dome` (bytes) or an unpacked directory. */
672
+ async read(input, opts = {}) {
673
+ const inp = input instanceof Uint8Array ? { kind: "file", bytes: input } : input;
674
+ const limits = { ...DEFAULT_ZIP_LIMITS, ...opts.limits };
675
+ const warnings = [];
676
+ let entries = /* @__PURE__ */ new Map();
677
+ let form;
678
+ let mimetypeOk = false;
679
+ if (inp.kind === "dir") {
680
+ form = "dir";
681
+ entries = readDirectory(inp, limits);
682
+ } else {
683
+ form = "zip";
684
+ const zip = openZip(inp.bytes, limits);
685
+ const first = zip.entries[0];
686
+ for (const e of zip.entries) entries.set(e.name, zip.read(e.name));
687
+ if (first?.name === "mimetype") {
688
+ if (first.method !== 0 || first.localExtraLength !== 0)
689
+ warnings.push("mimetype entry is not stored without extra field (01b \xA72)");
690
+ } else if (entries.has("mimetype")) warnings.push("mimetype is not the first entry (01b \xA72)");
691
+ }
692
+ if (entries.has("mimetype")) {
693
+ const m = latin1(entries.get("mimetype"));
694
+ if (m !== DOME_MIME)
695
+ throw new CodecError(
696
+ "unsupported-format",
697
+ `mimetype is "${m.slice(0, 80)}", not ${DOME_MIME}`
698
+ );
699
+ mimetypeOk = true;
700
+ entries.delete("mimetype");
701
+ } else if (form === "zip") warnings.push("no mimetype entry (01b \xA72)");
702
+ const manifestBytes = entries.get("dome.json");
703
+ entries.delete("dome.json");
704
+ if (!manifestBytes) {
705
+ if (mimetypeOk)
706
+ throw vf("dome.json missing", [{ pointer: "/entries/dome.json", detail: "required" }]);
707
+ throw new CodecError("unsupported-format", "neither a dome mimetype nor dome.json");
708
+ }
709
+ if (manifestBytes.length > limits.maxManifestBytes)
710
+ throw new CodecError("payload-too-large", `dome.json is ${manifestBytes.length} bytes`);
711
+ let text = fromUtf8(manifestBytes);
712
+ if (text.charCodeAt(0) === 65279) {
713
+ warnings.push("dome.json starts with a UTF-8 BOM");
714
+ text = text.slice(1);
715
+ }
716
+ let manifest;
717
+ try {
718
+ manifest = JSON.parse(text);
719
+ } catch (e) {
720
+ throw vf(`dome.json is not valid JSON: ${e.message}`);
721
+ }
722
+ if (manifest === null || typeof manifest !== "object" || Array.isArray(manifest))
723
+ throw vf("dome.json is not a JSON object");
724
+ if (manifest.format !== "dome") {
725
+ if (!mimetypeOk)
726
+ throw new CodecError("unsupported-format", 'dome.json "format" is not "dome"');
727
+ throw vf('"format" must be "dome"', [{ pointer: "/format", detail: 'must be "dome"' }]);
728
+ }
729
+ const doc = {
730
+ manifest,
731
+ entries,
732
+ form,
733
+ warnings,
734
+ normalised: false,
735
+ raw: utf8(text),
736
+ rawCanon: JSON.stringify(manifest)
737
+ };
738
+ normalise(doc);
739
+ validateDoc(doc);
740
+ await checkSignature(doc, opts);
741
+ return doc;
742
+ },
743
+ /** Deterministic zip: mimetype, dome.json, then byte order; media stored, the rest deflated. */
744
+ write(doc, opts = {}) {
745
+ const names = [...doc.entries.keys()].sort(byteOrder);
746
+ return writeZip(
747
+ [
748
+ { name: "mimetype", data: fromLatin1(DOME_MIME), store: true },
749
+ { name: "dome.json", data: manifestBytesFor(doc), store: false },
750
+ ...names.map((n) => ({ name: n, data: doc.entries.get(n), store: STORED_EXT.test(n) }))
751
+ ],
752
+ opts
753
+ );
754
+ },
755
+ /** Unpacked form as a path → bytes map. */
756
+ toDirectory(doc) {
757
+ const out = /* @__PURE__ */ new Map([
758
+ ["mimetype", fromLatin1(DOME_MIME)],
759
+ ["dome.json", manifestBytesFor(doc)]
760
+ ]);
761
+ for (const [n, d] of doc.entries) {
762
+ const why = badEntryName(n);
763
+ if (why) throw vf(`cannot write "${n}": ${why}`);
764
+ out.set(n, d);
765
+ }
766
+ return out;
767
+ },
768
+ /** New document from a manifest object and entries. */
769
+ create(manifest, entries = /* @__PURE__ */ new Map()) {
770
+ return { manifest, entries, form: "zip", warnings: [], normalised: false };
771
+ }
772
+ };
773
+ function normalise(doc) {
774
+ const m = doc.manifest;
775
+ let changed = false;
776
+ if (Array.isArray(m.displays)) {
777
+ for (const d of m.displays) {
778
+ if (d && typeof d === "object" && d["x-freedome-optics"] !== void 0 && d.optics === void 0) {
779
+ d.optics = d["x-freedome-optics"];
780
+ delete d["x-freedome-optics"];
781
+ changed = true;
782
+ }
783
+ }
784
+ }
785
+ for (const holder of [m.show, m]) {
786
+ const xa = holder?.["x-ananta"];
787
+ if (xa && typeof xa === "object" && xa.mode !== void 0 && m.show && typeof m.show === "object" && m.show.audioMode === void 0) {
788
+ m.show.audioMode = xa.mode;
789
+ delete xa.mode;
790
+ if (Object.keys(xa).length === 0) delete holder["x-ananta"];
791
+ changed = true;
792
+ }
793
+ }
794
+ if (changed) {
795
+ doc.normalised = true;
796
+ const v = /^1\.(\d+)\./.exec(String(m.formatVersion ?? ""));
797
+ if (v && Number(v[1]) < 1) m.formatVersion = DOME_WRITER_VERSION;
798
+ doc.warnings.push("interim x-* keys mapped to 1.1 fields (01b \xA76.1)");
799
+ }
800
+ }
801
+ function validateDoc(doc) {
802
+ const m = doc.manifest;
803
+ const ver = /^(\d+)\.(\d+)\.(\d+)/.exec(
804
+ typeof m.formatVersion === "string" ? m.formatVersion : ""
805
+ );
806
+ if (!ver)
807
+ throw vf("formatVersion missing or not semver", [
808
+ { pointer: "/formatVersion", detail: "semver required" }
809
+ ]);
810
+ if (ver[1] !== "1")
811
+ throw new CodecError(
812
+ "unsupported-format",
813
+ `format major ${ver[1]} is not supported (reader implements 1.x)`
814
+ );
815
+ const minor = `1.${Number(ver[2])}`;
816
+ const newest = import_validate.domeMinors[import_validate.domeMinors.length - 1];
817
+ const lenient = !import_validate.domeMinors.includes(minor);
818
+ if (lenient && Number(ver[2]) < Number(newest.split(".")[1]))
819
+ throw new CodecError("unsupported-format", `no schema for ${minor}`);
820
+ const all = (0, import_validate.validate)(`dome/${lenient ? newest : minor}/dome.schema.json`, m);
821
+ if (all.length) {
822
+ const errs = all.filter((e) => !(lenient && e.keyword === "additionalProperties"));
823
+ const ignored = all.filter((e) => lenient && e.keyword === "additionalProperties");
824
+ if (ignored.length)
825
+ doc.warnings.push(`newer minor ${minor}: ignored ${ignored.length} unknown key(s)`);
826
+ const leaves = errs.filter((e) => !["if", "anyOf", "oneOf", "allOf"].includes(e.keyword));
827
+ const report = leaves.length ? leaves : errs;
828
+ if (report.length) {
829
+ throw vf(
830
+ "dome.json does not match the .dome schema",
831
+ report.slice(0, 20).map((e) => ({ pointer: e.instancePath || "/", detail: e.message || e.keyword }))
832
+ );
833
+ }
834
+ }
835
+ semanticChecks(doc);
836
+ checkChecksums(doc);
837
+ }
838
+ function checkChecksums(doc) {
839
+ const file = doc.entries.get(CHECKSUMS);
840
+ if (!file) return;
841
+ const lines = fromUtf8(file).split("\n").filter((l) => l.trim() !== "");
842
+ const errors = [];
843
+ lines.forEach((line, i) => {
844
+ const mm = /^([0-9a-f]{64}) [ *](.+)$/.exec(line.replace(/\r$/, ""));
845
+ if (!mm) {
846
+ errors.push({ pointer: `/entries/${CHECKSUMS}/${i + 1}`, detail: "malformed line" });
847
+ return;
848
+ }
849
+ const [, hex, path] = mm;
850
+ const data = path === "dome.json" ? manifestBytesFor(doc) : doc.entries.get(path);
851
+ const actual = data ? sha256(data) : void 0;
852
+ if (actual === void 0)
853
+ errors.push({
854
+ pointer: `/entries/${path}`,
855
+ detail: "listed in checksums.sha256 but missing"
856
+ });
857
+ else if (actual !== hex)
858
+ errors.push({ pointer: `/entries/${path}`, detail: "sha256 mismatch" });
859
+ });
860
+ if (errors.length) throw vf("checksums.sha256 does not match the container", errors);
861
+ }
862
+ async function checkSignature(doc, opts) {
863
+ const sj = doc.entries.get(META_SIG_JSON);
864
+ const sig = doc.entries.get(META_SIG);
865
+ if (!sj && !sig) {
866
+ if (opts.requireSignature)
867
+ throw vf("unsigned .dome where a signature is required", [
868
+ { pointer: `/entries/${META_SIG_JSON}`, detail: "missing" }
869
+ ]);
870
+ return;
871
+ }
872
+ if (!sj || !sig)
873
+ throw vf(
874
+ "incomplete signature: META-INF/signature and META-INF/signature.json are both required"
875
+ );
876
+ let meta;
877
+ try {
878
+ meta = JSON.parse(fromUtf8(sj));
879
+ } catch {
880
+ throw vf("META-INF/signature.json is not valid JSON");
881
+ }
882
+ const se = (0, import_validate.validate)(`dome/${import_validate.domeMinors[import_validate.domeMinors.length - 1]}/signature.schema.json`, meta);
883
+ if (se.length) {
884
+ throw vf(
885
+ "META-INF/signature.json does not match its schema",
886
+ se.slice(0, 10).map((e) => ({
887
+ pointer: `/entries/${META_SIG_JSON}${e.instancePath}`,
888
+ detail: e.message || e.keyword
889
+ }))
890
+ );
891
+ }
892
+ const listed = /* @__PURE__ */ new Map();
893
+ for (const e of meta.signedEntries) listed.set(e.path, e);
894
+ const errors = [];
895
+ for (const name of signedEntryNames(doc))
896
+ if (!listed.has(name))
897
+ errors.push({ pointer: `/entries/${name}`, detail: "entry not covered by the signature" });
898
+ for (const [name, e] of listed) {
899
+ const data = name === "dome.json" ? manifestBytesFor(doc) : doc.entries.get(name);
900
+ if (!data) errors.push({ pointer: `/entries/${name}`, detail: "signed entry missing" });
901
+ else if (data.length !== e.size || sha256(data) !== e.sha256)
902
+ errors.push({ pointer: `/entries/${name}`, detail: "signed entry modified" });
903
+ }
904
+ if (errors.length) throw vf("signature does not cover the container", errors);
905
+ if (sig.length !== 64) throw vf("META-INF/signature must be 64 raw bytes (Ed25519)");
906
+ const k = opts.keys?.[meta.keyId];
907
+ if (!k) {
908
+ if (opts.requireSignature) throw vf(`no public key for keyId "${meta.keyId}"`);
909
+ doc.warnings.push(`signature by "${meta.keyId}" not verified (no public key)`);
910
+ return;
911
+ }
912
+ const spki = typeof k === "string" ? pemToDer(k) : k;
913
+ if (!await (opts.verify ?? webCryptoVerify)(spki, sj, sig)) {
914
+ throw vf("Ed25519 signature invalid", [
915
+ { pointer: `/entries/${META_SIG}`, detail: "does not verify" }
916
+ ]);
917
+ }
918
+ }
919
+ function readDirectory(inp, limits) {
920
+ const out = /* @__PURE__ */ new Map();
921
+ const refused = new Map((inp.refused ?? []).map((r) => [r.path, r.reason]));
922
+ let total = 0;
923
+ const names = [.../* @__PURE__ */ new Set([...inp.files.keys(), ...refused.keys()])].sort(byteOrder);
924
+ for (const rel of names) {
925
+ const why = refused.get(rel);
926
+ if (why === "symlink")
927
+ throw vf(`"${rel}" is a symbolic link`, [
928
+ { pointer: `/entries/${rel}`, detail: "symbolic links are not allowed" }
929
+ ]);
930
+ if (why) throw vf(`"${rel}" is not a regular file`);
931
+ const bad = badEntryName(rel);
932
+ if (bad) throw vf(`entry "${rel}": ${bad}`);
933
+ if (out.size + 1 > limits.maxEntries)
934
+ throw new CodecError("payload-too-large", `more than ${limits.maxEntries} entries`);
935
+ const data = inp.files.get(rel);
936
+ total += data.length;
937
+ if (total > limits.maxTotalBytes)
938
+ throw new CodecError("payload-too-large", `total size above ${limits.maxTotalBytes} bytes`);
939
+ out.set(rel, data);
940
+ }
941
+ return out;
942
+ }
943
+ function semanticChecks(doc) {
944
+ const m = doc.manifest;
945
+ const errors = [];
946
+ const ids = (list, ptr) => {
947
+ const s = /* @__PURE__ */ new Set();
948
+ (list ?? []).forEach((x, i) => {
949
+ if (x?.id === void 0) return;
950
+ if (s.has(x.id)) errors.push({ pointer: `${ptr}/${i}/id`, detail: `duplicate id "${x.id}"` });
951
+ s.add(x.id);
952
+ });
953
+ return s;
954
+ };
955
+ const show = m.show ?? {};
956
+ const displays = ids(m.displays, "/displays");
957
+ const assets = ids(m.assets, "/assets");
958
+ const playlists = ids(show.playlists, "/show/playlists");
959
+ const timelines = ids(show.timelines, "/show/timelines");
960
+ ids(show.cues, "/show/cues");
961
+ const triggers = ids(show.triggers, "/show/triggers");
962
+ ids(show.mediaPlayers, "/show/mediaPlayers");
963
+ ids(m.audio?.speakers, "/audio/speakers");
964
+ ids(m.audio?.devices, "/audio/devices");
965
+ const need = (set, id, pointer, what) => {
966
+ if (id !== void 0 && !set.has(id))
967
+ errors.push({ pointer, detail: `unknown ${what} "${id}"` });
968
+ };
969
+ const hasDisplays = Array.isArray(m.displays);
970
+ if (hasDisplays)
971
+ for (const k of Object.keys(m.calibration?.displays ?? {}))
972
+ need(displays, k, `/calibration/displays/${k}`, "display");
973
+ (show.playlists ?? []).forEach(
974
+ (p, i) => (p.items ?? []).forEach(
975
+ (it, j) => need(assets, it.asset, `/show/playlists/${i}/items/${j}/asset`, "asset")
976
+ )
977
+ );
978
+ (show.timelines ?? []).forEach(
979
+ (t, i) => (t.tracks ?? []).forEach(
980
+ (tr, j) => (tr.clips ?? []).forEach(
981
+ (c, k) => need(assets, c.asset, `/show/timelines/${i}/tracks/${j}/clips/${k}/asset`, "asset")
982
+ )
983
+ )
984
+ );
985
+ if (show.matrix) {
986
+ const axis = (a) => new Set((a ?? []).map((x) => typeof x === "string" ? x : x.id));
987
+ const rows = axis(show.matrix.rows);
988
+ const cols = axis(show.matrix.columns);
989
+ (show.matrix.cells ?? []).forEach((c, i) => {
990
+ need(rows, c.row, `/show/matrix/cells/${i}/row`, "matrix row");
991
+ need(cols, c.column, `/show/matrix/cells/${i}/column`, "matrix column");
992
+ need(assets, c.asset, `/show/matrix/cells/${i}/asset`, "asset");
993
+ });
994
+ }
995
+ (show.cues ?? []).forEach((c, i) => {
996
+ need(timelines, c.at?.timeline, `/show/cues/${i}/at/timeline`, "timeline");
997
+ need(triggers, c.at?.trigger, `/show/cues/${i}/at/trigger`, "trigger");
998
+ });
999
+ const matrixIds = new Set(show.matrix?.id ? [show.matrix.id] : []);
1000
+ const ref = (r, ptr) => {
1001
+ if (!r) return;
1002
+ need(playlists, r.playlist, `${ptr}/playlist`, "playlist");
1003
+ need(timelines, r.timeline, `${ptr}/timeline`, "timeline");
1004
+ need(matrixIds, r.matrix, `${ptr}/matrix`, "matrix");
1005
+ need(assets, r.asset, `${ptr}/asset`, "asset");
1006
+ };
1007
+ ref(show.startup, "/show/startup");
1008
+ (show.mediaPlayers ?? []).forEach((p, i) => {
1009
+ ref(p.source, `/show/mediaPlayers/${i}/source`);
1010
+ if (hasDisplays)
1011
+ (p.target?.displays ?? []).forEach(
1012
+ (d, j) => need(displays, d, `/show/mediaPlayers/${i}/target/displays/${j}`, "display")
1013
+ );
1014
+ });
1015
+ const files = [];
1016
+ (m.assets ?? []).forEach((a, i) => {
1017
+ if (typeof a.src === "string" && !URI.test(a.src)) files.push([`/assets/${i}/src`, a.src]);
1018
+ files.push([`/assets/${i}/thumbnail`, a.thumbnail]);
1019
+ });
1020
+ for (const [id, c] of Object.entries(m.calibration?.displays ?? {})) {
1021
+ files.push(
1022
+ [`/calibration/displays/${id}/warp/file`, c.warp?.file],
1023
+ [`/calibration/displays/${id}/blend/file`, c.blend?.file],
1024
+ [`/calibration/displays/${id}/colour/lut`, c.colour?.lut],
1025
+ [`/calibration/displays/${id}/report/file`, c.report?.file]
1026
+ );
1027
+ if (c.warp?.file && doc.entries.has(c.warp.file)) {
1028
+ const h = checkFdmesh(doc.entries.get(c.warp.file));
1029
+ if (typeof h === "string")
1030
+ errors.push({
1031
+ pointer: `/calibration/displays/${id}/warp/file`,
1032
+ detail: `not a valid FDMESH: ${h}`
1033
+ });
1034
+ else if (Array.isArray(c.warp.size) && (c.warp.size[0] !== h.cols || c.warp.size[1] !== h.rows)) {
1035
+ errors.push({
1036
+ pointer: `/calibration/displays/${id}/warp/size`,
1037
+ detail: `FDMESH header is ${h.cols}x${h.rows}`
1038
+ });
1039
+ }
1040
+ }
1041
+ }
1042
+ files.push(["/audio/roomCorrection/file", m.audio?.roomCorrection?.file]);
1043
+ for (const [pointer, path] of files)
1044
+ if (path !== void 0 && !doc.entries.has(path))
1045
+ errors.push({ pointer, detail: `entry "${path}" missing` });
1046
+ if (errors.length) throw vf("dome.json is inconsistent", errors);
1047
+ }
1048
+ function sameDome(a, b) {
1049
+ if (JSON.stringify(a.manifest) !== JSON.stringify(b.manifest) || a.entries.size !== b.entries.size)
1050
+ return false;
1051
+ for (const [n, d] of a.entries) {
1052
+ const o = b.entries.get(n);
1053
+ if (!o || !equalBytes(o, d)) return false;
1054
+ }
1055
+ return true;
1056
+ }
1057
+
1058
+ // src/codecs/formats.ts
1059
+ var import_validate2 = require("@freedome/protocol/validate");
1060
+ var FORMAT_MIME = {
1061
+ domeZip: "application/vnd.nativemind.freedome.dome+zip",
1062
+ zelimJson: "application/vnd.nativemind.zelim+json",
1063
+ zelimBinary: "application/vnd.nativemind.zelim",
1064
+ borankoJson: "application/vnd.nativemind.boranko+json",
1065
+ borankoZip: "application/vnd.nativemind.boranko+zip",
1066
+ comicsZip: "application/vnd.nativemind.comics+zip"
1067
+ };
1068
+ var BOM = new Uint8Array([239, 187, 191]);
1069
+ var IMAGE_RE = /\.(png|jpe?g|webp|gif|bmp)$/i;
1070
+ var isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
1071
+ var hasBom = (b) => b.length >= 3 && equalBytes(b.subarray(0, 3), BOM);
1072
+ function decodeText(buf, what) {
1073
+ const b = hasBom(buf) ? buf.subarray(3) : buf;
1074
+ try {
1075
+ return new TextDecoder("utf-8", { fatal: true }).decode(b);
1076
+ } catch {
1077
+ throw invalid(`${what}: not valid UTF-8`, "");
1078
+ }
1079
+ }
1080
+ function parseJson(buf, what) {
1081
+ const text = decodeText(buf, what);
1082
+ try {
1083
+ return JSON.parse(text);
1084
+ } catch (e) {
1085
+ throw invalid(`${what}: invalid JSON (${e.message})`, "");
1086
+ }
1087
+ }
1088
+ function firstJsonByte(buf) {
1089
+ let i = hasBom(buf) ? 3 : 0;
1090
+ while (i < buf.length && [32, 9, 13, 10].includes(buf[i])) i++;
1091
+ return i < buf.length ? buf[i] : -1;
1092
+ }
1093
+ function check(schemaRel, data, what) {
1094
+ const all = (0, import_validate2.validate)(`${schemaRel}.schema.json`, data);
1095
+ if (!all.length) return;
1096
+ const errs = all.filter((e) => !["if", "anyOf", "allOf"].includes(e.keyword));
1097
+ const list = (errs.length ? errs : all).slice(0, 20).map((e) => ({ pointer: e.instancePath, detail: `${e.keyword}: ${e.message}` }));
1098
+ throw new CodecError("validation-failed", `${what}: schema validation failed`, list);
1099
+ }
1100
+ function minorFor(version, known) {
1101
+ const m = /^(\d+)\.(\d+)\./.exec(version);
1102
+ const minor = m ? Number(m[2]) : 0;
1103
+ return known.filter((k) => Number(k.split(".")[1]) <= minor).at(-1) ?? known[0];
1104
+ }
1105
+ function dirEntry(inp, name) {
1106
+ const r = inp.refused?.find((x) => x.path === name);
1107
+ if (r) throw invalid(`${name}: not a regular file`, "");
1108
+ return inp.files.get(name) ?? null;
1109
+ }
1110
+ var asInput = (i) => i instanceof Uint8Array ? { kind: "file", bytes: i } : i;
1111
+ function sniff(input) {
1112
+ const inp = asInput(input);
1113
+ if (inp.kind === "dir") {
1114
+ const dj = dirEntry(inp, "dome.json");
1115
+ if (dj) {
1116
+ let j;
1117
+ try {
1118
+ j = parseJson(dj, "dome.json");
1119
+ } catch {
1120
+ throw unsupported("directory: dome.json is not JSON");
1121
+ }
1122
+ if (isObj(j) && j.format === "dome")
1123
+ return { format: "dome", variant: "directory", mime: FORMAT_MIME.domeZip, warnings: [] };
1124
+ }
1125
+ const data = dirEntry(inp, "data.json");
1126
+ if (data) {
1127
+ let j;
1128
+ try {
1129
+ j = parseJson(data, "data.json");
1130
+ } catch {
1131
+ throw unsupported("directory: data.json is not JSON");
1132
+ }
1133
+ if (isObj(j) && Array.isArray(j.pages))
1134
+ return {
1135
+ format: "boranko",
1136
+ variant: "directory",
1137
+ mime: FORMAT_MIME.borankoJson,
1138
+ warnings: []
1139
+ };
1140
+ }
1141
+ throw unsupported("directory without dome.json (format dome) or boranko data.json");
1142
+ }
1143
+ const buf = inp.bytes;
1144
+ if (isZip(buf)) return sniffZip(buf);
1145
+ if (buf.length >= 5 && latin1(buf.subarray(0, 5)) === "ZELIM") {
1146
+ if (buf.length < 64 || buf[5] || buf[6] || buf[7])
1147
+ throw unsupported("ZELIM magic without a complete 64-byte header");
1148
+ return { format: "zelim", variant: "binary", mime: FORMAT_MIME.zelimBinary, warnings: [] };
1149
+ }
1150
+ if (firstJsonByte(buf) === 123) {
1151
+ let j;
1152
+ try {
1153
+ j = parseJson(buf, "file");
1154
+ } catch {
1155
+ throw unsupported('starts with "{" but is not UTF-8 JSON');
1156
+ }
1157
+ if (isObj(j.header) && j.header.format === "zelim")
1158
+ return { format: "zelim", variant: "json", mime: FORMAT_MIME.zelimJson, warnings: [] };
1159
+ if (Array.isArray(j.pages) && (j.version === void 0 || typeof j.version === "string" && /^1\.0\./.test(j.version))) {
1160
+ return {
1161
+ format: "boranko",
1162
+ variant: "single-json",
1163
+ mime: FORMAT_MIME.borankoJson,
1164
+ warnings: []
1165
+ };
1166
+ }
1167
+ throw unsupported("JSON document of no known format");
1168
+ }
1169
+ throw unsupported("no known signature");
1170
+ }
1171
+ function sniffZip(buf) {
1172
+ const z = openZip(buf, DEFAULT_ZIP_LIMITS);
1173
+ const names = z.entries.map((e) => e.name);
1174
+ if (names[0] === "mimetype" && latin1(z.read("mimetype")) === FORMAT_MIME.domeZip) {
1175
+ return { format: "dome", variant: "zip", mime: FORMAT_MIME.domeZip, warnings: [] };
1176
+ }
1177
+ if (names.includes("dome.json")) {
1178
+ let j;
1179
+ try {
1180
+ j = parseJson(z.read("dome.json"), "dome.json");
1181
+ } catch {
1182
+ j = null;
1183
+ }
1184
+ if (isObj(j) && j.format === "dome")
1185
+ return {
1186
+ format: "dome",
1187
+ variant: "zip",
1188
+ mime: FORMAT_MIME.domeZip,
1189
+ warnings: ["no-mimetype"]
1190
+ };
1191
+ }
1192
+ if (names.includes("data.json")) {
1193
+ let j;
1194
+ try {
1195
+ j = parseJson(z.read("data.json"), "data.json");
1196
+ } catch {
1197
+ return { format: "comics", variant: "data", mime: FORMAT_MIME.comicsZip, warnings: [] };
1198
+ }
1199
+ if (isObj(j) && ("layers" in j || "sounds" in j))
1200
+ return { format: "comics", variant: "data", mime: FORMAT_MIME.comicsZip, warnings: [] };
1201
+ if (isObj(j) && Array.isArray(j.pages))
1202
+ return { format: "boranko", variant: "zip", mime: FORMAT_MIME.borankoZip, warnings: [] };
1203
+ throw unsupported("ZIP data.json of no known format");
1204
+ }
1205
+ if (names.some((n) => /^[^/]+_boranko\/data\.json$/.test(n)))
1206
+ return { format: "boranko", variant: "zip", mime: FORMAT_MIME.borankoZip, warnings: [] };
1207
+ const files = names.filter((n) => !n.endsWith("/"));
1208
+ if (files.some((n) => IMAGE_RE.test(n)) && files.every((n) => IMAGE_RE.test(n) || /^(metadata|info)\.json$/.test(n))) {
1209
+ return { format: "comics", variant: "legacy", mime: FORMAT_MIME.comicsZip, warnings: [] };
1210
+ }
1211
+ throw unsupported("ZIP of no known format (no mimetype, dome.json, data.json or images)");
1212
+ }
1213
+ var ROOT_PARENT = 4294967295;
1214
+ var utf8Fatal = (b) => new TextDecoder("utf-8", { fatal: true }).decode(b);
1215
+ function decodeZelimBinary(buf) {
1216
+ if (buf.length < 64) throw invalid("shorter than the 64-byte header", "");
1217
+ if (latin1(buf.subarray(0, 8)) !== "ZELIM\0\0\0") throw unsupported("bad ZELIM magic");
1218
+ const version = u32(buf, 8);
1219
+ if (version !== 1 && version !== 2) throw unsupported(`ZELIM version ${version}`);
1220
+ const timestamp = Number(u64big(buf, 12));
1221
+ const compRaw = buf.subarray(24, 40);
1222
+ const nul = compRaw.indexOf(0);
1223
+ const compression = latin1(compRaw.subarray(0, nul < 0 ? 16 : nul));
1224
+ if (/[^\x20-\x7e]/.test(compression)) throw invalid("compression is not ASCII", "/compression");
1225
+ if (version === 2 && compression !== "none" && compression !== "")
1226
+ throw invalid(`v2 compression "${compression}"`, "/compression");
1227
+ const ne = u32(buf, 40);
1228
+ const ng = u32(buf, 44);
1229
+ const eOff = u32(buf, 48);
1230
+ const gOff = u32(buf, 52);
1231
+ const mOff = u32(buf, 56);
1232
+ const flags = u32(buf, 60);
1233
+ const es = version === 1 ? 128 : 144;
1234
+ if (eOff < 64 || eOff + ne * es > buf.length)
1235
+ throw invalid("element records beyond EOF", "/elementsOffset");
1236
+ if (version === 2 && (gOff === 0 || mOff === 0))
1237
+ throw invalid("v2 requires explicit offsets", gOff === 0 ? "/groupsOffset" : "/metadataOffset");
1238
+ const gPos = gOff || eOff + ne * es;
1239
+ const mPos = mOff || gPos + ng * 64;
1240
+ if (gPos < 64 || gPos + ng * 64 > buf.length)
1241
+ throw invalid("group records beyond EOF", "/groupsOffset");
1242
+ if (mPos < 64 || mPos + 4 > buf.length) throw invalid("metadata beyond EOF", "/metadataOffset");
1243
+ if (version === 2 && flags !== 0) throw invalid("v2 flags must be 0", "/flags");
1244
+ const mLen = u32(buf, mPos);
1245
+ if (mLen > 1048576 || mPos + 4 + mLen > buf.length)
1246
+ throw invalid("metadata length beyond EOF", "/metadata");
1247
+ let metadata;
1248
+ try {
1249
+ metadata = JSON.parse(utf8Fatal(buf.subarray(mPos + 4, mPos + 4 + mLen)));
1250
+ } catch {
1251
+ throw invalid("metadata is not UTF-8 JSON", "/metadata");
1252
+ }
1253
+ const d = (o) => f64(buf, o);
1254
+ const elements = [];
1255
+ for (let i = 0; i < ne; i++) {
1256
+ const o = eOff + i * es;
1257
+ if (version === 1) {
1258
+ const id = u64big(buf, o);
1259
+ if (id > 0xfffffffen) throw invalid(`element ${i}: id beyond u32`, `/elements/${i}/id`);
1260
+ elements.push({
1261
+ id: Number(id),
1262
+ parentId: ROOT_PARENT,
1263
+ orbitAngle: d(o + 8),
1264
+ radius: d(o + 16),
1265
+ phase: d(o + 24),
1266
+ energyLevel: d(o + 32),
1267
+ quantumState: u32(buf, o + 40),
1268
+ attractionCoefficient: d(o + 44),
1269
+ conservationFactor: d(o + 52),
1270
+ interactionMatrix: [...Array(8).keys()].map((k) => d(o + 60 + 8 * k)).concat([0])
1271
+ });
1272
+ } else {
1273
+ elements.push({
1274
+ id: u32(buf, o),
1275
+ parentId: u32(buf, o + 4),
1276
+ orbitAngle: d(o + 8),
1277
+ radius: d(o + 16),
1278
+ phase: d(o + 24),
1279
+ energyLevel: d(o + 32),
1280
+ quantumState: u32(buf, o + 40),
1281
+ attractionCoefficient: d(o + 48),
1282
+ conservationFactor: d(o + 56),
1283
+ interactionMatrix: [...Array(9).keys()].map((k) => d(o + 64 + 8 * k))
1284
+ });
1285
+ }
1286
+ }
1287
+ const groups = [];
1288
+ for (let i = 0; i < ng; i++) {
1289
+ const o = gPos + i * 64;
1290
+ const id = version === 1 ? u64big(buf, o) : BigInt(u32(buf, o));
1291
+ if (id > 0xffffffffn) throw invalid(`group ${i}: id beyond u32`, `/groups/${i}/id`);
1292
+ const t = buf.subarray(o + 24, o + 40);
1293
+ const tn = t.indexOf(0);
1294
+ let groupType;
1295
+ try {
1296
+ groupType = utf8Fatal(t.subarray(0, tn < 0 ? 16 : tn));
1297
+ } catch {
1298
+ throw invalid(`group ${i}: type not UTF-8`, `/groups/${i}/groupType`);
1299
+ }
1300
+ const slots = [0, 1, 2, 3, 4].map((k) => u32(buf, o + 40 + 4 * k));
1301
+ const count = buf[o + 60];
1302
+ if (version === 2 && count > 5)
1303
+ throw invalid(`group ${i}: memberCount ${count} > 5`, `/groups/${i}/memberCount`);
1304
+ groups.push({
1305
+ id: Number(id),
1306
+ energyTransferRate: d(o + 8),
1307
+ collisionThreshold: d(o + 16),
1308
+ groupType,
1309
+ members: version === 1 ? slots.filter((x) => x !== 0) : slots.slice(0, count)
1310
+ });
1311
+ }
1312
+ return {
1313
+ format: "zelim",
1314
+ variant: "binary",
1315
+ version,
1316
+ timestamp,
1317
+ compression: compression || "none",
1318
+ elements,
1319
+ groups,
1320
+ metadata
1321
+ };
1322
+ }
1323
+ async function decodeZelimJson(buf, sibling) {
1324
+ const doc = parseJson(buf, ".zelim");
1325
+ const version = isObj(doc) && isObj(doc.header) && typeof doc.header.version === "string" ? doc.header.version : "";
1326
+ if (!/^\d+\.\d+\.\d+/.test(version)) check("zelim/1.0/zelim-project", doc, ".zelim");
1327
+ if (!version.startsWith("1."))
1328
+ throw unsupported(`.zelim JSON major ${version.split(".")[0]} (reader supports 1)`);
1329
+ const minor = minorFor(version, ["1.0", "1.1"]);
1330
+ check(`zelim/${minor}/zelim-project`, doc, ".zelim");
1331
+ const warnings = [];
1332
+ const scene = doc.quantum?.scene;
1333
+ if (minor !== "1.0" && isObj(scene) && sibling) {
1334
+ const b = await sibling(String(scene.src));
1335
+ if (!b) warnings.push("quantum-scene-missing");
1336
+ else {
1337
+ if (b.length !== scene.size)
1338
+ throw invalid(
1339
+ `quantum.scene ${scene.src}: ${b.length} bytes, declared ${scene.size}`,
1340
+ "/quantum/scene/size"
1341
+ );
1342
+ if (new Sha256().update(b).hex() !== scene.sha256)
1343
+ throw invalid(`quantum.scene ${scene.src}: sha256 mismatch`, "/quantum/scene/sha256");
1344
+ decodeZelimBinary(b);
1345
+ }
1346
+ }
1347
+ return {
1348
+ result: {
1349
+ format: "zelim",
1350
+ variant: "json",
1351
+ formatVersion: version,
1352
+ schema: minor,
1353
+ project: doc
1354
+ },
1355
+ warnings
1356
+ };
1357
+ }
1358
+ async function decodeZelim(input) {
1359
+ const inp = asInput(input);
1360
+ const s = sniff(inp);
1361
+ if (s.format !== "zelim" || inp.kind !== "file")
1362
+ throw unsupported(`.zelim matches neither variant (content is ${s.format})`);
1363
+ if (s.variant === "binary") return { result: decodeZelimBinary(inp.bytes), warnings: [] };
1364
+ return decodeZelimJson(inp.bytes, inp.sibling);
1365
+ }
1366
+ var BALLOON_DEFAULTS = { type: "speech", aspectRatio: 1, analogDigitalCoefficient: 0.5 };
1367
+ function normaliseBoranko(doc, warnings) {
1368
+ const out = {
1369
+ ...doc,
1370
+ version: doc.version ?? "1.0.0",
1371
+ pages: [],
1372
+ localizations: doc.localizations ?? {},
1373
+ assets: doc.assets ?? null
1374
+ };
1375
+ (Array.isArray(doc.pages) ? doc.pages : []).forEach((p, i) => {
1376
+ if (!isObj(p)) {
1377
+ out.pages.push(p);
1378
+ return;
1379
+ }
1380
+ let z = p.zDepth ?? 100;
1381
+ if (typeof z === "number" && (z < 0 || z > 108)) {
1382
+ warnings.push(`zdepth-clamped:/pages/${i}/zDepth`);
1383
+ z = Math.min(108, Math.max(0, z));
1384
+ }
1385
+ out.pages.push({
1386
+ ...p,
1387
+ fileName: p.fileName ?? p.imagePath,
1388
+ originalPath: p.originalPath ?? "",
1389
+ zDepth: z,
1390
+ domeOptimized: p.domeOptimized ?? false,
1391
+ quantumCompatible: p.quantumCompatible ?? false,
1392
+ text: p.text ?? null,
1393
+ sounds: (p.sounds ?? []).map(
1394
+ (s) => isObj(s) ? { ...s, startTime: s.startTime ?? 0, volume: s.volume ?? 1 } : s
1395
+ ),
1396
+ balloons: (p.balloons ?? []).map((b) => isObj(b) ? { ...BALLOON_DEFAULTS, ...b } : b)
1397
+ });
1398
+ });
1399
+ if (isObj(out.assets)) {
1400
+ out.assets = {
1401
+ originalImages: [],
1402
+ vectorizedImages: [],
1403
+ balloonsOriginalPath: "assets/balloons_original",
1404
+ balloonsCleanedPath: "assets/balloons",
1405
+ ...out.assets
1406
+ };
1407
+ }
1408
+ if (!Array.isArray(doc.pages) && doc.pages !== void 0) out.pages = doc.pages;
1409
+ return out;
1410
+ }
1411
+ function borankoPaths(doc) {
1412
+ const paths = [];
1413
+ (doc.pages ?? []).forEach((p, i) => {
1414
+ paths.push([`/pages/${i}/imagePath`, p.imagePath]);
1415
+ (p.sounds ?? []).forEach(
1416
+ (s, k) => paths.push([`/pages/${i}/sounds/${k}/soundPath`, s.soundPath])
1417
+ );
1418
+ (p.balloons ?? []).forEach((b, k) => {
1419
+ paths.push([`/pages/${i}/balloons/${k}/originalImagePath`, b.originalImagePath]);
1420
+ paths.push([`/pages/${i}/balloons/${k}/cleanedImagePath`, b.cleanedImagePath]);
1421
+ });
1422
+ });
1423
+ return paths;
1424
+ }
1425
+ async function decodeBoranko(input) {
1426
+ const inp = asInput(input);
1427
+ const s = sniff(inp);
1428
+ if (s.format !== "boranko") throw unsupported(`not a .boranko (content is ${s.format})`);
1429
+ let raw;
1430
+ let exists;
1431
+ if (inp.kind === "dir") {
1432
+ raw = dirEntry(inp, "data.json");
1433
+ exists = (p) => inp.files.has(p) || [...inp.files.keys()].some((k) => k.startsWith(`${p}/`));
1434
+ } else if (s.variant === "single-json") {
1435
+ raw = inp.bytes;
1436
+ exists = null;
1437
+ } else {
1438
+ const z = openZip(inp.bytes, DEFAULT_ZIP_LIMITS);
1439
+ const dj = z.entries.find((e) => e.name === "data.json") ?? z.entries.find((e) => /^[^/]+_boranko\/data\.json$/.test(e.name));
1440
+ const prefix = dj.name.slice(0, -"data.json".length);
1441
+ const names = new Set(z.entries.map((e) => e.name));
1442
+ raw = z.read(dj.name);
1443
+ exists = (p) => names.has(prefix + p);
1444
+ }
1445
+ const doc = parseJson(raw, "data.json");
1446
+ if (!isObj(doc)) throw invalid("data.json root is not an object", "");
1447
+ const version = doc.version ?? "1.0.0";
1448
+ if (typeof version === "string" && !version.startsWith("1."))
1449
+ throw unsupported(`.boranko major ${version.split(".")[0]} (reader supports 1)`);
1450
+ const warnings = [];
1451
+ const out = normaliseBoranko(doc, warnings);
1452
+ const minor = s.variant === "single-json" ? "1.0" : minorFor(String(version), ["1.0", "1.1"]);
1453
+ check(`boranko/${minor}/boranko`, out, "data.json");
1454
+ if (exists) {
1455
+ for (const [ptr, p] of borankoPaths(out)) if (!exists(p)) warnings.push(`missing-file:${ptr}`);
1456
+ }
1457
+ return {
1458
+ result: {
1459
+ format: "boranko",
1460
+ variant: s.variant,
1461
+ formatVersion: out.version,
1462
+ schema: minor,
1463
+ project: out
1464
+ },
1465
+ warnings
1466
+ };
1467
+ }
1468
+ var ANIM_KINDS = [
1469
+ ["TranslateAnim", "translate"],
1470
+ ["ScaleAnim", "scale"],
1471
+ ["RotateAnim", "rotate"],
1472
+ ["SoundAnim", "sound"]
1473
+ ];
1474
+ function animKind(type) {
1475
+ for (const [suffix, kind] of ANIM_KINDS)
1476
+ if (new RegExp(`(^|\\.)${suffix}(,|$)`).test(type)) return kind;
1477
+ return "unknown";
1478
+ }
1479
+ var normAnims = (list) => (list ?? []).map(({ $type, ...params }) => ({ kind: animKind($type), $type, params }));
1480
+ async function decodeComicsData(buf, entryNames = null) {
1481
+ const data = parseJson(buf, "data.json");
1482
+ check("comics/1.0/comics-data", data, "data.json");
1483
+ const warnings = [];
1484
+ const { width, height, layers = [], sounds = [], ...extra } = data;
1485
+ const out = {
1486
+ format: "comics",
1487
+ variant: "data",
1488
+ width,
1489
+ height,
1490
+ layers: layers.map(({ images = [], animations, ...rest }, i) => ({
1491
+ id: `layer_${i}`,
1492
+ images,
1493
+ animations: normAnims(animations),
1494
+ ...Object.keys(rest).length ? { extra: rest } : {}
1495
+ })),
1496
+ sounds: sounds.map(({ file, animations, ...rest }, i) => ({
1497
+ id: `sound_${i}`,
1498
+ file,
1499
+ animations: normAnims(animations),
1500
+ ...Object.keys(rest).length ? { extra: rest } : {}
1501
+ })),
1502
+ extra
1503
+ };
1504
+ if (entryNames) {
1505
+ out.entries = [...entryNames].sort();
1506
+ out.sounds.forEach((s, i) => {
1507
+ if (!entryNames.includes(`sounds/${s.file}`)) warnings.push(`missing-file:/sounds/${i}/file`);
1508
+ });
1509
+ out.layers.forEach(
1510
+ (l, i) => l.images.forEach((img, k) => {
1511
+ if (img.file && !entryNames.some((n) => n.startsWith(`layers/${String(img.file).split("{0}")[0]}`)))
1512
+ warnings.push(`missing-tiles:/layers/${i}/images/${k}`);
1513
+ })
1514
+ );
1515
+ }
1516
+ return { result: out, warnings };
1517
+ }
1518
+ async function decodeComics(input) {
1519
+ const inp = asInput(input);
1520
+ const s = sniff(inp);
1521
+ if (s.format !== "comics" || inp.kind !== "file")
1522
+ throw unsupported(`not a .comics (content is ${s.format})`);
1523
+ const z = openZip(inp.bytes, DEFAULT_ZIP_LIMITS);
1524
+ const names = z.entries.map((e) => e.name).filter((n) => !n.endsWith("/"));
1525
+ if (s.variant === "data") return decodeComicsData(z.read("data.json"), names);
1526
+ const metaName = names.find((n) => n === "metadata.json") ?? names.find((n) => n === "info.json") ?? null;
1527
+ let metadata = null;
1528
+ if (metaName) {
1529
+ metadata = parseJson(z.read(metaName), metaName);
1530
+ check("comics/1.0/comics-metadata", metadata, metaName);
1531
+ }
1532
+ const images = names.filter((n) => IMAGE_RE.test(n)).sort();
1533
+ const warnings = [];
1534
+ let pages = images;
1535
+ if (metadata?.pages?.length) {
1536
+ pages = metadata.pages;
1537
+ metadata.pages.forEach((p, i) => {
1538
+ if (!names.includes(p)) warnings.push(`missing-file:/metadata/pages/${i}`);
1539
+ });
1540
+ }
1541
+ return {
1542
+ result: { format: "comics", variant: "legacy", pages, metadata, entries: [...names].sort() },
1543
+ warnings
1544
+ };
1545
+ }
1546
+
1547
+ // src/codecs/input.ts
1548
+ var bytesInput = (bytes, name) => ({
1549
+ kind: "file",
1550
+ bytes,
1551
+ ...name ? { name } : {}
1552
+ });
1553
+ var directoryInput = (files, name) => ({
1554
+ kind: "dir",
1555
+ files: files instanceof Map ? files : new Map(Object.entries(files)),
1556
+ ...name ? { name } : {}
1557
+ });
1558
+ // Annotate the CommonJS export names for ESM import in node:
1559
+ 0 && (module.exports = {
1560
+ CodecError,
1561
+ DEFAULT_ZIP_LIMITS,
1562
+ DOME_MIME,
1563
+ DOME_WRITER_VERSION,
1564
+ DOS_DATE_1980_01_01,
1565
+ DomeCodec,
1566
+ FORMAT_MIME,
1567
+ LeWriter,
1568
+ addChecksums,
1569
+ animKind,
1570
+ badEntryName,
1571
+ byteOrder,
1572
+ bytesInput,
1573
+ checkFdmesh,
1574
+ concat,
1575
+ crc32,
1576
+ decodeBoranko,
1577
+ decodeComics,
1578
+ decodeComicsData,
1579
+ decodeText,
1580
+ decodeZelim,
1581
+ decodeZelimBinary,
1582
+ decodeZelimJson,
1583
+ directoryInput,
1584
+ equalBytes,
1585
+ f32,
1586
+ f64,
1587
+ fromLatin1,
1588
+ fromUtf8,
1589
+ invalid,
1590
+ isZip,
1591
+ latin1,
1592
+ manifestBytesFor,
1593
+ openZip,
1594
+ parseJson,
1595
+ pemToDer,
1596
+ sameDome,
1597
+ signDome,
1598
+ signedEntryNames,
1599
+ sniff,
1600
+ tooLarge,
1601
+ u16,
1602
+ u32,
1603
+ u64big,
1604
+ unsupported,
1605
+ utf8,
1606
+ webCryptoVerify,
1607
+ writeZip
1608
+ });