@daasboard/embed 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ import type { DocumentAdapter } from "@daasboard/doc";
2
+ import type { Scene } from "@daasboard/render-core";
3
+ export declare function createBoardDocument(source: DocumentAdapter, readOnly?: boolean): {
4
+ doc: DocumentAdapter;
5
+ scene: Scene;
6
+ dispose(): void;
7
+ };
@@ -0,0 +1,86 @@
1
+ export function createBoardDocument(source, readOnly = false) {
2
+ const scene = { objects: new Map(), order: [...source.order()] };
3
+ for (const id of scene.order) {
4
+ const object = source.get(id);
5
+ if (object)
6
+ scene.objects.set(id, object);
7
+ }
8
+ const live = new Set(scene.objects.keys());
9
+ const listeners = new Set();
10
+ let disposed = false;
11
+ const writable = () => !readOnly && !disposed;
12
+ const unsubscribe = source.subscribe((change, meta) => {
13
+ if (disposed)
14
+ return;
15
+ const next = { added: [], updated: [], removed: [] };
16
+ if (change.reordered !== undefined)
17
+ next.reordered = change.reordered;
18
+ for (const id of change.removed)
19
+ if (live.delete(id))
20
+ next.removed.push(id);
21
+ for (const object of [...change.added, ...change.updated]) {
22
+ const current = source.get(object.id);
23
+ if (!current) {
24
+ if (live.delete(object.id))
25
+ next.removed.push(object.id);
26
+ }
27
+ else if (live.has(object.id))
28
+ next.updated.push(current);
29
+ else {
30
+ live.add(object.id);
31
+ next.added.push(current);
32
+ }
33
+ }
34
+ if (change.order)
35
+ next.order = change.order;
36
+ else if (next.added.length || next.removed.length || next.reordered)
37
+ next.order = source.order();
38
+ let firstError;
39
+ let threw = false;
40
+ for (const listener of listeners) {
41
+ try {
42
+ listener(next, meta);
43
+ }
44
+ catch (error) {
45
+ if (!threw)
46
+ firstError = error;
47
+ threw = true;
48
+ }
49
+ }
50
+ if (threw)
51
+ throw firstError;
52
+ });
53
+ const doc = {
54
+ get: (id) => source.get(id),
55
+ order: () => source.order(),
56
+ transact(label, fn) {
57
+ if (writable())
58
+ source.transact(label, fn);
59
+ },
60
+ endTyping() {
61
+ if (writable())
62
+ source.endTyping();
63
+ },
64
+ undo: () => writable() && source.undo(),
65
+ redo: () => writable() && source.redo(),
66
+ canUndo: () => writable() && source.canUndo(),
67
+ canRedo: () => writable() && source.canRedo(),
68
+ subscribe(listener) {
69
+ if (disposed)
70
+ return () => { };
71
+ listeners.add(listener);
72
+ return () => { listeners.delete(listener); };
73
+ },
74
+ };
75
+ return {
76
+ doc,
77
+ scene,
78
+ dispose() {
79
+ if (disposed)
80
+ return;
81
+ disposed = true;
82
+ unsubscribe();
83
+ listeners.clear();
84
+ },
85
+ };
86
+ }
@@ -0,0 +1,53 @@
1
+ import { type ClipboardAssetShares } from "../assets/clipboardAssets.js";
2
+ import type { DocumentAdapter } from "@daasboard/doc";
3
+ import { type EmbedRef, type ImageRef, type SceneObject } from "@daasboard/render-core";
4
+ import { preprocessImage, type PreparedImage } from "./preprocess.js";
5
+ import type { BoardImageOptions, ImagePlacement, ImageErrorReason, OnImageError, Rung, TouchOptions, TouchResult } from "./types.js";
6
+ export declare const emptyTouchResult: () => TouchResult;
7
+ export declare function imageRefs(object: SceneObject): ImageRef[];
8
+ export declare class BoardImages {
9
+ private readonly o;
10
+ private disposed;
11
+ private readonly operations;
12
+ private readonly unsubscribe;
13
+ constructor(o: {
14
+ document: DocumentAdapter;
15
+ images?: BoardImageOptions;
16
+ canWrite(): boolean;
17
+ commit(refs: readonly ImageRef[], placement: ImagePlacement): readonly string[];
18
+ onError?: OnImageError;
19
+ onScaled?: (facts: {
20
+ originalWidth: number;
21
+ originalHeight: number;
22
+ width: number;
23
+ height: number;
24
+ }) => void;
25
+ onProgress?: (sent: number, total: number) => void;
26
+ onPrepared?: (image: PreparedImage, placement: ImagePlacement) => void;
27
+ onReferencePending?: (objects: readonly SceneObject[]) => (() => void) | void;
28
+ preprocess?: typeof preprocessImage;
29
+ });
30
+ report(hash: string, rung: Rung, reason: ImageErrorReason): void;
31
+ private reportResult;
32
+ touch(hashes: readonly string[], options?: TouchOptions, notify?: boolean): Promise<TouchResult>;
33
+ flush(): Promise<TouchResult>;
34
+ register(hashes: readonly string[], options?: {
35
+ signal?: AbortSignal;
36
+ }): Promise<TouchResult>;
37
+ withReferences(objects: readonly SceneObject[], commit: (objects: readonly SceneObject[]) => string[], options?: {
38
+ valid?(): boolean;
39
+ assets?: ClipboardAssetShares;
40
+ }): string[] | Promise<string[]>;
41
+ lookupLink(source: EmbedRef | (() => Promise<EmbedRef>)): Promise<EmbedRef>;
42
+ private withHashes;
43
+ get(hash: string, rung: Rung, options?: {
44
+ signal?: AbortSignal;
45
+ }): Promise<import("./types.js").ImageSource | null>;
46
+ refreshUrl(hash: string, rung: Rung, options: {
47
+ url: string;
48
+ signal?: AbortSignal;
49
+ }): Promise<import("./types.js").ImageSource | null>;
50
+ insert(files: readonly Blob[], placement: ImagePlacement, commit?: (refs: readonly ImageRef[], placement: ImagePlacement) => readonly string[]): Promise<readonly string[]>;
51
+ cancel(): void;
52
+ dispose(): void;
53
+ }
@@ -0,0 +1,241 @@
1
+ import { importClipboardAssets } from "../assets/clipboardAssets.js";
2
+ import { hashAsset, sanitizeImageRef } from "@daasboard/render-core";
3
+ import { preprocessImage } from "./preprocess.js";
4
+ export const emptyTouchResult = () => ({ stored: new Set(), missing: new Set(), denied: new Set(), pending: new Set() });
5
+ export function imageRefs(object) {
6
+ return [object.image, object.embed?.icon, object.embed?.preview].filter((ref) => !!ref);
7
+ }
8
+ function withoutDeniedEmbedRefs(embed, denied) {
9
+ const { icon, preview, ...rest } = embed;
10
+ return { ...rest, ...(icon && !denied.has(icon.hash) ? { icon } : {}),
11
+ ...(preview && !denied.has(preview.hash) ? { preview } : {}) };
12
+ }
13
+ function waitFor(promise, signal) {
14
+ if (!signal)
15
+ return promise;
16
+ return new Promise((resolve, reject) => {
17
+ const cleanup = () => signal.removeEventListener("abort", abort);
18
+ const abort = () => { cleanup(); reject(signal.reason); };
19
+ signal.addEventListener("abort", abort, { once: true });
20
+ promise.then((value) => { cleanup(); resolve(value); }, (error) => { cleanup(); reject(error); });
21
+ if (signal.aborted)
22
+ abort();
23
+ });
24
+ }
25
+ export class BoardImages {
26
+ o;
27
+ disposed = false;
28
+ operations = new Set();
29
+ unsubscribe;
30
+ constructor(o) {
31
+ this.o = o;
32
+ if (o.images?.store.touch && !o.images.room)
33
+ throw new Error("createBoard: images.room is required for a store with touch");
34
+ this.unsubscribe = o.document.subscribe((cs, meta) => {
35
+ if (meta.origin !== "undo" && meta.origin !== "redo" && !(meta.origin === "local" && meta.label === "Duplicate"))
36
+ return;
37
+ const hashes = [...new Set([...cs.added, ...cs.updated].flatMap((object) => imageRefs(object).map((ref) => ref.hash)))];
38
+ if (hashes.length)
39
+ void this.touch(hashes);
40
+ });
41
+ }
42
+ report(hash, rung, reason) {
43
+ if (!this.disposed)
44
+ this.o.onError?.(hash, rung, reason);
45
+ }
46
+ reportResult(result) {
47
+ for (const hash of result.missing)
48
+ this.report(hash, 256, "missing");
49
+ for (const hash of result.denied)
50
+ this.report(hash, 256, "denied");
51
+ return result;
52
+ }
53
+ async touch(hashes, options = {}, notify = true) {
54
+ const { store, room } = this.o.images ?? {};
55
+ if (this.disposed && options.until === "answered")
56
+ throw new DOMException("Board disposed", "AbortError");
57
+ if (this.disposed || !store?.touch || !room)
58
+ return emptyTouchResult();
59
+ try {
60
+ const result = await waitFor(store.touch(room, hashes, options), options.signal);
61
+ if (options.until === "answered" && (result.pending.size || hashes.some((hash) => !result.stored.has(hash) && !result.missing.has(hash) && !result.denied.has(hash)))) {
62
+ throw new Error("ImageStore.touch(until: answered) returned an unanswered hash");
63
+ }
64
+ return notify ? this.reportResult(result) : result;
65
+ }
66
+ catch (error) {
67
+ if (options.until === "answered" || options.signal?.aborted)
68
+ throw error;
69
+ return { ...emptyTouchResult(), pending: new Set(hashes) };
70
+ }
71
+ }
72
+ async flush() {
73
+ const { store, room } = this.o.images ?? {};
74
+ if (this.disposed || !store?.flush || !room)
75
+ return emptyTouchResult();
76
+ try {
77
+ return this.reportResult(await store.flush(room));
78
+ }
79
+ catch {
80
+ return { ...emptyTouchResult(), pending: new Set(store.pending?.().filter((p) => p.room === room).map((p) => p.hash)) };
81
+ }
82
+ }
83
+ register(hashes, options = {}) {
84
+ return this.touch(hashes, { ...options, until: "answered" });
85
+ }
86
+ withReferences(objects, commit, options = {}) {
87
+ const hashes = [...new Set(objects.flatMap((object) => imageRefs(object).map((ref) => ref.hash)))];
88
+ return this.withHashes(hashes, (denied) => commit(objects.flatMap((object) => {
89
+ if (object.image && denied.has(object.image.hash)) {
90
+ if (object.kind === "image")
91
+ return [];
92
+ const { image: _image, ...rest } = object;
93
+ object = rest;
94
+ }
95
+ return [{ ...object, ...(object.embed ? { embed: withoutDeniedEmbedRefs(object.embed, denied) } : {}) }];
96
+ })), () => [], options.valid, objects, options.assets && this.o.images?.store.import ? (result, signal) => importClipboardAssets(result.missing, options.assets, this.o.images.store, this.o.images.room, signal, (hash, rung, reason) => this.report(hash, rung, reason)) : undefined);
97
+ }
98
+ async lookupLink(source) {
99
+ const cancelled = () => { throw new DOMException("Image reference operation cancelled", "AbortError"); };
100
+ if (this.disposed || !this.o.canWrite())
101
+ return cancelled();
102
+ const operation = new AbortController();
103
+ this.operations.add(operation);
104
+ const valid = () => !this.disposed && !operation.signal.aborted && this.o.canWrite();
105
+ try {
106
+ const ref = typeof source === "function" ? await waitFor(source(), operation.signal) : source;
107
+ if (!valid())
108
+ return cancelled();
109
+ const hashes = [...new Set([ref.icon?.hash, ref.preview?.hash].filter((hash) => !!hash))];
110
+ const result = await this.withHashes(hashes, (denied) => withoutDeniedEmbedRefs(ref, denied), cancelled, valid);
111
+ return valid() ? result : cancelled();
112
+ }
113
+ finally {
114
+ this.operations.delete(operation);
115
+ }
116
+ }
117
+ withHashes(hashes, commit, cancelled, stillValid, objects = [], prepare) {
118
+ const valid = () => !this.disposed && this.o.canWrite() && (stillValid?.() ?? true);
119
+ if (!valid())
120
+ return cancelled();
121
+ if (!this.o.images?.store.touch || !hashes.length)
122
+ return commit(new Set());
123
+ const held = new Set();
124
+ for (const id of this.o.document.order()) {
125
+ const object = this.o.document.get(id);
126
+ if (object)
127
+ for (const ref of imageRefs(object))
128
+ held.add(ref.hash);
129
+ }
130
+ const incoming = hashes.filter((hash) => !held.has(hash));
131
+ const refresh = hashes.filter((hash) => held.has(hash));
132
+ const finish = (denied) => {
133
+ try {
134
+ return commit(denied);
135
+ }
136
+ finally {
137
+ if (refresh.length)
138
+ void this.touch(refresh);
139
+ }
140
+ };
141
+ if (!incoming.length)
142
+ return finish(new Set());
143
+ const operation = new AbortController();
144
+ this.operations.add(operation);
145
+ const cleanup = this.o.onReferencePending?.(objects);
146
+ return (async () => {
147
+ try {
148
+ let result;
149
+ try {
150
+ result = await this.touch(incoming, { until: "answered", signal: operation.signal }, !prepare);
151
+ if (prepare && valid() && !operation.signal.aborted) {
152
+ for (const hash of result.denied)
153
+ this.report(hash, 256, "denied");
154
+ await waitFor(prepare(result, operation.signal), operation.signal);
155
+ }
156
+ }
157
+ catch {
158
+ if (valid() && !operation.signal.aborted)
159
+ for (const hash of incoming)
160
+ this.report(hash, 256, "store");
161
+ return cancelled();
162
+ }
163
+ return valid() && !operation.signal.aborted ? finish(result.denied) : cancelled();
164
+ }
165
+ finally {
166
+ this.operations.delete(operation);
167
+ cleanup?.();
168
+ }
169
+ })();
170
+ }
171
+ async get(hash, rung, options = {}) {
172
+ if (this.disposed || !this.o.images || !/^[0-9a-f]{64}$/.test(hash))
173
+ return null;
174
+ const { store, room } = this.o.images;
175
+ options.signal?.throwIfAborted();
176
+ return waitFor(store.get(hash, rung, { ...(room === undefined ? {} : { room }), ...options }), options.signal);
177
+ }
178
+ async refreshUrl(hash, rung, options) {
179
+ if (this.disposed || !this.o.images?.store.refreshUrl || !/^[0-9a-f]{64}$/.test(hash))
180
+ return null;
181
+ const { store, room } = this.o.images;
182
+ options.signal?.throwIfAborted();
183
+ return waitFor(store.refreshUrl(hash, rung, { ...(room === undefined ? {} : { room }), ...options }), options.signal);
184
+ }
185
+ async insert(files, placement, commit = this.o.commit) {
186
+ if (this.disposed || !this.o.canWrite() || !this.o.images)
187
+ return [];
188
+ const operation = new AbortController();
189
+ this.operations.add(operation);
190
+ const { store, room } = this.o.images;
191
+ const valid = () => !this.disposed && !operation.signal.aborted && this.o.canWrite()
192
+ && (!placement.parent || !!this.o.document.get(placement.parent));
193
+ const refs = [];
194
+ try {
195
+ for (const file of files) {
196
+ if (!valid())
197
+ break;
198
+ let hash = "";
199
+ try {
200
+ const prepared = await (this.o.preprocess ?? preprocessImage)(file, {
201
+ signal: operation.signal, ...(store.renders ? { renders: store.renders } : {}),
202
+ ...(this.o.onScaled ? { onScaled: this.o.onScaled } : {}),
203
+ });
204
+ if (!valid())
205
+ break;
206
+ this.o.onPrepared?.(prepared, placement);
207
+ hash = await hashAsset(prepared.bytes, { signal: operation.signal });
208
+ if (!valid())
209
+ break;
210
+ const stored = await store.put({ hash, bytes: prepared.bytes, mime: prepared.mime, w: prepared.w, h: prepared.h }, {
211
+ ...(room === undefined ? {} : { room }), signal: operation.signal,
212
+ ...(this.o.onProgress ? { onProgress: this.o.onProgress } : {}),
213
+ });
214
+ if (!valid())
215
+ break;
216
+ const facts = stored ?? prepared;
217
+ if ((stored && stored.hash !== hash) || !Number.isFinite(facts.w) || !Number.isFinite(facts.h) || facts.w <= 0 || facts.h <= 0) {
218
+ this.report(hash, "full", "bad_image");
219
+ continue;
220
+ }
221
+ refs.push(sanitizeImageRef({ hash, mime: facts.mime, w: facts.w, h: facts.h,
222
+ ...((facts.thumb ?? prepared.thumb) === undefined ? {} : { thumb: facts.thumb ?? prepared.thumb }) }));
223
+ }
224
+ catch (error) {
225
+ if (!valid())
226
+ break;
227
+ const reason = error.reason ?? "store";
228
+ this.report(hash, "full", reason);
229
+ }
230
+ }
231
+ return valid() && refs.length ? commit(refs, placement) : [];
232
+ }
233
+ finally {
234
+ this.operations.delete(operation);
235
+ }
236
+ }
237
+ cancel() { for (const operation of this.operations)
238
+ operation.abort(); this.operations.clear(); }
239
+ dispose() { if (this.disposed)
240
+ return; this.disposed = true; this.cancel(); this.unsubscribe(); }
241
+ }
@@ -0,0 +1,27 @@
1
+ export declare const ASSET_MAX_BYTES: number;
2
+ export declare const IMAGE_INPUT_MAX_BYTES: number;
3
+ export declare const IMAGE_INPUT_MAX_PIXELS = 100000000;
4
+ export declare const IMAGE_MAX_SIDE = 16383;
5
+ export interface PreparedImage {
6
+ bytes: Blob;
7
+ mime: string;
8
+ w: number;
9
+ h: number;
10
+ thumb?: string;
11
+ }
12
+ export interface ImageScaleNotice {
13
+ originalWidth: number;
14
+ originalHeight: number;
15
+ width: number;
16
+ height: number;
17
+ }
18
+ export interface PreprocessImageOptions {
19
+ signal?: AbortSignal;
20
+ renders?: readonly string[];
21
+ onScaled?(facts: ImageScaleNotice): void;
22
+ }
23
+ export declare class ImagePreprocessError extends Error {
24
+ readonly reason: "unsupported" | "too_large" | "bad_image" | "worker_unavailable";
25
+ constructor(reason: "unsupported" | "too_large" | "bad_image" | "worker_unavailable", message: string);
26
+ }
27
+ export declare function preprocessImage(file: Blob, options?: PreprocessImageOptions): Promise<PreparedImage>;
@@ -0,0 +1,196 @@
1
+ import { encodeThumbHash, inspectImage, withoutImageOrientation, imageOrientationTransform } from "@daasboard/render-core";
2
+ export const ASSET_MAX_BYTES = 32 * 1024 * 1024;
3
+ export const IMAGE_INPUT_MAX_BYTES = 128 * 1024 * 1024;
4
+ export const IMAGE_INPUT_MAX_PIXELS = 100_000_000;
5
+ export const IMAGE_MAX_SIDE = 16_383;
6
+ export class ImagePreprocessError extends Error {
7
+ reason;
8
+ constructor(reason, message) {
9
+ super(message);
10
+ this.reason = reason;
11
+ this.name = "ImagePreprocessError";
12
+ }
13
+ }
14
+ const abortError = () => new DOMException("Image insertion cancelled", "AbortError");
15
+ const checkAbort = (signal) => { if (signal?.aborted)
16
+ throw abortError(); };
17
+ let queue = Promise.resolve();
18
+ export function preprocessImage(file, options = {}) {
19
+ if (options.signal?.aborted)
20
+ return Promise.reject(abortError());
21
+ const task = queue.then(() => prepare(file, options));
22
+ queue = task.then(() => { }, () => { });
23
+ if (!options.signal)
24
+ return task;
25
+ const signal = options.signal;
26
+ return new Promise((resolve, reject) => {
27
+ const abort = () => reject(abortError());
28
+ signal.addEventListener("abort", abort, { once: true });
29
+ task.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
30
+ });
31
+ }
32
+ async function prepare(file, options) {
33
+ checkAbort(options.signal);
34
+ if (!file.size || file.size > IMAGE_INPUT_MAX_BYTES)
35
+ throw new ImagePreprocessError("too_large", "Image exceeds the 128 MiB input limit");
36
+ const encoded = new Uint8Array(await file.arrayBuffer());
37
+ checkAbort(options.signal);
38
+ let facts = inspectImage(encoded);
39
+ if (!facts && (file.type === "image/svg+xml" || /^\s*(?:<\?xml[^>]*>\s*)?(?:<!--[\s\S]*?-->\s*)?<svg[\s>]/i.test(new TextDecoder().decode(encoded.subarray(0, 4096))))) {
40
+ if (!options.renders?.includes("image/svg+xml"))
41
+ throw new ImagePreprocessError("unsupported", "This image store does not render SVG images");
42
+ if (file.size > 4 * 1024 * 1024)
43
+ throw new ImagePreprocessError("too_large", "SVG exceeds the 4 MiB input limit");
44
+ const root = new TextDecoder().decode(encoded.subarray(0, 4096)).match(/<svg\b[^>]*>/i)?.[0] ?? "";
45
+ const number = (name) => Number(root.match(new RegExp(`\\b${name}\\s*=\\s*["']([0-9.]+)(?:px)?["']`, "i"))?.[1]);
46
+ const box = root.match(/\bviewBox\s*=\s*["']([^"']+)["']/i)?.[1]?.trim().split(/[\s,]+/).map(Number);
47
+ const w = number("width") || box?.[2] || 1, h = number("height") || box?.[3] || 1;
48
+ facts = { mime: "image/svg+xml", w, h, rawW: w, rawH: h, orientation: 1, alpha: true, depth: 8, lossy: false };
49
+ }
50
+ if (!facts)
51
+ throw new ImagePreprocessError("unsupported", "Use PNG, JPEG, GIF or WebP, or a store that renders this image type");
52
+ if (!Number.isFinite(facts.w * facts.h) || facts.w <= 0 || facts.h <= 0 || facts.w * facts.h > IMAGE_INPUT_MAX_PIXELS) {
53
+ throw new ImagePreprocessError("too_large", "Image exceeds the 100 megapixel input limit");
54
+ }
55
+ const ownDecoder = ["image/png", "image/jpeg", "image/gif", "image/webp"].includes(facts.mime);
56
+ if (!ownDecoder) {
57
+ if (!options.renders?.includes(facts.mime))
58
+ throw new ImagePreprocessError("unsupported", `This image store does not render ${facts.mime}`);
59
+ if (file.size > ASSET_MAX_BYTES)
60
+ throw new ImagePreprocessError("too_large", "Image exceeds the 32 MiB stored-original limit");
61
+ return { bytes: file, mime: facts.mime, w: facts.w, h: facts.h };
62
+ }
63
+ const result = await workerPrepare(file, facts, options.signal);
64
+ checkAbort(options.signal);
65
+ if (result.scaled)
66
+ options.onScaled?.({ originalWidth: result.originalWidth, originalHeight: result.originalHeight, width: result.w, height: result.h });
67
+ return { bytes: result.bytes, mime: result.mime, w: result.w, h: result.h, thumb: result.thumb };
68
+ }
69
+ function workerBody(encode, strip, transform) {
70
+ const scope = self;
71
+ scope.onmessage = async ({ data: { file, facts } }) => {
72
+ let bitmap = null;
73
+ let canvas = null;
74
+ try {
75
+ if (typeof createImageBitmap !== "function" || typeof OffscreenCanvas !== "function")
76
+ throw new Error("Worker image preprocessing is unavailable");
77
+ let decodeFile = file, normalize = false;
78
+ if (facts.orientation !== 1 && (facts.mime === "image/png" || facts.mime === "image/webp")) {
79
+ const encoded = new Uint8Array(await file.arrayBuffer());
80
+ const stripped = strip(encoded, facts.mime);
81
+ normalize = stripped !== encoded;
82
+ if (normalize)
83
+ decodeFile = new Blob([stripped], { type: facts.mime });
84
+ }
85
+ const orient = normalize && facts.orientation !== 1;
86
+ bitmap = await createImageBitmap(decodeFile);
87
+ const swap = orient && facts.orientation >= 5;
88
+ const originalWidth = swap ? bitmap.height : bitmap.width;
89
+ const originalHeight = swap ? bitmap.width : bitmap.height;
90
+ if (originalWidth * originalHeight > 100_000_000)
91
+ throw new Error("Decoded image exceeds the 100 megapixel input limit");
92
+ const pixels = facts.alpha && facts.depth > 8 ? 22_000_000 : facts.alpha || facts.depth > 8 ? 44_000_000 : 50_000_000;
93
+ const scale = Math.min(1, 16383 / Math.max(originalWidth, originalHeight), Math.sqrt(pixels / (originalWidth * originalHeight)));
94
+ let w = Math.max(1, Math.floor(originalWidth * scale)), h = Math.max(1, Math.floor(originalHeight * scale));
95
+ const scaled = scale < 1 || file.size > 32 * 1024 * 1024;
96
+ let bytes = file, mime = facts.mime;
97
+ if (scaled || normalize) {
98
+ mime = facts.lossy && !facts.alpha ? "image/jpeg" : normalize && facts.lossy ? "image/webp" : "image/png";
99
+ for (let attempt = 0; attempt < 4; attempt++) {
100
+ canvas = new OffscreenCanvas(w, h);
101
+ const ctx = canvas.getContext("2d");
102
+ if (!ctx)
103
+ throw new Error("Worker canvas is unavailable");
104
+ ctx.scale(w / originalWidth, h / originalHeight);
105
+ if (orient)
106
+ ctx.transform(...transform(facts.orientation, bitmap.width, bitmap.height));
107
+ ctx.drawImage(bitmap, 0, 0);
108
+ bytes = await canvas.convertToBlob({ type: mime, quality: 0.9 });
109
+ canvas.width = 0;
110
+ canvas.height = 0;
111
+ canvas = null;
112
+ if (bytes.type !== mime)
113
+ throw new Error(`This browser cannot encode ${mime}; image was not stored`);
114
+ if (bytes.size <= 32 * 1024 * 1024)
115
+ break;
116
+ if (!scaled) {
117
+ scope.postMessage({ error: "Normalizing this image exceeds the 32 MiB stored-original limit; the image was not resized", reason: "too_large" });
118
+ return;
119
+ }
120
+ if (attempt === 3)
121
+ throw new Error("Image still exceeds 32 MiB after three scaling retries");
122
+ w = Math.max(1, Math.floor(w / Math.SQRT2));
123
+ h = Math.max(1, Math.floor(h / Math.SQRT2));
124
+ }
125
+ }
126
+ bitmap.close();
127
+ bitmap = null;
128
+ const ratio = Math.min(1, 100 / Math.max(w, h));
129
+ const tw = Math.max(1, Math.round(w * ratio)), th = Math.max(1, Math.round(h * ratio));
130
+ bitmap = await createImageBitmap(bytes, { resizeWidth: tw, resizeHeight: th, resizeQuality: "high" });
131
+ canvas = new OffscreenCanvas(tw, th);
132
+ const ctx = canvas.getContext("2d", { willReadFrequently: true });
133
+ if (!ctx)
134
+ throw new Error("Worker canvas is unavailable");
135
+ ctx.drawImage(bitmap, 0, 0);
136
+ bitmap.close();
137
+ bitmap = null;
138
+ const thumb = encode(tw, th, ctx.getImageData(0, 0, tw, th).data);
139
+ scope.postMessage({ bytes, mime, w, h, thumb, scaled, originalWidth, originalHeight });
140
+ }
141
+ catch (error) {
142
+ scope.postMessage({ error: error instanceof Error ? error.message : String(error) });
143
+ }
144
+ finally {
145
+ bitmap?.close();
146
+ if (canvas) {
147
+ canvas.width = 0;
148
+ canvas.height = 0;
149
+ }
150
+ }
151
+ };
152
+ }
153
+ function workerPrepare(file, facts, signal) {
154
+ checkAbort(signal);
155
+ if (typeof Worker !== "function")
156
+ return Promise.reject(new ImagePreprocessError("worker_unavailable", "Image preprocessing requires a worker; this host does not allow one"));
157
+ return new Promise((resolve, reject) => {
158
+ let worker;
159
+ let url;
160
+ let timer;
161
+ let done = false;
162
+ const finish = (error, value) => {
163
+ if (done)
164
+ return;
165
+ done = true;
166
+ worker?.terminate();
167
+ if (url)
168
+ URL.revokeObjectURL(url);
169
+ if (timer)
170
+ clearTimeout(timer);
171
+ signal?.removeEventListener("abort", abort);
172
+ if (error)
173
+ reject(error);
174
+ else
175
+ resolve(value);
176
+ };
177
+ const abort = () => finish(abortError());
178
+ signal?.addEventListener("abort", abort, { once: true });
179
+ try {
180
+ url = URL.createObjectURL(new Blob([`(${workerBody.toString()})(${encodeThumbHash.toString()}, ${withoutImageOrientation.toString()}, ${imageOrientationTransform.toString()});`], { type: "text/javascript" }));
181
+ worker = new Worker(url, { name: "daas-image-preprocess" });
182
+ worker.onerror = (event) => { event.preventDefault(); finish(new ImagePreprocessError("worker_unavailable", "Image preprocessing worker was blocked or failed to start")); };
183
+ worker.onmessage = ({ data }) => {
184
+ if ("error" in data)
185
+ finish(new ImagePreprocessError(data.reason ?? "bad_image", data.error));
186
+ else
187
+ finish(undefined, data);
188
+ };
189
+ timer = setTimeout(() => finish(new ImagePreprocessError("bad_image", "Image preprocessing timed out")), 120_000);
190
+ worker.postMessage({ file, facts });
191
+ }
192
+ catch {
193
+ finish(new ImagePreprocessError("worker_unavailable", "Image preprocessing requires a worker; this host does not allow one"));
194
+ }
195
+ });
196
+ }