@hussmartinez/image-sdk 0.3.0 → 0.5.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,3009 @@
1
+ import { SdkError, applyCommands, coreLimits, createAssetsResolver, createErrorHelpers, createHistory, createStore, createWorkerClient, defineLimits, defineMessages, isSdkError, plural, sdkCoreMessages, withProcessingTime } from "@hussmartinez/sdk-core";
2
+ // src/core/errors/image-error.ts
3
+ var ImageError = class extends SdkError {
4
+ name = "ImageError";
5
+ };
6
+ function isImageError(value, code) {
7
+ return isSdkError(value, code) && value.name === "ImageError";
8
+ }
9
+ // src/core/errors/error-helpers.ts
10
+ var { adapt: asImageError, abortError, throwIfAborted } = createErrorHelpers(ImageError, {
11
+ fallbackCode: "UNKNOWN",
12
+ fallbackMessage: "Image processing failed."
13
+ });
14
+ // src/core/errors/image-limits.ts
15
+ var imageLimitDefinitions = {
16
+ ...coreLimits,
17
+ maxDecodedSize: {
18
+ ...coreLimits.maxDecodedSize,
19
+ default: 1e9,
20
+ warning: 4e8
21
+ },
22
+ maxImagePixels: {
23
+ code: "IMAGE_TOO_LARGE",
24
+ unit: "pixels",
25
+ default: 5e7,
26
+ warning: 24e6
27
+ },
28
+ maxImageDimension: {
29
+ code: "IMAGE_DIMENSION_TOO_LARGE",
30
+ unit: "pixels",
31
+ default: 16384
32
+ },
33
+ maxFrames: {
34
+ code: "TOO_MANY_FRAMES",
35
+ unit: "count",
36
+ default: 300,
37
+ warning: 100
38
+ },
39
+ maxSessionSize: {
40
+ code: "SESSION_TOO_LARGE",
41
+ unit: "bytes",
42
+ default: 1e9,
43
+ warning: 5e8
44
+ },
45
+ maxLayers: {
46
+ code: "TOO_MANY_LAYERS",
47
+ unit: "count",
48
+ default: 256
49
+ },
50
+ maxDrawingPoints: {
51
+ code: "TOO_MANY_POINTS",
52
+ unit: "count",
53
+ default: 2e5,
54
+ warning: 1e5
55
+ }
56
+ };
57
+ var imageLimits = /* @__PURE__ */ defineLimits(imageLimitDefinitions, { errorClass: ImageError });
58
+ var PER_FILE_LIMITS = [
59
+ "maxFileSize",
60
+ "maxImageDimension",
61
+ "maxImagePixels",
62
+ "maxFrames",
63
+ "maxDecodedSize"
64
+ ];
65
+ function checkFileLimits(policy, fileSize, probe) {
66
+ const { width, height } = probe.oriented;
67
+ const actual = {
68
+ maxFileSize: fileSize,
69
+ maxImageDimension: Math.max(width, height),
70
+ maxImagePixels: width * height,
71
+ maxFrames: probe.frames,
72
+ maxDecodedSize: probe.decodedPixelBound * 4
73
+ };
74
+ return PER_FILE_LIMITS.filter((limit) => policy.check(limit, actual[limit]) === "warning");
75
+ }
76
+ var OUTPUT_LIMITS = ["maxImageDimension", "maxImagePixels"];
77
+ function checkOutputLimits(policy, size) {
78
+ policy.check("maxImageDimension", Math.max(size.width, size.height));
79
+ policy.check("maxImagePixels", size.width * size.height);
80
+ }
81
+ // src/adapters/worker-lifecycle.ts
82
+ function createWorkerLifecycle(clearSources, submitted) {
83
+ let current;
84
+ let sequence = 0;
85
+ let terminal = false;
86
+ let destroyed = false;
87
+ const listeners = /* @__PURE__ */ new Set();
88
+ const invalidated = () => new ImageError("WORKER_TERMINATED", "Recreate the image engine before reopening the image.", { details: { reason: "engine-invalidated" } });
89
+ const check = (generation) => {
90
+ if (destroyed) throw new Error("The image engine has been destroyed.");
91
+ if (terminal || generation && (generation.closed || generation !== current)) throw invalidated();
92
+ };
93
+ return {
94
+ check,
95
+ current: () => current,
96
+ getSnapshot: () => terminal,
97
+ subscribe(listener) {
98
+ const notify = () => listener();
99
+ listeners.add(notify);
100
+ return () => {
101
+ listeners.delete(notify);
102
+ };
103
+ },
104
+ destroy() {
105
+ destroyed = true;
106
+ listeners.clear();
107
+ clearSources();
108
+ },
109
+ wrap(worker) {
110
+ check();
111
+ const generation = {
112
+ number: ++sequence,
113
+ closed: false,
114
+ ownsResources: false
115
+ };
116
+ current = generation;
117
+ return {
118
+ postMessage(message, transfer) {
119
+ check(generation);
120
+ const call = message;
121
+ if (call?.type === "call" && (call.method === "register" || call.method === "attachCanvas")) generation.ownsResources = true;
122
+ if (call?.type === "call" && call.method === "register" && typeof call.input?.id === "string") submitted(call.input.id, generation);
123
+ worker.postMessage(message, transfer);
124
+ },
125
+ addEventListener(type, listener) {
126
+ worker.addEventListener(type, listener);
127
+ },
128
+ removeEventListener(type, listener) {
129
+ worker.removeEventListener(type, listener);
130
+ },
131
+ terminate() {
132
+ if (generation.closed) return;
133
+ generation.closed = true;
134
+ try {
135
+ if (current !== generation) return;
136
+ clearSources();
137
+ if (destroyed || !generation.ownsResources || terminal) return;
138
+ terminal = true;
139
+ const notified = [...listeners];
140
+ queueMicrotask(() => {
141
+ if (destroyed) return;
142
+ for (const listener of notified) {
143
+ if (!listeners.has(listener)) continue;
144
+ try {
145
+ listener();
146
+ } catch {}
147
+ }
148
+ });
149
+ } finally {
150
+ worker.terminate();
151
+ }
152
+ }
153
+ };
154
+ }
155
+ };
156
+ }
157
+ function closeRejectedResult(value) {
158
+ if (value && typeof value === "object" && "close" in value && typeof value.close === "function") try {
159
+ value.close();
160
+ } catch {}
161
+ }
162
+ // src/adapters/image-engine.ts
163
+ var ENGINE_INTERNALS = Symbol("hm-image-engine");
164
+ function engineInternals(engine) {
165
+ return engine[ENGINE_INTERNALS];
166
+ }
167
+ function createImageEngine(options = {}) {
168
+ const asset = options.assetsUrl === void 0 ? void 0 : createAssetsResolver(options.assetsUrl);
169
+ let workerUrl;
170
+ return createEngine({
171
+ loadWorker: asset ? async () => () => {
172
+ workerUrl = asset("image/render.worker.js");
173
+ return new Worker(workerUrl, {
174
+ type: "module",
175
+ name: "hm-image-render"
176
+ });
177
+ } : async () => (await import("../lazy/inline-worker-BGAoQbIR.js")).createInlineWorker,
178
+ version: "0.5.0",
179
+ get asset() {
180
+ return workerUrl ?? "inline";
181
+ }
182
+ });
183
+ }
184
+ function createEngine(environment) {
185
+ let startWorker;
186
+ let destroyed = false;
187
+ const ids = /* @__PURE__ */ new Map();
188
+ const lifecycle = createWorkerLifecycle(() => ids.clear(), (id, generation) => {
189
+ const reservation = ids.get(id);
190
+ if (reservation) reservation.generation = generation;
191
+ });
192
+ const client = createWorkerClient({
193
+ createWorker: () => {
194
+ if (!startWorker) throw new ImageError("WORKER_START_FAILED", "The render worker hasn't loaded.");
195
+ return lifecycle.wrap(startWorker());
196
+ },
197
+ errorClasses: { ImageError },
198
+ idleTimeout: 0,
199
+ cancelTimeout: 3e4,
200
+ packageVersion: environment.version,
201
+ get workerAsset() {
202
+ return environment.asset ?? "inline";
203
+ }
204
+ });
205
+ async function ready() {
206
+ if (destroyed) throw new Error("The image engine has been destroyed.");
207
+ startWorker ??= await environment.loadWorker();
208
+ }
209
+ const call = async (method, input, options) => {
210
+ lifecycle.check();
211
+ throwIfAborted(options?.signal);
212
+ await ready();
213
+ lifecycle.check();
214
+ const pending = client.call(method, input, options);
215
+ const generation = lifecycle.current();
216
+ const result = await pending.catch((error) => {
217
+ throw error instanceof TypeError ? error : asImageError(error);
218
+ });
219
+ try {
220
+ lifecycle.check(generation);
221
+ } catch (error) {
222
+ closeRejectedResult(result);
223
+ throw error;
224
+ }
225
+ return result;
226
+ };
227
+ const prepare = async () => {
228
+ lifecycle.check();
229
+ await ready();
230
+ lifecycle.check();
231
+ const pending = client.start();
232
+ const generation = lifecycle.current();
233
+ try {
234
+ await pending;
235
+ } catch (error) {
236
+ throw asImageError(error);
237
+ }
238
+ lifecycle.check(generation);
239
+ if (!generation) throw new Error("The worker did not create a generation.");
240
+ return generation;
241
+ };
242
+ const callOptions = (options) => options?.signal ? { signal: options.signal } : {};
243
+ return {
244
+ [ENGINE_INTERNALS]: {
245
+ call,
246
+ prepare,
247
+ check: lifecycle.check,
248
+ getSnapshot: lifecycle.getSnapshot,
249
+ subscribe: lifecycle.subscribe,
250
+ has: (id) => ids.get(id)?.registered === true
251
+ },
252
+ probe(file, options) {
253
+ return call("probe", { file }, callOptions(options));
254
+ },
255
+ async register(id, file, probe, options) {
256
+ lifecycle.check();
257
+ if (ids.has(id)) throw new TypeError(`The source id "${id}" is already in use.`);
258
+ const reservation = {
259
+ registered: false,
260
+ released: false
261
+ };
262
+ ids.set(id, reservation);
263
+ try {
264
+ const size = await call("register", {
265
+ id,
266
+ file,
267
+ probe,
268
+ limits: Object.fromEntries(PER_FILE_LIMITS.map((limit) => [limit, (options?.filePolicy ?? imageLimits.resolve()).limits[limit].maximum]))
269
+ }, callOptions(options));
270
+ lifecycle.check(reservation.generation);
271
+ if (reservation.released) throw new TypeError("The source was released during registration.");
272
+ reservation.registered = true;
273
+ options?.onProgress?.(1);
274
+ lifecycle.check(reservation.generation);
275
+ return {
276
+ id,
277
+ format: probe.format,
278
+ width: size.width,
279
+ height: size.height,
280
+ frames: 1,
281
+ hasAlpha: probe.hasAlpha,
282
+ decodedBytes: size.width * size.height * 4
283
+ };
284
+ } catch (error) {
285
+ if (ids.get(id) === reservation) ids.delete(id);
286
+ if ((options?.signal?.aborted || reservation.released) && reservation.generation && !reservation.generation.closed && !destroyed && !lifecycle.getSnapshot()) call("release", { id }).catch(() => void 0);
287
+ throw error;
288
+ }
289
+ },
290
+ async thumbnail(id, maxSize, options) {
291
+ lifecycle.check();
292
+ if (!ids.get(id)?.registered) throw new TypeError(`There's no source with the id "${id}".`);
293
+ if (!(maxSize >= 1)) throw new RangeError("maxSize must be at least 1.");
294
+ return call("thumbnail", {
295
+ id,
296
+ maxSize
297
+ }, callOptions(options));
298
+ },
299
+ async release(id) {
300
+ const reservation = ids.get(id);
301
+ if (!reservation) return;
302
+ if (!reservation.registered) {
303
+ reservation.released = true;
304
+ return;
305
+ }
306
+ ids.delete(id);
307
+ if (destroyed || lifecycle.getSnapshot() || reservation.generation?.closed) return;
308
+ await call("release", { id });
309
+ },
310
+ async destroy() {
311
+ if (destroyed) return;
312
+ destroyed = true;
313
+ lifecycle.destroy();
314
+ client.destroy();
315
+ }
316
+ };
317
+ }
318
+ // src/adapters/image-processor.ts
319
+ var FORMATS = /* @__PURE__ */ new Set([
320
+ "png",
321
+ "jpeg",
322
+ "webp"
323
+ ]);
324
+ function createImageProcessor(engine) {
325
+ const internals = engineInternals(engine);
326
+ if (!internals) throw new TypeError("createImageProcessor needs an engine from createImageEngine.");
327
+ let destroyed = false;
328
+ return {
329
+ async export(job, options) {
330
+ if (destroyed) throw new Error("The image processor has been destroyed.");
331
+ const { plan, format } = job;
332
+ if (!FORMATS.has(format.type)) throw new TypeError(`"${String(format.type)}" isn't an export format.`);
333
+ if (format.type !== "png" && format.quality !== void 0) {
334
+ if (!(format.quality >= 0 && format.quality <= 1)) throw new RangeError("quality must be from 0 to 1.");
335
+ }
336
+ internals.check();
337
+ const missing = [plan.base.source, ...layerSources(plan)].find((id) => !internals.has(id));
338
+ if (missing !== void 0) throw new TypeError(`There's no source with the id "${missing}".`);
339
+ const signal = options?.signal;
340
+ throwIfAborted(signal);
341
+ const policy = options?.filePolicy ?? imageLimits.resolve();
342
+ try {
343
+ const blob = await internals.call("export", {
344
+ plan,
345
+ format,
346
+ limits: Object.fromEntries(OUTPUT_LIMITS.map((limit) => [limit, policy.limits[limit].maximum]))
347
+ }, signal ? { signal } : {});
348
+ options?.onProgress?.(1);
349
+ internals.check();
350
+ return blob;
351
+ } catch (error) {
352
+ if (error instanceof TypeError) throw error;
353
+ throw asImageError(error);
354
+ }
355
+ },
356
+ async destroy() {
357
+ destroyed = true;
358
+ }
359
+ };
360
+ }
361
+ function layerSources(plan) {
362
+ return Array.isArray(plan.layers) ? plan.layers.flatMap((layer) => layer.kind === "image" ? [layer.source] : []) : [];
363
+ }
364
+ // src/core/ports/image-renderer.ts
365
+ var MAX_PIXEL_RATIO = 4;
366
+ function backingSize(view) {
367
+ const ratio = Math.min(view.pixelRatio, 4);
368
+ return {
369
+ width: Math.max(1, Math.round(view.width * ratio)),
370
+ height: Math.max(1, Math.round(view.height * ratio))
371
+ };
372
+ }
373
+ function fittedView(width, height, pixelRatio = 1) {
374
+ return {
375
+ width,
376
+ height,
377
+ pixelRatio,
378
+ zoom: 1,
379
+ pan: {
380
+ x: 0,
381
+ y: 0
382
+ }
383
+ };
384
+ }
385
+ function placement(composition, view) {
386
+ const inset = view.inset ?? 0;
387
+ const fit = Math.min((view.width - 2 * inset) / composition.width, (view.height - 2 * inset) / composition.height);
388
+ const scale = Math.max(0, fit) * view.zoom;
389
+ const width = composition.width * scale;
390
+ const height = composition.height * scale;
391
+ return {
392
+ x: (view.width - width) / 2 + view.pan.x,
393
+ y: (view.height - height) / 2 + view.pan.y,
394
+ width,
395
+ height,
396
+ scale
397
+ };
398
+ }
399
+ // src/adapters/image-renderer.ts
400
+ var RENDERER_INTERNALS = Symbol("hm-image-renderer");
401
+ var nextCanvasId = 0;
402
+ function checkView(view) {
403
+ const positive = (n) => Number.isFinite(n) && n > 0;
404
+ if (!positive(view.width) || !positive(view.height) || !positive(view.pixelRatio) || !positive(view.zoom) || !Number.isFinite(view.pan.x) || !Number.isFinite(view.pan.y) || view.inset !== void 0 && !(view.inset >= 0 && 2 * view.inset < Math.min(view.width, view.height))) throw new RangeError("A view needs a positive size, pixel ratio and zoom, a finite pan, and an inset under half its size.");
405
+ }
406
+ function createImageRenderer(engine) {
407
+ const internals = engineInternals(engine);
408
+ if (!internals) throw new TypeError("createImageRenderer needs an engine from createImageEngine.");
409
+ nextCanvasId += 1;
410
+ const id = `preview-${nextCanvasId}`;
411
+ let attached = false;
412
+ let destroyed = false;
413
+ let drawn = 0;
414
+ let pending;
415
+ let inFlight;
416
+ const pump = () => {
417
+ if (inFlight || !pending) return;
418
+ const request = pending;
419
+ pending = void 0;
420
+ const controller = new AbortController();
421
+ const onAbort = () => controller.abort(request.signal?.reason);
422
+ request.signal?.addEventListener("abort", onAbort, { once: true });
423
+ inFlight = { controller };
424
+ internals.call("render", {
425
+ id,
426
+ plan: request.plan,
427
+ view: request.view,
428
+ limits: request.limits
429
+ }, { signal: controller.signal }).then(() => {
430
+ try {
431
+ internals.check();
432
+ } catch (error) {
433
+ request.reject(error);
434
+ return;
435
+ }
436
+ drawn += 1;
437
+ request.resolve("drawn");
438
+ }, (error) => {
439
+ if (!internals.getSnapshot() && controller.signal.aborted && !request.signal?.aborted && isImageError(error, "ABORTED")) request.resolve("superseded");
440
+ else request.reject(error instanceof TypeError ? error : asImageError(error));
441
+ }).finally(() => {
442
+ request.signal?.removeEventListener("abort", onAbort);
443
+ inFlight = void 0;
444
+ pump();
445
+ });
446
+ };
447
+ return {
448
+ [RENDERER_INTERNALS]: {
449
+ snapshot: async () => internals.call("snapshot", { id }),
450
+ drawn: () => drawn
451
+ },
452
+ async attach(canvas) {
453
+ if (destroyed) throw new Error("The image renderer has been destroyed.");
454
+ internals.check();
455
+ if (attached) throw new TypeError("The renderer already has a canvas.");
456
+ if (typeof canvas.transferControlToOffscreen !== "function") throw new ImageError("UNSUPPORTED_ENVIRONMENT", "This browser can't draw the preview in a worker.", { details: { feature: "transferControlToOffscreen" } });
457
+ try {
458
+ const generation = await internals.prepare();
459
+ internals.check(generation);
460
+ if (destroyed) throw new Error("The image renderer has been destroyed.");
461
+ const offscreen = canvas.transferControlToOffscreen();
462
+ await internals.call("attachCanvas", {
463
+ id,
464
+ canvas: offscreen
465
+ }, { transfer: true });
466
+ internals.check(generation);
467
+ if (destroyed) {
468
+ await internals.call("detachCanvas", { id });
469
+ throw new Error("The image renderer has been destroyed.");
470
+ }
471
+ attached = true;
472
+ } catch (error) {
473
+ throw asImageError(error);
474
+ }
475
+ },
476
+ render(plan, view, options) {
477
+ if (destroyed) return Promise.reject(/* @__PURE__ */ new Error("The image renderer has been destroyed."));
478
+ try {
479
+ internals.check();
480
+ } catch (error) {
481
+ return Promise.reject(error);
482
+ }
483
+ if (!attached) return Promise.reject(/* @__PURE__ */ new TypeError("Attach a canvas before rendering."));
484
+ const missing = [plan.base.source, ...layerSources(plan)].find((id) => !internals.has(id));
485
+ if (missing !== void 0) return Promise.reject(/* @__PURE__ */ new TypeError(`There's no source with the id "${missing}".`));
486
+ const policy = options?.filePolicy ?? imageLimits.resolve();
487
+ try {
488
+ checkView(view);
489
+ checkOutputLimits(policy, backingSize(view));
490
+ throwIfAborted(options?.signal);
491
+ } catch (error) {
492
+ return Promise.reject(error);
493
+ }
494
+ const limits = Object.fromEntries(OUTPUT_LIMITS.map((limit) => [limit, policy.limits[limit].maximum]));
495
+ return new Promise((resolve, reject) => {
496
+ pending?.resolve("superseded");
497
+ pending = {
498
+ plan,
499
+ view,
500
+ resolve,
501
+ reject,
502
+ signal: options?.signal,
503
+ limits
504
+ };
505
+ inFlight?.controller.abort(new DOMException("A later render replaced this one.", "AbortError"));
506
+ pump();
507
+ });
508
+ },
509
+ async destroy() {
510
+ if (destroyed) return;
511
+ destroyed = true;
512
+ if (pending) try {
513
+ internals.check();
514
+ pending.resolve("superseded");
515
+ } catch (error) {
516
+ pending.reject(error);
517
+ }
518
+ pending = void 0;
519
+ inFlight?.controller.abort(new DOMException("The renderer was destroyed.", "AbortError"));
520
+ if (attached && !internals.getSnapshot()) try {
521
+ await internals.call("detachCanvas", { id });
522
+ } catch {}
523
+ }
524
+ };
525
+ }
526
+ // src/core/model/plan.ts
527
+ var DEVELOP_ADJUSTMENTS = [
528
+ "temperature",
529
+ "tint",
530
+ "exposure",
531
+ "highlights",
532
+ "shadows",
533
+ "contrast",
534
+ "saturation",
535
+ "vibrance"
536
+ ];
537
+ var NEUTRAL_DEVELOP = Object.freeze({
538
+ temperature: 0,
539
+ tint: 0,
540
+ exposure: 0,
541
+ highlights: 0,
542
+ shadows: 0,
543
+ contrast: 0,
544
+ saturation: 0,
545
+ vibrance: 0
546
+ });
547
+ var FILTER_PRESETS = [
548
+ "vivid",
549
+ "warm",
550
+ "cool",
551
+ "fade",
552
+ "mono",
553
+ "noir",
554
+ "sepia"
555
+ ];
556
+ var MAX_PLAN_ITEMS = 1024;
557
+ var MAX_KEY_LENGTH = 64;
558
+ var MAX_SCENE_COORDINATE = 65536;
559
+ var REDACTION_MODES = ["solid", "pixelate"];
560
+ var MAX_LAYER_TEXT_LENGTH = 1e3;
561
+ var MAX_LAYER_NAME_LENGTH = 100;
562
+ var MAX_STROKE_WIDTH = 1024;
563
+ var MAX_RUN_POINTS = 2e3;
564
+ var MAX_STROKE_RUNS = 64;
565
+ var MAX_DRAWING_STROKES = 1024;
566
+ var LAYER_FONTS = [
567
+ "sans-serif",
568
+ "serif",
569
+ "monospace"
570
+ ];
571
+ var LAYER_ALIGNMENTS = [
572
+ "start",
573
+ "center",
574
+ "end"
575
+ ];
576
+ var LAYER_SHAPES = ["rectangle", "ellipse"];
577
+ var LAYER_KINDS = [
578
+ "text",
579
+ "shape",
580
+ "image",
581
+ "drawing",
582
+ "arrow"
583
+ ];
584
+ var UPRIGHT = Object.freeze({
585
+ rotate: 0,
586
+ flipX: false,
587
+ flipY: false
588
+ });
589
+ var FULL_SIZE = Object.freeze({
590
+ kind: "scale",
591
+ scale: 1
592
+ });
593
+ function createPlan(source) {
594
+ return {
595
+ base: {
596
+ source,
597
+ crop: null,
598
+ orientation: UPRIGHT,
599
+ develop: NEUTRAL_DEVELOP,
600
+ filter: null
601
+ },
602
+ layers: [],
603
+ redactions: [],
604
+ animation: null,
605
+ output: FULL_SIZE,
606
+ metadata: {
607
+ title: "",
608
+ description: "",
609
+ artist: "",
610
+ copyright: ""
611
+ }
612
+ };
613
+ }
614
+ function isValidCrop(crop, source) {
615
+ const { x, y, width, height } = crop;
616
+ return [
617
+ x,
618
+ y,
619
+ width,
620
+ height
621
+ ].every(Number.isSafeInteger) && x >= 0 && y >= 0 && width >= 1 && height >= 1 && x + width <= source.width && y + height <= source.height;
622
+ }
623
+ // src/core/model/source.ts
624
+ var NO_METADATA = Object.freeze({
625
+ location: false,
626
+ camera: false,
627
+ timestamps: false,
628
+ thumbnail: false,
629
+ colourProfile: false,
630
+ other: false
631
+ });
632
+ var EMPTY_KEEPABLE_METADATA = Object.freeze({
633
+ title: "",
634
+ description: "",
635
+ artist: "",
636
+ copyright: ""
637
+ });
638
+ var MAX_METADATA_LENGTH = 2e3;
639
+ function longerThan(text, max) {
640
+ if (text.length <= max) return false;
641
+ let count = 0;
642
+ for (const _ of text) {
643
+ count += 1;
644
+ if (count > max) return true;
645
+ }
646
+ return false;
647
+ }
648
+ // src/core/operations/checks.ts
649
+ var Invalid = class extends Error {
650
+ reason;
651
+ constructor(reason, message) {
652
+ super(message);
653
+ this.reason = reason;
654
+ }
655
+ };
656
+ function invalid(reason, message) {
657
+ throw new Invalid(reason, message);
658
+ }
659
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
660
+ function onlyFields(value, fields, what) {
661
+ for (const name of Object.keys(value)) if (!fields.includes(name)) invalid("malformed-command", `${what} has no field "${name}"`);
662
+ }
663
+ function allFields(value, fields, what) {
664
+ onlyFields(value, fields, what);
665
+ for (const name of fields) if (!Object.hasOwn(value, name)) invalid("malformed-command", `${what} needs "${name}"`);
666
+ }
667
+ var isWhole = (value, min, max = Number.MAX_SAFE_INTEGER) => Number.isSafeInteger(value) && value >= min && value <= max;
668
+ function checkCrop(value) {
669
+ if (!isRecord(value)) invalid("malformed-command", "a crop is an object");
670
+ allFields(value, [
671
+ "x",
672
+ "y",
673
+ "width",
674
+ "height"
675
+ ], "a crop");
676
+ const { x, y, width, height } = value;
677
+ if (!isWhole(x, 0) || !isWhole(y, 0) || !isWhole(width, 1) || !isWhole(height, 1)) invalid("malformed-command", "a crop is whole pixels from 0, at least 1 × 1");
678
+ return {
679
+ x,
680
+ y,
681
+ width,
682
+ height
683
+ };
684
+ }
685
+ function checkCropInSource(crop, source) {
686
+ if (!isValidCrop(crop, source)) invalid("crop-outside-source", "a crop must fit inside its source");
687
+ }
688
+ // src/core/operations/keyed-list.ts
689
+ function checkKey(value) {
690
+ if (typeof value !== "string") invalid("malformed-command", "a key is text");
691
+ if (value === "" || longerThan(value, 64)) invalid("invalid-key", `a key has 1 to 64 code points`);
692
+ return value;
693
+ }
694
+ function checkList(value, what) {
695
+ if (!Array.isArray(value)) invalid("malformed-command", `${what} is a list`);
696
+ if (value.length === 0) invalid("malformed-command", `${what} has at least one item`);
697
+ return value;
698
+ }
699
+ function checkKeys(value) {
700
+ const keys = checkList(value, "keys").map(checkKey);
701
+ if (new Set(keys).size !== keys.length) invalid("malformed-command", "a key is listed twice");
702
+ return keys;
703
+ }
704
+ function checkIndex(value, max) {
705
+ if (!isWhole(value, 0)) invalid("malformed-command", "an index is a whole number from 0");
706
+ if (value > max) invalid("invalid-index", `an index is from 0 to ${max}`);
707
+ return value;
708
+ }
709
+ function indexes(list, keys, names) {
710
+ return keys.map((key) => {
711
+ const index = list.findIndex((item) => item.key === key);
712
+ if (index < 0) invalid(names.unknown, `there's no ${names.item} "${key}"`);
713
+ return index;
714
+ });
715
+ }
716
+ function checkUnused(keys, taken) {
717
+ const seen = new Set(taken);
718
+ for (const key of keys) {
719
+ if (seen.has(key)) invalid("duplicate-key", `the key "${key}" is already used`);
720
+ seen.add(key);
721
+ }
722
+ }
723
+ function insertItems(list, at, items, taken) {
724
+ const index = checkIndex(at, list.length);
725
+ const keys = items.map((item) => item.key);
726
+ checkUnused(keys, taken);
727
+ return {
728
+ list: [
729
+ ...list.slice(0, index),
730
+ ...items,
731
+ ...list.slice(index)
732
+ ],
733
+ keys
734
+ };
735
+ }
736
+ function removeItems(list, keys, names) {
737
+ const removed = new Set(indexes(list, checkKeys(keys), names));
738
+ const entries = [];
739
+ list.forEach((item, at) => {
740
+ if (removed.has(at)) entries.push({
741
+ at,
742
+ item
743
+ });
744
+ });
745
+ return {
746
+ list: list.filter((_, at) => !removed.has(at)),
747
+ entries
748
+ };
749
+ }
750
+ function restoreItems(list, entries, taken) {
751
+ const keys = entries.map(({ item }) => item.key);
752
+ checkUnused(keys, taken);
753
+ const next = [...list];
754
+ let last = -1;
755
+ for (const { at, item } of entries) {
756
+ const index = checkIndex(at, next.length);
757
+ if (index <= last) invalid("invalid-index", "restored items are listed by rising index");
758
+ last = index;
759
+ next.splice(index, 0, item);
760
+ }
761
+ return {
762
+ list: next,
763
+ keys
764
+ };
765
+ }
766
+ function moveItems(list, keys, to, names) {
767
+ const moving = new Set(indexes(list, checkKeys(keys), names));
768
+ const moved = list.filter((_, at) => moving.has(at));
769
+ const rest = list.filter((_, at) => !moving.has(at));
770
+ const index = checkIndex(to, rest.length);
771
+ return {
772
+ list: [
773
+ ...rest.slice(0, index),
774
+ ...moved,
775
+ ...rest.slice(index)
776
+ ],
777
+ order: list.map((item) => item.key)
778
+ };
779
+ }
780
+ function orderItems(list, keys, names) {
781
+ const order = indexes(list, checkKeys(keys), names);
782
+ if (order.length !== list.length) invalid("invalid-order", "an order lists every key once");
783
+ return {
784
+ list: order.map((at) => list[at]),
785
+ order: list.map((item) => item.key)
786
+ };
787
+ }
788
+ function updateItems(list, updates, names, patch) {
789
+ const entries = checkList(updates, "updates").map((update) => {
790
+ if (!isRecord(update)) invalid("malformed-command", "an update is an object");
791
+ allFields(update, ["key", "props"], "an update");
792
+ return {
793
+ key: checkKey(update.key),
794
+ props: update.props
795
+ };
796
+ });
797
+ const keys = entries.map(({ key }) => key);
798
+ if (new Set(keys).size !== keys.length) invalid("duplicate-key", "a key is updated twice");
799
+ const at = indexes(list, keys, names);
800
+ const next = [...list];
801
+ return {
802
+ list: next,
803
+ previous: entries.map(({ key, props }, i) => {
804
+ const index = at[i];
805
+ const patched = patch(next[index], props);
806
+ next[index] = patched.item;
807
+ return {
808
+ key,
809
+ props: patched.previous
810
+ };
811
+ })
812
+ };
813
+ }
814
+ // src/core/operations/redactions.ts
815
+ var REDACTION_NAMES = {
816
+ unknown: "unknown-redaction",
817
+ item: "redaction"
818
+ };
819
+ var MODES = REDACTION_MODES;
820
+ var REGION = [
821
+ "x",
822
+ "y",
823
+ "width",
824
+ "height"
825
+ ];
826
+ var PROPS = [
827
+ "mode",
828
+ ...REGION,
829
+ "colour"
830
+ ];
831
+ var COLOUR = /^#[0-9a-f]{6}$/;
832
+ function checkColour(value) {
833
+ if (typeof value !== "string") invalid("malformed-command", "a colour is text");
834
+ if (!COLOUR.test(value)) invalid("invalid-colour", "a colour is #rrggbb, in lower case");
835
+ return value;
836
+ }
837
+ function checkRedaction(value) {
838
+ if (!isRecord(value)) invalid("malformed-command", "a redaction is an object");
839
+ const { mode } = value;
840
+ if (typeof mode !== "string") invalid("malformed-command", "a redaction's mode is text");
841
+ if (!MODES.includes(mode)) invalid("unknown-redaction-mode", `a redaction's mode is one of ${REDACTION_MODES.join(", ")}`);
842
+ const solid = mode === "solid";
843
+ allFields(value, [
844
+ "key",
845
+ "mode",
846
+ ...REGION,
847
+ ...solid ? ["colour"] : []
848
+ ], "a redaction");
849
+ const key = checkKey(value["key"]);
850
+ const { x, y, width, height } = value;
851
+ if (![
852
+ x,
853
+ y,
854
+ width,
855
+ height
856
+ ].every(Number.isInteger)) invalid("malformed-command", "a redaction's region is whole pixels");
857
+ if (!isWhole(x, -65536, 65536) || !isWhole(y, -65536, 65536) || !isWhole(width, 1, 65536) || !isWhole(height, 1, 65536)) invalid("invalid-region", `a redaction's region is at least 1 × 1, within ${MAX_SCENE_COORDINATE} pixels of the scene's origin`);
858
+ return solid ? {
859
+ key,
860
+ mode: "solid",
861
+ x,
862
+ y,
863
+ width,
864
+ height,
865
+ colour: checkColour(value["colour"])
866
+ } : {
867
+ key,
868
+ mode: "pixelate",
869
+ x,
870
+ y,
871
+ width,
872
+ height
873
+ };
874
+ }
875
+ function patchRedaction(item, props) {
876
+ if (!isRecord(props)) invalid("malformed-command", "an update's props are an object");
877
+ onlyFields(props, PROPS, "a redaction's props");
878
+ const merged = { ...item };
879
+ const previous = {};
880
+ const before = item;
881
+ for (const name of PROPS) {
882
+ if (!Object.hasOwn(props, name)) continue;
883
+ merged[name] = props[name];
884
+ if (Object.hasOwn(before, name)) previous[name] = before[name];
885
+ }
886
+ if (merged["mode"] === "pixelate") {
887
+ if (Object.hasOwn(props, "colour")) invalid("unexpected-colour", "a pixelated redaction has no colour");
888
+ if (item.mode === "solid") previous["colour"] = item.colour;
889
+ delete merged["colour"];
890
+ } else if (merged["mode"] === "solid" && !Object.hasOwn(merged, "colour")) invalid("missing-colour", "a redaction set to solid needs a colour in the same update");
891
+ return {
892
+ item: checkRedaction(merged),
893
+ previous
894
+ };
895
+ }
896
+ // src/core/operations/layers.ts
897
+ var LAYER_NAMES = {
898
+ unknown: "unknown-layer",
899
+ item: "layer"
900
+ };
901
+ var COMMON = [
902
+ "key",
903
+ "kind",
904
+ "name",
905
+ "visible",
906
+ "opacity"
907
+ ];
908
+ var BOX = [
909
+ "x",
910
+ "y",
911
+ "width",
912
+ "height",
913
+ "rotation",
914
+ "flipX"
915
+ ];
916
+ var OWN = {
917
+ text: [
918
+ ...BOX,
919
+ "text",
920
+ "font",
921
+ "bold",
922
+ "colour",
923
+ "align"
924
+ ],
925
+ shape: [
926
+ ...BOX,
927
+ "shape",
928
+ "fill",
929
+ "stroke"
930
+ ],
931
+ image: [
932
+ ...BOX,
933
+ "source",
934
+ "crop"
935
+ ],
936
+ drawing: [
937
+ "x",
938
+ "y",
939
+ "strokes"
940
+ ],
941
+ arrow: [
942
+ "from",
943
+ "to",
944
+ "colour",
945
+ "width"
946
+ ]
947
+ };
948
+ var NOT_UPDATED = { drawing: ["strokes"] };
949
+ var KINDS_BY_VERSION = {
950
+ 2: [
951
+ "text",
952
+ "shape",
953
+ "image"
954
+ ],
955
+ 3: LAYER_KINDS
956
+ };
957
+ var ANY_OWN = new Set(Object.values(OWN).flat());
958
+ var FORBIDDEN_IN_TEXT = /[\u0000-\u0009\u000B-\u001F\u007F‪-‮⁦-⁩]/u;
959
+ function checkText(value, max, what) {
960
+ if (typeof value !== "string") invalid("malformed-command", `${what} is text`);
961
+ if (longerThan(value, max)) invalid("text-too-long", `${what} has at most ${max} code points`);
962
+ if (FORBIDDEN_IN_TEXT.test(value)) invalid("invalid-text", `${what} can't hold control characters other than a line feed, or bidirectional controls`);
963
+ return value;
964
+ }
965
+ function checkOneOf(value, options, what) {
966
+ if (typeof value !== "string" || !options.includes(value)) invalid("malformed-command", `${what} is one of ${options.join(", ")}`);
967
+ return value;
968
+ }
969
+ function checkBoolean(value, what) {
970
+ if (typeof value !== "boolean") invalid("malformed-command", `${what} is true or false`);
971
+ return value;
972
+ }
973
+ var isCoordinate = (value) => isWhole(value, -MAX_SCENE_COORDINATE, MAX_SCENE_COORDINATE);
974
+ function checkWidth(value, what) {
975
+ if (!isWhole(value, 1, 1024)) invalid("malformed-command", `${what}'s width is from 1 to ${MAX_STROKE_WIDTH} pixels`);
976
+ return value;
977
+ }
978
+ function checkStroke(value, origin) {
979
+ if (!isRecord(value)) invalid("malformed-command", "a stroke is an object");
980
+ allFields(value, [
981
+ "colour",
982
+ "width",
983
+ "runs"
984
+ ], "a stroke");
985
+ const colour = checkColour(value.colour);
986
+ const width = checkWidth(value.width, "a stroke");
987
+ const { runs } = value;
988
+ if (!Array.isArray(runs) || runs.length < 1 || runs.length > 64) invalid("malformed-command", `a stroke has 1 to 64 runs`);
989
+ return {
990
+ colour,
991
+ width,
992
+ runs: runs.map((run) => {
993
+ if (!Array.isArray(run) || run.length < 2 || run.length > 4e3) invalid("malformed-command", `a run has 1 to ${MAX_RUN_POINTS} points`);
994
+ const numbers = run;
995
+ if (!numbers.every((value) => isWhole(value, -131072, 131072))) invalid("malformed-command", "a run's coordinates are whole numbers of pixels");
996
+ if (run.length % 2 !== 0) invalid("invalid-points", "a run has an x and a y for each point");
997
+ for (let i = 0; i < run.length; i += 2) if (!isCoordinate(origin.x + numbers[i]) || !isCoordinate(origin.y + numbers[i + 1])) invalid("invalid-points", `a point is within ${MAX_SCENE_COORDINATE} pixels of the scene's origin`);
998
+ return [...numbers];
999
+ })
1000
+ };
1001
+ }
1002
+ function checkStrokes(value, origin) {
1003
+ if (!Array.isArray(value) || value.length > 1024) invalid("malformed-command", `a drawing has at most ${MAX_DRAWING_STROKES} strokes`);
1004
+ return value.map((stroke) => checkStroke(stroke, origin));
1005
+ }
1006
+ function checkPoint(value, what) {
1007
+ if (!isRecord(value)) invalid("malformed-command", `${what} is a point`);
1008
+ allFields(value, ["x", "y"], what);
1009
+ const { x, y } = value;
1010
+ if (!isCoordinate(x) || !isCoordinate(y)) invalid("malformed-command", `${what} is in whole pixels, within ${MAX_SCENE_COORDINATE} of the scene's origin`);
1011
+ return {
1012
+ x,
1013
+ y
1014
+ };
1015
+ }
1016
+ function checkLayer(value, sourceSize, version = 3) {
1017
+ if (!isRecord(value)) invalid("malformed-command", "a layer is an object");
1018
+ const { kind } = value;
1019
+ if (typeof kind !== "string") invalid("malformed-command", "a layer's kind is text");
1020
+ const kinds = KINDS_BY_VERSION[version];
1021
+ if (!kinds.includes(kind)) invalid("unknown-layer-kind", `a layer's kind is one of ${kinds.join(", ")}`);
1022
+ const own = OWN[kind];
1023
+ allFields(value, [...COMMON, ...own], `a ${kind} layer`);
1024
+ const key = checkKey(value["key"]);
1025
+ const name = checkText(value["name"], 100, "a layer's name");
1026
+ const visible = checkBoolean(value["visible"], "a layer's visible");
1027
+ const { opacity } = value;
1028
+ if (!Number.isInteger(opacity)) invalid("malformed-command", "a layer's opacity is a whole number");
1029
+ if (!isWhole(opacity, 0, 100)) invalid("invalid-opacity", "a layer's opacity is from 0 to 100");
1030
+ const shared = {
1031
+ key,
1032
+ name,
1033
+ visible,
1034
+ opacity
1035
+ };
1036
+ if (kind === "drawing") {
1037
+ const { x, y } = value;
1038
+ if (!isCoordinate(x) || !isCoordinate(y)) invalid("malformed-command", `a drawing's origin is in whole pixels, within ${MAX_SCENE_COORDINATE} of the scene's origin`);
1039
+ const strokes = checkStrokes(value["strokes"], {
1040
+ x,
1041
+ y
1042
+ });
1043
+ if (strokes.length === 0) invalid("empty-drawing", "a drawing has at least one stroke");
1044
+ return {
1045
+ ...shared,
1046
+ kind,
1047
+ x,
1048
+ y,
1049
+ strokes
1050
+ };
1051
+ }
1052
+ if (kind === "arrow") {
1053
+ const from = checkPoint(value["from"], "an arrow's from");
1054
+ const to = checkPoint(value["to"], "an arrow's to");
1055
+ if (from.x === to.x && from.y === to.y) invalid("empty-arrow", "an arrow's ends differ");
1056
+ return {
1057
+ ...shared,
1058
+ kind,
1059
+ from,
1060
+ to,
1061
+ colour: checkColour(value["colour"]),
1062
+ width: checkWidth(value["width"], "an arrow")
1063
+ };
1064
+ }
1065
+ const { x, y, width, height, rotation } = value;
1066
+ if (![
1067
+ x,
1068
+ y,
1069
+ width,
1070
+ height,
1071
+ rotation
1072
+ ].every(Number.isInteger)) invalid("malformed-command", "a layer's box is in whole numbers");
1073
+ if (!isCoordinate(x) || !isCoordinate(y) || !isWhole(width, 1, 65536) || !isWhole(height, 1, 65536) || !isWhole(rotation, 0, 3599)) invalid("invalid-box", `a layer's box is at least 1 × 1, within ${MAX_SCENE_COORDINATE} pixels of the scene's origin, turned by 0 to 3599 tenths of a degree`);
1074
+ const flipX = checkBoolean(value["flipX"], "a layer's flipX");
1075
+ const common = {
1076
+ ...shared,
1077
+ x,
1078
+ y,
1079
+ width,
1080
+ height,
1081
+ rotation,
1082
+ flipX
1083
+ };
1084
+ if (kind === "text") return {
1085
+ ...common,
1086
+ kind,
1087
+ text: checkText(value["text"], MAX_LAYER_TEXT_LENGTH, "a layer's text"),
1088
+ font: checkOneOf(value["font"], LAYER_FONTS, "a layer's font"),
1089
+ bold: checkBoolean(value["bold"], "a layer's bold"),
1090
+ colour: checkColour(value["colour"]),
1091
+ align: checkOneOf(value["align"], LAYER_ALIGNMENTS, "a layer's align")
1092
+ };
1093
+ if (kind === "shape") {
1094
+ const shape = checkOneOf(value["shape"], LAYER_SHAPES, "a layer's shape");
1095
+ const fill = value["fill"] === null ? null : checkColour(value["fill"]);
1096
+ let stroke = null;
1097
+ if (value["stroke"] !== null) {
1098
+ const given = value["stroke"];
1099
+ if (!isRecord(given)) invalid("malformed-command", "a stroke is an object or null");
1100
+ allFields(given, ["colour", "width"], "a stroke");
1101
+ stroke = {
1102
+ colour: checkColour(given.colour),
1103
+ width: checkWidth(given.width, "a stroke")
1104
+ };
1105
+ }
1106
+ if (fill === null && stroke === null) invalid("empty-shape", "a shape has a fill or a stroke");
1107
+ return {
1108
+ ...common,
1109
+ kind,
1110
+ shape,
1111
+ fill,
1112
+ stroke
1113
+ };
1114
+ }
1115
+ const source = value["source"];
1116
+ if (typeof source !== "string" || source === "") invalid("malformed-command", "an image layer's source is a source id");
1117
+ const size = sourceSize(source);
1118
+ if (size === void 0) invalid("unknown-source", `unknown source "${source}"`);
1119
+ const crop = value["crop"] === null ? null : checkCrop(value["crop"]);
1120
+ if (crop !== null) checkCropInSource(crop, size);
1121
+ return {
1122
+ ...common,
1123
+ kind: "image",
1124
+ source,
1125
+ crop
1126
+ };
1127
+ }
1128
+ function patchLayer(item, props, sourceSize) {
1129
+ if (!isRecord(props)) invalid("malformed-command", "an update's props are an object");
1130
+ const notUpdated = NOT_UPDATED[item.kind] ?? [];
1131
+ const allowed = new Set([...COMMON.slice(2), ...OWN[item.kind]].filter((name) => !notUpdated.includes(name)));
1132
+ const before = item;
1133
+ const merged = { ...item };
1134
+ const previous = {};
1135
+ for (const name of Object.keys(props)) {
1136
+ if (notUpdated.includes(name)) invalid("malformed-command", `a ${item.kind} layer's "${name}" isn't set by an update`);
1137
+ if (!allowed.has(name)) {
1138
+ if (ANY_OWN.has(name)) invalid("wrong-kind", `a ${item.kind} layer has no "${name}"`);
1139
+ invalid("malformed-command", `a layer's props have no field "${name}"`);
1140
+ }
1141
+ merged[name] = props[name];
1142
+ previous[name] = before[name];
1143
+ }
1144
+ return {
1145
+ item: checkLayer(merged, sourceSize),
1146
+ previous
1147
+ };
1148
+ }
1149
+ // src/core/operations/strokes.ts
1150
+ function drawingOf(plan, key) {
1151
+ if (typeof key !== "string") invalid("malformed-command", "a key is text");
1152
+ const at = plan.layers.findIndex((layer) => layer.key === key);
1153
+ const layer = plan.layers[at];
1154
+ if (layer === void 0) invalid("unknown-layer", `no layer has the key "${key}"`);
1155
+ if (layer.kind !== "drawing") invalid("wrong-kind", `a ${layer.kind} layer has no strokes`);
1156
+ return {
1157
+ at,
1158
+ drawing: layer
1159
+ };
1160
+ }
1161
+ function withStrokes(plan, at, strokes) {
1162
+ return {
1163
+ ...plan,
1164
+ layers: plan.layers.map((layer, index) => index === at && layer.kind === "drawing" ? {
1165
+ ...layer,
1166
+ strokes
1167
+ } : layer)
1168
+ };
1169
+ }
1170
+ function some(value, what) {
1171
+ if (!Array.isArray(value) || value.length === 0) invalid("malformed-command", `${what} is a list of at least one`);
1172
+ return value;
1173
+ }
1174
+ function addStrokes(plan, key, value) {
1175
+ const { at, drawing } = drawingOf(plan, key);
1176
+ const strokes = some(value, "strokes").map((stroke) => checkStroke(stroke, drawing));
1177
+ const before = drawing.strokes.length;
1178
+ if (before + strokes.length > 1024) invalid("too-many-strokes", `a drawing has at most ${MAX_DRAWING_STROKES} strokes`);
1179
+ return {
1180
+ state: withStrokes(plan, at, [...drawing.strokes, ...strokes]),
1181
+ inverse: {
1182
+ type: "image.removeStrokes",
1183
+ key: drawing.key,
1184
+ indexes: strokes.map((_, index) => before + index)
1185
+ }
1186
+ };
1187
+ }
1188
+ function removeStrokes(plan, key, value) {
1189
+ const { at, drawing } = drawingOf(plan, key);
1190
+ const indexes = some(value, "indexes");
1191
+ if (!indexes.every((index) => Number.isSafeInteger(index) && index >= 0)) invalid("malformed-command", "an index is a whole number from 0");
1192
+ const chosen = new Set(indexes);
1193
+ if (chosen.size !== indexes.length) invalid("invalid-index", "an index is listed once");
1194
+ for (const index of chosen) if (index >= drawing.strokes.length) invalid("invalid-index", `the drawing has no stroke ${index}`);
1195
+ if (chosen.size === drawing.strokes.length) invalid("empty-drawing", "a drawing keeps at least one stroke; remove the layer instead");
1196
+ return {
1197
+ state: withStrokes(plan, at, drawing.strokes.filter((_, index) => !chosen.has(index))),
1198
+ inverse: {
1199
+ type: "image.restoreStrokes",
1200
+ key: drawing.key,
1201
+ entries: [...chosen].sort((a, b) => a - b).map((index) => ({
1202
+ at: index,
1203
+ stroke: drawing.strokes[index]
1204
+ }))
1205
+ }
1206
+ };
1207
+ }
1208
+ function restoreStrokes(plan, key, value) {
1209
+ const { at, drawing } = drawingOf(plan, key);
1210
+ const strokes = [...drawing.strokes];
1211
+ let last = -1;
1212
+ const indexes = [];
1213
+ for (const entry of some(value, "entries")) {
1214
+ if (!isRecord(entry)) invalid("malformed-command", "an entry is an object");
1215
+ allFields(entry, ["at", "stroke"], "an entry");
1216
+ const index = entry.at;
1217
+ if (!Number.isSafeInteger(index) || index < 0) invalid("malformed-command", "an index is a whole number from 0");
1218
+ if (index <= last || index > strokes.length) invalid("invalid-index", "entries are by rising index, each within the drawing");
1219
+ last = index;
1220
+ strokes.splice(last, 0, checkStroke(entry.stroke, drawing));
1221
+ indexes.push(last);
1222
+ }
1223
+ if (strokes.length > 1024) invalid("too-many-strokes", `a drawing has at most ${MAX_DRAWING_STROKES} strokes`);
1224
+ return {
1225
+ state: withStrokes(plan, at, strokes),
1226
+ inverse: {
1227
+ type: "image.removeStrokes",
1228
+ key: drawing.key,
1229
+ indexes
1230
+ }
1231
+ };
1232
+ }
1233
+ // src/core/operations/commands.ts
1234
+ function checkOrientation(value) {
1235
+ if (!isRecord(value)) invalid("malformed-command", "an orientation is an object");
1236
+ allFields(value, [
1237
+ "rotate",
1238
+ "flipX",
1239
+ "flipY"
1240
+ ], "an orientation");
1241
+ const { rotate, flipX, flipY } = value;
1242
+ if (typeof flipX !== "boolean" || typeof flipY !== "boolean") invalid("malformed-command", "an orientation's flips are booleans");
1243
+ if (![
1244
+ 0,
1245
+ 90,
1246
+ 180,
1247
+ 270
1248
+ ].includes(rotate)) invalid("invalid-orientation", "a rotation is 0, 90, 180 or 270 degrees");
1249
+ return {
1250
+ rotate,
1251
+ flipX,
1252
+ flipY
1253
+ };
1254
+ }
1255
+ function checkOutput(value) {
1256
+ if (!isRecord(value)) invalid("malformed-command", "an output is an object");
1257
+ if (value.kind === "scale") {
1258
+ allFields(value, ["kind", "scale"], "a scale output");
1259
+ if (typeof value.scale !== "number") invalid("malformed-command", "a scale is a number");
1260
+ if (!(Number.isFinite(value.scale) && value.scale > 0 && value.scale <= 1)) invalid("invalid-output", "an output scale is more than 0 and at most 1");
1261
+ return {
1262
+ kind: "scale",
1263
+ scale: value.scale
1264
+ };
1265
+ }
1266
+ if (value.kind === "fit") {
1267
+ allFields(value, [
1268
+ "kind",
1269
+ "width",
1270
+ "height"
1271
+ ], "a box output");
1272
+ const { width, height } = value;
1273
+ if (!Number.isInteger(width) || !Number.isInteger(height)) invalid("malformed-command", "a box's width and height are whole numbers");
1274
+ if (!isWhole(width, 1) || !isWhole(height, 1)) invalid("invalid-output", "an output box is at least 1 × 1 pixel");
1275
+ return {
1276
+ kind: "fit",
1277
+ width,
1278
+ height
1279
+ };
1280
+ }
1281
+ return invalid("malformed-command", "an output is either a scale or a box to fit");
1282
+ }
1283
+ var METADATA_FIELDS = [
1284
+ "title",
1285
+ "description",
1286
+ "artist",
1287
+ "copyright"
1288
+ ];
1289
+ function checkMetadataValue(field, value) {
1290
+ if (typeof value !== "string") invalid("malformed-command", `metadata.${field} is text`);
1291
+ if (longerThan(value, 2e3)) invalid("metadata-too-long", `metadata.${field} has more than ${MAX_METADATA_LENGTH} code points`);
1292
+ return value;
1293
+ }
1294
+ function checkMetadata(value) {
1295
+ if (!isRecord(value)) invalid("malformed-command", "metadata is an object");
1296
+ allFields(value, METADATA_FIELDS, "metadata");
1297
+ return Object.fromEntries(METADATA_FIELDS.map((field) => [field, checkMetadataValue(field, value[field])]));
1298
+ }
1299
+ var ADJUSTMENTS = DEVELOP_ADJUSTMENTS;
1300
+ var PRESETS = FILTER_PRESETS;
1301
+ function checkDevelop(value, all = false) {
1302
+ if (!isRecord(value)) invalid("malformed-command", "develop values are an object");
1303
+ const values = {};
1304
+ for (const [name, level] of Object.entries(value)) {
1305
+ if (!ADJUSTMENTS.includes(name)) invalid("unknown-adjustment", `"${name}" isn't a develop adjustment`);
1306
+ if (typeof level !== "number") invalid("malformed-command", `${name} is a number`);
1307
+ if (!isWhole(level, -100, 100)) invalid("invalid-level", `${name} is a whole number from -100 to 100`);
1308
+ values[name] = level;
1309
+ }
1310
+ if (all) allFields(value, ADJUSTMENTS, "develop");
1311
+ return Object.fromEntries(DEVELOP_ADJUSTMENTS.filter((name) => name in values).map((name) => [name, values[name]]));
1312
+ }
1313
+ function checkFilter(value) {
1314
+ if (value === null) return null;
1315
+ if (!isRecord(value)) invalid("malformed-command", "a filter is an object or null");
1316
+ allFields(value, ["preset", "strength"], "a filter");
1317
+ if (typeof value.preset !== "string") invalid("malformed-command", "a filter's preset is text");
1318
+ if (!PRESETS.includes(value.preset)) invalid("unknown-preset", `a filter's preset is one of ${FILTER_PRESETS.join(", ")}`);
1319
+ if (typeof value.strength !== "number") invalid("malformed-command", "a filter's strength is a number");
1320
+ if (!isWhole(value.strength, 0, 100)) invalid("invalid-strength", "a filter's strength is a whole number from 0 to 100");
1321
+ return {
1322
+ preset: value.preset,
1323
+ strength: value.strength
1324
+ };
1325
+ }
1326
+ var COMMAND_FIELDS = {
1327
+ "image.setCrop": ["type", "crop"],
1328
+ "image.setOrientation": ["type", "orientation"],
1329
+ "image.setOutput": ["type", "output"],
1330
+ "image.setMetadata": [
1331
+ "type",
1332
+ "field",
1333
+ "value"
1334
+ ],
1335
+ "image.setDevelop": ["type", "values"],
1336
+ "image.setFilter": ["type", "filter"],
1337
+ "image.insertLayers": [
1338
+ "type",
1339
+ "at",
1340
+ "layers"
1341
+ ],
1342
+ "image.removeLayers": ["type", "keys"],
1343
+ "image.moveLayers": [
1344
+ "type",
1345
+ "keys",
1346
+ "to"
1347
+ ],
1348
+ "image.updateLayers": ["type", "updates"],
1349
+ "image.restoreLayers": ["type", "entries"],
1350
+ "image.setLayerOrder": ["type", "keys"],
1351
+ "image.addStrokes": [
1352
+ "type",
1353
+ "key",
1354
+ "strokes"
1355
+ ],
1356
+ "image.removeStrokes": [
1357
+ "type",
1358
+ "key",
1359
+ "indexes"
1360
+ ],
1361
+ "image.restoreStrokes": [
1362
+ "type",
1363
+ "key",
1364
+ "entries"
1365
+ ],
1366
+ "image.insertRedactions": [
1367
+ "type",
1368
+ "at",
1369
+ "redactions"
1370
+ ],
1371
+ "image.removeRedactions": ["type", "keys"],
1372
+ "image.moveRedactions": [
1373
+ "type",
1374
+ "keys",
1375
+ "to"
1376
+ ],
1377
+ "image.updateRedactions": ["type", "updates"],
1378
+ "image.restoreRedactions": ["type", "entries"],
1379
+ "image.setRedactionOrder": ["type", "keys"]
1380
+ };
1381
+ function planKeys(plan) {
1382
+ return new Set([...plan.layers, ...plan.redactions].map((item) => item.key));
1383
+ }
1384
+ function checkRoom(plan, added) {
1385
+ if (plan.layers.length + plan.redactions.length + added > 1024) invalid("too-many-layers", `a plan holds at most ${MAX_PLAN_ITEMS} layers and redactions together`);
1386
+ }
1387
+ function checkLayers(value, sourceSize) {
1388
+ if (!Array.isArray(value)) invalid("malformed-command", "layers is a list");
1389
+ if (value.length === 0) invalid("malformed-command", "layers has at least one item");
1390
+ return value.map((layer) => checkLayer(layer, sourceSize));
1391
+ }
1392
+ function checkLayerEntries(value, sourceSize) {
1393
+ if (!Array.isArray(value)) invalid("malformed-command", "entries is a list");
1394
+ if (value.length === 0) invalid("malformed-command", "entries has at least one item");
1395
+ return value.map((entry) => {
1396
+ if (!isRecord(entry)) invalid("malformed-command", "an entry is an object");
1397
+ allFields(entry, ["at", "layer"], "an entry");
1398
+ return {
1399
+ at: entry.at,
1400
+ item: checkLayer(entry.layer, sourceSize)
1401
+ };
1402
+ });
1403
+ }
1404
+ function checkRedactions(value) {
1405
+ if (!Array.isArray(value)) invalid("malformed-command", "redactions is a list");
1406
+ if (value.length === 0) invalid("malformed-command", "redactions has at least one item");
1407
+ return value.map(checkRedaction);
1408
+ }
1409
+ function checkRedactionEntries(value) {
1410
+ if (!Array.isArray(value)) invalid("malformed-command", "entries is a list");
1411
+ if (value.length === 0) invalid("malformed-command", "entries has at least one item");
1412
+ return value.map((entry) => {
1413
+ if (!isRecord(entry)) invalid("malformed-command", "an entry is an object");
1414
+ allFields(entry, ["at", "redaction"], "an entry");
1415
+ return {
1416
+ at: entry.at,
1417
+ item: checkRedaction(entry.redaction)
1418
+ };
1419
+ });
1420
+ }
1421
+ function apply(plan, input, sourceSize) {
1422
+ if (!isRecord(input)) invalid("malformed-command", "a command is an object");
1423
+ const { type } = input;
1424
+ if (typeof type !== "string") invalid("malformed-command", "a command's type is text");
1425
+ if (!Object.hasOwn(COMMAND_FIELDS, type)) invalid("unknown-command", `"${type}" isn't a command`);
1426
+ const command = input;
1427
+ allFields(command, COMMAND_FIELDS[command.type], `${command.type}`);
1428
+ switch (command.type) {
1429
+ case "image.setCrop": {
1430
+ const crop = command.crop === null ? null : checkCrop(command.crop);
1431
+ if (crop !== null) {
1432
+ const size = sourceSize(plan.base.source);
1433
+ if (size === void 0) invalid("unknown-source", `unknown source "${plan.base.source}"`);
1434
+ checkCropInSource(crop, size);
1435
+ }
1436
+ return {
1437
+ state: {
1438
+ ...plan,
1439
+ base: {
1440
+ ...plan.base,
1441
+ crop
1442
+ }
1443
+ },
1444
+ inverse: {
1445
+ type: "image.setCrop",
1446
+ crop: plan.base.crop
1447
+ }
1448
+ };
1449
+ }
1450
+ case "image.setOrientation": {
1451
+ const orientation = checkOrientation(command.orientation);
1452
+ return {
1453
+ state: {
1454
+ ...plan,
1455
+ base: {
1456
+ ...plan.base,
1457
+ orientation
1458
+ }
1459
+ },
1460
+ inverse: {
1461
+ type: "image.setOrientation",
1462
+ orientation: plan.base.orientation
1463
+ }
1464
+ };
1465
+ }
1466
+ case "image.setOutput": {
1467
+ const output = checkOutput(command.output);
1468
+ return {
1469
+ state: {
1470
+ ...plan,
1471
+ output
1472
+ },
1473
+ inverse: {
1474
+ type: "image.setOutput",
1475
+ output: plan.output
1476
+ }
1477
+ };
1478
+ }
1479
+ case "image.setMetadata": {
1480
+ const { field } = command;
1481
+ if (typeof field !== "string") invalid("malformed-command", "a metadata field is text");
1482
+ if (!METADATA_FIELDS.includes(field)) invalid("unknown-metadata-field", "only title, description, artist and copyright are kept");
1483
+ const value = checkMetadataValue(field, command.value);
1484
+ return {
1485
+ state: {
1486
+ ...plan,
1487
+ metadata: {
1488
+ ...plan.metadata,
1489
+ [field]: value
1490
+ }
1491
+ },
1492
+ inverse: {
1493
+ type: "image.setMetadata",
1494
+ field,
1495
+ value: plan.metadata[field]
1496
+ }
1497
+ };
1498
+ }
1499
+ case "image.setDevelop": {
1500
+ const values = checkDevelop(command.values);
1501
+ const previous = {};
1502
+ for (const name of Object.keys(values)) previous[name] = plan.base.develop[name];
1503
+ return {
1504
+ state: {
1505
+ ...plan,
1506
+ base: {
1507
+ ...plan.base,
1508
+ develop: {
1509
+ ...plan.base.develop,
1510
+ ...values
1511
+ }
1512
+ }
1513
+ },
1514
+ inverse: {
1515
+ type: "image.setDevelop",
1516
+ values: previous
1517
+ }
1518
+ };
1519
+ }
1520
+ case "image.setFilter": {
1521
+ const filter = checkFilter(command.filter);
1522
+ return {
1523
+ state: {
1524
+ ...plan,
1525
+ base: {
1526
+ ...plan.base,
1527
+ filter
1528
+ }
1529
+ },
1530
+ inverse: {
1531
+ type: "image.setFilter",
1532
+ filter: plan.base.filter
1533
+ }
1534
+ };
1535
+ }
1536
+ case "image.insertLayers": {
1537
+ const layers = checkLayers(command.layers, sourceSize);
1538
+ const { list, keys } = insertItems(plan.layers, command.at, layers, planKeys(plan));
1539
+ checkRoom(plan, layers.length);
1540
+ return {
1541
+ state: {
1542
+ ...plan,
1543
+ layers: list
1544
+ },
1545
+ inverse: {
1546
+ type: "image.removeLayers",
1547
+ keys
1548
+ }
1549
+ };
1550
+ }
1551
+ case "image.removeLayers": {
1552
+ const { list, entries } = removeItems(plan.layers, command.keys, LAYER_NAMES);
1553
+ return {
1554
+ state: {
1555
+ ...plan,
1556
+ layers: list
1557
+ },
1558
+ inverse: {
1559
+ type: "image.restoreLayers",
1560
+ entries: entries.map(({ at, item }) => ({
1561
+ at,
1562
+ layer: item
1563
+ }))
1564
+ }
1565
+ };
1566
+ }
1567
+ case "image.restoreLayers": {
1568
+ const entries = checkLayerEntries(command.entries, sourceSize);
1569
+ const { list, keys } = restoreItems(plan.layers, entries, planKeys(plan));
1570
+ checkRoom(plan, entries.length);
1571
+ return {
1572
+ state: {
1573
+ ...plan,
1574
+ layers: list
1575
+ },
1576
+ inverse: {
1577
+ type: "image.removeLayers",
1578
+ keys
1579
+ }
1580
+ };
1581
+ }
1582
+ case "image.moveLayers": {
1583
+ const { list, order } = moveItems(plan.layers, command.keys, command.to, LAYER_NAMES);
1584
+ return {
1585
+ state: {
1586
+ ...plan,
1587
+ layers: list
1588
+ },
1589
+ inverse: {
1590
+ type: "image.setLayerOrder",
1591
+ keys: order
1592
+ }
1593
+ };
1594
+ }
1595
+ case "image.setLayerOrder": {
1596
+ const { list, order } = orderItems(plan.layers, command.keys, LAYER_NAMES);
1597
+ return {
1598
+ state: {
1599
+ ...plan,
1600
+ layers: list
1601
+ },
1602
+ inverse: {
1603
+ type: "image.setLayerOrder",
1604
+ keys: order
1605
+ }
1606
+ };
1607
+ }
1608
+ case "image.updateLayers": {
1609
+ const { list, previous } = updateItems(plan.layers, command.updates, LAYER_NAMES, (item, props) => patchLayer(item, props, sourceSize));
1610
+ return {
1611
+ state: {
1612
+ ...plan,
1613
+ layers: list
1614
+ },
1615
+ inverse: {
1616
+ type: "image.updateLayers",
1617
+ updates: previous
1618
+ }
1619
+ };
1620
+ }
1621
+ case "image.addStrokes": return addStrokes(plan, command.key, command.strokes);
1622
+ case "image.removeStrokes": return removeStrokes(plan, command.key, command.indexes);
1623
+ case "image.restoreStrokes": return restoreStrokes(plan, command.key, command.entries);
1624
+ case "image.insertRedactions": {
1625
+ const redactions = checkRedactions(command.redactions);
1626
+ const { list, keys } = insertItems(plan.redactions, command.at, redactions, planKeys(plan));
1627
+ checkRoom(plan, redactions.length);
1628
+ return {
1629
+ state: {
1630
+ ...plan,
1631
+ redactions: list
1632
+ },
1633
+ inverse: {
1634
+ type: "image.removeRedactions",
1635
+ keys
1636
+ }
1637
+ };
1638
+ }
1639
+ case "image.removeRedactions": {
1640
+ const { list, entries } = removeItems(plan.redactions, command.keys, REDACTION_NAMES);
1641
+ return {
1642
+ state: {
1643
+ ...plan,
1644
+ redactions: list
1645
+ },
1646
+ inverse: {
1647
+ type: "image.restoreRedactions",
1648
+ entries: entries.map(({ at, item }) => ({
1649
+ at,
1650
+ redaction: item
1651
+ }))
1652
+ }
1653
+ };
1654
+ }
1655
+ case "image.restoreRedactions": {
1656
+ const entries = checkRedactionEntries(command.entries);
1657
+ const { list, keys } = restoreItems(plan.redactions, entries, planKeys(plan));
1658
+ checkRoom(plan, entries.length);
1659
+ return {
1660
+ state: {
1661
+ ...plan,
1662
+ redactions: list
1663
+ },
1664
+ inverse: {
1665
+ type: "image.removeRedactions",
1666
+ keys
1667
+ }
1668
+ };
1669
+ }
1670
+ case "image.moveRedactions": {
1671
+ const { list, order } = moveItems(plan.redactions, command.keys, command.to, REDACTION_NAMES);
1672
+ return {
1673
+ state: {
1674
+ ...plan,
1675
+ redactions: list
1676
+ },
1677
+ inverse: {
1678
+ type: "image.setRedactionOrder",
1679
+ keys: order
1680
+ }
1681
+ };
1682
+ }
1683
+ case "image.setRedactionOrder": {
1684
+ const { list, order } = orderItems(plan.redactions, command.keys, REDACTION_NAMES);
1685
+ return {
1686
+ state: {
1687
+ ...plan,
1688
+ redactions: list
1689
+ },
1690
+ inverse: {
1691
+ type: "image.setRedactionOrder",
1692
+ keys: order
1693
+ }
1694
+ };
1695
+ }
1696
+ case "image.updateRedactions": {
1697
+ const { list, previous } = updateItems(plan.redactions, command.updates, REDACTION_NAMES, patchRedaction);
1698
+ return {
1699
+ state: {
1700
+ ...plan,
1701
+ redactions: list
1702
+ },
1703
+ inverse: {
1704
+ type: "image.updateRedactions",
1705
+ updates: previous
1706
+ }
1707
+ };
1708
+ }
1709
+ }
1710
+ }
1711
+ function createImageReducer(sourceSize) {
1712
+ return (plan, command) => {
1713
+ try {
1714
+ return apply(plan, command, sourceSize);
1715
+ } catch (error) {
1716
+ if (!(error instanceof Invalid)) throw error;
1717
+ throw new ImageError("INVALID_COMMAND", `Invalid command: ${error.message}.`, { details: { reason: error.reason } });
1718
+ }
1719
+ };
1720
+ }
1721
+ // src/core/model/geometry.ts
1722
+ function orientedSize(stored, orientation) {
1723
+ return orientation >= 5 ? {
1724
+ width: stored.height,
1725
+ height: stored.width
1726
+ } : stored;
1727
+ }
1728
+ function cropRect(crop, source) {
1729
+ return crop ?? {
1730
+ x: 0,
1731
+ y: 0,
1732
+ width: source.width,
1733
+ height: source.height
1734
+ };
1735
+ }
1736
+ function compositionSize(plan, source) {
1737
+ const { width, height } = cropRect(plan.base.crop, source);
1738
+ return plan.base.orientation.rotate % 180 !== 0 ? {
1739
+ width: height,
1740
+ height: width
1741
+ } : {
1742
+ width,
1743
+ height
1744
+ };
1745
+ }
1746
+ function outputSize(output, composition) {
1747
+ const factor = output.kind === "scale" ? output.scale : Math.min(1, output.width / composition.width, output.height / composition.height);
1748
+ return {
1749
+ width: Math.max(1, Math.round(composition.width * factor)),
1750
+ height: Math.max(1, Math.round(composition.height * factor))
1751
+ };
1752
+ }
1753
+ function sourceToComposition(point, crop, orientation) {
1754
+ const x = point.x - crop.x;
1755
+ const y = point.y - crop.y;
1756
+ const { width, height } = crop;
1757
+ let turned;
1758
+ switch (orientation.rotate) {
1759
+ case 90:
1760
+ turned = {
1761
+ x: height - y,
1762
+ y: x
1763
+ };
1764
+ break;
1765
+ case 180:
1766
+ turned = {
1767
+ x: width - x,
1768
+ y: height - y
1769
+ };
1770
+ break;
1771
+ case 270:
1772
+ turned = {
1773
+ x: y,
1774
+ y: width - x
1775
+ };
1776
+ break;
1777
+ default: turned = {
1778
+ x,
1779
+ y
1780
+ };
1781
+ }
1782
+ const size = orientation.rotate % 180 === 0 ? {
1783
+ width,
1784
+ height
1785
+ } : {
1786
+ width: height,
1787
+ height: width
1788
+ };
1789
+ return {
1790
+ x: orientation.flipX ? size.width - turned.x : turned.x,
1791
+ y: orientation.flipY ? size.height - turned.y : turned.y
1792
+ };
1793
+ }
1794
+ function compositionToSource(point, crop, orientation) {
1795
+ const { width, height } = crop;
1796
+ const size = orientation.rotate % 180 === 0 ? {
1797
+ width,
1798
+ height
1799
+ } : {
1800
+ width: height,
1801
+ height: width
1802
+ };
1803
+ const x = orientation.flipX ? size.width - point.x : point.x;
1804
+ const y = orientation.flipY ? size.height - point.y : point.y;
1805
+ let source;
1806
+ switch (orientation.rotate) {
1807
+ case 90:
1808
+ source = {
1809
+ x: y,
1810
+ y: height - x
1811
+ };
1812
+ break;
1813
+ case 180:
1814
+ source = {
1815
+ x: width - x,
1816
+ y: height - y
1817
+ };
1818
+ break;
1819
+ case 270:
1820
+ source = {
1821
+ x: width - y,
1822
+ y: x
1823
+ };
1824
+ break;
1825
+ default: source = {
1826
+ x,
1827
+ y
1828
+ };
1829
+ }
1830
+ return {
1831
+ x: source.x + crop.x,
1832
+ y: source.y + crop.y
1833
+ };
1834
+ }
1835
+ // src/core/model/crop.ts
1836
+ var ASPECT_PRESETS = [
1837
+ "free",
1838
+ "original",
1839
+ [1, 1],
1840
+ [4, 3],
1841
+ [3, 2],
1842
+ [16, 9],
1843
+ [3, 4],
1844
+ [2, 3],
1845
+ [9, 16]
1846
+ ];
1847
+ function aspectRatio(aspect, source) {
1848
+ if (aspect === "free") return void 0;
1849
+ if (aspect === "original") return source.width / source.height;
1850
+ return aspect[0] / aspect[1];
1851
+ }
1852
+ var wholeCrop = (source) => ({
1853
+ x: 0,
1854
+ y: 0,
1855
+ width: source.width,
1856
+ height: source.height
1857
+ });
1858
+ function fitAspect(within, ratio) {
1859
+ if (ratio === void 0) return within;
1860
+ let width = within.width;
1861
+ let height = Math.round(width / ratio);
1862
+ if (height > within.height) {
1863
+ height = within.height;
1864
+ width = Math.round(height * ratio);
1865
+ }
1866
+ width = Math.max(1, Math.min(within.width, width));
1867
+ height = Math.max(1, Math.min(within.height, height));
1868
+ return {
1869
+ x: within.x + Math.floor((within.width - width) / 2),
1870
+ y: within.y + Math.floor((within.height - height) / 2),
1871
+ width,
1872
+ height
1873
+ };
1874
+ }
1875
+ function moveCrop(crop, dx, dy, source) {
1876
+ return {
1877
+ ...crop,
1878
+ x: Math.min(source.width - crop.width, Math.max(0, crop.x + Math.round(dx))),
1879
+ y: Math.min(source.height - crop.height, Math.max(0, crop.y + Math.round(dy)))
1880
+ };
1881
+ }
1882
+ function dragHandle(crop, handle, dx, dy, source, ratio) {
1883
+ let left = crop.x;
1884
+ let top = crop.y;
1885
+ let right = crop.x + crop.width;
1886
+ let bottom = crop.y + crop.height;
1887
+ if (handle.includes("w")) left = Math.min(right - 1, Math.max(0, left + dx));
1888
+ if (handle.includes("e")) right = Math.max(left + 1, Math.min(source.width, right + dx));
1889
+ if (handle.includes("n")) top = Math.min(bottom - 1, Math.max(0, top + dy));
1890
+ if (handle.includes("s")) bottom = Math.max(top + 1, Math.min(source.height, bottom + dy));
1891
+ left = Math.round(left);
1892
+ right = Math.round(right);
1893
+ top = Math.round(top);
1894
+ bottom = Math.round(bottom);
1895
+ if (ratio === void 0) return {
1896
+ x: left,
1897
+ y: top,
1898
+ width: right - left,
1899
+ height: bottom - top
1900
+ };
1901
+ const horizontal = handle.includes("e") || handle.includes("w");
1902
+ const vertical = handle.includes("n") || handle.includes("s");
1903
+ let width = right - left;
1904
+ let height = bottom - top;
1905
+ if (horizontal && !vertical) height = width / ratio;
1906
+ else if (vertical && !horizontal) width = height * ratio;
1907
+ else if (width / height > ratio) width = height * ratio;
1908
+ else height = width / ratio;
1909
+ const roomRight = handle.includes("w") ? right : source.width - left;
1910
+ const roomDown = handle.includes("n") ? bottom : source.height - top;
1911
+ const scale = Math.min(1, roomRight / width, roomDown / height);
1912
+ width = Math.max(1, Math.round(width * scale));
1913
+ height = Math.max(1, Math.round(height * scale));
1914
+ const x = handle.includes("w") ? right - width : left;
1915
+ let y = handle.includes("n") ? bottom - height : top;
1916
+ let cx = x;
1917
+ if (vertical && !horizontal) cx = Math.round(crop.x + (crop.width - width) / 2);
1918
+ if (horizontal && !vertical) y = Math.round(crop.y + (crop.height - height) / 2);
1919
+ return {
1920
+ x: Math.min(source.width - width, Math.max(0, cx)),
1921
+ y: Math.min(source.height - height, Math.max(0, y)),
1922
+ width,
1923
+ height
1924
+ };
1925
+ }
1926
+ function cropInComposition(crop, orientation, source) {
1927
+ const whole = wholeCrop(source);
1928
+ const a = sourceToComposition({
1929
+ x: crop.x,
1930
+ y: crop.y
1931
+ }, whole, orientation);
1932
+ const b = sourceToComposition({
1933
+ x: crop.x + crop.width,
1934
+ y: crop.y + crop.height
1935
+ }, whole, orientation);
1936
+ return {
1937
+ x: Math.min(a.x, b.x),
1938
+ y: Math.min(a.y, b.y),
1939
+ width: Math.abs(b.x - a.x),
1940
+ height: Math.abs(b.y - a.y)
1941
+ };
1942
+ }
1943
+ function compositionDeltaToSource(dx, dy, orientation, source) {
1944
+ const whole = wholeCrop(source);
1945
+ const origin = compositionToSource({
1946
+ x: 0,
1947
+ y: 0
1948
+ }, whole, orientation);
1949
+ const moved = compositionToSource({
1950
+ x: dx,
1951
+ y: dy
1952
+ }, whole, orientation);
1953
+ return {
1954
+ dx: moved.x - origin.x,
1955
+ dy: moved.y - origin.y
1956
+ };
1957
+ }
1958
+ function handleInSource(handle, orientation) {
1959
+ const vector = {
1960
+ x: 0,
1961
+ y: 0
1962
+ };
1963
+ if (handle.includes("e")) vector.x = 1;
1964
+ if (handle.includes("w")) vector.x = -1;
1965
+ if (handle.includes("s")) vector.y = 1;
1966
+ if (handle.includes("n")) vector.y = -1;
1967
+ const unit = compositionDeltaToSource(vector.x, vector.y, orientation, {
1968
+ width: 2,
1969
+ height: 2
1970
+ });
1971
+ return `${unit.dy > 0 ? "s" : unit.dy < 0 ? "n" : ""}${unit.dx > 0 ? "e" : unit.dx < 0 ? "w" : ""}`;
1972
+ }
1973
+ function nudgeCropOnScreen(crop, key, step, resize, orientation, source, ratio) {
1974
+ const dx = key === "ArrowLeft" ? -step : key === "ArrowRight" ? step : 0;
1975
+ const moved = compositionDeltaToSource(dx, key === "ArrowUp" ? -step : key === "ArrowDown" ? step : 0, orientation, source);
1976
+ if (!resize) return moveCrop(crop, moved.dx, moved.dy, source);
1977
+ return dragHandle(crop, handleInSource(dx === 0 ? "s" : "e", orientation), moved.dx, moved.dy, source, ratio);
1978
+ }
1979
+ // src/core/model/drawing-geometry.ts
1980
+ function simplifyRun(xs, ys, tolerance) {
1981
+ const count = xs.length;
1982
+ const keep = new Uint8Array(count);
1983
+ keep[0] = 1;
1984
+ keep[count - 1] = 1;
1985
+ const limit = BigInt(tolerance) * BigInt(tolerance);
1986
+ const stack = [0, count - 1];
1987
+ while (stack.length > 0) {
1988
+ const last = stack.pop();
1989
+ const first = stack.pop();
1990
+ if (last - first < 2) continue;
1991
+ const ax = xs[first];
1992
+ const ay = ys[first];
1993
+ const dx = xs[last] - ax;
1994
+ const dy = ys[last] - ay;
1995
+ const length = dx * dx + dy * dy;
1996
+ let farthest = -1;
1997
+ let most = -1n;
1998
+ for (let index = first + 1; index < last; index += 1) {
1999
+ const px = xs[index] - ax;
2000
+ const py = ys[index] - ay;
2001
+ let measure;
2002
+ if (length === 0) measure = BigInt(px * px + py * py);
2003
+ else {
2004
+ const along = px * dx + py * dy;
2005
+ if (along <= 0) measure = BigInt(px * px + py * py) * BigInt(length);
2006
+ else if (along >= length) {
2007
+ const qx = px - dx;
2008
+ const qy = py - dy;
2009
+ measure = BigInt(qx * qx + qy * qy) * BigInt(length);
2010
+ } else {
2011
+ const cross = BigInt(px * dy - py * dx);
2012
+ measure = cross * cross;
2013
+ }
2014
+ }
2015
+ if (measure > most) {
2016
+ most = measure;
2017
+ farthest = index;
2018
+ }
2019
+ }
2020
+ if (most > (length === 0 ? limit : limit * BigInt(length))) {
2021
+ keep[farthest] = 1;
2022
+ stack.push(first, farthest, farthest, last);
2023
+ }
2024
+ }
2025
+ const points = [];
2026
+ for (let index = 0; index < count; index += 1) if (keep[index] === 1) points.push(xs[index], ys[index]);
2027
+ return points;
2028
+ }
2029
+ function simplifyStroke(points, tolerance) {
2030
+ if (points.length < 2 || points.length % 2 !== 0) throw new RangeError("A stroke's samples are an x and a y for each of at least one point.");
2031
+ if (!Number.isSafeInteger(tolerance) || tolerance < 0) throw new RangeError("A tolerance is a whole number of pixels, from 0.");
2032
+ const xs = [];
2033
+ const ys = [];
2034
+ for (let index = 0; index < points.length; index += 2) {
2035
+ const x = points[index];
2036
+ const y = points[index + 1];
2037
+ if (!Number.isSafeInteger(x) || !Number.isSafeInteger(y)) throw new RangeError("A stroke's samples are in whole pixels.");
2038
+ const previous = xs.length - 1;
2039
+ if (previous >= 0 && xs[previous] === x && ys[previous] === y) continue;
2040
+ xs.push(x);
2041
+ ys.push(y);
2042
+ }
2043
+ if (xs.length === 1) return [[xs[0], ys[0]]];
2044
+ const runs = [];
2045
+ for (let start = 0; start < xs.length - 1; start += MAX_RUN_POINTS - 1) {
2046
+ if (runs.length === 64) throw new RangeError(`A stroke holds at most 64 runs of samples.`);
2047
+ const end = Math.min(start + MAX_RUN_POINTS, xs.length);
2048
+ runs.push(simplifyRun(xs.slice(start, end), ys.slice(start, end), tolerance));
2049
+ }
2050
+ return runs;
2051
+ }
2052
+ function arrowOutline(from, to, width) {
2053
+ const dx = to.x - from.x;
2054
+ const dy = to.y - from.y;
2055
+ const length = Math.hypot(dx, dy);
2056
+ if (!(length > 0)) throw new RangeError("An arrow's ends differ.");
2057
+ const ux = dx / length;
2058
+ const uy = dy / length;
2059
+ const lx = uy;
2060
+ const ly = -ux;
2061
+ const head = Math.min(4 * width, length);
2062
+ const half = head / 2;
2063
+ const shaft = Math.min(width / 2, half);
2064
+ const base = {
2065
+ x: to.x - ux * head,
2066
+ y: to.y - uy * head
2067
+ };
2068
+ const at = (origin, left) => ({
2069
+ x: origin.x + lx * left || 0,
2070
+ y: origin.y + ly * left || 0
2071
+ });
2072
+ return [
2073
+ at(from, shaft),
2074
+ at(from, -shaft),
2075
+ at(base, -shaft),
2076
+ at(base, -half),
2077
+ {
2078
+ x: to.x,
2079
+ y: to.y
2080
+ },
2081
+ at(base, half),
2082
+ at(base, shaft)
2083
+ ];
2084
+ }
2085
+ var around = (left, top, right, bottom) => {
2086
+ const x = Math.floor(left);
2087
+ const y = Math.floor(top);
2088
+ return {
2089
+ x,
2090
+ y,
2091
+ width: Math.ceil(right) - x,
2092
+ height: Math.ceil(bottom) - y
2093
+ };
2094
+ };
2095
+ function drawingBounds(drawing) {
2096
+ let left = Number.POSITIVE_INFINITY;
2097
+ let top = Number.POSITIVE_INFINITY;
2098
+ let right = Number.NEGATIVE_INFINITY;
2099
+ let bottom = Number.NEGATIVE_INFINITY;
2100
+ for (const stroke of drawing.strokes) {
2101
+ const reach = stroke.width / 2;
2102
+ for (const run of stroke.runs) for (let index = 0; index + 1 < run.length; index += 2) {
2103
+ const x = drawing.x + run[index];
2104
+ const y = drawing.y + run[index + 1];
2105
+ left = Math.min(left, x - reach);
2106
+ top = Math.min(top, y - reach);
2107
+ right = Math.max(right, x + reach);
2108
+ bottom = Math.max(bottom, y + reach);
2109
+ }
2110
+ }
2111
+ if (left > right) return {
2112
+ x: drawing.x,
2113
+ y: drawing.y,
2114
+ width: 0,
2115
+ height: 0
2116
+ };
2117
+ return around(left, top, right, bottom);
2118
+ }
2119
+ function arrowBounds(arrow) {
2120
+ const outline = arrowOutline(arrow.from, arrow.to, arrow.width);
2121
+ const xs = outline.map((point) => point.x);
2122
+ const ys = outline.map((point) => point.y);
2123
+ return around(Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys));
2124
+ }
2125
+ function drawingPoints(plan) {
2126
+ let points = 0;
2127
+ for (const layer of plan.layers) {
2128
+ if (layer.kind !== "drawing") continue;
2129
+ for (const stroke of layer.strokes) for (const run of stroke.runs) points += run.length / 2;
2130
+ }
2131
+ return points;
2132
+ }
2133
+ // src/core/model/keys.ts
2134
+ function createImageKey(used) {
2135
+ for (;;) {
2136
+ const bytes = globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12));
2137
+ const key = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
2138
+ if (!used?.has(key)) return key;
2139
+ }
2140
+ }
2141
+ // src/core/model/layer-geometry.ts
2142
+ function then(first, second) {
2143
+ const [a1, b1, c1, d1, e1, f1] = first;
2144
+ const [a2, b2, c2, d2, e2, f2] = second;
2145
+ return [
2146
+ a2 * a1 + c2 * b1,
2147
+ b2 * a1 + d2 * b1,
2148
+ a2 * c1 + c2 * d1,
2149
+ b2 * c1 + d2 * d1,
2150
+ a2 * e1 + c2 * f1 + e2,
2151
+ b2 * e1 + d2 * f1 + f2
2152
+ ];
2153
+ }
2154
+ function sceneToOutput(crop, orientation, output) {
2155
+ const composition = orientation.rotate % 180 !== 0 ? {
2156
+ width: crop.height,
2157
+ height: crop.width
2158
+ } : {
2159
+ width: crop.width,
2160
+ height: crop.height
2161
+ };
2162
+ const scaleX = output.width / composition.width;
2163
+ const scaleY = output.height / composition.height;
2164
+ const at = (x, y) => {
2165
+ const point = sourceToComposition({
2166
+ x,
2167
+ y
2168
+ }, crop, orientation);
2169
+ return {
2170
+ x: point.x * scaleX,
2171
+ y: point.y * scaleY
2172
+ };
2173
+ };
2174
+ const origin = at(0, 0);
2175
+ const alongX = at(1, 0);
2176
+ const alongY = at(0, 1);
2177
+ return [
2178
+ alongX.x - origin.x,
2179
+ alongX.y - origin.y,
2180
+ alongY.x - origin.x,
2181
+ alongY.y - origin.y,
2182
+ origin.x,
2183
+ origin.y
2184
+ ];
2185
+ }
2186
+ function layerToScene(box) {
2187
+ const radians = box.rotation * Math.PI / 1800;
2188
+ const quarter = box.rotation % 900 === 0 ? box.rotation / 900 % 4 : -1;
2189
+ const cos = quarter >= 0 ? [
2190
+ 1,
2191
+ 0,
2192
+ -1,
2193
+ 0
2194
+ ][quarter] : Math.cos(radians);
2195
+ const sin = quarter >= 0 ? [
2196
+ 0,
2197
+ 1,
2198
+ 0,
2199
+ -1
2200
+ ][quarter] : Math.sin(radians);
2201
+ const negative = (value) => value === 0 ? 0 : -value;
2202
+ const a = box.flipX ? negative(cos) : cos;
2203
+ const b = box.flipX ? negative(sin) : sin;
2204
+ const c = negative(sin);
2205
+ const d = cos;
2206
+ return [
2207
+ a,
2208
+ b,
2209
+ c,
2210
+ d,
2211
+ box.x + box.width / 2 - (a * box.width + c * box.height) / 2,
2212
+ box.y + box.height / 2 - (b * box.width + d * box.height) / 2
2213
+ ];
2214
+ }
2215
+ function layerToOutput(box, crop, orientation, output) {
2216
+ return then(layerToScene(box), sceneToOutput(crop, orientation, output));
2217
+ }
2218
+ function invertMatrix(matrix) {
2219
+ const [a, b, c, d, e, f] = matrix;
2220
+ const determinant = a * d - b * c;
2221
+ return [
2222
+ d / determinant,
2223
+ -b / determinant,
2224
+ -c / determinant,
2225
+ a / determinant,
2226
+ (c * f - d * e) / determinant,
2227
+ (b * e - a * f) / determinant
2228
+ ];
2229
+ }
2230
+ function sceneToLayerSource(box, crop) {
2231
+ const boxToSource = [
2232
+ crop.width / box.width,
2233
+ 0,
2234
+ 0,
2235
+ crop.height / box.height,
2236
+ crop.x,
2237
+ crop.y
2238
+ ];
2239
+ return then(invertMatrix(layerToScene(box)), boxToSource);
2240
+ }
2241
+ function applyMatrix(matrix, point) {
2242
+ const [a, b, c, d, e, f] = matrix;
2243
+ return {
2244
+ x: a * point.x + c * point.y + e,
2245
+ y: b * point.x + d * point.y + f
2246
+ };
2247
+ }
2248
+ function fitTextLines(lines, lineHeight, ascent, box, align, rightToLeft) {
2249
+ const widest = Math.max(0, ...lines.map((line) => line.width));
2250
+ if (!(widest > 0) || !(lineHeight > 0)) return null;
2251
+ const scale = Math.min(box.width / widest, box.height / (lineHeight * lines.length));
2252
+ const top = (box.height - lineHeight * lines.length * scale) / 2;
2253
+ const side = align === "center" ? .5 : align === "start" === rightToLeft ? 1 : 0;
2254
+ return {
2255
+ scale,
2256
+ lines: lines.map((line, index) => ({
2257
+ x: (box.width - line.width * scale) * side,
2258
+ baseline: top + (index * lineHeight + ascent) * scale
2259
+ }))
2260
+ };
2261
+ }
2262
+ function isRightToLeft(text) {
2263
+ for (const character of text) {
2264
+ if (RIGHT_TO_LEFT.test(character)) return true;
2265
+ if (LEFT_TO_RIGHT.test(character)) return false;
2266
+ }
2267
+ return false;
2268
+ }
2269
+ var RIGHT_TO_LEFT = /[֐-ࣿיִ-﷿ﹰ-\u{10800}-\u{10FFF}\u{1E800}-\u{1EFFF}]/u;
2270
+ var LEFT_TO_RIGHT = /\p{L}/u;
2271
+ // src/core/model/redaction-geometry.ts
2272
+ var MIN_BLOCK = 8;
2273
+ var MAX_BLOCKS = 12;
2274
+ function redactionBlockSize(region) {
2275
+ return Math.max(MIN_BLOCK, Math.ceil(Math.max(region.width, region.height) / MAX_BLOCKS));
2276
+ }
2277
+ function boundaries(start, length, block) {
2278
+ const edges = [start];
2279
+ for (let at = start + block; at < start + length; at += block) edges.push(at);
2280
+ edges.push(start + length);
2281
+ return edges;
2282
+ }
2283
+ function cells(xs, ys) {
2284
+ const rects = [];
2285
+ for (let row = 0; row + 1 < ys.length; row += 1) {
2286
+ const y = ys[row];
2287
+ const height = ys[row + 1] - y;
2288
+ if (height <= 0) continue;
2289
+ for (let column = 0; column + 1 < xs.length; column += 1) {
2290
+ const x = xs[column];
2291
+ const width = xs[column + 1] - x;
2292
+ if (width > 0) rects.push({
2293
+ x,
2294
+ y,
2295
+ width,
2296
+ height
2297
+ });
2298
+ }
2299
+ }
2300
+ return rects;
2301
+ }
2302
+ var clamp$1 = (value, min, max) => Math.min(max, Math.max(min, value));
2303
+ function redactionBlocksInScene(region, within) {
2304
+ const block = redactionBlockSize(region);
2305
+ const clip = (edges, min, max) => edges.map((edge) => clamp$1(edge, min, max));
2306
+ return cells(clip(boundaries(region.x, region.width, block), within.x, within.x + within.width), clip(boundaries(region.y, region.height, block), within.y, within.y + within.height));
2307
+ }
2308
+ function toOutput(crop, orientation, output) {
2309
+ const turned = orientation.rotate % 180 !== 0;
2310
+ const composition = turned ? {
2311
+ width: crop.height,
2312
+ height: crop.width
2313
+ } : {
2314
+ width: crop.width,
2315
+ height: crop.height
2316
+ };
2317
+ const scaleX = output.width / composition.width;
2318
+ const scaleY = output.height / composition.height;
2319
+ const at = (x, y) => {
2320
+ const point = sourceToComposition({
2321
+ x,
2322
+ y
2323
+ }, crop, orientation);
2324
+ return {
2325
+ x: point.x * scaleX,
2326
+ y: point.y * scaleY
2327
+ };
2328
+ };
2329
+ return {
2330
+ turned,
2331
+ fromX: (value) => turned ? at(value, crop.y).y : at(value, crop.y).x,
2332
+ fromY: (value) => turned ? at(crop.x, value).x : at(crop.x, value).y
2333
+ };
2334
+ }
2335
+ function outputEdges(values, size) {
2336
+ const sorted = [...values].sort((a, b) => a - b);
2337
+ const last = sorted.length - 1;
2338
+ let previous = 0;
2339
+ return sorted.map((value, index) => {
2340
+ previous = Math.max(previous, clamp$1(index === 0 ? Math.floor(value) : index === last ? Math.ceil(value) : Math.round(value), 0, size));
2341
+ return previous;
2342
+ });
2343
+ }
2344
+ function redactionRectInOutput(region, crop, orientation, output) {
2345
+ const { turned, fromX, fromY } = toOutput(crop, orientation, output);
2346
+ const alongX = [fromX(region.x), fromX(region.x + region.width)];
2347
+ const alongY = [fromY(region.y), fromY(region.y + region.height)];
2348
+ const [left, right] = outputEdges(turned ? alongY : alongX, output.width);
2349
+ const [top, bottom] = outputEdges(turned ? alongX : alongY, output.height);
2350
+ if (right <= left || bottom <= top) return null;
2351
+ return {
2352
+ x: left,
2353
+ y: top,
2354
+ width: right - left,
2355
+ height: bottom - top
2356
+ };
2357
+ }
2358
+ function redactionBlocksInOutput(region, crop, orientation, output) {
2359
+ const block = redactionBlockSize(region);
2360
+ const { turned, fromX, fromY } = toOutput(crop, orientation, output);
2361
+ const alongX = boundaries(region.x, region.width, block).map(fromX);
2362
+ const alongY = boundaries(region.y, region.height, block).map(fromY);
2363
+ return cells(outputEdges(turned ? alongY : alongX, output.width), outputEdges(turned ? alongX : alongY, output.height));
2364
+ }
2365
+ function between(a, b) {
2366
+ const x = Math.min(a.x, b.x);
2367
+ const y = Math.min(a.y, b.y);
2368
+ return {
2369
+ x,
2370
+ y,
2371
+ width: Math.max(a.x, b.x) - x,
2372
+ height: Math.max(a.y, b.y) - y
2373
+ };
2374
+ }
2375
+ function sceneRectToComposition(rect, crop, orientation) {
2376
+ return between(sourceToComposition({
2377
+ x: rect.x,
2378
+ y: rect.y
2379
+ }, crop, orientation), sourceToComposition({
2380
+ x: rect.x + rect.width,
2381
+ y: rect.y + rect.height
2382
+ }, crop, orientation));
2383
+ }
2384
+ function compositionRectToScene(rect, crop, orientation) {
2385
+ return between(compositionToSource({
2386
+ x: rect.x,
2387
+ y: rect.y
2388
+ }, crop, orientation), compositionToSource({
2389
+ x: rect.x + rect.width,
2390
+ y: rect.y + rect.height
2391
+ }, crop, orientation));
2392
+ }
2393
+ function fitRedactionRegion(rect) {
2394
+ const limit = MAX_SCENE_COORDINATE;
2395
+ const x = clamp$1(Math.floor(rect.x), -limit, limit - 1);
2396
+ const y = clamp$1(Math.floor(rect.y), -limit, limit - 1);
2397
+ const right = clamp$1(Math.ceil(rect.x + rect.width), x + 1, limit);
2398
+ const bottom = clamp$1(Math.ceil(rect.y + rect.height), y + 1, limit);
2399
+ return {
2400
+ x,
2401
+ y,
2402
+ width: right - x,
2403
+ height: bottom - y
2404
+ };
2405
+ }
2406
+ // src/core/model/layer-placement.ts
2407
+ var QUARTERS = [
2408
+ 0,
2409
+ 900,
2410
+ 1800,
2411
+ 2700
2412
+ ];
2413
+ var clamp = (value, min, max) => Math.min(max, Math.max(min, value));
2414
+ function newLayerBox(plan, source, seen) {
2415
+ const crop = cropRect(plan.base.crop, source);
2416
+ const { orientation } = plan.base;
2417
+ const composition = compositionSize(plan, source);
2418
+ const width = clamp(Math.round(seen.width), 1, MAX_SCENE_COORDINATE);
2419
+ const height = clamp(Math.round(seen.height), 1, MAX_SCENE_COORDINATE);
2420
+ const asSeen = (rotation, flipX) => {
2421
+ const [a, , , d] = layerToOutput({
2422
+ x: 0,
2423
+ y: 0,
2424
+ width,
2425
+ height,
2426
+ rotation,
2427
+ flipX
2428
+ }, crop, orientation, composition);
2429
+ return a > .5 && d > .5;
2430
+ };
2431
+ const flipX = !QUARTERS.some((rotation) => asSeen(rotation, false));
2432
+ const rotation = QUARTERS.find((quarter) => asSeen(quarter, flipX)) ?? 0;
2433
+ const centre = compositionToSource({
2434
+ x: composition.width / 2,
2435
+ y: composition.height / 2
2436
+ }, crop, orientation);
2437
+ return {
2438
+ x: Math.round(centre.x - width / 2) || 0,
2439
+ y: Math.round(centre.y - height / 2) || 0,
2440
+ width,
2441
+ height,
2442
+ rotation,
2443
+ flipX
2444
+ };
2445
+ }
2446
+ function fittedImageSize(plan, source, image) {
2447
+ const { width, height } = compositionSize(plan, source);
2448
+ const scale = Math.min(1, width / 2 / image.width, height / 2 / image.height);
2449
+ return {
2450
+ width: image.width * scale,
2451
+ height: image.height * scale
2452
+ };
2453
+ }
2454
+ // src/core/session/session.ts
2455
+ function sourcesIn(command) {
2456
+ const of = (layer) => layer.kind === "image" && typeof layer.source === "string" ? [layer.source] : [];
2457
+ switch (command.type) {
2458
+ case "image.insertLayers": return command.layers.flatMap(of);
2459
+ case "image.restoreLayers": return command.entries.flatMap(({ layer }) => of(layer));
2460
+ case "image.updateLayers": return command.updates.flatMap(({ props }) => typeof props["source"] === "string" ? [props["source"]] : []);
2461
+ default: return [];
2462
+ }
2463
+ }
2464
+ var MAX_HISTORY_POINTS = 1e6;
2465
+ function pointsIn(command) {
2466
+ const ofStrokes = (strokes) => strokes.reduce((points, stroke) => points + stroke.runs.reduce((sum, run) => sum + run.length / 2, 0), 0);
2467
+ const ofLayers = (layers) => layers.reduce((points, layer) => points + (layer.kind === "drawing" ? ofStrokes(layer.strokes) : 0), 0);
2468
+ switch (command.type) {
2469
+ case "image.addStrokes": return ofStrokes(command.strokes);
2470
+ case "image.restoreStrokes": return ofStrokes(command.entries.map((entry) => entry.stroke));
2471
+ case "image.insertLayers": return ofLayers(command.layers);
2472
+ case "image.restoreLayers": return ofLayers(command.entries.map((entry) => entry.layer));
2473
+ default: return 0;
2474
+ }
2475
+ }
2476
+ var sourcesOf = (plan) => plan.layers.flatMap((layer) => layer.kind === "image" ? [layer.source] : []);
2477
+ function defaultLayer(source, plan, base) {
2478
+ return {
2479
+ key: createImageKey(new Set([...plan.layers, ...plan.redactions].map((item) => item.key))),
2480
+ kind: "image",
2481
+ name: "",
2482
+ visible: true,
2483
+ opacity: 100,
2484
+ ...newLayerBox(plan, base, fittedImageSize(plan, base, source)),
2485
+ source: source.id,
2486
+ crop: null
2487
+ };
2488
+ }
2489
+ var same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
2490
+ function commandsBetween(from, to) {
2491
+ const commands = [];
2492
+ if (!same(from.base.crop, to.base.crop)) commands.push({
2493
+ type: "image.setCrop",
2494
+ crop: to.base.crop
2495
+ });
2496
+ if (!same(from.base.orientation, to.base.orientation)) commands.push({
2497
+ type: "image.setOrientation",
2498
+ orientation: to.base.orientation
2499
+ });
2500
+ const develop = Object.fromEntries(Object.entries(to.base.develop).filter(([name, value]) => from.base.develop[name] !== value));
2501
+ if (Object.keys(develop).length > 0) commands.push({
2502
+ type: "image.setDevelop",
2503
+ values: develop
2504
+ });
2505
+ if (!same(from.base.filter, to.base.filter)) commands.push({
2506
+ type: "image.setFilter",
2507
+ filter: to.base.filter
2508
+ });
2509
+ if (!same(from.output, to.output)) commands.push({
2510
+ type: "image.setOutput",
2511
+ output: to.output
2512
+ });
2513
+ for (const field of Object.keys(to.metadata)) if (from.metadata[field] !== to.metadata[field]) commands.push({
2514
+ type: "image.setMetadata",
2515
+ field,
2516
+ value: to.metadata[field]
2517
+ });
2518
+ if (!same(from.layers, to.layers)) {
2519
+ if (from.layers.length > 0) commands.push({
2520
+ type: "image.removeLayers",
2521
+ keys: from.layers.map((layer) => layer.key)
2522
+ });
2523
+ if (to.layers.length > 0) commands.push({
2524
+ type: "image.insertLayers",
2525
+ at: 0,
2526
+ layers: to.layers
2527
+ });
2528
+ }
2529
+ if (!same(from.redactions, to.redactions)) {
2530
+ if (from.redactions.length > 0) commands.push({
2531
+ type: "image.removeRedactions",
2532
+ keys: from.redactions.map((redaction) => redaction.key)
2533
+ });
2534
+ if (to.redactions.length > 0) commands.push({
2535
+ type: "image.insertRedactions",
2536
+ at: 0,
2537
+ redactions: to.redactions
2538
+ });
2539
+ }
2540
+ return commands;
2541
+ }
2542
+ var PRESENCE = [
2543
+ "location",
2544
+ "camera",
2545
+ "timestamps",
2546
+ "thumbnail",
2547
+ "colourProfile",
2548
+ "other"
2549
+ ];
2550
+ var decodedBytes = (probe) => probe.oriented.width * probe.oriented.height * 4;
2551
+ function checkSource(policy, file, probe) {
2552
+ const near = checkFileLimits(policy, file.size, probe);
2553
+ const bytes = decodedBytes(probe);
2554
+ if (policy.check("maxSessionSize", bytes) === "warning") near.push("maxSessionSize");
2555
+ return near;
2556
+ }
2557
+ function createImageSession(options) {
2558
+ const { engine, processor } = options;
2559
+ const policy = imageLimits.resolve(options.filePolicy);
2560
+ const history = createHistory();
2561
+ let source = null;
2562
+ const extras = /* @__PURE__ */ new Map();
2563
+ const exports = /* @__PURE__ */ new Set();
2564
+ const sourceOf = (id) => source?.id === id ? source : extras.get(id);
2565
+ const reducer = createImageReducer(sourceOf);
2566
+ let plan = null;
2567
+ let opens = 0;
2568
+ let opening = 0;
2569
+ let exporting = 0;
2570
+ let inserting = 0;
2571
+ let generation = 0;
2572
+ let warnings = [];
2573
+ let error = null;
2574
+ let nextId = 0;
2575
+ let destroyed = false;
2576
+ const snapshot = () => ({
2577
+ status: plan !== null ? "ready" : !destroyed && opening > 0 ? "opening" : "empty",
2578
+ plan,
2579
+ source,
2580
+ sources: source ? [source, ...extras.values()] : [],
2581
+ canUndo: history.canUndo,
2582
+ canRedo: history.canRedo,
2583
+ historyTrimmed: history.trimmed,
2584
+ inserting: !destroyed && inserting > 0,
2585
+ opening: !destroyed && opening > 0,
2586
+ exporting: !destroyed && exporting > 0,
2587
+ warnings,
2588
+ error
2589
+ });
2590
+ const store = createStore(snapshot());
2591
+ const publish = () => store.set(snapshot());
2592
+ const emit = (event) => {
2593
+ try {
2594
+ options.onEvent?.(event);
2595
+ } catch {}
2596
+ };
2597
+ const assertAlive = () => {
2598
+ if (destroyed) throw new Error("The image session has been destroyed.");
2599
+ };
2600
+ const fail = (reason) => {
2601
+ error = isImageError(reason) ? reason : asImageError(reason);
2602
+ return error;
2603
+ };
2604
+ const superseded = () => new ImageError("ABORTED", "A later open replaced this one.", { details: { reason: "superseded" } });
2605
+ const referenced = (dropped = 0) => {
2606
+ const ids = /* @__PURE__ */ new Set();
2607
+ for (const held of [plan, ...exports]) if (held) for (const id of sourcesOf(held)) ids.add(id);
2608
+ const gone = new Set(history.dropOrder.slice(0, dropped));
2609
+ for (const step of history.steps) {
2610
+ if (gone.has(step)) continue;
2611
+ for (const command of [...step.commands, ...step.inverses]) for (const id of sourcesIn(command)) ids.add(id);
2612
+ }
2613
+ return ids;
2614
+ };
2615
+ const releaseUnreferenced = () => {
2616
+ const kept = referenced();
2617
+ for (const id of [...extras.keys()]) {
2618
+ if (kept.has(id)) continue;
2619
+ extras.delete(id);
2620
+ engine.release(id).catch(() => {});
2621
+ }
2622
+ };
2623
+ const heldBytes = (without = /* @__PURE__ */ new Set()) => {
2624
+ let bytes = source?.decodedBytes ?? 0;
2625
+ for (const [id, extra] of extras) if (!without.has(id)) bytes += extra.decodedBytes;
2626
+ return bytes;
2627
+ };
2628
+ const fits = (bytes) => {
2629
+ try {
2630
+ return policy.check("maxSessionSize", bytes);
2631
+ } catch {
2632
+ return false;
2633
+ }
2634
+ };
2635
+ const makeRoom = (bytes) => {
2636
+ const warned = (outcome) => outcome === "warning" ? ["maxSessionSize"] : [];
2637
+ const now = fits(heldBytes() + bytes);
2638
+ if (now !== false) return warned(now);
2639
+ for (let dropped = 1; dropped <= history.dropOrder.length; dropped += 1) {
2640
+ const kept = referenced(dropped);
2641
+ const freed = new Set([...extras.keys()].filter((id) => !kept.has(id)));
2642
+ const after = fits(heldBytes(freed) + bytes);
2643
+ if (after === false) continue;
2644
+ history.drop(dropped);
2645
+ releaseUnreferenced();
2646
+ return warned(after);
2647
+ }
2648
+ policy.check("maxSessionSize", heldBytes() + bytes);
2649
+ return [];
2650
+ };
2651
+ const attempt = (from, commands) => {
2652
+ const { state, inverses } = applyCommands(reducer, from, commands);
2653
+ if (source) checkOutputLimits(policy, outputSize(state.output, compositionSize(state, source)));
2654
+ const items = state.layers.length + state.redactions.length;
2655
+ if (items > from.layers.length + from.redactions.length) policy.check("maxLayers", items);
2656
+ const points = drawingPoints(state);
2657
+ if (points > drawingPoints(from)) policy.check("maxDrawingPoints", points);
2658
+ return {
2659
+ state,
2660
+ step: {
2661
+ commands: [...commands],
2662
+ inverses: [...inverses]
2663
+ }
2664
+ };
2665
+ };
2666
+ const notePoints = () => {
2667
+ let near = false;
2668
+ try {
2669
+ near = plan !== null && policy.check("maxDrawingPoints", drawingPoints(plan)) === "warning";
2670
+ } catch {
2671
+ near = true;
2672
+ }
2673
+ const noted = warnings.includes("maxDrawingPoints");
2674
+ if (near && !noted) warnings = [...warnings, "maxDrawingPoints"];
2675
+ if (!near && noted) warnings = warnings.filter((name) => name !== "maxDrawingPoints");
2676
+ };
2677
+ const trimPoints = () => {
2678
+ const held = () => history.steps.reduce((points, step) => points + [...step.commands, ...step.inverses].reduce((sum, c) => sum + pointsIn(c), 0), 0);
2679
+ while (history.dropOrder.length > 1 && held() > MAX_HISTORY_POINTS) history.drop(1);
2680
+ };
2681
+ const replay = (direction) => {
2682
+ assertAlive();
2683
+ const step = direction === "undo" ? history.undo() : history.redo();
2684
+ if (!step || plan === null) return false;
2685
+ const commands = direction === "undo" ? step.inverses : step.commands;
2686
+ try {
2687
+ plan = applyCommands(reducer, plan, commands).state;
2688
+ } catch (reason) {
2689
+ history.restore(direction);
2690
+ publish();
2691
+ emit({
2692
+ type: direction,
2693
+ outcome: "failed",
2694
+ commands: commands.map((c) => c.type)
2695
+ });
2696
+ throw fail(reason);
2697
+ }
2698
+ error = null;
2699
+ notePoints();
2700
+ releaseUnreferenced();
2701
+ publish();
2702
+ emit({
2703
+ type: direction,
2704
+ outcome: "done",
2705
+ commands: commands.map((c) => c.type)
2706
+ });
2707
+ return true;
2708
+ };
2709
+ const executeCommands = (input) => {
2710
+ assertAlive();
2711
+ const commands = Array.isArray(input) ? input : [input];
2712
+ try {
2713
+ if (plan === null) throw new ImageError("INVALID_COMMAND", "There's nothing to edit before a file is open.");
2714
+ const result = attempt(plan, commands);
2715
+ plan = result.state;
2716
+ history.push(result.step);
2717
+ trimPoints();
2718
+ notePoints();
2719
+ error = null;
2720
+ releaseUnreferenced();
2721
+ emit({
2722
+ type: "execute",
2723
+ outcome: "done",
2724
+ commands: commands.map((c) => c.type)
2725
+ });
2726
+ } catch (reason) {
2727
+ emit({
2728
+ type: "execute",
2729
+ outcome: "failed",
2730
+ commands: commands.map((c) => c.type)
2731
+ });
2732
+ throw fail(reason);
2733
+ } finally {
2734
+ publish();
2735
+ }
2736
+ };
2737
+ return {
2738
+ getSnapshot: () => store.getSnapshot(),
2739
+ subscribe: (listener) => store.subscribe(listener),
2740
+ async open(file, openOptions = {}) {
2741
+ assertAlive();
2742
+ opens += 1;
2743
+ const ticket = opens;
2744
+ nextId += 1;
2745
+ const id = `source-${nextId}`;
2746
+ let registered = false;
2747
+ opening += 1;
2748
+ publish();
2749
+ try {
2750
+ const { probe, near, info } = await withProcessingTime(policy, async (signal) => {
2751
+ throwIfAborted(signal);
2752
+ policy.check("maxFileSize", file.size);
2753
+ const probe = await engine.probe(file, { signal });
2754
+ throwIfAborted(signal);
2755
+ const near = checkSource(policy, file, probe);
2756
+ if (ticket !== opens) throw superseded();
2757
+ const info = await engine.register(id, file, probe, {
2758
+ filePolicy: policy,
2759
+ signal
2760
+ });
2761
+ registered = true;
2762
+ throwIfAborted(signal);
2763
+ return {
2764
+ probe,
2765
+ near,
2766
+ info
2767
+ };
2768
+ }, openOptions);
2769
+ assertAlive();
2770
+ if (ticket !== opens) throw superseded();
2771
+ const previous = source;
2772
+ source = {
2773
+ ...info,
2774
+ fileSize: file.size,
2775
+ metadata: probe.metadata,
2776
+ keepable: probe.keepable
2777
+ };
2778
+ plan = createPlan(id);
2779
+ history.clear();
2780
+ generation += 1;
2781
+ warnings = near;
2782
+ error = null;
2783
+ if (previous) engine.release(previous.id).catch(() => {});
2784
+ releaseUnreferenced();
2785
+ emit({
2786
+ type: "open",
2787
+ outcome: "done",
2788
+ commands: []
2789
+ });
2790
+ return source;
2791
+ } catch (reason) {
2792
+ if (registered && source?.id !== id) await engine.release(id).catch(() => {});
2793
+ const failure = isImageError(reason) ? reason : asImageError(reason);
2794
+ const cancelled = failure.code === "ABORTED";
2795
+ if (!cancelled && !destroyed && ticket === opens) fail(failure);
2796
+ emit({
2797
+ type: "open",
2798
+ outcome: cancelled ? "cancelled" : "failed",
2799
+ commands: []
2800
+ });
2801
+ throw failure;
2802
+ } finally {
2803
+ opening -= 1;
2804
+ if (!destroyed) publish();
2805
+ }
2806
+ },
2807
+ async insertImage(file, insertOptions = {}) {
2808
+ assertAlive();
2809
+ if (plan === null || source === null) throw new ImageError("INVALID_COMMAND", "There's no image to add a layer to yet.");
2810
+ const started = generation;
2811
+ nextId += 1;
2812
+ const id = `source-${nextId}`;
2813
+ let registered = false;
2814
+ let held = false;
2815
+ inserting += 1;
2816
+ publish();
2817
+ try {
2818
+ const { probe, info } = await withProcessingTime(policy, async (signal) => {
2819
+ throwIfAborted(signal);
2820
+ policy.check("maxFileSize", file.size);
2821
+ const probe = await engine.probe(file, { signal });
2822
+ throwIfAborted(signal);
2823
+ checkFileLimits(policy, file.size, probe);
2824
+ const info = await engine.register(id, file, probe, {
2825
+ filePolicy: policy,
2826
+ signal
2827
+ });
2828
+ registered = true;
2829
+ throwIfAborted(signal);
2830
+ return {
2831
+ probe,
2832
+ info
2833
+ };
2834
+ }, insertOptions);
2835
+ assertAlive();
2836
+ if (started !== generation || plan === null || source === null) throw superseded();
2837
+ const near = checkFileLimits(policy, file.size, probe);
2838
+ if (policy.check("maxFiles", extras.size + 2) === "warning") near.push("maxFiles");
2839
+ near.push(...makeRoom(info.decodedBytes));
2840
+ const added = {
2841
+ ...info,
2842
+ fileSize: file.size,
2843
+ metadata: probe.metadata,
2844
+ keepable: probe.keepable
2845
+ };
2846
+ extras.set(id, added);
2847
+ held = true;
2848
+ try {
2849
+ const placed = insertOptions.place?.(added, plan) ?? {
2850
+ type: "image.insertLayers",
2851
+ at: plan.layers.length,
2852
+ layers: [defaultLayer(added, plan, source)]
2853
+ };
2854
+ const commands = Array.isArray(placed) ? placed : [placed];
2855
+ if (!commands.some((command) => sourcesIn(command).includes(id))) throw new ImageError("INVALID_COMMAND", "The commands don't add the image to the plan.");
2856
+ executeCommands(commands);
2857
+ } finally {
2858
+ releaseUnreferenced();
2859
+ }
2860
+ warnings = near;
2861
+ emit({
2862
+ type: "insert",
2863
+ outcome: "done",
2864
+ commands: []
2865
+ });
2866
+ return added;
2867
+ } catch (reason) {
2868
+ if (registered && !held) await engine.release(id).catch(() => {});
2869
+ const failure = isImageError(reason) ? reason : asImageError(reason);
2870
+ const cancelled = failure.code === "ABORTED";
2871
+ if (!cancelled && !destroyed && started === generation) fail(failure);
2872
+ emit({
2873
+ type: "insert",
2874
+ outcome: cancelled ? "cancelled" : "failed",
2875
+ commands: []
2876
+ });
2877
+ throw failure;
2878
+ } finally {
2879
+ inserting -= 1;
2880
+ if (!destroyed) publish();
2881
+ }
2882
+ },
2883
+ execute: (input) => executeCommands(input),
2884
+ applyPlan(next) {
2885
+ assertAlive();
2886
+ const shaped = Array.isArray(next.redactions) && Array.isArray(next.layers) && next.animation === null;
2887
+ if (plan === null || !shaped || next.base.source !== plan.base.source) {
2888
+ const failure = new ImageError("INVALID_COMMAND", shaped ? "The plan isn't for the open image." : "The plan needs layers, redactions and animation, as createPlan gives them.");
2889
+ error = failure;
2890
+ publish();
2891
+ throw failure;
2892
+ }
2893
+ const commands = commandsBetween(plan, next);
2894
+ if (commands.length > 0) executeCommands(commands);
2895
+ },
2896
+ group(fn) {
2897
+ assertAlive();
2898
+ return history.group(fn);
2899
+ },
2900
+ undo: () => replay("undo"),
2901
+ redo: () => replay("redo"),
2902
+ async export(format, exportOptions = {}) {
2903
+ assertAlive();
2904
+ const { onProgress } = exportOptions;
2905
+ if (plan === null || source === null) throw new ImageError("INVALID_COMMAND", "There's nothing to export before a file is open.");
2906
+ const started = generation;
2907
+ const exported = plan;
2908
+ const from = source;
2909
+ exporting += 1;
2910
+ exports.add(exported);
2911
+ publish();
2912
+ try {
2913
+ const size = outputSize(exported.output, compositionSize(exported, from));
2914
+ const blob = await withProcessingTime(policy, async (signal) => {
2915
+ throwIfAborted(signal);
2916
+ const blob = await processor.export({
2917
+ plan: exported,
2918
+ format
2919
+ }, {
2920
+ filePolicy: policy,
2921
+ signal,
2922
+ ...onProgress ? { onProgress } : {}
2923
+ });
2924
+ throwIfAborted(signal);
2925
+ return blob;
2926
+ }, exportOptions);
2927
+ if (started !== generation || destroyed) throw new ImageError("ABORTED", "Another file was opened during the export.", { details: { reason: "superseded" } });
2928
+ error = null;
2929
+ emit({
2930
+ type: "export",
2931
+ outcome: "done",
2932
+ commands: []
2933
+ });
2934
+ return {
2935
+ blob,
2936
+ width: size.width,
2937
+ height: size.height,
2938
+ removed: PRESENCE.filter((kind) => from.metadata[kind]),
2939
+ kept: Object.keys(exported.metadata).filter((field) => exported.metadata[field] !== "")
2940
+ };
2941
+ } catch (reason) {
2942
+ const failure = isImageError(reason) ? reason : asImageError(reason);
2943
+ const cancelled = failure.code === "ABORTED";
2944
+ if (!cancelled && !destroyed && started === generation) fail(failure);
2945
+ emit({
2946
+ type: "export",
2947
+ outcome: cancelled ? "cancelled" : "failed",
2948
+ commands: []
2949
+ });
2950
+ throw failure;
2951
+ } finally {
2952
+ exporting -= 1;
2953
+ exports.delete(exported);
2954
+ if (!destroyed) {
2955
+ releaseUnreferenced();
2956
+ publish();
2957
+ }
2958
+ }
2959
+ },
2960
+ async destroy() {
2961
+ if (destroyed) return;
2962
+ destroyed = true;
2963
+ const held = [...source ? [source.id] : [], ...extras.keys()];
2964
+ source = null;
2965
+ extras.clear();
2966
+ plan = null;
2967
+ history.clear();
2968
+ publish();
2969
+ await Promise.all(held.map((id) => engine.release(id).catch(() => {})));
2970
+ }
2971
+ };
2972
+ }
2973
+ // src/messages/en.ts
2974
+ var imageMessages = /* @__PURE__ */ defineMessages({
2975
+ ...sdkCoreMessages,
2976
+ "errors.INVALID_IMAGE": "This file isn't a valid image, or it's too damaged to open.",
2977
+ "errors.UNSUPPORTED_FORMAT": "This image format isn't supported. Try converting the file to PNG or JPEG, then open it again.",
2978
+ "errors.DECODE_FAILED": "This browser can't open this kind of image. Try another browser, or convert the file to PNG or JPEG.",
2979
+ "errors.INVALID_COMMAND": "This edit couldn't be made. Please try again.",
2980
+ "errors.INVALID_DOCUMENT": "This project is damaged, or it isn't an image project.",
2981
+ "errors.UNSUPPORTED_PLAN": "This image has edits this version can't show. Update the application and try again.",
2982
+ "errors.IMAGE_TOO_LARGE": "This image has more pixels than the editor can handle. Try a smaller version of it.",
2983
+ "errors.IMAGE_DIMENSION_TOO_LARGE": "This image is {actual, number} pixels across, which is over the {maximum, number}-pixel limit.",
2984
+ "errors.TOO_MANY_FRAMES": /* @__PURE__ */ plural("maximum", {
2985
+ one: "This animation has {actual, number} frames, which is over the {maximum}-frame limit.",
2986
+ other: "This animation has {actual, number} frames, which is over the {maximum, number}-frame limit."
2987
+ }),
2988
+ "errors.SESSION_TOO_LARGE": "The open images would use {actual, fileSize} of memory, which is over the {maximum, fileSize} limit. Close an image, or clear the undo history, and try again.",
2989
+ "errors.TOO_MANY_LAYERS": /* @__PURE__ */ plural("maximum", {
2990
+ one: "An image can have {maximum} layer. Merge or delete layers, and try again.",
2991
+ other: "An image can have up to {maximum, number} layers. Merge or delete layers, and try again."
2992
+ }),
2993
+ "errors.TOO_MANY_POINTS": "This image's drawings would have {actual, number} points, which is over the limit of {maximum, number}. Remove some strokes, and try again.",
2994
+ "warnings.maxImagePixels": "This image is large, and may be slow to edit on some devices.",
2995
+ "warnings.maxImageDimension": "This image is very wide or tall, and may be slow to edit.",
2996
+ "warnings.maxFrames": /* @__PURE__ */ plural("actual", {
2997
+ one: "This animation has {actual} frame.",
2998
+ other: "This animation has {actual, number} frames, and may be slow to edit and export."
2999
+ }),
3000
+ "warnings.maxSessionSize": "The open images use {actual, fileSize} of memory. Clearing the undo history frees memory.",
3001
+ "warnings.maxLayers": /* @__PURE__ */ plural("actual", {
3002
+ one: "This image has {actual} layer.",
3003
+ other: "This image has {actual, number} layers, and may be slow to edit and export."
3004
+ }),
3005
+ "warnings.maxDrawingPoints": "This image has a lot of drawing, and may be slow to edit and export."
3006
+ });
3007
+ export { invalid as $, fitAspect as A, placement as At, sourceToComposition as B, asImageError as Bt, drawingPoints as C, REDACTION_MODES as Ct, compositionDeltaToSource as D, MAX_PIXEL_RATIO as Dt, aspectRatio as E, createImageRenderer as Et, compositionSize as F, PER_FILE_LIMITS as Ft, checkOutput as G, checkFilter as H, isImageError as Ht, compositionToSource as I, checkFileLimits as It, checkLayer as J, createImageReducer as K, cropRect as L, checkOutputLimits as Lt, moveCrop as M, createImageEngine as Mt, nudgeCropOnScreen as N, engineInternals as Nt, cropInComposition as O, backingSize as Ot, wholeCrop as P, OUTPUT_LIMITS as Pt, checkCropInSource as Q, orientedSize as R, imageLimitDefinitions as Rt, drawingBounds as S, NEUTRAL_DEVELOP as St, ASPECT_PRESETS as T, createPlan as Tt, checkMetadata as U, checkDevelop as V, ImageError as Vt, checkOrientation as W, Invalid as X, checkRedaction as Y, checkCrop as Z, sceneToLayerSource as _, MAX_PLAN_ITEMS as _t, fitRedactionRegion as a, longerThan as at, arrowBounds as b, MAX_STROKE_RUNS as bt, redactionBlocksInScene as c, FULL_SIZE as ct, applyMatrix as d, LAYER_KINDS as dt, isRecord as et, fitTextLines as f, LAYER_SHAPES as ft, layerToScene as g, MAX_LAYER_TEXT_LENGTH as gt, layerToOutput as h, MAX_LAYER_NAME_LENGTH as ht, compositionRectToScene as i, NO_METADATA as it, handleInSource as j, createImageProcessor as jt, dragHandle as k, fittedView as kt, redactionRectInOutput as l, LAYER_ALIGNMENTS as lt, isRightToLeft as m, MAX_KEY_LENGTH as mt, createImageSession as n, EMPTY_KEEPABLE_METADATA as nt, redactionBlockSize as o, DEVELOP_ADJUSTMENTS as ot, invertMatrix as p, MAX_DRAWING_STROKES as pt, FORBIDDEN_IN_TEXT as q, newLayerBox as r, MAX_METADATA_LENGTH as rt, redactionBlocksInOutput as s, FILTER_PRESETS as st, imageMessages as t, onlyFields as tt, sceneRectToComposition as u, LAYER_FONTS as ut, sceneToOutput as v, MAX_RUN_POINTS as vt, simplifyStroke as w, UPRIGHT as wt, arrowOutline as x, MAX_STROKE_WIDTH as xt, createImageKey as y, MAX_SCENE_COORDINATE as yt, outputSize as z, imageLimits as zt };
3008
+
3009
+ //# sourceMappingURL=core-DKUm3jGZ.js.map