jpegxl 8.4.0 → 8.4.1
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/README.md +294 -229
- package/dist/animation.browser.mjs +2 -2
- package/dist/animation.mjs +2 -2
- package/dist/capture-complete.browser.mjs +2 -2
- package/dist/capture-complete.mjs +2 -2
- package/dist/capture-groups.mjs +2 -2
- package/dist/capture.browser.mjs +2 -2
- package/dist/capture.mjs +2 -2
- package/dist/cli-add.mjs +2 -2
- package/dist/cli-astro.mjs +2 -2
- package/dist/cli-cloudflare.mjs +2 -2
- package/dist/cli-emdash.mjs +2 -2
- package/dist/cli-places.mjs +2 -2
- package/dist/cli-selftest.mjs +2 -2
- package/dist/cli-workers.mjs +2 -2
- package/dist/cli.mjs +2 -2
- package/dist/decode.browser.mjs +2 -2
- package/dist/decode.mjs +2 -2
- package/dist/decode.node.mjs +2 -2
- package/dist/format.browser.mjs +2 -2
- package/dist/format.mjs +2 -2
- package/dist/hdr.mjs +2 -2
- package/dist/helpers.mjs +2 -2
- package/dist/index.browser.mjs +2 -2
- package/dist/index.mjs +2 -2
- package/dist/jpeg.browser.mjs +2 -2
- package/dist/jpeg.mjs +2 -2
- package/dist/jpeg.node.mjs +2 -2
- package/dist/metadata.mjs +2 -2
- package/dist/polyfill.mjs +2 -2
- package/dist/resumable.mjs +2 -2
- package/dist/resumable.node.mjs +2 -2
- package/dist/serve.mjs +2 -2
- package/dist/serve.node.mjs +2 -2
- package/dist/upload.browser.mjs +2 -2
- package/dist/upload.mjs +2 -2
- package/dist/verify.mjs +2 -2
- package/dist/verify.node.mjs +2 -2
- package/dist/wasm-modules.mjs +2 -2
- package/examples/agents/jxl-tools.mjs +8 -8
- package/examples/android/prepare-assets.mjs +2 -2
- package/examples/capacitor/prepare-assets.mjs +2 -2
- package/examples/emdash/admin-work.mjs +1 -1
- package/examples/emdash/backfill.mjs +4 -4
- package/examples/emdash/background.mjs +5 -5
- package/examples/emdash/browser-candidate.mjs +1 -1
- package/examples/emdash/deliver.mjs +2 -2
- package/examples/emdash/host-policy.mjs +6 -6
- package/examples/emdash/index.mjs +3 -3
- package/examples/emdash/job-runner.mjs +31 -31
- package/examples/emdash/job-store.mjs +21 -21
- package/examples/emdash/jpeg-source.mjs +2 -2
- package/examples/emdash/library-jobs.mjs +21 -21
- package/examples/emdash/local-store.mjs +16 -16
- package/examples/emdash/media-admin.mjs +9 -9
- package/examples/emdash/media-plugin.mjs +62 -62
- package/examples/emdash/media-storage.mjs +55 -55
- package/examples/emdash/media-words.mjs +89 -89
- package/examples/emdash/media-worker.mjs +1 -1
- package/examples/emdash/original-envelope.mjs +2 -2
- package/examples/emdash/originals.mjs +77 -77
- package/examples/emdash/r2-store.mjs +3 -3
- package/examples/emdash/read-all.mjs +14 -14
- package/examples/emdash/server-only.mjs +1 -1
- package/examples/emdash/storage.mjs +1 -1
- package/examples/emdash/structural-delivery.mjs +42 -42
- package/examples/emdash/thread-driver.mjs +15 -15
- package/examples/emdash/thread-worker.mjs +3 -3
- package/examples/emdash/work-queue.mjs +11 -11
- package/examples/flutter/prepare-assets.mjs +3 -3
- package/examples/ios/prepare-assets.mjs +3 -3
- package/examples/page-rects.js +14 -14
- package/examples/react-native/src/JXLProvider.tsx +19 -9
- package/examples/snapdom/jxl.js +3 -2
- package/examples/svg-jxl.js +10 -10
- package/package.json +1 -1
- package/types/animation.d.mts +2 -2
- package/types/capture-complete.d.mts +5 -5
- package/types/capture.d.mts +1 -1
- package/types/format.d.mts +2 -2
- package/types/index.d.mts +6 -6
- package/types/jpeg.d.mts +1 -1
- package/types/result.d.mts +5 -4
- package/types/resumable.d.mts +7 -7
- package/types/serve.d.mts +1 -1
- package/types/types.d.mts +19 -18
- package/types/upload.d.mts +1 -1
- package/types/verify.d.mts +4 -4
|
@@ -17,17 +17,17 @@ function bufferBytes(value) {
|
|
|
17
17
|
// A Uint8Array on an ordinary, attached ArrayBuffer: its length.
|
|
18
18
|
function viewLength(value) {
|
|
19
19
|
if (typedName.call(value) !== 'Uint8Array' || bufferBytes(typedBuffer.call(value)) === null)
|
|
20
|
-
throw fail('JXL_INPUT', "
|
|
20
|
+
throw fail('JXL_INPUT', "body: bytes, Blob or stream");
|
|
21
21
|
return typedLength.call(value);
|
|
22
22
|
}
|
|
23
23
|
function copy(value) {
|
|
24
24
|
viewLength(value);
|
|
25
25
|
try { return new Uint8Array(value); }
|
|
26
|
-
catch { throw fail('JXL_INPUT', "
|
|
26
|
+
catch { throw fail('JXL_INPUT', "body: attached buffer"); }
|
|
27
27
|
}
|
|
28
28
|
// An aborted signal throws its own reason.
|
|
29
29
|
function check(signal) {
|
|
30
|
-
if (signal?.aborted) throw signal.reason ?? fail('JXL_IO', "
|
|
30
|
+
if (signal?.aborted) throw signal.reason ?? fail('JXL_IO', "read: new signal");
|
|
31
31
|
}
|
|
32
32
|
function wait(promise, signal) {
|
|
33
33
|
if (!signal) return promise;
|
|
@@ -42,15 +42,15 @@ function wait(promise, signal) {
|
|
|
42
42
|
}
|
|
43
43
|
function settings(value) {
|
|
44
44
|
if (value === undefined) return {};
|
|
45
|
-
if (!value || typeof value !== 'object' || Array.isArray(value)) throw fail('JXL_OPTIONS', "
|
|
45
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw fail('JXL_OPTIONS', "options: object");
|
|
46
46
|
if (Object.values(Object.getOwnPropertyDescriptors(value)).some(field => !('value' in field)))
|
|
47
|
-
throw fail('JXL_OPTIONS', "
|
|
48
|
-
for (const key of Object.keys(value)) if (key !== 'maxBytes' && key !== 'signal') throw fail('JXL_OPTIONS', `
|
|
47
|
+
throw fail('JXL_OPTIONS', "options: plain values");
|
|
48
|
+
for (const key of Object.keys(value)) if (key !== 'maxBytes' && key !== 'signal') throw fail('JXL_OPTIONS', `unknown option: ${key}`);
|
|
49
49
|
const {maxBytes = MAX_BYTES, signal} = value;
|
|
50
50
|
if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > MAX_BYTES)
|
|
51
|
-
throw fail('JXL_OPTIONS', "
|
|
51
|
+
throw fail('JXL_OPTIONS', "maxBytes: integer 1-268435456");
|
|
52
52
|
if (signal !== undefined && (!signal || typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function'))
|
|
53
|
-
throw fail('JXL_OPTIONS', "
|
|
53
|
+
throw fail('JXL_OPTIONS', "signal: AbortSignal");
|
|
54
54
|
return {maxBytes, signal};
|
|
55
55
|
}
|
|
56
56
|
|
|
@@ -58,23 +58,23 @@ function settings(value) {
|
|
|
58
58
|
export async function readAll(body, options) {
|
|
59
59
|
const {maxBytes, signal} = settings(options);
|
|
60
60
|
check(signal);
|
|
61
|
-
const over = () => fail('JXL_LIMIT', `
|
|
61
|
+
const over = () => fail('JXL_LIMIT', `body: >maxBytes ${maxBytes}`);
|
|
62
62
|
if (typeof Blob !== 'undefined' && body instanceof Blob) {
|
|
63
63
|
if (body.size > maxBytes) throw over();
|
|
64
64
|
let buffer;
|
|
65
65
|
try { buffer = await wait(body.arrayBuffer(), signal); }
|
|
66
|
-
catch (cause) { if (signal?.aborted) throw cause; throw Object.assign(fail('JXL_IO', "
|
|
67
|
-
if (buffer.byteLength !== body.size) throw fail('JXL_INPUT', "
|
|
66
|
+
catch (cause) { if (signal?.aborted) throw cause; throw Object.assign(fail('JXL_IO', "read: storage failure"), {cause}); }
|
|
67
|
+
if (buffer.byteLength !== body.size) throw fail('JXL_INPUT', "file: changed; reread");
|
|
68
68
|
return new Uint8Array(buffer);
|
|
69
69
|
}
|
|
70
70
|
const length = bufferBytes(body);
|
|
71
71
|
if (length !== null) {
|
|
72
72
|
if (length > maxBytes) throw over();
|
|
73
73
|
try { return new Uint8Array(new Uint8Array(body)); }
|
|
74
|
-
catch { throw fail('JXL_INPUT', "
|
|
74
|
+
catch { throw fail('JXL_INPUT', "body: attached buffer"); }
|
|
75
75
|
}
|
|
76
76
|
if (ArrayBuffer.isView(body)) { if (viewLength(body) > maxBytes) throw over(); return copy(body); }
|
|
77
|
-
if (!body || typeof body.getReader !== 'function') throw fail('JXL_INPUT', "
|
|
77
|
+
if (!body || typeof body.getReader !== 'function') throw fail('JXL_INPUT', "body: bytes, Blob or stream");
|
|
78
78
|
const reader = body.getReader(), chunks = [];
|
|
79
79
|
let total = 0, ended = false;
|
|
80
80
|
try {
|
|
@@ -85,7 +85,7 @@ export async function readAll(body, options) {
|
|
|
85
85
|
catch (cause) {
|
|
86
86
|
// The stream's own failure (a dropped connection, a source that throws) is JXL_IO; an abort is the caller's.
|
|
87
87
|
if (signal?.aborted || typeof cause?.code === 'string' && cause.code.startsWith('JXL_')) throw cause;
|
|
88
|
-
throw Object.assign(fail('JXL_IO', "
|
|
88
|
+
throw Object.assign(fail('JXL_IO', "read: storage failure"), {cause});
|
|
89
89
|
}
|
|
90
90
|
check(signal);
|
|
91
91
|
if (done) {
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// SPDX-License-Identifier: MIT
|
|
2
|
-
throw Object.assign(new Error('
|
|
2
|
+
throw Object.assign(new Error('server: import jpegxl/emdash in astro.config.mjs'), {code: 'JXL_PLATFORM'});
|
|
@@ -7,6 +7,6 @@ const ENTRIES = {
|
|
|
7
7
|
|
|
8
8
|
export function rapierStorage(descriptor, options = {}) {
|
|
9
9
|
const entry = ENTRIES[descriptor?.entrypoint];
|
|
10
|
-
if (!entry) throw Object.assign(new TypeError("
|
|
10
|
+
if (!entry) throw Object.assign(new TypeError("storage: r2() or local()"), {code: 'JXL_OPTIONS'});
|
|
11
11
|
return {entrypoint: fileURLToPath(new URL(entry, import.meta.url)), config: {...descriptor.config, rapier: options}};
|
|
12
12
|
}
|
|
@@ -10,28 +10,28 @@ export const DELIVERY_BYTES = 8 * 1024 * 1024;
|
|
|
10
10
|
const SEGMENTS = 256;
|
|
11
11
|
const fail = (code, message) => Object.assign(new Error(message), {code});
|
|
12
12
|
const invalid = message => { throw fail('JXL_INPUT', message); };
|
|
13
|
-
const incomplete = () => { throw Object.assign(fail('JXL_UNSUPPORTED', "
|
|
13
|
+
const incomplete = () => { throw Object.assign(fail('JXL_UNSUPPORTED', "dimensions: server verification"), {incomplete: true}); };
|
|
14
14
|
const dimensions = (width, height, maxPixels) => {
|
|
15
15
|
if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width < 1 || height < 1 ||
|
|
16
16
|
!Number.isSafeInteger(width * height) || maxPixels !== undefined && width * height > maxPixels)
|
|
17
|
-
throw fail('JXL_LIMIT', "
|
|
17
|
+
throw fail('JXL_LIMIT', "dimensions: positive integers <=maxPixels");
|
|
18
18
|
};
|
|
19
19
|
function tiffOrientation(bytes) {
|
|
20
20
|
const big = bytes[0] === 77 && bytes[1] === 77;
|
|
21
|
-
if (bytes.length < 8 || !big && !(bytes[0] === 73 && bytes[1] === 73)) invalid("
|
|
21
|
+
if (bytes.length < 8 || !big && !(bytes[0] === 73 && bytes[1] === 73)) invalid("Exif: byte order");
|
|
22
22
|
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
23
23
|
const u16 = at => view.getUint16(at, !big), u32 = at => view.getUint32(at, !big);
|
|
24
|
-
if (u16(2) !== 42) invalid("
|
|
24
|
+
if (u16(2) !== 42) invalid("Exif: signature");
|
|
25
25
|
const at = u32(4);
|
|
26
|
-
if (at < 8 || at > bytes.length - 2) invalid("
|
|
26
|
+
if (at < 8 || at > bytes.length - 2) invalid("Exif: directory");
|
|
27
27
|
const count = u16(at);
|
|
28
|
-
if (count > 512 || at + 2 + count * 12 + 4 > bytes.length) invalid("
|
|
28
|
+
if (count > 512 || at + 2 + count * 12 + 4 > bytes.length) invalid("Exif: directory length");
|
|
29
29
|
let orientation = null;
|
|
30
30
|
for (let i = 0, entry = at + 2; i < count; i++, entry += 12) if (u16(entry) === 274) {
|
|
31
31
|
if (orientation !== null || u16(entry + 2) !== 3 || u32(entry + 4) !== 1)
|
|
32
|
-
invalid("
|
|
32
|
+
invalid("Exif: repeated orientation");
|
|
33
33
|
orientation = u16(entry + 8);
|
|
34
|
-
if (orientation < 1 || orientation > 8) invalid("
|
|
34
|
+
if (orientation < 1 || orientation > 8) invalid("Exif orientation: 1-8");
|
|
35
35
|
}
|
|
36
36
|
return orientation ?? 1;
|
|
37
37
|
}
|
|
@@ -39,40 +39,40 @@ function jpegGeometry(bytes) {
|
|
|
39
39
|
let at = 2, width, height, components, orientation = 1, exif = false;
|
|
40
40
|
for (let count = 0; count < SEGMENTS; count++) {
|
|
41
41
|
if (at >= bytes.length) incomplete();
|
|
42
|
-
if (bytes[at++] !== 255) invalid("
|
|
42
|
+
if (bytes[at++] !== 255) invalid("JPEG: marker");
|
|
43
43
|
while (at < bytes.length && bytes[at] === 255) at++;
|
|
44
44
|
if (at >= bytes.length) incomplete();
|
|
45
45
|
const marker = bytes[at++];
|
|
46
46
|
if (marker === 1) continue;
|
|
47
47
|
if (marker === 0 || marker === 216 || marker === 217 || marker >= 208 && marker <= 215)
|
|
48
|
-
invalid("
|
|
48
|
+
invalid("JPEG: header marker");
|
|
49
49
|
if (!(marker >= 192 && marker <= 207) && ![218, 219, 221, 254].includes(marker) && !(marker >= 224 && marker <= 239))
|
|
50
|
-
invalid("
|
|
50
|
+
invalid("JPEG: unknown marker");
|
|
51
51
|
if (at + 2 > bytes.length) incomplete();
|
|
52
52
|
const length = bytes[at] * 256 + bytes[at + 1], body = at + 2, end = at + length;
|
|
53
|
-
if (length < 2) invalid("
|
|
53
|
+
if (length < 2) invalid("JPEG: segment length");
|
|
54
54
|
if (end > bytes.length) incomplete();
|
|
55
55
|
if ([192, 193, 194].includes(marker)) {
|
|
56
|
-
if (width !== undefined || length < 11) invalid("
|
|
56
|
+
if (width !== undefined || length < 11) invalid("JPEG: repeated frame");
|
|
57
57
|
components = bytes[body + 5];
|
|
58
58
|
if (![8, 12].includes(bytes[body]) || components < 1 || components > 4 || length !== 8 + 3 * components)
|
|
59
|
-
invalid("
|
|
59
|
+
invalid("JPEG: frame geometry");
|
|
60
60
|
height = bytes[body + 1] * 256 + bytes[body + 2]; width = bytes[body + 3] * 256 + bytes[body + 4];
|
|
61
61
|
} else if ([195, 197, 198, 199, 201, 202, 203, 205, 206, 207].includes(marker))
|
|
62
|
-
throw fail('JXL_UNSUPPORTED', "JPEG delivery
|
|
62
|
+
throw fail('JXL_UNSUPPORTED', "JPEG delivery: server verification");
|
|
63
63
|
if (marker === 225 && [69, 120, 105, 102, 0, 0].every((value, i) => bytes[body + i] === value)) {
|
|
64
|
-
if (exif) invalid("
|
|
64
|
+
if (exif) invalid("Exif: one metadata block");
|
|
65
65
|
exif = true; orientation = tiffOrientation(bytes.subarray(body + 6, end));
|
|
66
66
|
}
|
|
67
67
|
if (marker === 218) {
|
|
68
68
|
const scans = bytes[body];
|
|
69
69
|
if (width === undefined || scans < 1 || scans > components || length !== 6 + scans * 2)
|
|
70
|
-
invalid("
|
|
70
|
+
invalid("JPEG: scan header");
|
|
71
71
|
return {format: 'jpeg', width, height, orientation};
|
|
72
72
|
}
|
|
73
73
|
at = end;
|
|
74
74
|
}
|
|
75
|
-
throw fail('JXL_LIMIT', "
|
|
75
|
+
throw fail('JXL_LIMIT', "header: too large; server verify");
|
|
76
76
|
}
|
|
77
77
|
const PNG = [137, 80, 78, 71, 13, 10, 26, 10];
|
|
78
78
|
const crcTable = Uint32Array.from({length: 256}, (_, n) => {
|
|
@@ -86,47 +86,47 @@ function pngGeometry(bytes) {
|
|
|
86
86
|
if (at + 8 > bytes.length) incomplete();
|
|
87
87
|
const length = view.getUint32(at), type = String.fromCharCode(...bytes.subarray(at + 4, at + 8));
|
|
88
88
|
const body = at + 8, end = body + length;
|
|
89
|
-
if (length > 0x7fffffff) invalid("
|
|
90
|
-
if (!/^[A-Za-z]{4}$/.test(type) || type[2] !== type[2].toUpperCase()) invalid("
|
|
91
|
-
if (!count && (type !== 'IHDR' || length !== 13)) invalid("PNG
|
|
89
|
+
if (length > 0x7fffffff) invalid("PNG: chunk length");
|
|
90
|
+
if (!/^[A-Za-z]{4}$/.test(type) || type[2] !== type[2].toUpperCase()) invalid("PNG: chunk type");
|
|
91
|
+
if (!count && (type !== 'IHDR' || length !== 13)) invalid("PNG: IHDR first");
|
|
92
92
|
if (type === 'IDAT') {
|
|
93
|
-
if (width === undefined || colour === 3 && !palette) invalid("
|
|
93
|
+
if (width === undefined || colour === 3 && !palette) invalid("PNG: header incomplete");
|
|
94
94
|
return {format: 'png', width, height, orientation};
|
|
95
95
|
}
|
|
96
96
|
if (end + 4 > bytes.length) incomplete();
|
|
97
97
|
let crc = 0xffffffff;
|
|
98
98
|
for (let i = at + 4; i < end; i++) crc = crcTable[(crc ^ bytes[i]) & 255] ^ crc >>> 8;
|
|
99
|
-
if (((crc ^ 0xffffffff) >>> 0) !== view.getUint32(end)) invalid("
|
|
99
|
+
if (((crc ^ 0xffffffff) >>> 0) !== view.getUint32(end)) invalid("PNG: header CRC");
|
|
100
100
|
if (type === 'IHDR') {
|
|
101
|
-
if (count) invalid("
|
|
101
|
+
if (count) invalid("PNG: repeated IHDR");
|
|
102
102
|
width = view.getUint32(body); height = view.getUint32(body + 4); colour = bytes[body + 9];
|
|
103
103
|
const depths = {0: [1, 2, 4, 8, 16], 2: [8, 16], 3: [1, 2, 4, 8], 4: [8, 16], 6: [8, 16]};
|
|
104
104
|
if (!depths[colour]?.includes(bytes[body + 8]) || bytes[body + 10] !== 0 || bytes[body + 11] !== 0 || bytes[body + 12] > 1)
|
|
105
|
-
invalid("
|
|
105
|
+
invalid("PNG: IHDR");
|
|
106
106
|
} else if (type === 'PLTE') {
|
|
107
|
-
if (palette || !length || length > 768 || length % 3 || [0, 4].includes(colour)) invalid("
|
|
107
|
+
if (palette || !length || length > 768 || length % 3 || [0, 4].includes(colour)) invalid("PNG: palette");
|
|
108
108
|
palette = true;
|
|
109
109
|
} else if (type === 'eXIf') {
|
|
110
|
-
if (exif) invalid("
|
|
110
|
+
if (exif) invalid("Exif: one metadata block");
|
|
111
111
|
exif = true; orientation = tiffOrientation(bytes.subarray(body, end));
|
|
112
112
|
} else if (['acTL', 'fcTL', 'fdAT'].includes(type))
|
|
113
|
-
throw fail('JXL_UNSUPPORTED', "
|
|
114
|
-
else if (type[0] === type[0].toUpperCase()) invalid("
|
|
113
|
+
throw fail('JXL_UNSUPPORTED', "animation: server verification");
|
|
114
|
+
else if (type[0] === type[0].toUpperCase()) invalid("PNG: critical header chunk");
|
|
115
115
|
at = end + 4;
|
|
116
116
|
}
|
|
117
|
-
throw fail('JXL_LIMIT', "
|
|
117
|
+
throw fail('JXL_LIMIT', "header: too large; server verify");
|
|
118
118
|
}
|
|
119
119
|
|
|
120
120
|
// Only pre-scan JPEG Exif and pre-IDAT PNG eXIf can be observed in this prefix. Structural admission is deliberately
|
|
121
121
|
// not a proof about metadata after image data, pixel equality, fidelity, or JPEG reconstruction.
|
|
122
122
|
export function originalGeometry(bytes, {mimeType, maxPixels, maxHeaderBytes = SOURCE_HEADER_BYTES} = {}) {
|
|
123
123
|
if (!Number.isSafeInteger(maxHeaderBytes) || maxHeaderBytes < 8 || maxHeaderBytes > EXTENDED_SOURCE_HEADER_BYTES)
|
|
124
|
-
throw fail('JXL_OPTIONS', "
|
|
124
|
+
throw fail('JXL_OPTIONS', "header limit: bounded size");
|
|
125
125
|
if (!(bytes instanceof Uint8Array) || bytes.length < 8 || bytes.length > maxHeaderBytes)
|
|
126
|
-
throw fail('JXL_LIMIT', "
|
|
126
|
+
throw fail('JXL_LIMIT', "header: missing/large; server verify");
|
|
127
127
|
const info = bytes[0] === 255 && bytes[1] === 216 ? jpegGeometry(bytes)
|
|
128
128
|
: PNG.every((value, i) => bytes[i] === value) ? pngGeometry(bytes) : null;
|
|
129
|
-
if (!info || mimeType !== `image/${info.format}`) invalid("
|
|
129
|
+
if (!info || mimeType !== `image/${info.format}`) invalid("original: bytes/type mismatch");
|
|
130
130
|
dimensions(info.width, info.height, maxPixels);
|
|
131
131
|
return {...info, displayWidth: info.orientation >= 5 ? info.height : info.width,
|
|
132
132
|
displayHeight: info.orientation >= 5 ? info.width : info.height};
|
|
@@ -140,33 +140,33 @@ export function headerIncomplete(bytes, mimeType) {
|
|
|
140
140
|
export async function structuralDelivery(result, original, selected, {width, maxPixels} = {}) {
|
|
141
141
|
const site = settings(selected), bytes = result?.bytes;
|
|
142
142
|
if (!(bytes instanceof Uint8Array) || bytes.length < 2 || bytes.length > DELIVERY_BYTES)
|
|
143
|
-
throw fail('JXL_LIMIT', "
|
|
143
|
+
throw fail('JXL_LIMIT', "delivery: too large; server verify");
|
|
144
144
|
if (site.maxKilobytes && bytes.length > site.maxKilobytes * 1024)
|
|
145
|
-
throw fail('JXL_TARGET', "
|
|
145
|
+
throw fail('JXL_TARGET', "copy: size target exceeded");
|
|
146
146
|
const exact = result.fidelity === 'exact' || result.fidelity?.maxError === 0 || result.fidelity?.quality === 100;
|
|
147
147
|
// Match the shared ImageResult exact endpoints: a payload cannot describe its own preservation as lossy while
|
|
148
148
|
// promising exact pixels. This is metadata consistency, not server verification of the pixels.
|
|
149
149
|
if (exact && result.kept === 'lossy')
|
|
150
|
-
throw fail('JXL_INPUT', "
|
|
150
|
+
throw fail('JXL_INPUT', "lossy delivery: measured quality");
|
|
151
151
|
if (!exact && (site.exact || !Number.isFinite(result.fidelity?.quality) || result.fidelity.quality > 100 ||
|
|
152
152
|
result.fidelity.quality < (site.maxKilobytes ? 1 : site.quality)))
|
|
153
|
-
throw fail('JXL_TARGET', "
|
|
153
|
+
throw fail('JXL_TARGET', "copy: fidelity target missed");
|
|
154
154
|
if (width !== undefined && (!site.widths.includes(width) || width >= original.displayWidth))
|
|
155
|
-
throw fail('JXL_DIMENSIONS', "
|
|
155
|
+
throw fail('JXL_DIMENSIONS', "width: configured value");
|
|
156
156
|
const expectedWidth = width ?? original.displayWidth;
|
|
157
157
|
const expectedHeight = width === undefined ? original.displayHeight : Math.max(1, Math.round(width * original.displayHeight / original.displayWidth));
|
|
158
158
|
dimensions(expectedWidth, expectedHeight, maxPixels);
|
|
159
159
|
if (result?.format !== 'jxl' || result.meetsTarget !== true || result.width !== expectedWidth || result.height !== expectedHeight)
|
|
160
|
-
throw fail('JXL_DIMENSIONS', "
|
|
160
|
+
throw fail('JXL_DIMENSIONS', "delivery dimensions: current settings");
|
|
161
161
|
const info = await inspect(bytes, {details: ['layout'], maxInputBytes: DELIVERY_BYTES, maxPixels, maxBoxes: SEGMENTS});
|
|
162
162
|
const shownWidth = info.orientation >= 5 ? info.height : info.width, shownHeight = info.orientation >= 5 ? info.width : info.height;
|
|
163
163
|
if (info.animation || shownWidth !== expectedWidth || shownHeight !== expectedHeight)
|
|
164
|
-
throw fail('JXL_DIMENSIONS', "
|
|
164
|
+
throw fail('JXL_DIMENSIONS', "header dimensions: current settings");
|
|
165
165
|
if (result.kept === 'jpeg-bytes') {
|
|
166
166
|
if (width !== undefined || original.format !== 'jpeg' || result.fidelity !== 'exact' || !info.reconstruction)
|
|
167
|
-
throw fail('JXL_INPUT', "
|
|
167
|
+
throw fail('JXL_INPUT', "JPEG reconstruction: recompress()");
|
|
168
168
|
} else if (!['pixels', 'lossy'].includes(result.kept))
|
|
169
|
-
throw fail('JXL_INPUT', "
|
|
169
|
+
throw fail('JXL_INPUT', "delivery: pixel-encoding result");
|
|
170
170
|
// The browser may normalize orientation into pixels. Compare displayed geometry; literal tag equality would
|
|
171
171
|
// reject an equivalent normalized result. Pixel/orientation equivalence itself is the browser verifier's claim.
|
|
172
172
|
return {kind: 'structural', scope: 'delivery', browserVerification: 'informational',
|
|
@@ -19,7 +19,7 @@ const tasks = new Map();
|
|
|
19
19
|
function threads() {
|
|
20
20
|
const builtin = globalThis.process?.getBuiltinModule;
|
|
21
21
|
const module = typeof builtin === 'function' ? builtin('node:worker_threads') : null;
|
|
22
|
-
if (!module?.Worker) throw fail('JXL_PLATFORM', "
|
|
22
|
+
if (!module?.Worker) throw fail('JXL_PLATFORM', "workers: Node worker_threads");
|
|
23
23
|
return module;
|
|
24
24
|
}
|
|
25
25
|
|
|
@@ -28,10 +28,10 @@ async function readInput(input, store, signal) {
|
|
|
28
28
|
for (let at = 0; at < bytes.length; at += READ) {
|
|
29
29
|
signal?.throwIfAborted();
|
|
30
30
|
const length = Math.min(READ, bytes.length - at), part = await store.readSource(at, length);
|
|
31
|
-
if (!(part instanceof Uint8Array) || part.length !== length) throw fail('JXL_IO', "
|
|
31
|
+
if (!(part instanceof Uint8Array) || part.length !== length) throw fail('JXL_IO', "read: storage failure");
|
|
32
32
|
bytes.set(part, at);
|
|
33
33
|
}
|
|
34
|
-
if (await digest(bytes) !== input.sha256) throw fail('JXL_INPUT', "
|
|
34
|
+
if (await digest(bytes) !== input.sha256) throw fail('JXL_INPUT', "source: changed; reload record");
|
|
35
35
|
return bytes;
|
|
36
36
|
}
|
|
37
37
|
|
|
@@ -56,11 +56,11 @@ async function readCandidate(options, store, signal) {
|
|
|
56
56
|
const refs = options.parts;
|
|
57
57
|
const parts = store.readMany ? await store.readMany(refs) : await Promise.all(refs.map(ref => store.read(ref)));
|
|
58
58
|
signal?.throwIfAborted();
|
|
59
|
-
if (!Array.isArray(parts) || parts.length !== refs.length) throw fail('JXL_IO', "
|
|
59
|
+
if (!Array.isArray(parts) || parts.length !== refs.length) throw fail('JXL_IO', "candidate part: restore missing");
|
|
60
60
|
let length = 0;
|
|
61
61
|
for (const [i, part] of parts.entries()) {
|
|
62
|
-
if (!(part instanceof Uint8Array) || part.length !== refs[i].length) throw fail('JXL_IO', "
|
|
63
|
-
if (await digest(part) !== refs[i].hash) throw fail('JXL_INPUT', "
|
|
62
|
+
if (!(part instanceof Uint8Array) || part.length !== refs[i].length) throw fail('JXL_IO', "candidate part: restore missing/truncated");
|
|
63
|
+
if (await digest(part) !== refs[i].hash) throw fail('JXL_INPUT', "candidate part: reverify original");
|
|
64
64
|
length += part.length;
|
|
65
65
|
}
|
|
66
66
|
const bytes = new Uint8Array(length);
|
|
@@ -82,7 +82,7 @@ function verificationReceipt(checkpoint, input) {
|
|
|
82
82
|
JSON.stringify(receipt.fidelity) !== JSON.stringify(result.fidelity) ||
|
|
83
83
|
JSON.stringify(receipt.transform) !== JSON.stringify(result.transform) ||
|
|
84
84
|
JSON.stringify(receipt.readAs) !== JSON.stringify(result.readAs))
|
|
85
|
-
throw fail('JXL_INPUT', "
|
|
85
|
+
throw fail('JXL_INPUT', "verification: reverify original/candidate");
|
|
86
86
|
return receipt;
|
|
87
87
|
}
|
|
88
88
|
|
|
@@ -192,8 +192,8 @@ export function createThreadDriver(operations, base = resumable) {
|
|
|
192
192
|
const {owner, ...begin} = context;
|
|
193
193
|
if (!name || name !== 'verify' && !context.verify || name === 'verify' && context.input?.kind !== 'file') return base.start(begin);
|
|
194
194
|
const {input, options = {}} = context;
|
|
195
|
-
if (!/^[a-f0-9]{32}$/.test(owner ?? '')) throw fail('JXL_OPTIONS', "
|
|
196
|
-
if (!['file', 'pixels', undefined].includes(input?.kind)) throw fail('JXL_INPUT', "
|
|
195
|
+
if (!/^[a-f0-9]{32}$/.test(owner ?? '')) throw fail('JXL_OPTIONS', "job ID: 32 lowercase hex");
|
|
196
|
+
if (!['file', 'pixels', undefined].includes(input?.kind)) throw fail('JXL_INPUT', "source: stored file or pixels");
|
|
197
197
|
// Reuse the public stored-verification validator, without inspecting its checkpoint internals.
|
|
198
198
|
if (name === 'verify') await base.start(begin);
|
|
199
199
|
const key = await threadKey(owner, name, input, options);
|
|
@@ -206,7 +206,7 @@ export function createThreadDriver(operations, base = resumable) {
|
|
|
206
206
|
const remaining = () => Math.max(0, deadline - performance.now());
|
|
207
207
|
if (context.owner !== checkpoint.owner || nameOf(context.operation) !== checkpoint.operation ||
|
|
208
208
|
await threadKey(context.owner, checkpoint.operation, input, checkpoint.options) !== checkpoint.key)
|
|
209
|
-
throw fail('JXL_INPUT', "
|
|
209
|
+
throw fail('JXL_INPUT', "checkpoint: reload matching job");
|
|
210
210
|
if (checkpoint.status === 'done') return {checkpoint, released: [], done: true};
|
|
211
211
|
let task = tasks.get(checkpoint.key);
|
|
212
212
|
if (!task) {
|
|
@@ -239,23 +239,23 @@ export function createThreadDriver(operations, base = resumable) {
|
|
|
239
239
|
},
|
|
240
240
|
async finish(checkpoint, context) {
|
|
241
241
|
if (!ours(checkpoint)) return base.finish(checkpoint, context);
|
|
242
|
-
if (checkpoint.status !== 'done') throw fail('JXL_INPUT', "
|
|
242
|
+
if (checkpoint.status !== 'done') throw fail('JXL_INPUT', "job: advance until done");
|
|
243
243
|
if (context.owner !== checkpoint.owner || nameOf(context.operation) !== checkpoint.operation ||
|
|
244
244
|
await threadKey(context.owner, checkpoint.operation, context.input, checkpoint.options) !== checkpoint.key)
|
|
245
|
-
throw fail('JXL_INPUT', "
|
|
245
|
+
throw fail('JXL_INPUT', "checkpoint: reload matching job");
|
|
246
246
|
if (checkpoint.operation === 'verify') return verificationReceipt(checkpoint, context.input);
|
|
247
247
|
const parts = checkpoint.parts.length ? await context.store.readMany(checkpoint.parts) : [];
|
|
248
248
|
const length = checkpoint.parts.reduce((sum, ref) => sum + ref.length, 0), bytes = new Uint8Array(length);
|
|
249
249
|
let at = 0;
|
|
250
250
|
// Every part is checked against its name, and the whole file against the receipt's output digest.
|
|
251
|
-
if (!Array.isArray(parts) || parts.length !== checkpoint.parts.length) throw fail('JXL_IO', "
|
|
251
|
+
if (!Array.isArray(parts) || parts.length !== checkpoint.parts.length) throw fail('JXL_IO', "finished part: restore missing");
|
|
252
252
|
for (const [index, part] of parts.entries()) {
|
|
253
253
|
if (!(part instanceof Uint8Array) || part.length !== checkpoint.parts[index].length || await digest(part) !== checkpoint.parts[index].hash)
|
|
254
|
-
throw fail('JXL_INPUT', "
|
|
254
|
+
throw fail('JXL_INPUT', "finished part: reverify original");
|
|
255
255
|
bytes.set(part, at); at += part.length;
|
|
256
256
|
}
|
|
257
257
|
if ('sha256:' + await digest(bytes) !== checkpoint.record?.verification?.outputDigest)
|
|
258
|
-
throw fail('JXL_INPUT', "
|
|
258
|
+
throw fail('JXL_INPUT', "file receipt: reverify original");
|
|
259
259
|
return {...checkpoint.record, bytes};
|
|
260
260
|
},
|
|
261
261
|
};
|
|
@@ -12,7 +12,7 @@ const {name, input, options, bytes, candidate} = workerData;
|
|
|
12
12
|
try {
|
|
13
13
|
configureDecoder(decode, restore);
|
|
14
14
|
const operation = {encode, fit, recompress}[name];
|
|
15
|
-
if (!operation && name !== 'verify') throw Object.assign(new Error("
|
|
15
|
+
if (!operation && name !== 'verify') throw Object.assign(new Error("operation: encode, fit, recompress, verify"), {code: 'JXL_OPTIONS'});
|
|
16
16
|
const png = bytes[0] === 0x89 && bytes[1] === 0x50;
|
|
17
17
|
const jpeg = bytes[0] === 255 && bytes[1] === 216;
|
|
18
18
|
const maxPixels = options?.maxPixels ?? input.maxPixels;
|
|
@@ -36,9 +36,9 @@ try {
|
|
|
36
36
|
// Classify the authenticated source bytes; the public readers still own every size and format check.
|
|
37
37
|
const photo = bytes[0] === 255 && bytes[1] === 216 ||
|
|
38
38
|
[137, 80, 78, 71, 13, 10, 26, 10].every((value, i) => bytes[i] === value);
|
|
39
|
-
if (!photo) throw Object.assign(new Error("
|
|
39
|
+
if (!photo) throw Object.assign(new Error("original: JPEG or PNG"), {code: 'JXL_UNSUPPORTED'});
|
|
40
40
|
if (options.result.format !== 'jxl' || header(candidate).animation)
|
|
41
|
-
throw Object.assign(new Error("
|
|
41
|
+
throw Object.assign(new Error("candidate: still JPEG XL"), {code: 'JXL_UNSUPPORTED'});
|
|
42
42
|
const receipt = await verify(source(), {...options.result, bytes: candidate},
|
|
43
43
|
{maxPixels: options.maxPixels, onProgress: report(0, 1)});
|
|
44
44
|
parentPort.postMessage({receipt});
|
|
@@ -11,7 +11,7 @@ function json(value) {
|
|
|
11
11
|
throw new TypeError();
|
|
12
12
|
return record(item) ? Object.fromEntries(Object.keys(item).sort().map(key => [key, item[key]])) : item;
|
|
13
13
|
});
|
|
14
|
-
} catch { throw fail('JXL_INPUT', "
|
|
14
|
+
} catch { throw fail('JXL_INPUT', "work command: immutable JSON"); }
|
|
15
15
|
}
|
|
16
16
|
|
|
17
17
|
// One recurring task per site, backed by immutable work rows. An idle task is retained: canceling it after an
|
|
@@ -20,17 +20,17 @@ export function createWorkQueue(ctx, {scope, call = action => action()} = {}) {
|
|
|
20
20
|
const table = ctx?.storage?.jxlWork;
|
|
21
21
|
if (typeof scope !== 'string' || typeof call !== 'function' || typeof ctx?.cron?.schedule !== 'function' || typeof ctx?.cron?.list !== 'function' ||
|
|
22
22
|
['get', 'compareAndSet', 'delete', 'query'].some(name => typeof table?.[name] !== 'function'))
|
|
23
|
-
throw fail('JXL_OPTIONS', "
|
|
23
|
+
throw fail('JXL_OPTIONS', "work: storage and scheduler");
|
|
24
24
|
function keyOf(kind, id) {
|
|
25
25
|
if (!['image', 'library', 'originals'].includes(kind) || typeof id !== 'string' || !ID.test(id))
|
|
26
|
-
throw fail('JXL_INPUT', "
|
|
26
|
+
throw fail('JXL_INPUT', "work ID: image, library, originals");
|
|
27
27
|
return `${scope}:${kind}:${id}`;
|
|
28
28
|
}
|
|
29
29
|
function rowOf(kind, id, command) {
|
|
30
30
|
keyOf(kind, id);
|
|
31
31
|
if (kind === 'image' && (!record(command) || command.id !== id || command.scope !== scope) ||
|
|
32
32
|
kind !== 'image' && command !== undefined)
|
|
33
|
-
throw fail('JXL_INPUT', "
|
|
33
|
+
throw fail('JXL_INPUT', "work command: reload record");
|
|
34
34
|
return {scope, kind, id, ...(command === undefined ? {} : {command})};
|
|
35
35
|
}
|
|
36
36
|
return {
|
|
@@ -39,31 +39,31 @@ export function createWorkQueue(ctx, {scope, call = action => action()} = {}) {
|
|
|
39
39
|
// Scheduling an existing EmDash task resets its next wake. Keep the persistent task so busy uploads do not
|
|
40
40
|
// continually postpone it. Establish it before the registry row; concurrent first admissions may both upsert.
|
|
41
41
|
const tasks = await call(() => ctx.cron.list());
|
|
42
|
-
if (!Array.isArray(tasks)) throw fail('JXL_IO', "
|
|
42
|
+
if (!Array.isArray(tasks)) throw fail('JXL_IO', "scheduled tasks: storage");
|
|
43
43
|
if (!tasks.some(task => task?.name === 'jxl-work'))
|
|
44
44
|
await call(() => ctx.cron.schedule('jxl-work', {schedule: '* * * * * *', data: {kind: 'images'}}));
|
|
45
45
|
const saved = await call(() => table.compareAndSet(key, null, value));
|
|
46
46
|
if (saved?.applied === true) return;
|
|
47
|
-
if (saved?.applied !== false) throw fail('JXL_IO', "
|
|
47
|
+
if (saved?.applied !== false) throw fail('JXL_IO', "work registry: unconfirmed");
|
|
48
48
|
const current = await call(() => table.get(key));
|
|
49
|
-
if (current === null) throw fail('JXL_IO', "
|
|
50
|
-
if (json(current) !== encoded) throw fail('JXL_INPUT', "
|
|
49
|
+
if (current === null) throw fail('JXL_IO', "work registry: changed; reload");
|
|
50
|
+
if (json(current) !== encoded) throw fail('JXL_INPUT', "work command: reload record");
|
|
51
51
|
},
|
|
52
52
|
remove(kind, id) {
|
|
53
53
|
const key = keyOf(kind, id);
|
|
54
54
|
return call(() => table.delete(key));
|
|
55
55
|
},
|
|
56
56
|
async list(cursor) {
|
|
57
|
-
if (cursor !== undefined && typeof cursor !== 'string') throw fail('JXL_INPUT', "
|
|
57
|
+
if (cursor !== undefined && typeof cursor !== 'string') throw fail('JXL_INPUT', "cursor: preceding page");
|
|
58
58
|
// EmDash's default query order is created_at ASC, id ASC and its cursor survives a removed anchor row.
|
|
59
59
|
const page = await call(() => table.query({where: {scope}, limit: 16, ...(cursor === undefined ? {} : {cursor})}));
|
|
60
60
|
if (!record(page) || !Array.isArray(page.items) || page.items.length > 16 || typeof page.hasMore !== 'boolean' ||
|
|
61
61
|
page.cursor !== undefined && typeof page.cursor !== 'string' || page.hasMore && !page.cursor)
|
|
62
|
-
throw fail('JXL_IO', "
|
|
62
|
+
throw fail('JXL_IO', "work page: storage");
|
|
63
63
|
for (const row of page.items) {
|
|
64
64
|
if (!record(row?.data) || row.data.scope !== scope || row.id !== keyOf(row.data.kind, row.data.id) ||
|
|
65
65
|
json(row.data) !== json(rowOf(row.data.kind, row.data.id, row.data.command)))
|
|
66
|
-
throw fail('JXL_INPUT', "
|
|
66
|
+
throw fail('JXL_INPUT', "work command: reload record");
|
|
67
67
|
}
|
|
68
68
|
return page;
|
|
69
69
|
},
|
|
@@ -14,18 +14,18 @@ export async function prepareAssets({example = here, packageDir = process.env.JX
|
|
|
14
14
|
for (const name of modules) {
|
|
15
15
|
const path = `dist/${name}.mjs`;
|
|
16
16
|
if (manifest.exports?.[`./${name}`]?.import !== `./${path}`)
|
|
17
|
-
throw new Error(
|
|
17
|
+
throw Object.assign(new Error(`${pkg} is not a built package with ./${name}.`), {code: 'JXL_PACKAGE'});
|
|
18
18
|
await copyFile(join(pkg, path), join(out, `${name}.mjs`));
|
|
19
19
|
}
|
|
20
20
|
for (const name of browserFiles) {
|
|
21
21
|
if (manifest.exports?.[`./${name.replace('.browser', '')}`]?.browser !== `./dist/${name}.mjs`)
|
|
22
|
-
throw new Error(
|
|
22
|
+
throw Object.assign(new Error(`${pkg} has no browser file for ./${name.replace('.browser', '')}.`), {code: 'JXL_PACKAGE'});
|
|
23
23
|
await copyFile(join(pkg, `dist/${name}.mjs`), join(out, `${name}.mjs`));
|
|
24
24
|
}
|
|
25
25
|
await copyFile(join(pkg, 'LICENSE'), join(out, 'LICENSE'));
|
|
26
26
|
// The tests read an animation back with the package's decoder in the page, and its .wasm names what a host says when it
|
|
27
27
|
// refuses the decoder; the app carries neither.
|
|
28
|
-
if (manifest.exports?.['./decode']?.import !== './dist/decode.mjs') throw new Error(
|
|
28
|
+
if (manifest.exports?.['./decode']?.import !== './dist/decode.mjs') throw Object.assign(new Error(`${pkg} has no ./decode.`), {code: 'JXL_PACKAGE'});
|
|
29
29
|
for (const name of ['decode.mjs', 'decode.wasm']) await copyFile(join(pkg, 'dist', name), join(example, 'example/assets/fixtures', name));
|
|
30
30
|
return {package: {name: manifest.name, version: manifest.version}};
|
|
31
31
|
}
|
|
@@ -16,17 +16,17 @@ export async function prepareAssets({example = here, packageDir = process.env.JX
|
|
|
16
16
|
for (const name of modules) {
|
|
17
17
|
const path = `dist/${name}.mjs`;
|
|
18
18
|
if (manifest.exports?.[`./${name}`]?.import !== `./${path}`)
|
|
19
|
-
throw new Error(
|
|
19
|
+
throw Object.assign(new Error(`${pkg} is not a built package with ./${name}.`), {code: 'JXL_PACKAGE'});
|
|
20
20
|
await copyFile(join(pkg, path), join(out, `${name}.mjs`));
|
|
21
21
|
}
|
|
22
22
|
for (const name of browserFiles) {
|
|
23
23
|
if (manifest.exports?.[`./${name.replace('.browser', '')}`]?.browser !== `./dist/${name}.mjs`)
|
|
24
|
-
throw new Error(
|
|
24
|
+
throw Object.assign(new Error(`${pkg} has no browser file for ./${name.replace('.browser', '')}.`), {code: 'JXL_PACKAGE'});
|
|
25
25
|
await copyFile(join(pkg, `dist/${name}.mjs`), join(out, `${name}.mjs`));
|
|
26
26
|
}
|
|
27
27
|
await copyFile(join(pkg, 'LICENSE'), join(out, 'LICENSE'));
|
|
28
28
|
// The tests read an animation back with the package's decoder in the page; the app does not carry it.
|
|
29
|
-
if (manifest.exports?.['./decode']?.import !== './dist/decode.mjs') throw new Error(
|
|
29
|
+
if (manifest.exports?.['./decode']?.import !== './dist/decode.mjs') throw Object.assign(new Error(`${pkg} has no ./decode.`), {code: 'JXL_PACKAGE'});
|
|
30
30
|
await copyFile(join(pkg, 'dist/decode.mjs'), join(example, 'Tests/RapierJXLTests/Fixtures/decode.mjs'));
|
|
31
31
|
const files = [];
|
|
32
32
|
for (const path of ['encoder.html', 'page.mjs', 'encoder.mjs', 'headers.json', ...[...modules, ...browserFiles].map(n => `jpegxl/${n}.mjs`), 'jpegxl/LICENSE']) {
|
package/examples/page-rects.js
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
export function measure(element, options = {}) {
|
|
8
8
|
admitElement(element, options);
|
|
9
9
|
if (typeof document === 'undefined' || typeof document.createRange !== 'function' || typeof getComputedStyle !== 'function')
|
|
10
|
-
throw refuse('JXL_PLATFORM', '
|
|
10
|
+
throw refuse('JXL_PLATFORM', 'document: browser page');
|
|
11
11
|
const { edges = false, keep } = options;
|
|
12
12
|
const clip = clipper(element, keep);
|
|
13
13
|
return { box: elementBox(element), text: textParts(element, clip), photos: photoParts(element, clip), textComplete: true, ...(edges && { edges: edgeParts(element, clip) }) };
|
|
@@ -15,20 +15,20 @@ export function measure(element, options = {}) {
|
|
|
15
15
|
|
|
16
16
|
// `area`: the part of the element the canvas shows, in CSS pixels from its border box's corner (default all of it).
|
|
17
17
|
export function pageRects(page, canvas, options = {}) {
|
|
18
|
-
if (!object(page)) throw refuse('JXL_INPUT', "
|
|
18
|
+
if (!object(page)) throw refuse('JXL_INPUT', "page: Element or measure() result");
|
|
19
19
|
const measuredBox = page.box;
|
|
20
|
-
if (measuredBox === undefined && typeof page.getBoundingClientRect !== 'function') throw refuse('JXL_INPUT', "
|
|
21
|
-
if (!object(canvas)) throw refuse('JXL_INPUT', "
|
|
20
|
+
if (measuredBox === undefined && typeof page.getBoundingClientRect !== 'function') throw refuse('JXL_INPUT', "page: Element or measure() result");
|
|
21
|
+
if (!object(canvas)) throw refuse('JXL_INPUT', "canvas: pixel width and height");
|
|
22
22
|
const {width: cw, height: ch} = canvas;
|
|
23
|
-
if (![cw, ch].every(n => Number.isSafeInteger(n) && n > 0)) throw refuse('JXL_DIMENSIONS', "
|
|
23
|
+
if (![cw, ch].every(n => Number.isSafeInteger(n) && n > 0)) throw refuse('JXL_DIMENSIONS', "canvas: positive integer pixels");
|
|
24
24
|
admitOptions(options, 'pageRects', ['area', 'edges']);
|
|
25
25
|
const { area = {}, edges = false } = options;
|
|
26
26
|
if (!object(area) || Object.keys(area).some(key => !['x', 'y', 'width', 'height'].includes(key) || !Number.isFinite(area[key]) || key.length > 1 && area[key] < 0))
|
|
27
|
-
throw refuse('JXL_OPTIONS', "
|
|
27
|
+
throw refuse('JXL_OPTIONS', "area: finite bounds, nonnegative size");
|
|
28
28
|
const shot = measuredBox === undefined ? measure(page, { edges }) : page, box = measuredBox ?? shot.box;
|
|
29
29
|
if (!object(box) || ![box.left, box.top, box.width, box.height].every(Number.isFinite) || box.width < 0 || box.height < 0 ||
|
|
30
30
|
!Array.isArray(shot.photos) || !Array.isArray(shot.text) || shot.edges !== undefined && !Array.isArray(shot.edges))
|
|
31
|
-
throw refuse('JXL_INPUT', "
|
|
31
|
+
throw refuse('JXL_INPUT', "measurement: measure() result");
|
|
32
32
|
const left = box.left + (area.x ?? 0), top = box.top + (area.y ?? 0);
|
|
33
33
|
const width = area.width ?? box.width, height = area.height ?? box.height;
|
|
34
34
|
// Nothing of the element is shown (a 0 x 0 box or area): no rectangle, where dividing by it made a whole-canvas one.
|
|
@@ -36,7 +36,7 @@ export function pageRects(page, canvas, options = {}) {
|
|
|
36
36
|
const sx = cw / width, sy = ch / height;
|
|
37
37
|
const place = (r, grow) => {
|
|
38
38
|
if (!object(r) || ![r.left, r.top, r.right, r.bottom, grow].every(Number.isFinite) || grow < 0)
|
|
39
|
-
throw refuse('JXL_INPUT', "
|
|
39
|
+
throw refuse('JXL_INPUT', "rectangle: finite bounds, nonnegative margin");
|
|
40
40
|
const gx = Math.ceil(grow * sx), gy = Math.ceil(grow * sy);
|
|
41
41
|
const x = Math.max(0, Math.floor((r.left - left) * sx) - gx), y = Math.max(0, Math.floor((r.top - top) * sy) - gy);
|
|
42
42
|
const right = Math.min(cw, Math.ceil((r.right - left) * sx) + gx), bottom = Math.min(ch, Math.ceil((r.bottom - top) * sy) + gy);
|
|
@@ -50,7 +50,7 @@ export function pageRects(page, canvas, options = {}) {
|
|
|
50
50
|
// phone card larger than WebP).
|
|
51
51
|
const exactRects = [];
|
|
52
52
|
for (const part of shot.text) {
|
|
53
|
-
if (!object(part)) throw refuse('JXL_INPUT', "
|
|
53
|
+
if (!object(part)) throw refuse('JXL_INPUT', "text rectangle: measure() result");
|
|
54
54
|
const {r, grow, solidText} = part, b = place(r, grow);
|
|
55
55
|
if (b) exactRects.push(solidText ? { ...b, solidText } : b);
|
|
56
56
|
}
|
|
@@ -63,14 +63,14 @@ export function pageRects(page, canvas, options = {}) {
|
|
|
63
63
|
const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
64
64
|
const refuse = (code, message) => Object.assign(new TypeError(message), { code });
|
|
65
65
|
function admitElement(element, options) {
|
|
66
|
-
if (!object(element) || typeof element.getBoundingClientRect !== 'function') throw refuse('JXL_INPUT', "
|
|
66
|
+
if (!object(element) || typeof element.getBoundingClientRect !== 'function') throw refuse('JXL_INPUT', "element: DOM Element");
|
|
67
67
|
admitOptions(options, 'measure', ['edges', 'keep']);
|
|
68
|
-
if (options.keep != null && typeof options.keep.has !== 'function') throw refuse('JXL_OPTIONS', "
|
|
68
|
+
if (options.keep != null && typeof options.keep.has !== 'function') throw refuse('JXL_OPTIONS', "keep: Set");
|
|
69
69
|
}
|
|
70
70
|
function admitOptions(options, name, keys) {
|
|
71
|
-
if (!object(options)) throw refuse('JXL_OPTIONS',
|
|
72
|
-
for (const key of Object.keys(options)) if (!keys.includes(key)) throw refuse('JXL_OPTIONS', `
|
|
73
|
-
if (options.edges !== undefined && typeof options.edges !== 'boolean') throw refuse('JXL_OPTIONS', "
|
|
71
|
+
if (!object(options)) throw refuse('JXL_OPTIONS', `${name}: {${keys.join(', ')}}`);
|
|
72
|
+
for (const key of Object.keys(options)) if (!keys.includes(key)) throw refuse('JXL_OPTIONS', `unknown ${name} option: ${key}`);
|
|
73
|
+
if (options.edges !== undefined && typeof options.edges !== 'boolean') throw refuse('JXL_OPTIONS', "edges: boolean");
|
|
74
74
|
}
|
|
75
75
|
function elementBox(element) {
|
|
76
76
|
const r = element.getBoundingClientRect();
|