@hussmartinez/image-sdk 0.5.0 → 0.7.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.
@@ -36,6 +36,12 @@ var imageLimitDefinitions = {
36
36
  default: 300,
37
37
  warning: 100
38
38
  },
39
+ maxAnimationPixels: {
40
+ code: "ANIMATION_TOO_LARGE",
41
+ unit: "pixels",
42
+ default: 8e6,
43
+ warning: 2e6
44
+ },
39
45
  maxSessionSize: {
40
46
  code: "SESSION_TOO_LARGE",
41
47
  unit: "bytes",
@@ -62,17 +68,41 @@ var PER_FILE_LIMITS = [
62
68
  "maxFrames",
63
69
  "maxDecodedSize"
64
70
  ];
65
- function checkFileLimits(policy, fileSize, probe) {
71
+ function checkFileLimits(policy, fileSize, probe, frames = "all") {
66
72
  const { width, height } = probe.oriented;
67
73
  const actual = {
68
74
  maxFileSize: fileSize,
69
75
  maxImageDimension: Math.max(width, height),
70
76
  maxImagePixels: width * height,
71
- maxFrames: probe.frames,
72
- maxDecodedSize: probe.decodedPixelBound * 4
77
+ maxFrames: frames === "all" ? probe.frames : 1,
78
+ maxDecodedSize: (frames === "all" ? probe.decodedPixelBound : width * height) * 4
73
79
  };
74
80
  return PER_FILE_LIMITS.filter((limit) => policy.check(limit, actual[limit]) === "warning");
75
81
  }
82
+ var ANIMATION_LIMITS = [
83
+ "maxFrames",
84
+ "maxDecodedSize",
85
+ "maxAnimationPixels"
86
+ ];
87
+ function animationLimits(policy, probe, ceiling = Number.POSITIVE_INFINITY) {
88
+ const actual = {
89
+ maxFrames: probe.frames,
90
+ maxDecodedSize: probe.decodedPixelBound * 4,
91
+ maxAnimationPixels: probe.oriented.width * probe.oriented.height
92
+ };
93
+ const over = [];
94
+ const near = [];
95
+ for (const limit of ANIMATION_LIMITS) try {
96
+ if (policy.check(limit, actual[limit]) === "warning") near.push(limit);
97
+ } catch {
98
+ over.push(limit);
99
+ }
100
+ if (probe.frames > ceiling && !over.includes("maxFrames")) over.push("maxFrames");
101
+ return {
102
+ over,
103
+ near
104
+ };
105
+ }
76
106
  var OUTPUT_LIMITS = ["maxImageDimension", "maxImagePixels"];
77
107
  function checkOutputLimits(policy, size) {
78
108
  policy.check("maxImageDimension", Math.max(size.width, size.height));
@@ -174,8 +204,21 @@ function createImageEngine(options = {}) {
174
204
  type: "module",
175
205
  name: "hm-image-render"
176
206
  });
177
- } : async () => (await import("../lazy/inline-worker-BGAoQbIR.js")).createInlineWorker,
178
- version: "0.5.0",
207
+ } : async () => (await import("../lazy/inline-worker-DdS6iQ9X.js")).createInlineWorker,
208
+ loadJobWorker: asset ? async () => {
209
+ const url = asset("image/job.worker.js");
210
+ return {
211
+ start: () => new Worker(url, {
212
+ type: "module",
213
+ name: "hm-image-job"
214
+ }),
215
+ asset: url
216
+ };
217
+ } : async () => ({
218
+ start: (await import("../lazy/inline-job-worker-2EbG2Vzb.js")).createInlineJobWorker,
219
+ asset: "inline"
220
+ }),
221
+ version: "0.7.0",
179
222
  get asset() {
180
223
  return workerUrl ?? "inline";
181
224
  }
@@ -247,7 +290,16 @@ function createEngine(environment) {
247
290
  check: lifecycle.check,
248
291
  getSnapshot: lifecycle.getSnapshot,
249
292
  subscribe: lifecycle.subscribe,
250
- has: (id) => ids.get(id)?.registered === true
293
+ has: (id) => ids.get(id)?.registered === true,
294
+ drawable: (id) => {
295
+ const reservation = ids.get(id);
296
+ return reservation?.registered === true || reservation?.firstFrame === true && !reservation.released;
297
+ },
298
+ loadJobWorker: async () => {
299
+ if (!environment.loadJobWorker) throw new ImageError("UNSUPPORTED_FORMAT", "This engine can't write GIFs.", { details: { format: "gif" } });
300
+ return environment.loadJobWorker();
301
+ },
302
+ version: environment.version
251
303
  },
252
304
  probe(file, options) {
253
305
  return call("probe", { file }, callOptions(options));
@@ -261,12 +313,25 @@ function createEngine(environment) {
261
313
  };
262
314
  ids.set(id, reservation);
263
315
  try {
264
- const size = await call("register", {
316
+ const decoded = await call("register", {
265
317
  id,
266
318
  file,
267
319
  probe,
320
+ frames: options?.frames ?? "first",
321
+ animationPixels: (options?.filePolicy ?? imageLimits.resolve()).limits.maxAnimationPixels.maximum,
268
322
  limits: Object.fromEntries(PER_FILE_LIMITS.map((limit) => [limit, (options?.filePolicy ?? imageLimits.resolve()).limits[limit].maximum]))
269
- }, callOptions(options));
323
+ }, {
324
+ ...callOptions(options),
325
+ onProgress: ({ done, total, firstFrame }) => {
326
+ if (firstFrame) {
327
+ if (reservation.released || reservation.firstFrame) return;
328
+ reservation.firstFrame = true;
329
+ options?.onFirstFrame?.();
330
+ return;
331
+ }
332
+ options?.onProgress?.(done / total);
333
+ }
334
+ });
270
335
  lifecycle.check(reservation.generation);
271
336
  if (reservation.released) throw new TypeError("The source was released during registration.");
272
337
  reservation.registered = true;
@@ -275,11 +340,13 @@ function createEngine(environment) {
275
340
  return {
276
341
  id,
277
342
  format: probe.format,
278
- width: size.width,
279
- height: size.height,
280
- frames: 1,
343
+ width: decoded.width,
344
+ height: decoded.height,
345
+ frames: decoded.frames,
281
346
  hasAlpha: probe.hasAlpha,
282
- decodedBytes: size.width * size.height * 4
347
+ decodedBytes: decoded.bytes,
348
+ timing: decoded.timing,
349
+ incomplete: decoded.incomplete
283
350
  };
284
351
  } catch (error) {
285
352
  if (ids.get(id) === reservation) ids.delete(id);
@@ -315,35 +382,147 @@ function createEngine(environment) {
315
382
  }
316
383
  };
317
384
  }
385
+ // src/adapters/export/gif-export.ts
386
+ function gifFrames(plan) {
387
+ return plan.animation === null ? [0] : plan.animation.frames.map((frame) => frame.delay);
388
+ }
389
+ async function exportGif(plan, workers, signal, onProgress) {
390
+ const delays = gifFrames(plan);
391
+ let started = false;
392
+ try {
393
+ for (const [index, delay] of delays.entries()) {
394
+ throwIfAborted(signal);
395
+ const frame = await workers.render(index, delays.length, signal);
396
+ if (!started) {
397
+ await workers.start(frame.width, frame.height, signal);
398
+ started = true;
399
+ }
400
+ throwIfAborted(signal);
401
+ await workers.write(frame, delay, signal);
402
+ onProgress?.((index + 1) / (delays.length + 1));
403
+ }
404
+ throwIfAborted(signal);
405
+ const blob = await workers.finish(signal);
406
+ onProgress?.(1);
407
+ return blob;
408
+ } finally {
409
+ if (started) await workers.abandon();
410
+ }
411
+ }
318
412
  // src/adapters/image-processor.ts
319
413
  var FORMATS = /* @__PURE__ */ new Set([
320
414
  "png",
321
415
  "jpeg",
322
- "webp"
416
+ "webp",
417
+ "gif"
323
418
  ]);
324
419
  function createImageProcessor(engine) {
325
420
  const internals = engineInternals(engine);
326
421
  if (!internals) throw new TypeError("createImageProcessor needs an engine from createImageEngine.");
327
422
  let destroyed = false;
423
+ let current;
424
+ const jobClients = /* @__PURE__ */ new Set();
425
+ let jobs = 0;
426
+ const acquire = async () => {
427
+ if (!current) {
428
+ const loaded = await internals.loadJobWorker();
429
+ if (destroyed) throw new Error("The image processor has been destroyed.");
430
+ current ??= {
431
+ client: createWorkerClient({
432
+ createWorker: loaded.start,
433
+ errorClasses: { ImageError },
434
+ packageVersion: internals.version,
435
+ workerAsset: loaded.asset
436
+ }),
437
+ active: 0,
438
+ retired: false
439
+ };
440
+ jobClients.add(current);
441
+ }
442
+ current.active += 1;
443
+ return current;
444
+ };
445
+ const release = (entry, finished) => {
446
+ entry.active -= 1;
447
+ if (!finished) {
448
+ entry.retired = true;
449
+ if (current === entry) current = void 0;
450
+ }
451
+ if (entry.retired && entry.active === 0) {
452
+ entry.client.destroy();
453
+ jobClients.delete(entry);
454
+ }
455
+ };
456
+ const gifWorkers = (client, plan, limits) => {
457
+ jobs += 1;
458
+ const id = `gif-${jobs}`;
459
+ const loop = plan.animation?.loop ?? null;
460
+ return {
461
+ render: (frame, count, signal) => internals.call("frame", {
462
+ plan,
463
+ frame,
464
+ count,
465
+ limits
466
+ }, { signal }),
467
+ start: (width, height, signal) => client.call("gifStart", {
468
+ id,
469
+ width,
470
+ height,
471
+ loop
472
+ }, { signal }),
473
+ write: (frame, delay, signal) => client.call("gifFrame", {
474
+ id,
475
+ pixels: frame.pixels,
476
+ delay
477
+ }, {
478
+ signal,
479
+ transfer: true
480
+ }),
481
+ finish: (signal) => client.call("gifFinish", { id }, { signal }),
482
+ abandon: () => client.call("gifAbandon", { id }).catch(() => void 0)
483
+ };
484
+ };
328
485
  return {
329
486
  async export(job, options) {
330
487
  if (destroyed) throw new Error("The image processor has been destroyed.");
331
- const { plan, format } = job;
488
+ const { plan, format, frame = 0 } = job;
332
489
  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) {
490
+ if ((format.type === "jpeg" || format.type === "webp") && format.quality !== void 0) {
334
491
  if (!(format.quality >= 0 && format.quality <= 1)) throw new RangeError("quality must be from 0 to 1.");
335
492
  }
493
+ checkFrame$1(plan, frame);
336
494
  internals.check();
337
495
  const missing = [plan.base.source, ...layerSources(plan)].find((id) => !internals.has(id));
338
496
  if (missing !== void 0) throw new TypeError(`There's no source with the id "${missing}".`);
339
497
  const signal = options?.signal;
340
498
  throwIfAborted(signal);
341
499
  const policy = options?.filePolicy ?? imageLimits.resolve();
500
+ const limits = Object.fromEntries(OUTPUT_LIMITS.map((limit) => [limit, policy.limits[limit].maximum]));
501
+ if (format.type === "gif") {
502
+ let entry;
503
+ let finished = false;
504
+ try {
505
+ entry = await acquire();
506
+ const blob = await exportGif(plan, gifWorkers(entry.client, plan, {
507
+ ...limits,
508
+ maxDecodedSize: policy.limits.maxDecodedSize.maximum
509
+ }), signal ?? new AbortController().signal, options?.onProgress);
510
+ finished = true;
511
+ internals.check();
512
+ return blob;
513
+ } catch (error) {
514
+ if (error instanceof TypeError) throw error;
515
+ throw asImageError(error);
516
+ } finally {
517
+ if (entry) release(entry, finished);
518
+ }
519
+ }
342
520
  try {
343
521
  const blob = await internals.call("export", {
344
522
  plan,
345
523
  format,
346
- limits: Object.fromEntries(OUTPUT_LIMITS.map((limit) => [limit, policy.limits[limit].maximum]))
524
+ frame,
525
+ limits
347
526
  }, signal ? { signal } : {});
348
527
  options?.onProgress?.(1);
349
528
  internals.check();
@@ -355,9 +534,16 @@ function createImageProcessor(engine) {
355
534
  },
356
535
  async destroy() {
357
536
  destroyed = true;
537
+ for (const entry of jobClients) entry.client.destroy();
538
+ jobClients.clear();
539
+ current = void 0;
358
540
  }
359
541
  };
360
542
  }
543
+ function checkFrame$1(plan, frame) {
544
+ const frames = Math.max(1, plan.animation?.frames.length ?? 1);
545
+ if (!Number.isInteger(frame) || frame < 0 || frame >= frames) throw new RangeError(frames === 1 ? "A still has only frame 0." : `frame must be from 0 to ${frames - 1}.`);
546
+ }
361
547
  function layerSources(plan) {
362
548
  return Array.isArray(plan.layers) ? plan.layers.flatMap((layer) => layer.kind === "image" ? [layer.source] : []) : [];
363
549
  }
@@ -425,6 +611,7 @@ function createImageRenderer(engine) {
425
611
  id,
426
612
  plan: request.plan,
427
613
  view: request.view,
614
+ frame: request.view.frame ?? 0,
428
615
  limits: request.limits
429
616
  }, { signal: controller.signal }).then(() => {
430
617
  try {
@@ -481,11 +668,12 @@ function createImageRenderer(engine) {
481
668
  return Promise.reject(error);
482
669
  }
483
670
  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));
671
+ const missing = !internals.has(plan.base.source) && !(internals.drawable(plan.base.source) && plan.animation === null && plan.layers.length === 0) ? plan.base.source : layerSources(plan).find((id) => !internals.has(id));
485
672
  if (missing !== void 0) return Promise.reject(/* @__PURE__ */ new TypeError(`There's no source with the id "${missing}".`));
486
673
  const policy = options?.filePolicy ?? imageLimits.resolve();
487
674
  try {
488
675
  checkView(view);
676
+ checkFrame$1(plan, view.frame ?? 0);
489
677
  checkOutputLimits(policy, backingSize(view));
490
678
  throwIfAborted(options?.signal);
491
679
  } catch (error) {
@@ -581,6 +769,8 @@ var LAYER_KINDS = [
581
769
  "drawing",
582
770
  "arrow"
583
771
  ];
772
+ var MAX_ANIMATION_FRAMES = 4096;
773
+ var MAX_FRAME_DELAY = 65535;
584
774
  var UPRIGHT = Object.freeze({
585
775
  rotate: 0,
586
776
  flipX: false,
@@ -811,6 +1001,186 @@ function updateItems(list, updates, names, patch) {
811
1001
  })
812
1002
  };
813
1003
  }
1004
+ // src/core/operations/frames.ts
1005
+ var FRAME_NAMES = {
1006
+ unknown: "unknown-frame",
1007
+ item: "frame"
1008
+ };
1009
+ var FRAME_FIELDS = [
1010
+ "key",
1011
+ "frame",
1012
+ "delay"
1013
+ ];
1014
+ function checkDelay(value) {
1015
+ if (typeof value !== "number") invalid("malformed-command", "a delay is a number");
1016
+ if (!isWhole(value, 0, 65535)) invalid("invalid-delay", `a delay is a whole number from 0 to ${MAX_FRAME_DELAY}`);
1017
+ return value;
1018
+ }
1019
+ function checkLoop(value) {
1020
+ if (value === null) return null;
1021
+ if (typeof value !== "number") invalid("malformed-command", "a loop count is a number or null");
1022
+ if (!isWhole(value, 0, 65535)) invalid("invalid-loop", `a loop count is a whole number from 0 to ${MAX_FRAME_DELAY}, or null`);
1023
+ return value;
1024
+ }
1025
+ function checkFrame(value, frames) {
1026
+ if (!isRecord(value)) invalid("malformed-command", "a frame is an object");
1027
+ allFields(value, FRAME_FIELDS, "a frame");
1028
+ const key = checkKey(value.key);
1029
+ const { frame } = value;
1030
+ if (typeof frame !== "number") invalid("malformed-command", "a frame's frame is a number");
1031
+ if (!isWhole(frame, 0)) invalid("malformed-command", "a frame's frame is a whole number from 0");
1032
+ if (frame >= frames) invalid("invalid-frame", `the source has no frame ${frame}`);
1033
+ return {
1034
+ key,
1035
+ frame,
1036
+ delay: checkDelay(value.delay)
1037
+ };
1038
+ }
1039
+ function checkAnimation(value, frames) {
1040
+ if (!isRecord(value)) invalid("malformed-command", "an animation is an object");
1041
+ allFields(value, ["loop", "frames"], "an animation");
1042
+ const loop = checkLoop(value.loop);
1043
+ if (!Array.isArray(value.frames)) invalid("malformed-command", "an animation's frames are a list");
1044
+ if (value.frames.length === 0 || value.frames.length > 4096) invalid("malformed-command", `an animation has 1 to ${MAX_ANIMATION_FRAMES} frames`);
1045
+ if (frames < 2) invalid("not-animated", "a source with one frame has no animation");
1046
+ return {
1047
+ loop,
1048
+ frames: value.frames.map((frame) => checkFrame(frame, frames))
1049
+ };
1050
+ }
1051
+ function animationOf(plan) {
1052
+ if (plan.animation === null) invalid("not-animated", "the plan has no animation");
1053
+ return plan.animation;
1054
+ }
1055
+ var withFrames = (plan, frames) => ({
1056
+ ...plan,
1057
+ animation: {
1058
+ loop: animationOf(plan).loop,
1059
+ frames
1060
+ }
1061
+ });
1062
+ function checkRoom$1(count) {
1063
+ if (count > 4096) invalid("too-many-frames", `an animation has at most ${MAX_ANIMATION_FRAMES} frames`);
1064
+ }
1065
+ function some$1(value, what) {
1066
+ if (!Array.isArray(value)) invalid("malformed-command", `${what} is a list`);
1067
+ if (value.length === 0) invalid("malformed-command", `${what} has at least one item`);
1068
+ return value;
1069
+ }
1070
+ function insertFrames(plan, at, value, taken, sourceFrames) {
1071
+ const animation = animationOf(plan);
1072
+ const frames = some$1(value, "frames").map((frame) => checkFrame(frame, sourceFrames));
1073
+ const { list, keys } = insertItems(animation.frames, at, frames, taken);
1074
+ checkRoom$1(list.length);
1075
+ return {
1076
+ state: withFrames(plan, list),
1077
+ inverse: {
1078
+ type: "image.removeFrames",
1079
+ keys
1080
+ }
1081
+ };
1082
+ }
1083
+ function removeFrames(plan, keys) {
1084
+ const { list, entries } = removeItems(animationOf(plan).frames, keys, FRAME_NAMES);
1085
+ if (list.length === 0) invalid("no-frames", "an animation keeps at least one frame");
1086
+ return {
1087
+ state: withFrames(plan, list),
1088
+ inverse: {
1089
+ type: "image.restoreFrames",
1090
+ entries: entries.map(({ at, item }) => ({
1091
+ at,
1092
+ frame: item
1093
+ }))
1094
+ }
1095
+ };
1096
+ }
1097
+ function restoreFrames(plan, value, taken, sourceFrames) {
1098
+ const animation = animationOf(plan);
1099
+ const entries = some$1(value, "entries").map((entry) => {
1100
+ if (!isRecord(entry)) invalid("malformed-command", "an entry is an object");
1101
+ allFields(entry, ["at", "frame"], "an entry");
1102
+ return {
1103
+ at: entry.at,
1104
+ item: checkFrame(entry.frame, sourceFrames)
1105
+ };
1106
+ });
1107
+ const { list, keys } = restoreItems(animation.frames, entries, taken);
1108
+ checkRoom$1(list.length);
1109
+ return {
1110
+ state: withFrames(plan, list),
1111
+ inverse: {
1112
+ type: "image.removeFrames",
1113
+ keys
1114
+ }
1115
+ };
1116
+ }
1117
+ function moveFrames(plan, keys, to) {
1118
+ const { list, order } = moveItems(animationOf(plan).frames, keys, to, FRAME_NAMES);
1119
+ return {
1120
+ state: withFrames(plan, list),
1121
+ inverse: {
1122
+ type: "image.setFrameOrder",
1123
+ keys: order
1124
+ }
1125
+ };
1126
+ }
1127
+ function setFrameOrder(plan, keys) {
1128
+ const { list, order } = orderItems(animationOf(plan).frames, keys, FRAME_NAMES);
1129
+ return {
1130
+ state: withFrames(plan, list),
1131
+ inverse: {
1132
+ type: "image.setFrameOrder",
1133
+ keys: order
1134
+ }
1135
+ };
1136
+ }
1137
+ function reverseFrames(plan) {
1138
+ return {
1139
+ state: withFrames(plan, [...animationOf(plan).frames].reverse()),
1140
+ inverse: { type: "image.reverseFrames" }
1141
+ };
1142
+ }
1143
+ function patchFrame(item, props) {
1144
+ if (!isRecord(props)) invalid("malformed-command", "an update's props are an object");
1145
+ onlyFields(props, ["delay"], "a frame's props");
1146
+ if (!Object.hasOwn(props, "delay")) return {
1147
+ item,
1148
+ previous: {}
1149
+ };
1150
+ return {
1151
+ item: {
1152
+ ...item,
1153
+ delay: checkDelay(props["delay"])
1154
+ },
1155
+ previous: { delay: item.delay }
1156
+ };
1157
+ }
1158
+ function updateFrames(plan, updates) {
1159
+ const { list, previous } = updateItems(animationOf(plan).frames, updates, FRAME_NAMES, patchFrame);
1160
+ return {
1161
+ state: withFrames(plan, list),
1162
+ inverse: {
1163
+ type: "image.updateFrames",
1164
+ updates: previous
1165
+ }
1166
+ };
1167
+ }
1168
+ function setLoop(plan, value) {
1169
+ const animation = animationOf(plan);
1170
+ return {
1171
+ state: {
1172
+ ...plan,
1173
+ animation: {
1174
+ ...animation,
1175
+ loop: checkLoop(value)
1176
+ }
1177
+ },
1178
+ inverse: {
1179
+ type: "image.setLoop",
1180
+ loop: animation.loop
1181
+ }
1182
+ };
1183
+ }
814
1184
  // src/core/operations/redactions.ts
815
1185
  var REDACTION_NAMES = {
816
1186
  unknown: "unknown-redaction",
@@ -1376,14 +1746,39 @@ var COMMAND_FIELDS = {
1376
1746
  ],
1377
1747
  "image.updateRedactions": ["type", "updates"],
1378
1748
  "image.restoreRedactions": ["type", "entries"],
1379
- "image.setRedactionOrder": ["type", "keys"]
1749
+ "image.setRedactionOrder": ["type", "keys"],
1750
+ "image.insertFrames": [
1751
+ "type",
1752
+ "at",
1753
+ "frames"
1754
+ ],
1755
+ "image.removeFrames": ["type", "keys"],
1756
+ "image.moveFrames": [
1757
+ "type",
1758
+ "keys",
1759
+ "to"
1760
+ ],
1761
+ "image.reverseFrames": ["type"],
1762
+ "image.updateFrames": ["type", "updates"],
1763
+ "image.setLoop": ["type", "loop"],
1764
+ "image.restoreFrames": ["type", "entries"],
1765
+ "image.setFrameOrder": ["type", "keys"]
1380
1766
  };
1381
1767
  function planKeys(plan) {
1382
- return new Set([...plan.layers, ...plan.redactions].map((item) => item.key));
1768
+ return new Set([
1769
+ ...plan.layers,
1770
+ ...plan.redactions,
1771
+ ...plan.animation?.frames ?? []
1772
+ ].map((item) => item.key));
1383
1773
  }
1384
1774
  function checkRoom(plan, added) {
1385
1775
  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
1776
  }
1777
+ function sourceFrames(plan, sourceSize) {
1778
+ const source = sourceSize(plan.base.source);
1779
+ if (source === void 0) invalid("unknown-source", `unknown source "${plan.base.source}"`);
1780
+ return source.frames ?? 1;
1781
+ }
1387
1782
  function checkLayers(value, sourceSize) {
1388
1783
  if (!Array.isArray(value)) invalid("malformed-command", "layers is a list");
1389
1784
  if (value.length === 0) invalid("malformed-command", "layers has at least one item");
@@ -1706,6 +2101,14 @@ function apply(plan, input, sourceSize) {
1706
2101
  }
1707
2102
  };
1708
2103
  }
2104
+ case "image.insertFrames": return insertFrames(plan, command.at, command.frames, planKeys(plan), plan.animation === null ? 1 : sourceFrames(plan, sourceSize));
2105
+ case "image.removeFrames": return removeFrames(plan, command.keys);
2106
+ case "image.restoreFrames": return restoreFrames(plan, command.entries, planKeys(plan), plan.animation === null ? 1 : sourceFrames(plan, sourceSize));
2107
+ case "image.moveFrames": return moveFrames(plan, command.keys, command.to);
2108
+ case "image.setFrameOrder": return setFrameOrder(plan, command.keys);
2109
+ case "image.reverseFrames": return reverseFrames(plan);
2110
+ case "image.updateFrames": return updateFrames(plan, command.updates);
2111
+ case "image.setLoop": return setLoop(plan, command.loop);
1709
2112
  }
1710
2113
  }
1711
2114
  function createImageReducer(sourceSize) {
@@ -2451,6 +2854,10 @@ function fittedImageSize(plan, source, image) {
2451
2854
  height: image.height * scale
2452
2855
  };
2453
2856
  }
2857
+ // src/core/ports/image-processor.ts
2858
+ function keepsFields(format) {
2859
+ return format === "png" || format === "jpeg";
2860
+ }
2454
2861
  // src/core/session/session.ts
2455
2862
  function sourcesIn(command) {
2456
2863
  const of = (layer) => layer.kind === "image" && typeof layer.source === "string" ? [layer.source] : [];
@@ -2487,6 +2894,43 @@ function defaultLayer(source, plan, base) {
2487
2894
  };
2488
2895
  }
2489
2896
  var same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
2897
+ function animationCommands(from, to) {
2898
+ const commands = [];
2899
+ if (from.loop !== to.loop) commands.push({
2900
+ type: "image.setLoop",
2901
+ loop: to.loop
2902
+ });
2903
+ if (same(from.frames, to.frames)) return commands;
2904
+ const before = new Set(from.frames.map((frame) => frame.key));
2905
+ const after = new Set(to.frames.map((frame) => frame.key));
2906
+ const added = to.frames.filter((frame) => !before.has(frame.key));
2907
+ const removed = from.frames.filter((frame) => !after.has(frame.key)).map((frame) => frame.key);
2908
+ if (added.length > 0) commands.push({
2909
+ type: "image.insertFrames",
2910
+ at: from.frames.length,
2911
+ frames: added
2912
+ });
2913
+ if (removed.length > 0) commands.push({
2914
+ type: "image.removeFrames",
2915
+ keys: removed
2916
+ });
2917
+ const order = [...from.frames.filter((frame) => after.has(frame.key)).map((frame) => frame.key), ...added.map((frame) => frame.key)];
2918
+ const wanted = to.frames.map((frame) => frame.key);
2919
+ if (!same(order, wanted)) commands.push({
2920
+ type: "image.setFrameOrder",
2921
+ keys: wanted
2922
+ });
2923
+ const delays = new Map(from.frames.map((frame) => [frame.key, frame.delay]));
2924
+ const updates = to.frames.filter((frame) => delays.has(frame.key) && delays.get(frame.key) !== frame.delay).map((frame) => ({
2925
+ key: frame.key,
2926
+ props: { delay: frame.delay }
2927
+ }));
2928
+ if (updates.length > 0) commands.push({
2929
+ type: "image.updateFrames",
2930
+ updates
2931
+ });
2932
+ return commands;
2933
+ }
2490
2934
  function commandsBetween(from, to) {
2491
2935
  const commands = [];
2492
2936
  if (!same(from.base.crop, to.base.crop)) commands.push({
@@ -2526,6 +2970,7 @@ function commandsBetween(from, to) {
2526
2970
  layers: to.layers
2527
2971
  });
2528
2972
  }
2973
+ if (from.animation !== null && to.animation !== null) commands.push(...animationCommands(from.animation, to.animation));
2529
2974
  if (!same(from.redactions, to.redactions)) {
2530
2975
  if (from.redactions.length > 0) commands.push({
2531
2976
  type: "image.removeRedactions",
@@ -2547,9 +2992,24 @@ var PRESENCE = [
2547
2992
  "colourProfile",
2548
2993
  "other"
2549
2994
  ];
2995
+ function planFor(info) {
2996
+ const plan = createPlan(info.id);
2997
+ if (info.timing === null || info.frames < 2) return plan;
2998
+ return {
2999
+ ...plan,
3000
+ animation: {
3001
+ loop: info.timing.loop,
3002
+ frames: info.timing.delays.map((delay, frame) => ({
3003
+ key: `frame-${frame + 1}`,
3004
+ frame,
3005
+ delay
3006
+ }))
3007
+ }
3008
+ };
3009
+ }
2550
3010
  var decodedBytes = (probe) => probe.oriented.width * probe.oriented.height * 4;
2551
- function checkSource(policy, file, probe) {
2552
- const near = checkFileLimits(policy, file.size, probe);
3011
+ function checkSource(policy, file, probe, frames) {
3012
+ const near = checkFileLimits(policy, file.size, probe, frames);
2553
3013
  const bytes = decodedBytes(probe);
2554
3014
  if (policy.check("maxSessionSize", bytes) === "warning") near.push("maxSessionSize");
2555
3015
  return near;
@@ -2566,6 +3026,8 @@ function createImageSession(options) {
2566
3026
  let plan = null;
2567
3027
  let opens = 0;
2568
3028
  let opening = 0;
3029
+ let progress = null;
3030
+ let openingFrame = null;
2569
3031
  let exporting = 0;
2570
3032
  let inserting = 0;
2571
3033
  let generation = 0;
@@ -2583,6 +3045,8 @@ function createImageSession(options) {
2583
3045
  historyTrimmed: history.trimmed,
2584
3046
  inserting: !destroyed && inserting > 0,
2585
3047
  opening: !destroyed && opening > 0,
3048
+ progress: !destroyed && opening > 0 ? progress : null,
3049
+ openingFrame: !destroyed && opening > 0 ? openingFrame : null,
2586
3050
  exporting: !destroyed && exporting > 0,
2587
3051
  warnings,
2588
3052
  error
@@ -2625,21 +3089,21 @@ function createImageSession(options) {
2625
3089
  for (const [id, extra] of extras) if (!without.has(id)) bytes += extra.decodedBytes;
2626
3090
  return bytes;
2627
3091
  };
2628
- const fits = (bytes) => {
3092
+ const fits = (limit, value) => {
2629
3093
  try {
2630
- return policy.check("maxSessionSize", bytes);
3094
+ return policy.check(limit, value);
2631
3095
  } catch {
2632
3096
  return false;
2633
3097
  }
2634
3098
  };
2635
3099
  const makeRoom = (bytes) => {
2636
3100
  const warned = (outcome) => outcome === "warning" ? ["maxSessionSize"] : [];
2637
- const now = fits(heldBytes() + bytes);
3101
+ const now = fits("maxSessionSize", heldBytes() + bytes);
2638
3102
  if (now !== false) return warned(now);
2639
3103
  for (let dropped = 1; dropped <= history.dropOrder.length; dropped += 1) {
2640
3104
  const kept = referenced(dropped);
2641
3105
  const freed = new Set([...extras.keys()].filter((id) => !kept.has(id)));
2642
- const after = fits(heldBytes(freed) + bytes);
3106
+ const after = fits("maxSessionSize", heldBytes(freed) + bytes);
2643
3107
  if (after === false) continue;
2644
3108
  history.drop(dropped);
2645
3109
  releaseUnreferenced();
@@ -2653,6 +3117,8 @@ function createImageSession(options) {
2653
3117
  if (source) checkOutputLimits(policy, outputSize(state.output, compositionSize(state, source)));
2654
3118
  const items = state.layers.length + state.redactions.length;
2655
3119
  if (items > from.layers.length + from.redactions.length) policy.check("maxLayers", items);
3120
+ const frames = state.animation?.frames.length ?? 0;
3121
+ if (frames > (from.animation?.frames.length ?? 0)) policy.check("maxFrames", frames);
2656
3122
  const points = drawingPoints(state);
2657
3123
  if (points > drawingPoints(from)) policy.check("maxDrawingPoints", points);
2658
3124
  return {
@@ -2752,14 +3218,44 @@ function createImageSession(options) {
2752
3218
  policy.check("maxFileSize", file.size);
2753
3219
  const probe = await engine.probe(file, { signal });
2754
3220
  throwIfAborted(signal);
2755
- const near = checkSource(policy, file, probe);
3221
+ const wanted = probe.frames > 1 && options.animations !== false;
3222
+ const limits = wanted ? animationLimits(policy, probe, MAX_ANIMATION_FRAMES) : {
3223
+ over: [],
3224
+ near: []
3225
+ };
3226
+ const animated = wanted && limits.over.length === 0;
3227
+ const near = [...checkSource(policy, file, probe, animated ? "all" : "first")];
3228
+ for (const limit of [...limits.over, ...limits.near]) if (!near.includes(limit)) near.push(limit);
2756
3229
  if (ticket !== opens) throw superseded();
2757
3230
  const info = await engine.register(id, file, probe, {
2758
3231
  filePolicy: policy,
2759
- signal
3232
+ signal,
3233
+ ...animated ? {
3234
+ frames: "all",
3235
+ onFirstFrame: () => {
3236
+ if (ticket !== opens || destroyed) return;
3237
+ openingFrame = {
3238
+ source: id,
3239
+ width: probe.oriented.width,
3240
+ height: probe.oriented.height
3241
+ };
3242
+ publish();
3243
+ },
3244
+ onProgress: (fraction) => {
3245
+ if (ticket !== opens || destroyed) return;
3246
+ const done = Math.round(fraction * probe.frames);
3247
+ if (progress?.done === done) return;
3248
+ progress = {
3249
+ done,
3250
+ total: probe.frames
3251
+ };
3252
+ publish();
3253
+ }
3254
+ } : {}
2760
3255
  });
2761
3256
  registered = true;
2762
3257
  throwIfAborted(signal);
3258
+ if (info.frames > 1) policy.check("maxSessionSize", info.decodedBytes);
2763
3259
  return {
2764
3260
  probe,
2765
3261
  near,
@@ -2773,9 +3269,10 @@ function createImageSession(options) {
2773
3269
  ...info,
2774
3270
  fileSize: file.size,
2775
3271
  metadata: probe.metadata,
2776
- keepable: probe.keepable
3272
+ keepable: probe.keepable,
3273
+ fileFrames: probe.frames
2777
3274
  };
2778
- plan = createPlan(id);
3275
+ plan = planFor(info);
2779
3276
  history.clear();
2780
3277
  generation += 1;
2781
3278
  warnings = near;
@@ -2801,6 +3298,10 @@ function createImageSession(options) {
2801
3298
  throw failure;
2802
3299
  } finally {
2803
3300
  opening -= 1;
3301
+ if (ticket === opens) {
3302
+ progress = null;
3303
+ openingFrame = null;
3304
+ }
2804
3305
  if (!destroyed) publish();
2805
3306
  }
2806
3307
  },
@@ -2820,7 +3321,7 @@ function createImageSession(options) {
2820
3321
  policy.check("maxFileSize", file.size);
2821
3322
  const probe = await engine.probe(file, { signal });
2822
3323
  throwIfAborted(signal);
2823
- checkFileLimits(policy, file.size, probe);
3324
+ checkFileLimits(policy, file.size, probe, "first");
2824
3325
  const info = await engine.register(id, file, probe, {
2825
3326
  filePolicy: policy,
2826
3327
  signal
@@ -2834,14 +3335,15 @@ function createImageSession(options) {
2834
3335
  }, insertOptions);
2835
3336
  assertAlive();
2836
3337
  if (started !== generation || plan === null || source === null) throw superseded();
2837
- const near = checkFileLimits(policy, file.size, probe);
3338
+ const near = checkFileLimits(policy, file.size, probe, "first");
2838
3339
  if (policy.check("maxFiles", extras.size + 2) === "warning") near.push("maxFiles");
2839
3340
  near.push(...makeRoom(info.decodedBytes));
2840
3341
  const added = {
2841
3342
  ...info,
2842
3343
  fileSize: file.size,
2843
3344
  metadata: probe.metadata,
2844
- keepable: probe.keepable
3345
+ keepable: probe.keepable,
3346
+ fileFrames: probe.frames
2845
3347
  };
2846
3348
  extras.set(id, added);
2847
3349
  held = true;
@@ -2883,7 +3385,22 @@ function createImageSession(options) {
2883
3385
  execute: (input) => executeCommands(input),
2884
3386
  applyPlan(next) {
2885
3387
  assertAlive();
2886
- const shaped = Array.isArray(next.redactions) && Array.isArray(next.layers) && next.animation === null;
3388
+ const shaped = Array.isArray(next.redactions) && Array.isArray(next.layers) && (next.animation === null || typeof next.animation === "object");
3389
+ if (plan !== null && shaped && next.animation === null !== (plan.animation === null)) {
3390
+ const failure = new ImageError("INVALID_COMMAND", plan.animation === null ? "The open image isn't an animation." : "The open image is an animation, and the plan has none.", { details: { reason: plan.animation === null ? "not-animated" : "no-frames" } });
3391
+ error = failure;
3392
+ publish();
3393
+ throw failure;
3394
+ }
3395
+ if (plan !== null && shaped && next.base.source === plan.base.source) {
3396
+ const before = new Map(plan.animation?.frames.map((frame) => [frame.key, frame.frame]));
3397
+ if (next.animation?.frames.find((frame) => before.has(frame.key) && before.get(frame.key) !== frame.frame)) {
3398
+ const failure = new ImageError("INVALID_COMMAND", "A frame can't show another frame of the source and keep its key.", { details: { reason: "duplicate-key" } });
3399
+ error = failure;
3400
+ publish();
3401
+ throw failure;
3402
+ }
3403
+ }
2887
3404
  if (plan === null || !shaped || next.base.source !== plan.base.source) {
2888
3405
  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
3406
  error = failure;
@@ -2915,7 +3432,8 @@ function createImageSession(options) {
2915
3432
  throwIfAborted(signal);
2916
3433
  const blob = await processor.export({
2917
3434
  plan: exported,
2918
- format
3435
+ format,
3436
+ ...exportOptions.frame === void 0 ? {} : { frame: exportOptions.frame }
2919
3437
  }, {
2920
3438
  filePolicy: policy,
2921
3439
  signal,
@@ -2936,7 +3454,7 @@ function createImageSession(options) {
2936
3454
  width: size.width,
2937
3455
  height: size.height,
2938
3456
  removed: PRESENCE.filter((kind) => from.metadata[kind]),
2939
- kept: Object.keys(exported.metadata).filter((field) => exported.metadata[field] !== "")
3457
+ kept: !keepsFields(format.type) ? [] : Object.keys(exported.metadata).filter((field) => exported.metadata[field] !== "")
2940
3458
  };
2941
3459
  } catch (reason) {
2942
3460
  const failure = isImageError(reason) ? reason : asImageError(reason);
@@ -2985,6 +3503,7 @@ var imageMessages = /* @__PURE__ */ defineMessages({
2985
3503
  one: "This animation has {actual, number} frames, which is over the {maximum}-frame limit.",
2986
3504
  other: "This animation has {actual, number} frames, which is over the {maximum, number}-frame limit."
2987
3505
  }),
3506
+ "errors.ANIMATION_TOO_LARGE": "This animation is too large to open with all its frames. Its first frame can still be opened.",
2988
3507
  "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
3508
  "errors.TOO_MANY_LAYERS": /* @__PURE__ */ plural("maximum", {
2990
3509
  one: "An image can have {maximum} layer. Merge or delete layers, and try again.",
@@ -2997,6 +3516,7 @@ var imageMessages = /* @__PURE__ */ defineMessages({
2997
3516
  one: "This animation has {actual} frame.",
2998
3517
  other: "This animation has {actual, number} frames, and may be slow to edit and export."
2999
3518
  }),
3519
+ "warnings.maxAnimationPixels": "This animation is large, and may be slow to play, edit and export.",
3000
3520
  "warnings.maxSessionSize": "The open images use {actual, fileSize} of memory. Clearing the undo history frees memory.",
3001
3521
  "warnings.maxLayers": /* @__PURE__ */ plural("actual", {
3002
3522
  one: "This image has {actual} layer.",
@@ -3004,6 +3524,6 @@ var imageMessages = /* @__PURE__ */ defineMessages({
3004
3524
  }),
3005
3525
  "warnings.maxDrawingPoints": "This image has a lot of drawing, and may be slow to edit and export."
3006
3526
  });
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 };
3527
+ export { checkCrop as $, dragHandle as A, createImageRenderer as At, outputSize as B, PER_FILE_LIMITS as Bt, drawingBounds as C, MAX_SCENE_COORDINATE as Ct, aspectRatio as D, REDACTION_MODES as Dt, ASPECT_PRESETS as E, NEUTRAL_DEVELOP as Et, wholeCrop as F, createImageProcessor as Ft, checkOrientation as G, imageLimits as Gt, checkDevelop as H, checkFileLimits as Ht, compositionSize as I, createImageEngine as It, FORBIDDEN_IN_TEXT as J, isImageError as Jt, checkOutput as K, asImageError as Kt, compositionToSource as L, engineInternals as Lt, handleInSource as M, backingSize as Mt, moveCrop as N, fittedView as Nt, compositionDeltaToSource as O, UPRIGHT as Ot, nudgeCropOnScreen as P, placement as Pt, Invalid as Q, cropRect as R, ANIMATION_LIMITS as Rt, arrowOutline as S, MAX_RUN_POINTS as St, simplifyStroke as T, MAX_STROKE_WIDTH as Tt, checkFilter as U, checkOutputLimits as Ut, sourceToComposition as V, animationLimits as Vt, checkMetadata as W, imageLimitDefinitions as Wt, checkRedaction as X, checkLayer as Y, checkAnimation as Z, layerToScene as _, MAX_FRAME_DELAY as _t, compositionRectToScene as a, MAX_METADATA_LENGTH as at, createImageKey as b, MAX_LAYER_TEXT_LENGTH as bt, redactionBlocksInOutput as c, DEVELOP_ADJUSTMENTS as ct, sceneRectToComposition as d, LAYER_ALIGNMENTS as dt, checkCropInSource as et, applyMatrix as f, LAYER_FONTS as ft, layerToOutput as g, MAX_DRAWING_STROKES as gt, isRightToLeft as h, MAX_ANIMATION_FRAMES as ht, newLayerBox as i, EMPTY_KEEPABLE_METADATA as it, fitAspect as j, MAX_PIXEL_RATIO as jt, cropInComposition as k, createPlan as kt, redactionBlocksInScene as l, FILTER_PRESETS as lt, invertMatrix as m, LAYER_SHAPES as mt, createImageSession as n, isRecord as nt, fitRedactionRegion as o, NO_METADATA as ot, fitTextLines as p, LAYER_KINDS as pt, createImageReducer as q, ImageError as qt, keepsFields as r, onlyFields as rt, redactionBlockSize as s, longerThan as st, imageMessages as t, invalid as tt, redactionRectInOutput as u, FULL_SIZE as ut, sceneToLayerSource as v, MAX_KEY_LENGTH as vt, drawingPoints as w, MAX_STROKE_RUNS as wt, arrowBounds as x, MAX_PLAN_ITEMS as xt, sceneToOutput as y, MAX_LAYER_NAME_LENGTH as yt, orientedSize as z, OUTPUT_LIMITS as zt };
3008
3528
 
3009
- //# sourceMappingURL=core-DKUm3jGZ.js.map
3529
+ //# sourceMappingURL=core-A001a7oa.js.map