@hussmartinez/image-sdk 0.6.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.
- package/NOTICE +35 -0
- package/README.md +30 -2
- package/dist/assets/image/job.worker.js +1 -0
- package/dist/assets/image/render.worker.js +2 -2
- package/dist/element.d.ts +309 -9
- package/dist/element.js +3 -2
- package/dist/element.js.map +1 -1
- package/dist/index.d.ts +347 -22
- package/dist/index.js +52 -23
- package/dist/index.js.map +1 -1
- package/dist/lazy/inline-job-worker-2EbG2Vzb.js +30 -0
- package/dist/lazy/inline-job-worker-2EbG2Vzb.js.map +1 -0
- package/dist/lazy/inline-worker-DdS6iQ9X.js +30 -0
- package/dist/lazy/{inline-worker-COOlwTsC.js.map → inline-worker-DdS6iQ9X.js.map} +1 -1
- package/dist/react.d.ts +358 -10
- package/dist/react.js +1 -1
- package/dist/shared/{core-VHeENp7j.js → core-A001a7oa.js} +557 -37
- package/dist/shared/core-A001a7oa.js.map +1 -0
- package/dist/shared/{editor-Bj9Xo5nf.js → editor-CV39S-zb.js} +3112 -2375
- package/dist/shared/editor-CV39S-zb.js.map +1 -0
- package/dist/styles.css +154 -0
- package/formats/hm-image-command/v4.schema.json +418 -0
- package/formats/hm-image-plan/v4.schema.json +1114 -0
- package/package.json +4 -2
- package/dist/lazy/inline-worker-COOlwTsC.js +0 -30
- package/dist/shared/core-VHeENp7j.js.map +0 -1
- package/dist/shared/editor-Bj9Xo5nf.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"core-VHeENp7j.js","names":["clamp"],"sources":["../../src/core/errors/image-error.ts","../../src/core/errors/error-helpers.ts","../../src/core/errors/image-limits.ts","../../src/adapters/worker-lifecycle.ts","../../src/adapters/image-engine.ts","../../src/adapters/image-processor.ts","../../src/core/ports/image-renderer.ts","../../src/adapters/image-renderer.ts","../../src/core/model/plan.ts","../../src/core/model/source.ts","../../src/core/operations/checks.ts","../../src/core/operations/keyed-list.ts","../../src/core/operations/redactions.ts","../../src/core/operations/layers.ts","../../src/core/operations/strokes.ts","../../src/core/operations/commands.ts","../../src/core/model/geometry.ts","../../src/core/model/crop.ts","../../src/core/model/drawing-geometry.ts","../../src/core/model/keys.ts","../../src/core/model/layer-geometry.ts","../../src/core/model/redaction-geometry.ts","../../src/core/model/layer-placement.ts","../../src/core/session/session.ts","../../src/messages/en.ts"],"sourcesContent":["import { isSdkError, type SdkCoreErrorCode, SdkError } from \"@hussmartinez/sdk-core\";\n\n/**\n * Error codes of `@hussmartinez/image-sdk`: sdk-core's own codes, such as\n * `ABORTED`, `WORKER_CRASHED` and `FILE_TOO_LARGE`, plus the image SDK's\n * (ADR 0001, ADR 0004). They never change meaning once released.\n *\n * - `INVALID_IMAGE`: the file is malformed, its headers claim more than its\n * data can carry or less than its decoder would produce, or its decoded\n * size differs from what its headers declare.\n * - `UNSUPPORTED_FORMAT`: the format isn't recognised, its bound can't be\n * read, or the browser can't encode the requested export format.\n * `details.format` names it.\n * - `DECODE_FAILED`: the browser couldn't decode a file the SDK probed,\n * usually because it lacks the format. `details.format` names it.\n * - `INVALID_COMMAND`: an edit command doesn't apply to the plan, such as a\n * crop outside its source. `details.reason` says why, as a stable token\n * (`ImageCommandRejection`).\n * - `INVALID_DOCUMENT`: a plan document, such as a saved project, isn't\n * valid in its format. `details.reason` says why (`ImageDocumentRejection`).\n * A document of another format, or a later version, is `UNSUPPORTED_FORMAT`\n * instead, with `details.reason` `unknown-format` or `unknown-format-version`.\n * - `UNSUPPORTED_PLAN`: a plan holds something the renderer or processor\n * can't draw, such as a layer kind from a later release. Nothing is drawn\n * or exported without it (ADR 0009). `details.reason` names the part:\n * `layers`, `redactions` or `animation`.\n * - `IMAGE_TOO_LARGE`: an image, a frame, the canvas or the export exceeds\n * the `maxImagePixels` limit.\n * - `IMAGE_DIMENSION_TOO_LARGE`: a width or height exceeds the\n * `maxImageDimension` limit.\n * - `TOO_MANY_FRAMES`: an animation exceeds the `maxFrames` limit.\n * - `SESSION_TOO_LARGE`: the decoded images the session holds exceed the\n * `maxSessionSize` limit.\n * - `TOO_MANY_LAYERS`: the layer plan exceeds the `maxLayers` limit.\n * - `TOO_MANY_POINTS`: the plan's drawings hold more points than the\n * `maxDrawingPoints` limit.\n *\n * Limit codes carry `details` with the `limit`, its `maximum`, the `actual`\n * value and the `unit`. Other codes' `details` name the format involved,\n * and a `reason`, never data from the file.\n *\n * @public\n */\nexport type ImageErrorCode =\n | SdkCoreErrorCode\n | \"INVALID_IMAGE\"\n | \"UNSUPPORTED_FORMAT\"\n | \"DECODE_FAILED\"\n | \"INVALID_COMMAND\"\n | \"INVALID_DOCUMENT\"\n | \"UNSUPPORTED_PLAN\"\n | \"IMAGE_TOO_LARGE\"\n | \"IMAGE_DIMENSION_TOO_LARGE\"\n | \"TOO_MANY_FRAMES\"\n | \"SESSION_TOO_LARGE\"\n | \"TOO_MANY_LAYERS\"\n | \"TOO_MANY_POINTS\";\n\n/**\n * The error `@hussmartinez/image-sdk` throws and rejects with, with a stable\n * `code`, structured `details` and the underlying error as `cause`. Show\n * users the text for its code from {@link imageMessages}, never its\n * `message`, which is for developers and may contain text from the file.\n *\n * @example\n * ```ts\n * try {\n * await session.open(file);\n * } catch (error) {\n * if (isImageError(error, \"DECODE_FAILED\")) {\n * suggestConvertingToPng();\n * } else {\n * show(messages.error(error));\n * }\n * }\n * ```\n *\n * @public\n */\nexport class ImageError extends SdkError<ImageErrorCode> {\n /** Always `\"ImageError\"`, which survives minification and worker boundaries. */\n override readonly name = \"ImageError\";\n}\n\n/**\n * Checks whether a value is an {@link ImageError}, optionally with a given\n * code.\n *\n * Unlike `instanceof`, it recognises errors from another copy of this\n * package or another realm, and errors rebuilt after crossing a worker\n * boundary.\n *\n * @param value - Any thrown value.\n * @param code - When given, the error must also have this code.\n * @public\n */\nexport function isImageError<Code extends ImageErrorCode = ImageErrorCode>(\n value: unknown,\n code?: Code,\n): value is ImageError & { readonly code: Code } {\n return isSdkError(value, code) && value.name === \"ImageError\";\n}\n","import { createErrorHelpers } from \"@hussmartinez/sdk-core\";\nimport { ImageError } from \"./image-error.js\";\n\n/**\n * The SDK's error helpers, from sdk-core's `createErrorHelpers` (sdk-core\n * ADR 0034):\n *\n * - `asImageError` makes any failure an `ImageError`, as every port promises:\n * an `ImageError` as it is, another `SdkError` with its code, details and\n * message, and anything else as `UNKNOWN`, keeping the original as `cause`;\n * - `abortError` is the error an aborted call rejects with: an `SdkError`\n * reason adapted, so a file policy's `PROCESSING_TIME_EXCEEDED` keeps its\n * code, `TIMEOUT` for a timeout, and `ABORTED` otherwise;\n * - `throwIfAborted` throws `abortError` if the signal has aborted.\n *\n * @internal\n */\nexport const {\n adapt: asImageError,\n abortError,\n throwIfAborted,\n} = createErrorHelpers(ImageError, {\n fallbackCode: \"UNKNOWN\",\n fallbackMessage: \"Image processing failed.\",\n});\n","import {\n coreLimits,\n defineLimits,\n type FilePolicy,\n type FilePolicyOverrides,\n type Limits,\n} from \"@hussmartinez/sdk-core\";\nimport type { ImageProbe } from \"../model/source.js\";\nimport { ImageError } from \"./image-error.js\";\n\n/**\n * The image SDK's limit definitions: sdk-core's core limits with image\n * defaults, plus five for images (ADR 0004).\n *\n * | Limit | Code | Default maximum | Default warning |\n * |---|---|---|---|\n * | `maxFileSize` | `FILE_TOO_LARGE` | 100 MB | 50 MB |\n * | `maxFiles` | `TOO_MANY_FILES` | 20 | none |\n * | `maxDecodedSize` | `DECODED_SIZE_TOO_LARGE` | 1 GB | 400 MB |\n * | `maxProcessingTime` | `PROCESSING_TIME_EXCEEDED` | 120 s | none |\n * | `maxImagePixels` | `IMAGE_TOO_LARGE` | 50 megapixels | 24 megapixels |\n * | `maxImageDimension` | `IMAGE_DIMENSION_TOO_LARGE` | 16,384 pixels | none |\n * | `maxFrames` | `TOO_MANY_FRAMES` | 300 | 100 |\n * | `maxSessionSize` | `SESSION_TOO_LARGE` | 1 GB | 500 MB |\n * | `maxLayers` | `TOO_MANY_LAYERS` | 256 | none |\n * | `maxDrawingPoints` | `TOO_MANY_POINTS` | 200,000 | 100,000 |\n *\n * Sizes are decimal: 1 MB is 1,000,000 bytes. Decoded sizes count 4 bytes\n * per pixel. `maxImagePixels` is the same limit, with the same name, code\n * and unit, as `pdf-sdk`'s. `maxImageDimension` is a side length, in pixels.\n *\n * @public\n */\nexport const imageLimitDefinitions = {\n ...coreLimits,\n maxDecodedSize: { ...coreLimits.maxDecodedSize, default: 1_000_000_000, warning: 400_000_000 },\n maxImagePixels: {\n code: \"IMAGE_TOO_LARGE\",\n unit: \"pixels\",\n default: 50_000_000,\n warning: 24_000_000,\n },\n maxImageDimension: { code: \"IMAGE_DIMENSION_TOO_LARGE\", unit: \"pixels\", default: 16_384 },\n maxFrames: { code: \"TOO_MANY_FRAMES\", unit: \"count\", default: 300, warning: 100 },\n maxSessionSize: {\n code: \"SESSION_TOO_LARGE\",\n unit: \"bytes\",\n default: 1_000_000_000,\n warning: 500_000_000,\n },\n maxLayers: { code: \"TOO_MANY_LAYERS\", unit: \"count\", default: 256 },\n maxDrawingPoints: {\n code: \"TOO_MANY_POINTS\",\n unit: \"count\",\n default: 200_000,\n warning: 100_000,\n },\n} as const;\n\n/**\n * The type of {@link imageLimitDefinitions}.\n *\n * @public\n */\nexport type ImageLimitDefinitions = typeof imageLimitDefinitions;\n\n/**\n * The names of the image SDK's limits.\n *\n * @public\n */\nexport type ImageLimitName = keyof ImageLimitDefinitions;\n\n/**\n * A host's `filePolicy`: a new maximum, or `{ maximum, warning }`, for any of\n * the image SDK's limits. `Infinity` disables a maximum, which removes a\n * protection against hostile files, or disables a warning. Unknown limit\n * names throw `TypeError` when the policy is resolved.\n *\n * @example\n * ```ts\n * // Large scans: raise the pixel and decoded sizes together.\n * const filePolicy: ImageFilePolicyOverrides = {\n * maxImagePixels: 100_000_000,\n * maxDecodedSize: { maximum: 2e9, warning: 800e6 },\n * };\n * ```\n *\n * @public\n */\nexport type ImageFilePolicyOverrides = FilePolicyOverrides<ImageLimitDefinitions>;\n\n/**\n * A resolved file policy for the image SDK. Violations throw\n * {@link ImageError}.\n *\n * @public\n */\nexport type ImageFilePolicy = FilePolicy<ImageLimitDefinitions>;\n\n/**\n * The image SDK's limits, ready to resolve a host's `filePolicy`. Violations\n * are thrown as {@link ImageError}, with `details` naming the limit.\n *\n * @example\n * ```ts\n * const policy = imageLimits.resolve(props.filePolicy);\n * policy.check(\"maxImagePixels\", width * height); // throws ImageError(\"IMAGE_TOO_LARGE\") above 50 megapixels\n * ```\n *\n * @public\n */\nexport const imageLimits: Limits<ImageLimitDefinitions> = /* @__PURE__ */ defineLimits(\n imageLimitDefinitions,\n { errorClass: ImageError },\n);\n\n/**\n * The limits that apply to one file on its own, which the engine checks\n * against its own probe before it decodes anything (ADR 0004).\n *\n * @public\n */\nexport const PER_FILE_LIMITS = [\n \"maxFileSize\",\n \"maxImageDimension\",\n \"maxImagePixels\",\n \"maxFrames\",\n \"maxDecodedSize\",\n] as const satisfies readonly ImageLimitName[];\n\n/**\n * Checks one probed file against a policy's per-file limits, in the order\n * of {@link PER_FILE_LIMITS}, and throws the first violation as an\n * `ImageError` with the limit's code (ADR 0004). Returns the limits whose\n * warning threshold the file reaches.\n *\n * @public\n */\nexport function checkFileLimits(\n policy: ImageFilePolicy,\n fileSize: number,\n probe: ImageProbe,\n): ImageLimitName[] {\n const { width, height } = probe.oriented;\n const actual: Record<(typeof PER_FILE_LIMITS)[number], number> = {\n maxFileSize: fileSize,\n maxImageDimension: Math.max(width, height),\n maxImagePixels: width * height,\n maxFrames: probe.frames,\n maxDecodedSize: probe.decodedPixelBound * 4,\n };\n return PER_FILE_LIMITS.filter((limit) => policy.check(limit, actual[limit]) === \"warning\");\n}\n\n/**\n * The limits an export's output canvas is checked against before it's\n * allocated: its longest side and its pixels (ADR 0004).\n *\n * @public\n */\nexport const OUTPUT_LIMITS = [\n \"maxImageDimension\",\n \"maxImagePixels\",\n] as const satisfies readonly ImageLimitName[];\n\n/**\n * Checks an export's output size against a policy before its canvas is\n * allocated, and throws the first violation as an `ImageError` with the\n * limit's code (ADR 0004).\n *\n * @public\n */\nexport function checkOutputLimits(\n policy: ImageFilePolicy,\n size: { readonly width: number; readonly height: number },\n): void {\n policy.check(\"maxImageDimension\", Math.max(size.width, size.height));\n policy.check(\"maxImagePixels\", size.width * size.height);\n}\n","import type { WorkerLike } from \"@hussmartinez/sdk-core\";\nimport { ImageError } from \"../core/errors/image-error.js\";\n\nexport interface WorkerGeneration {\n readonly number: number;\n closed: boolean;\n ownsResources: boolean;\n}\n\n/** Resource lifetime above the RPC connection; no original image bytes are retained. */\nexport function createWorkerLifecycle(\n clearSources: () => void,\n submitted: (id: string, generation: WorkerGeneration) => void,\n) {\n let current: WorkerGeneration | undefined;\n let sequence = 0;\n let terminal = false;\n let destroyed = false;\n const listeners = new Set<() => void>();\n const invalidated = () =>\n new ImageError(\"WORKER_TERMINATED\", \"Recreate the image engine before reopening the image.\", {\n details: { reason: \"engine-invalidated\" },\n });\n\n const check = (generation?: WorkerGeneration) => {\n if (destroyed) throw new Error(\"The image engine has been destroyed.\");\n if (terminal || (generation && (generation.closed || generation !== current)))\n throw invalidated();\n };\n\n return {\n check,\n current: () => current,\n getSnapshot: () => terminal,\n subscribe(listener: () => void) {\n const notify = () => listener();\n listeners.add(notify);\n return () => {\n listeners.delete(notify);\n };\n },\n destroy() {\n destroyed = true;\n listeners.clear();\n clearSources();\n },\n wrap(worker: WorkerLike): WorkerLike {\n check();\n const generation: WorkerGeneration = {\n number: ++sequence,\n closed: false,\n ownsResources: false,\n };\n current = generation;\n return {\n postMessage(message, transfer) {\n check(generation);\n const call = message as {\n type?: unknown;\n method?: unknown;\n input?: { id?: unknown };\n } | null;\n // sdk-core invokes this transport only after its ready/version\n // handshake. Waiting API calls have not submitted any resources.\n const resource =\n call?.type === \"call\" && (call.method === \"register\" || call.method === \"attachCanvas\");\n if (resource) generation.ownsResources = true;\n if (\n call?.type === \"call\" &&\n call.method === \"register\" &&\n typeof call.input?.id === \"string\"\n )\n submitted(call.input.id, generation);\n // Once submission begins, a post failure is not proof that no\n // resource was transferred. Keep ownership conservative.\n worker.postMessage(message, transfer);\n },\n addEventListener(type, listener) {\n worker.addEventListener(type, listener);\n },\n removeEventListener(type, listener) {\n worker.removeEventListener(type, listener);\n },\n terminate() {\n if (generation.closed) return;\n generation.closed = true;\n try {\n if (current !== generation) return;\n clearSources();\n if (destroyed || !generation.ownsResources || terminal) return;\n terminal = true;\n const notified = [...listeners];\n // Let sdk-core finish rejecting/clearing pending RPCs before a\n // binding unmounts a dialog and aborts its controllers. The latch\n // and source invalidation above are already synchronous.\n queueMicrotask(() => {\n if (destroyed) return;\n for (const listener of notified) {\n if (!listeners.has(listener)) continue;\n try {\n listener();\n } catch {\n /* A binding cannot prevent transport cleanup. */\n }\n }\n });\n } finally {\n worker.terminate();\n }\n },\n };\n },\n };\n}\n\n/** The only owned closeable RPC results are preview/thumbnail bitmaps. */\nexport function closeRejectedResult(value: unknown): void {\n if (value && typeof value === \"object\" && \"close\" in value && typeof value.close === \"function\")\n try {\n value.close();\n } catch {\n /* Cleanup must preserve the invalidation error. */\n }\n}\n","import {\n createAssetsResolver,\n createWorkerClient,\n type WorkerClient,\n type WorkerLike,\n} from \"@hussmartinez/sdk-core\";\nimport { asImageError, throwIfAborted } from \"../core/errors/error-helpers.js\";\nimport { ImageError } from \"../core/errors/image-error.js\";\nimport { imageLimits, PER_FILE_LIMITS } from \"../core/errors/image-limits.js\";\nimport type { ImageProbe, ImageSourceInfo, ImageThumbnail } from \"../core/model/source.js\";\nimport type { ImageEngine } from \"../core/ports/image-engine.js\";\nimport type { ImageCallOptions, ImageRegisterOptions } from \"../core/ports/options.js\";\nimport type { RenderWorkerContract } from \"./render-worker/contract.js\";\nimport {\n closeRejectedResult,\n createWorkerLifecycle,\n type WorkerGeneration,\n} from \"./worker-lifecycle.js\";\n\n/**\n * Options for {@link createImageEngine}.\n *\n * @public\n */\nexport interface ImageEngineOptions {\n /**\n * Where the application serves the package's `dist/assets/` directory, to\n * load the render worker from its own origin instead of a `blob:` URL. The\n * worker is then `image/render.worker.js` there, and a Content Security\n * Policy needs `worker-src 'self'` and no `blob:` (docs/adr/0002). Copy\n * `dist/assets` again after every upgrade: a worker from another version\n * is refused with `WORKER_START_FAILED`. The base may be absolute or\n * relative to the page, including during server rendering: it is checked\n * at setup and resolved only when the worker starts. By default the\n * worker is inlined.\n */\n readonly assetsUrl?: string | URL;\n}\n\n/**\n * What a processor needs from the engine whose render worker it shares\n * (docs/adr/0002): its client, once the worker has loaded, and which sources\n * it holds.\n *\n * @internal\n */\nexport interface EngineInternals {\n readonly call: WorkerClient<RenderWorkerContract>[\"call\"];\n readonly prepare: () => Promise<WorkerGeneration>;\n readonly check: (generation?: WorkerGeneration) => void;\n readonly getSnapshot: () => boolean;\n readonly subscribe: (listener: () => void) => () => void;\n readonly has: (id: string) => boolean;\n}\n\n/** Where an engine made by {@link createImageEngine} keeps its internals. */\nexport const ENGINE_INTERNALS: unique symbol = Symbol(\"hm-image-engine\");\n\n/**\n * The internals of an engine made by {@link createImageEngine}, or\n * `undefined` for any other engine.\n *\n * @internal\n */\nexport function engineInternals(engine: ImageEngine): EngineInternals | undefined {\n return (engine as { [ENGINE_INTERNALS]?: EngineInternals })[ENGINE_INTERNALS];\n}\n\n/** What the engine needs from its environment, replaceable in tests. */\nexport interface EngineEnvironment {\n /** Loads the worker's code, on the first call, and returns how to start it. */\n readonly loadWorker: () => Promise<() => WorkerLike>;\n /** The version the worker must report: this package's. */\n readonly version: string;\n /** Where the worker comes from, for the version error's details. */\n readonly asset?: string;\n}\n\n/**\n * Creates the SDK's image engine (docs/adr/0001, docs/adr/0002,\n * docs/adr/0005). It probes files in its render worker with the SDK's own\n * readers, and decodes them there with `createImageBitmap`, upright: where\n * the browser doesn't apply a format's orientation, as its one-time\n * calibration shows, the worker applies it itself. Every decode must have\n * the probe's oriented size exactly. The worker holds the sources until\n * they're released or the engine is destroyed.\n *\n * Loss of a worker that owns sources or a transferred canvas makes this\n * engine terminal (ADR 0008). Later processing rejects with\n * `WORKER_TERMINATED` and `details.reason: \"engine-invalidated\"`; explicitly\n * recreate processing resources and reopen the image. No work is replayed.\n *\n * Nothing starts until the first call. By default the worker is inlined,\n * which needs `worker-src blob:` in a Content Security Policy; with\n * `assetsUrl` it loads from your own origin, which needs `worker-src 'self'`\n * instead. Either way it makes no requests of its own.\n *\n * @example\n * ```ts\n * const engine = createImageEngine();\n * const probe = await engine.probe(file);\n * policy.check(\"maxImagePixels\", probe.oriented.width * probe.oriented.height);\n * const source = await engine.register(\"photo\", file, probe);\n * ```\n *\n * @public\n */\nexport function createImageEngine(options: ImageEngineOptions = {}): ImageEngine {\n const asset =\n options.assetsUrl === undefined ? undefined : createAssetsResolver(options.assetsUrl);\n let workerUrl: string | undefined;\n return createEngine({\n loadWorker: asset\n ? async () => () => {\n workerUrl = asset(\"image/render.worker.js\");\n return new Worker(workerUrl, { type: \"module\", name: \"hm-image-render\" });\n }\n : async () => (await import(\"./render-worker/inline-worker.js\")).createInlineWorker,\n version: __IMAGE_SDK_VERSION__,\n get asset() {\n return workerUrl ?? \"inline\";\n },\n });\n}\n\n/**\n * The engine, with its environment passed in.\n *\n * @internal\n */\nexport function createEngine(\n environment: EngineEnvironment,\n): ImageEngine & { readonly [ENGINE_INTERNALS]: EngineInternals } {\n let startWorker: (() => WorkerLike) | undefined;\n let destroyed = false;\n /** Sources the worker holds, or is decoding, by id. */\n const ids = new Map<\n string,\n { generation?: WorkerGeneration; registered: boolean; released: boolean }\n >();\n const lifecycle = createWorkerLifecycle(\n () => ids.clear(),\n (id, generation) => {\n const reservation = ids.get(id);\n if (reservation) reservation.generation = generation;\n },\n );\n\n const client: WorkerClient<RenderWorkerContract> = createWorkerClient<RenderWorkerContract>({\n createWorker: () => {\n if (!startWorker) {\n throw new ImageError(\"WORKER_START_FAILED\", \"The render worker hasn't loaded.\");\n }\n return lifecycle.wrap(startWorker());\n },\n errorClasses: { ImageError },\n // The worker holds the sources, so it lives as long as the engine, and a\n // cancelled decode may finish rather than take the sources with it.\n idleTimeout: 0,\n cancelTimeout: 30_000,\n // A self-hosted worker copied before an upgrade speaks the same protocol\n // but runs older code: sdk-core refuses it before any call, with\n // WORKER_START_FAILED and the asset and both versions (ADR 0038).\n packageVersion: environment.version,\n // Read the final asset URL after worker creation, without resolving it\n // during setup just to populate diagnostics.\n get workerAsset() {\n return environment.asset ?? \"inline\";\n },\n });\n\n async function ready(): Promise<void> {\n if (destroyed) throw new Error(\"The image engine has been destroyed.\");\n startWorker ??= await environment.loadWorker();\n }\n\n const call: WorkerClient<RenderWorkerContract>[\"call\"] = async (method, input, options) => {\n lifecycle.check();\n throwIfAborted(options?.signal);\n await ready();\n lifecycle.check();\n // Keep startup cancellation in the RPC: start() alone has no signal.\n const pending = client.call(method, input, options);\n const generation = lifecycle.current();\n const result = await pending.catch((error: unknown) => {\n throw error instanceof TypeError ? error : asImageError(error);\n });\n try {\n lifecycle.check(generation);\n } catch (error) {\n closeRejectedResult(result);\n throw error;\n }\n return result;\n };\n\n const prepare = async () => {\n lifecycle.check();\n await ready();\n lifecycle.check();\n const pending = client.start();\n const generation = lifecycle.current();\n try {\n await pending;\n } catch (error) {\n throw asImageError(error);\n }\n lifecycle.check(generation);\n if (!generation) throw new Error(\"The worker did not create a generation.\");\n return generation;\n };\n\n const callOptions = (options: ImageCallOptions | undefined) =>\n options?.signal ? { signal: options.signal } : {};\n\n return {\n [ENGINE_INTERNALS]: {\n call,\n prepare,\n check: lifecycle.check,\n getSnapshot: lifecycle.getSnapshot,\n subscribe: lifecycle.subscribe,\n has: (id) => ids.get(id)?.registered === true,\n },\n\n probe(file: Blob, options?: ImageCallOptions): Promise<ImageProbe> {\n return call(\"probe\", { file }, callOptions(options));\n },\n\n async register(\n id: string,\n file: Blob,\n probe: ImageProbe,\n options?: ImageRegisterOptions,\n ): Promise<ImageSourceInfo> {\n lifecycle.check();\n if (ids.has(id)) throw new TypeError(`The source id \"${id}\" is already in use.`);\n const reservation: { generation?: WorkerGeneration; registered: boolean; released: boolean } =\n { registered: false, released: false };\n ids.set(id, reservation);\n try {\n const size = await call(\n \"register\",\n {\n id,\n file,\n probe,\n // The maxima cross to the worker, which checks them against its\n // own probe (docs/adr/0004).\n limits: Object.fromEntries(\n PER_FILE_LIMITS.map((limit) => [\n limit,\n (options?.filePolicy ?? imageLimits.resolve()).limits[limit].maximum,\n ]),\n ) as Record<(typeof PER_FILE_LIMITS)[number], number>,\n },\n callOptions(options),\n );\n lifecycle.check(reservation.generation);\n if (reservation.released)\n throw new TypeError(\"The source was released during registration.\");\n reservation.registered = true;\n options?.onProgress?.(1);\n lifecycle.check(reservation.generation);\n return {\n id,\n format: probe.format,\n width: size.width,\n height: size.height,\n // Animations open as their first frame until the GIF decoder lands\n // (docs/adr/0001).\n frames: 1,\n hasAlpha: probe.hasAlpha,\n decodedBytes: size.width * size.height * 4,\n };\n } catch (error) {\n if (ids.get(id) === reservation) ids.delete(id);\n // A cancelled decode may still finish in the worker; release it.\n if (\n (options?.signal?.aborted || reservation.released) &&\n reservation.generation &&\n !reservation.generation.closed &&\n !destroyed &&\n !lifecycle.getSnapshot()\n ) {\n call(\"release\", { id }).catch(() => undefined);\n }\n throw error;\n }\n },\n\n async thumbnail(\n id: string,\n maxSize: number,\n options?: ImageCallOptions,\n ): Promise<ImageThumbnail> {\n lifecycle.check();\n if (!ids.get(id)?.registered) throw new TypeError(`There's no source with the id \"${id}\".`);\n if (!(maxSize >= 1)) throw new RangeError(\"maxSize must be at least 1.\");\n return call(\"thumbnail\", { id, maxSize }, callOptions(options));\n },\n\n async release(id: string): Promise<void> {\n const reservation = ids.get(id);\n if (!reservation) return;\n if (!reservation.registered) {\n reservation.released = true;\n return;\n }\n ids.delete(id);\n if (destroyed || lifecycle.getSnapshot() || reservation.generation?.closed) return;\n await call(\"release\", { id });\n },\n\n async destroy(): Promise<void> {\n if (destroyed) return;\n destroyed = true;\n lifecycle.destroy();\n client.destroy();\n },\n };\n}\n","import { asImageError, throwIfAborted } from \"../core/errors/error-helpers.js\";\nimport { imageLimits, OUTPUT_LIMITS } from \"../core/errors/image-limits.js\";\nimport type { ImagePlan } from \"../core/model/plan.js\";\nimport type { ImageEngine } from \"../core/ports/image-engine.js\";\nimport type { ImageExportJob, ImageProcessor } from \"../core/ports/image-processor.js\";\nimport type { ImageExportOptions } from \"../core/ports/options.js\";\nimport { engineInternals } from \"./image-engine.js\";\n\nconst FORMATS = new Set([\"png\", \"jpeg\", \"webp\"]);\n\n/**\n * Creates the SDK's image processor over an engine from\n * {@link createImageEngine}, sharing its render worker, where the sources\n * are (docs/adr/0002). An export renders the plan at its output size in an\n * sRGB canvas, after checking that size against the file policy, encodes\n * it with the browser's encoder, and keeps nothing of the result but the\n * image data and the fields the user kept: title, description, artist and\n * copyright, as EXIF in JPEG and `iTXt` in PNG. WebP exports carry no\n * metadata. The encoded type is checked: a browser that can't encode the\n * requested format fails with `UNSUPPORTED_FORMAT` (docs/adr/0001,\n * docs/adr/0005).\n *\n * @example\n * ```ts\n * const engine = createImageEngine();\n * const processor = createImageProcessor(engine);\n * const blob = await processor.export({ plan, format: { type: \"jpeg\", quality: 0.9 } });\n * ```\n *\n * @throws `TypeError` for an engine that `createImageEngine` didn't make.\n * @public\n */\nexport function createImageProcessor(engine: ImageEngine): ImageProcessor {\n const internals = engineInternals(engine);\n if (!internals) {\n throw new TypeError(\"createImageProcessor needs an engine from createImageEngine.\");\n }\n let destroyed = false;\n return {\n async export(job: ImageExportJob, options?: ImageExportOptions): Promise<Blob> {\n if (destroyed) throw new Error(\"The image processor has been destroyed.\");\n const { plan, format } = job;\n if (!FORMATS.has(format.type)) {\n throw new TypeError(`\"${String(format.type)}\" isn't an export format.`);\n }\n if (format.type !== \"png\" && format.quality !== undefined) {\n if (!(format.quality >= 0 && format.quality <= 1)) {\n throw new RangeError(\"quality must be from 0 to 1.\");\n }\n }\n internals.check();\n // The base's source, and every image layer's: a plan that names one\n // the engine doesn't hold is the caller's mistake, found before the worker.\n const missing = [plan.base.source, ...layerSources(plan)].find((id) => !internals.has(id));\n if (missing !== undefined) {\n throw new TypeError(`There's no source with the id \"${missing}\".`);\n }\n const signal = options?.signal;\n throwIfAborted(signal);\n const policy = options?.filePolicy ?? imageLimits.resolve();\n try {\n const blob = await internals.call(\n \"export\",\n {\n plan,\n format,\n limits: Object.fromEntries(\n OUTPUT_LIMITS.map((limit) => [limit, policy.limits[limit].maximum]),\n ) as Record<(typeof OUTPUT_LIMITS)[number], number>,\n },\n signal ? { signal } : {},\n );\n options?.onProgress?.(1);\n internals.check();\n return blob;\n } catch (error) {\n if (error instanceof TypeError) throw error;\n throw asImageError(error);\n }\n },\n\n async destroy(): Promise<void> {\n destroyed = true;\n },\n };\n}\n\n/** The ids of the sources a plan's image layers draw. */\nexport function layerSources(plan: ImagePlan): string[] {\n return Array.isArray(plan.layers)\n ? plan.layers.flatMap((layer) => (layer.kind === \"image\" ? [layer.source] : []))\n : [];\n}\n","import type { ImageFilePolicy } from \"../errors/image-limits.js\";\nimport type { ImagePlan } from \"../model/plan.js\";\nimport type { ImageCallOptions } from \"./options.js\";\n\n/**\n * The highest device pixel ratio the preview draws at. A larger ratio is\n * drawn at this one: no display needs more, and it bounds the canvas a\n * runaway layout can ask for.\n *\n * @public\n */\nexport const MAX_PIXEL_RATIO = 4;\n\n/**\n * Where and how the preview is shown: the stage's size in CSS pixels, the\n * device pixel ratio, and the zoom and pan. At zoom 1 the composition fits\n * the stage; the pan moves it, in CSS pixels. The view isn't part of the\n * document (ADR 0003).\n *\n * @public\n */\nexport interface ImageView {\n readonly width: number;\n readonly height: number;\n /**\n * Device pixels per CSS pixel, such as `devicePixelRatio`. Ratios above\n * {@link MAX_PIXEL_RATIO} are drawn at it.\n */\n readonly pixelRatio: number;\n /** 1 fits the composition inside the stage; 2 is twice that. */\n readonly zoom: number;\n readonly pan: { readonly x: number; readonly y: number };\n /**\n * CSS pixels the fitted composition keeps clear inside each edge of the\n * stage, such as room for the crop frame's handles, which would otherwise\n * be cut off where the image meets the stage's edge. 0 when omitted.\n */\n readonly inset?: number;\n}\n\n/**\n * Options for a render.\n *\n * @public\n */\nexport interface ImageRenderOptions extends ImageCallOptions {\n /**\n * The limits the preview canvas's backing size, the view's size times its\n * pixel ratio, is checked against before the canvas is resized:\n * `maxImageDimension` and `maxImagePixels` (ADR 0004). The defaults of\n * `imageLimits` when omitted.\n */\n readonly filePolicy?: ImageFilePolicy;\n}\n\n/**\n * What became of one `render` call: `drawn`, or `superseded` when a later\n * call replaced it before it was drawn (ADR 0002).\n *\n * @public\n */\nexport type ImageRenderOutcome = \"drawn\" | \"superseded\";\n\n/**\n * The port for the preview (ADR 0002): a canvas on the page, drawn by the\n * engine's render worker through the same renderer as every export, so what\n * the editor shows is what the file will contain. Renders are coalesced:\n * when plans arrive faster than they're drawn, only the latest is drawn, and\n * a render in progress stops at its next strip.\n *\n * @public\n */\nexport interface ImageRenderer {\n /**\n * Hands a canvas to the render worker, once per canvas. The page can't\n * draw into or read it afterwards. Without `transferControlToOffscreen`\n * it rejects with `UNSUPPORTED_ENVIRONMENT`.\n */\n attach(canvas: HTMLCanvasElement): Promise<void>;\n /**\n * Draws a plan into the attached canvas for a view. It resolves `drawn`\n * when this plan is on screen, or `superseded` when a later call replaced\n * it. A plan whose source isn't registered is a `TypeError`. A view whose\n * backing size is over `filePolicy`'s limits rejects with the limit's code\n * before anything is drawn, and the canvas keeps its previous frame.\n */\n render(\n plan: ImagePlan,\n view: ImageView,\n options?: ImageRenderOptions,\n ): Promise<ImageRenderOutcome>;\n /** Releases the canvas in the worker. Pending renders resolve `superseded`, and later calls throw. */\n destroy(): Promise<void>;\n}\n\n/**\n * The size of the preview canvas's backing store for a view: its size times\n * its pixel ratio, at most {@link MAX_PIXEL_RATIO}, in whole pixels.\n *\n * @public\n */\nexport function backingSize(view: ImageView): { readonly width: number; readonly height: number } {\n const ratio = Math.min(view.pixelRatio, MAX_PIXEL_RATIO);\n return {\n width: Math.max(1, Math.round(view.width * ratio)),\n height: Math.max(1, Math.round(view.height * ratio)),\n };\n}\n\n/**\n * The view for a stage of this size: fitted, centred, at this ratio.\n *\n * @public\n */\nexport function fittedView(width: number, height: number, pixelRatio = 1): ImageView {\n return { width, height, pixelRatio, zoom: 1, pan: { x: 0, y: 0 } };\n}\n\n/**\n * Where a composition of this size is shown on the stage for a view, in the\n * stage's CSS pixels: fitted, zoomed, centred and panned. The renderer draws\n * there, and the editor's crop frame and handles are placed with it, so the\n * DOM over the canvas lines up with its pixels (ADR 0002).\n *\n * @public\n */\nexport function placement(\n composition: { readonly width: number; readonly height: number },\n view: ImageView,\n): {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n readonly scale: number;\n} {\n const inset = view.inset ?? 0;\n const fit = Math.min(\n (view.width - 2 * inset) / composition.width,\n (view.height - 2 * inset) / composition.height,\n );\n const scale = Math.max(0, fit) * view.zoom;\n const width = composition.width * scale;\n const height = composition.height * scale;\n return {\n x: (view.width - width) / 2 + view.pan.x,\n y: (view.height - height) / 2 + view.pan.y,\n width,\n height,\n scale,\n };\n}\n","import { asImageError, throwIfAborted } from \"../core/errors/error-helpers.js\";\nimport { ImageError, isImageError } from \"../core/errors/image-error.js\";\nimport { checkOutputLimits, imageLimits, OUTPUT_LIMITS } from \"../core/errors/image-limits.js\";\nimport type { ImagePlan } from \"../core/model/plan.js\";\nimport type { ImageEngine } from \"../core/ports/image-engine.js\";\nimport {\n backingSize,\n type ImageRenderer,\n type ImageRenderOptions,\n type ImageRenderOutcome,\n type ImageView,\n} from \"../core/ports/image-renderer.js\";\nimport { engineInternals } from \"./image-engine.js\";\nimport { layerSources } from \"./image-processor.js\";\n\n/** What tests reach of a renderer from {@link createImageRenderer}. */\nexport interface RendererInternals {\n /** A copy of the preview's pixels: the page can't read a transferred canvas. */\n readonly snapshot: () => Promise<ImageBitmap>;\n /** How many renders the worker has drawn, for the coalescing tests. */\n readonly drawn: () => number;\n}\n\n/** Where a renderer made by {@link createImageRenderer} keeps its internals. */\nexport const RENDERER_INTERNALS: unique symbol = Symbol(\"hm-image-renderer\");\n\n/**\n * The internals of a renderer made by {@link createImageRenderer}.\n *\n * @internal\n */\nexport function rendererInternals(renderer: ImageRenderer): RendererInternals | undefined {\n return (renderer as { [RENDERER_INTERNALS]?: RendererInternals })[RENDERER_INTERNALS];\n}\n\nlet nextCanvasId = 0;\n\ninterface Request {\n readonly plan: ImagePlan;\n readonly view: ImageView;\n readonly resolve: (outcome: ImageRenderOutcome) => void;\n readonly reject: (error: unknown) => void;\n readonly signal: AbortSignal | undefined;\n readonly limits: Readonly<Record<(typeof OUTPUT_LIMITS)[number], number>>;\n}\n\nfunction checkView(view: ImageView): void {\n const positive = (n: number) => Number.isFinite(n) && n > 0;\n if (\n !positive(view.width) ||\n !positive(view.height) ||\n !positive(view.pixelRatio) ||\n !positive(view.zoom) ||\n !Number.isFinite(view.pan.x) ||\n !Number.isFinite(view.pan.y) ||\n (view.inset !== undefined &&\n !(view.inset >= 0 && 2 * view.inset < Math.min(view.width, view.height)))\n ) {\n throw new RangeError(\n \"A view needs a positive size, pixel ratio and zoom, a finite pan, and an inset under half its size.\",\n );\n }\n}\n\n/**\n * Creates the SDK's preview renderer over an engine from\n * `createImageEngine`, sharing its render worker, where the sources are\n * (docs/adr/0002). The canvas is transferred to the worker once, and every\n * frame is drawn there by the same renderer as the export.\n *\n * Renders are coalesced, latest first: while one is being drawn, newer\n * calls replace the waiting one, which resolves `superseded`, and the one\n * being drawn is cancelled at its next strip. So a slider drag that sends\n * many plans ends with one final render of the last.\n *\n * @example\n * ```ts\n * const renderer = createImageRenderer(engine);\n * await renderer.attach(canvas);\n * await renderer.render(plan, fittedView(stage.clientWidth, stage.clientHeight, devicePixelRatio));\n * ```\n *\n * @throws `TypeError` for an engine that `createImageEngine` didn't make.\n * @public\n */\nexport function createImageRenderer(engine: ImageEngine): ImageRenderer {\n const internals = engineInternals(engine);\n if (!internals) {\n throw new TypeError(\"createImageRenderer needs an engine from createImageEngine.\");\n }\n nextCanvasId += 1;\n const id = `preview-${nextCanvasId}`;\n let attached = false;\n let destroyed = false;\n let drawn = 0;\n let pending: Request | undefined;\n let inFlight: { readonly controller: AbortController } | undefined;\n\n const pump = () => {\n if (inFlight || !pending) return;\n const request = pending;\n pending = undefined;\n const controller = new AbortController();\n const onAbort = () => controller.abort(request.signal?.reason);\n request.signal?.addEventListener(\"abort\", onAbort, { once: true });\n inFlight = { controller };\n internals\n .call(\n \"render\",\n { id, plan: request.plan, view: request.view, limits: request.limits },\n { signal: controller.signal },\n )\n .then(\n () => {\n try {\n internals.check();\n } catch (error) {\n request.reject(error);\n return;\n }\n drawn += 1;\n request.resolve(\"drawn\");\n },\n (error: unknown) => {\n if (\n !internals.getSnapshot() &&\n controller.signal.aborted &&\n !request.signal?.aborted &&\n isImageError(error, \"ABORTED\")\n )\n request.resolve(\"superseded\");\n else request.reject(error instanceof TypeError ? error : asImageError(error));\n },\n )\n .finally(() => {\n request.signal?.removeEventListener(\"abort\", onAbort);\n inFlight = undefined;\n pump();\n });\n };\n\n const renderer: ImageRenderer & { readonly [RENDERER_INTERNALS]: RendererInternals } = {\n [RENDERER_INTERNALS]: {\n snapshot: async () => internals.call(\"snapshot\", { id }),\n drawn: () => drawn,\n },\n\n async attach(canvas: HTMLCanvasElement): Promise<void> {\n if (destroyed) throw new Error(\"The image renderer has been destroyed.\");\n internals.check();\n if (attached) throw new TypeError(\"The renderer already has a canvas.\");\n if (typeof canvas.transferControlToOffscreen !== \"function\") {\n throw new ImageError(\n \"UNSUPPORTED_ENVIRONMENT\",\n \"This browser can't draw the preview in a worker.\",\n {\n details: { feature: \"transferControlToOffscreen\" },\n },\n );\n }\n try {\n const generation = await internals.prepare();\n internals.check(generation);\n if (destroyed) throw new Error(\"The image renderer has been destroyed.\");\n const offscreen = canvas.transferControlToOffscreen();\n await internals.call(\"attachCanvas\", { id, canvas: offscreen }, { transfer: true });\n internals.check(generation);\n if (destroyed) {\n await internals.call(\"detachCanvas\", { id });\n throw new Error(\"The image renderer has been destroyed.\");\n }\n attached = true;\n } catch (error) {\n throw asImageError(error);\n }\n },\n\n render(\n plan: ImagePlan,\n view: ImageView,\n options?: ImageRenderOptions,\n ): Promise<ImageRenderOutcome> {\n if (destroyed) return Promise.reject(new Error(\"The image renderer has been destroyed.\"));\n try {\n internals.check();\n } catch (error) {\n return Promise.reject(error);\n }\n if (!attached) return Promise.reject(new TypeError(\"Attach a canvas before rendering.\"));\n const missing = [plan.base.source, ...layerSources(plan)].find((id) => !internals.has(id));\n if (missing !== undefined) {\n return Promise.reject(new TypeError(`There's no source with the id \"${missing}\".`));\n }\n const policy = options?.filePolicy ?? imageLimits.resolve();\n try {\n checkView(view);\n // A runaway layout can't size the canvas past the limits; the\n // current frame stays (docs/adr/0004).\n checkOutputLimits(policy, backingSize(view));\n throwIfAborted(options?.signal);\n } catch (error) {\n return Promise.reject(error);\n }\n const limits = Object.fromEntries(\n OUTPUT_LIMITS.map((limit) => [limit, policy.limits[limit].maximum]),\n ) as Request[\"limits\"];\n return new Promise<ImageRenderOutcome>((resolve, reject) => {\n pending?.resolve(\"superseded\");\n pending = { plan, view, resolve, reject, signal: options?.signal, limits };\n // The render being drawn is stale now: stop it at its next strip.\n inFlight?.controller.abort(\n new DOMException(\"A later render replaced this one.\", \"AbortError\"),\n );\n pump();\n });\n },\n\n async destroy(): Promise<void> {\n if (destroyed) return;\n destroyed = true;\n if (pending) {\n try {\n internals.check();\n pending.resolve(\"superseded\");\n } catch (error) {\n pending.reject(error);\n }\n }\n pending = undefined;\n inFlight?.controller.abort(new DOMException(\"The renderer was destroyed.\", \"AbortError\"));\n if (attached && !internals.getSnapshot()) {\n try {\n await internals.call(\"detachCanvas\", { id });\n } catch {\n // The engine may already be destroyed, with its worker.\n }\n }\n },\n };\n return renderer;\n}\n","import type { ImageKeepableMetadata, ImageSize } from \"./source.js\";\n\n/**\n * A rectangle in whole pixels of the oriented source: `x` and `y` from its\n * top left, `width` and `height` at least 1 (ADR 0003).\n *\n * @public\n */\nexport interface ImageCrop {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n\n/**\n * A quarter-turn rotation, clockwise, in degrees.\n *\n * @public\n */\nexport type ImageRotation = 0 | 90 | 180 | 270;\n\n/**\n * The plan's own rotation and flips, applied after the crop. They're user\n * edits, separate from the file's EXIF orientation, which decoding has\n * already applied (ADR 0005).\n *\n * @public\n */\nexport interface ImageOrientation {\n readonly rotate: ImageRotation;\n /** Mirrors left to right, after the rotation. */\n readonly flipX: boolean;\n /** Mirrors top to bottom, after the rotation. */\n readonly flipY: boolean;\n}\n\n/**\n * The base's tonal and colour adjustments (ADR 0006). Each is an integer\n * from -100 to 100, where 0 is unchanged, applied in this order.\n *\n * @public\n */\nexport interface ImageDevelop {\n /** Warmer (positive) or cooler (negative). */\n readonly temperature: number;\n /** Toward magenta (positive) or green (negative). */\n readonly tint: number;\n /** In fiftieths of a stop: 100 is two stops brighter. */\n readonly exposure: number;\n readonly highlights: number;\n readonly shadows: number;\n readonly contrast: number;\n readonly saturation: number;\n /** Saturation weighted toward the least saturated colours. */\n readonly vibrance: number;\n}\n\n/**\n * The names of the develop adjustments, in the order they're applied.\n *\n * @public\n */\nexport const DEVELOP_ADJUSTMENTS = [\n \"temperature\",\n \"tint\",\n \"exposure\",\n \"highlights\",\n \"shadows\",\n \"contrast\",\n \"saturation\",\n \"vibrance\",\n] as const satisfies readonly (keyof ImageDevelop)[];\n\n/**\n * Every adjustment at 0: the base as it was decoded.\n *\n * @public\n */\nexport const NEUTRAL_DEVELOP: ImageDevelop = Object.freeze({\n temperature: 0,\n tint: 0,\n exposure: 0,\n highlights: 0,\n shadows: 0,\n contrast: 0,\n saturation: 0,\n vibrance: 0,\n});\n\n/**\n * The filter presets (ADR 0006). Names are part of the document format:\n * presets are only ever added.\n *\n * @public\n */\nexport const FILTER_PRESETS = [\"vivid\", \"warm\", \"cool\", \"fade\", \"mono\", \"noir\", \"sepia\"] as const;\n\n/**\n * A filter preset's name.\n *\n * @public\n */\nexport type ImageFilterPreset = (typeof FILTER_PRESETS)[number];\n\n/**\n * A filter preset and its strength, an integer from 0 (no effect) to 100.\n *\n * @public\n */\nexport interface ImageFilter {\n readonly preset: ImageFilterPreset;\n readonly strength: number;\n}\n\n/**\n * The image being edited: a source, its crop and orientation, and its\n * develop adjustments and filter.\n *\n * @public\n */\nexport interface ImageBase {\n /** The id of a registered source. */\n readonly source: string;\n /** The crop, or `null` for the whole image. */\n readonly crop: ImageCrop | null;\n readonly orientation: ImageOrientation;\n readonly develop: ImageDevelop;\n /** The filter, or `null` for none. */\n readonly filter: ImageFilter | null;\n}\n\n/**\n * The export's size: the composition scaled by a factor up to 1, or fitted\n * inside a box without enlarging it.\n *\n * @public\n */\nexport type ImageOutput =\n | { readonly kind: \"scale\"; readonly scale: number }\n | { readonly kind: \"fit\"; readonly width: number; readonly height: number };\n\n/**\n * The most layers and redactions a plan holds, together: the format's\n * ceiling, which the file policy's `maxLayers` applies below (ADR 0009).\n *\n * @public\n */\nexport const MAX_PLAN_ITEMS = 1_024;\n\n/**\n * The most Unicode code points in a key.\n *\n * @public\n */\nexport const MAX_KEY_LENGTH = 64;\n\n/**\n * How far from the scene's origin a position may be, in pixels, either way:\n * four times the longest side `maxImageDimension` allows by default (ADR\n * 0009).\n *\n * @public\n */\nexport const MAX_SCENE_COORDINATE = 65_536;\n\n/**\n * How a redaction replaces what it covers (ADR 0010): `solid` fills the\n * region with one colour, and `pixelate` with coarse blocks of the average\n * colour beneath each. Only `solid` destroys what was there.\n *\n * @public\n */\nexport type ImageRedactionMode = \"solid\" | \"pixelate\";\n\n/**\n * The redaction modes. Names are part of the document format.\n *\n * @public\n */\nexport const REDACTION_MODES = [\n \"solid\",\n \"pixelate\",\n] as const satisfies readonly ImageRedactionMode[];\n\n/**\n * What every redaction has, whatever its mode: its identity and its region.\n *\n * @public\n */\nexport interface ImageRedactionRegion {\n /**\n * Its identity: 1 to {@link MAX_KEY_LENGTH} code points, unique among the\n * plan's layers and redactions.\n */\n readonly key: string;\n /** The region's left edge, in whole pixels of the scene. May be negative. */\n readonly x: number;\n /** The region's top edge, in whole pixels of the scene. May be negative. */\n readonly y: number;\n /** At least 1. */\n readonly width: number;\n /** At least 1. */\n readonly height: number;\n}\n\n/**\n * A region of the image that an export doesn't show (ADR 0010): a rectangle\n * in whole pixels of the scene, the base's oriented source, so it stays on\n * the pixels it covers when the image is cropped or turned (ADR 0009).\n *\n * A redaction has no opacity, visibility or rotation, and is drawn over\n * every layer. Only exports are redacted: the plan describes the redaction,\n * and the source is unchanged.\n *\n * @public\n */\nexport type ImageRedaction =\n | (ImageRedactionRegion & {\n readonly mode: \"solid\";\n /** The fill, as `#rrggbb` in lower case. */\n readonly colour: string;\n })\n | (ImageRedactionRegion & { readonly mode: \"pixelate\" });\n\n/**\n * The most Unicode code points in a text layer's text (ADR 0009).\n *\n * @public\n */\nexport const MAX_LAYER_TEXT_LENGTH = 1_000;\n\n/**\n * The most Unicode code points in a layer's name.\n *\n * @public\n */\nexport const MAX_LAYER_NAME_LENGTH = 100;\n\n/**\n * The widest stroke of a shape or a drawing, and the widest arrow's shaft,\n * in scene pixels.\n *\n * @public\n */\nexport const MAX_STROKE_WIDTH = 1_024;\n\n/**\n * The most points in one run of a drawing's stroke (docs/adr/0014).\n *\n * @public\n */\nexport const MAX_RUN_POINTS = 2_000;\n\n/**\n * The most runs in a stroke (docs/adr/0014).\n *\n * @public\n */\nexport const MAX_STROKE_RUNS = 64;\n\n/**\n * The most strokes in a drawing (docs/adr/0014).\n *\n * @public\n */\nexport const MAX_DRAWING_STROKES = 1_024;\n\n/**\n * The fonts a text layer can use: the generic families, which every device\n * has, so the SDK ships and fetches none (ADR 0009). Names are part of the\n * document format.\n *\n * @public\n */\nexport const LAYER_FONTS = [\"sans-serif\", \"serif\", \"monospace\"] as const;\n\n/**\n * How a text layer's lines sit in its box, by the text's own direction.\n *\n * @public\n */\nexport const LAYER_ALIGNMENTS = [\"start\", \"center\", \"end\"] as const;\n\n/**\n * The shapes a shape layer can be.\n *\n * @public\n */\nexport const LAYER_SHAPES = [\"rectangle\", \"ellipse\"] as const;\n\n/**\n * The kinds of layer. Names are part of the document format.\n *\n * @public\n */\nexport const LAYER_KINDS = [\"text\", \"shape\", \"image\", \"drawing\", \"arrow\"] as const;\n\n/**\n * What every layer has (ADR 0009).\n *\n * @public\n */\nexport interface ImageLayerCommon {\n /**\n * Its identity: 1 to `MAX_KEY_LENGTH` code points, unique among the plan's\n * layers and redactions.\n */\n readonly key: string;\n /**\n * What the layers list calls it: up to `MAX_LAYER_NAME_LENGTH` code\n * points. Empty means the editor's own label for the kind.\n */\n readonly name: string;\n /** Whether it's drawn. */\n readonly visible: boolean;\n /** A whole number from 0, transparent, to 100, opaque. */\n readonly opacity: number;\n}\n\n/**\n * Where a positioned layer is: a box in whole pixels of the scene, the\n * base's oriented source, mirrored or not, then turned about its centre\n * (ADR 0009). The box stays\n * on the pixels it covers when the image is cropped or turned.\n *\n * @public\n */\nexport interface ImageLayerBox {\n /** The box's left edge, before its rotation. May be negative. */\n readonly x: number;\n /** The box's top edge, before its rotation. May be negative. */\n readonly y: number;\n /** At least 1. */\n readonly width: number;\n /** At least 1. */\n readonly height: number;\n /** Tenths of a degree, clockwise about the box's centre: 0 to 3599. */\n readonly rotation: number;\n /**\n * Whether the layer is mirrored left to right, about the box's own\n * vertical axis, before it's turned. With a half turn, that's a mirror top\n * to bottom, so one flip is all a box needs.\n */\n readonly flipX: boolean;\n}\n\n/**\n * Text, drawn as large as fits inside its box, never distorted (ADR 0009).\n * Lines break only at line feeds. Emoji are text.\n *\n * @public\n */\nexport interface ImageTextLayer extends ImageLayerCommon, ImageLayerBox {\n readonly kind: \"text\";\n /**\n * Up to `MAX_LAYER_TEXT_LENGTH` code points. Control characters other\n * than a line feed, and the bidirectional embedding, override and isolate\n * controls, are refused.\n */\n readonly text: string;\n readonly font: (typeof LAYER_FONTS)[number];\n readonly bold: boolean;\n /** The text's colour, as `#rrggbb` in lower case. */\n readonly colour: string;\n readonly align: (typeof LAYER_ALIGNMENTS)[number];\n}\n\n/**\n * A rectangle or an ellipse that fills its box, with a fill, a stroke drawn\n * inside the box, or both (ADR 0009).\n *\n * @public\n */\nexport interface ImageShapeLayer extends ImageLayerCommon, ImageLayerBox {\n readonly kind: \"shape\";\n readonly shape: (typeof LAYER_SHAPES)[number];\n /** The fill, as `#rrggbb` in lower case, or `null` for none. */\n readonly fill: string | null;\n /** The stroke, or `null` for none. A shape has a fill or a stroke. */\n readonly stroke: {\n readonly colour: string;\n /** In whole scene pixels, from 1 to `MAX_STROKE_WIDTH`. */\n readonly width: number;\n } | null;\n}\n\n/**\n * Another image, drawn to fill its box (ADR 0009).\n *\n * @public\n */\nexport interface ImageImageLayer extends ImageLayerCommon, ImageLayerBox {\n readonly kind: \"image\";\n /** The id of a registered source. */\n readonly source: string;\n /** The part of that source to draw, in its own pixels, or `null` for all of it. */\n readonly crop: ImageCrop | null;\n}\n\n/**\n * One stroke of a drawing: what one gesture drew, from the press to the\n * release (docs/adr/0014). It has more than one run only when it's long.\n *\n * @public\n */\nexport interface ImageStroke {\n /** `#rrggbb`. */\n readonly colour: string;\n /** In whole scene pixels: 1 to `MAX_STROKE_WIDTH`. */\n readonly width: number;\n /**\n * 1 to `MAX_STROKE_RUNS` runs, each a polyline `[x0, y0, x1, y1, …]` of 1\n * to `MAX_RUN_POINTS` points, in whole pixels from the drawing's origin.\n * A run of one point is a dot.\n */\n readonly runs: readonly (readonly number[])[];\n}\n\n/**\n * Freehand strokes (ADR 0009, docs/adr/0014). A drawing has an origin and\n * no box: moving it changes its origin, never its points. Its strokes are\n * drawn opaque and the drawing composited as one, so strokes that cross\n * don't darken each other.\n *\n * @public\n */\nexport interface ImageDrawingLayer extends ImageLayerCommon {\n readonly kind: \"drawing\";\n /** Its origin, in whole scene pixels. May be negative. */\n readonly x: number;\n readonly y: number;\n /** 1 to `MAX_DRAWING_STROKES` strokes, in the order they're drawn. */\n readonly strokes: readonly ImageStroke[];\n}\n\n/**\n * A point of the scene, in whole pixels.\n *\n * @public\n */\nexport interface ImageScenePoint {\n readonly x: number;\n readonly y: number;\n}\n\n/**\n * An arrow from one point of the scene to another (ADR 0009,\n * docs/adr/0014). Its head's size follows its width, and its tip is exactly\n * on `to`.\n *\n * @public\n */\nexport interface ImageArrowLayer extends ImageLayerCommon {\n readonly kind: \"arrow\";\n /** The tail. */\n readonly from: ImageScenePoint;\n /** The tip. It differs from `from`. */\n readonly to: ImageScenePoint;\n /** `#rrggbb`. */\n readonly colour: string;\n /** The shaft's width, in whole scene pixels: 1 to `MAX_STROKE_WIDTH`. */\n readonly width: number;\n}\n\n/**\n * A layer that has a box: text, a shape or an image.\n *\n * @public\n */\nexport type ImageBoxedLayer = ImageTextLayer | ImageShapeLayer | ImageImageLayer;\n\n/**\n * A layer over the base: text, a shape, another image, a drawing or an\n * arrow (ADR 0009). Layers are drawn bottom to top, in the plan's order, and\n * redactions over all of them.\n *\n * @public\n */\nexport type ImageLayer = ImageBoxedLayer | ImageDrawingLayer | ImageArrowLayer;\n\n/**\n * A layer's kind.\n *\n * @public\n */\nexport type ImageLayerKind = ImageLayer[\"kind\"];\n\n/**\n * The session's document: a description of the edits over an immutable\n * source, rendered to pixels only for display and export (ADR 0003, ADR\n * 0009).\n *\n * @public\n */\nexport interface ImagePlan {\n readonly base: ImageBase;\n /** The layers over the base, bottom to top, placed in the scene (ADR 0009). */\n readonly layers: readonly ImageLayer[];\n /** The redactions, applied over every layer (ADR 0010). */\n readonly redactions: readonly ImageRedaction[];\n /** The animation (ADR 0011). Always `null` until format version 4. */\n readonly animation: null;\n readonly output: ImageOutput;\n /** The fields the user chose to keep on export. Never a location (ADR 0005). */\n readonly metadata: ImageKeepableMetadata;\n}\n\n/**\n * No rotation and no flips.\n *\n * @public\n */\nexport const UPRIGHT: ImageOrientation = Object.freeze({ rotate: 0, flipX: false, flipY: false });\n\n/**\n * The export at full size.\n *\n * @public\n */\nexport const FULL_SIZE: ImageOutput = Object.freeze({ kind: \"scale\", scale: 1 });\n\n/**\n * The plan for a newly opened source: the whole image, upright, undeveloped\n * and unfiltered, with no layers or redactions, at full size, keeping no\n * metadata.\n *\n * @public\n */\nexport function createPlan(source: string): ImagePlan {\n return {\n base: { source, crop: null, orientation: UPRIGHT, develop: NEUTRAL_DEVELOP, filter: null },\n layers: [],\n redactions: [],\n animation: null,\n output: FULL_SIZE,\n metadata: { title: \"\", description: \"\", artist: \"\", copyright: \"\" },\n };\n}\n\n/**\n * Whether a crop is valid for a source of the given oriented size: whole\n * pixels, at least 1 × 1, and inside the source.\n *\n * @internal\n */\nexport function isValidCrop(crop: ImageCrop, source: ImageSize): boolean {\n const { x, y, width, height } = crop;\n return (\n [x, y, width, height].every(Number.isSafeInteger) &&\n x >= 0 &&\n y >= 0 &&\n width >= 1 &&\n height >= 1 &&\n x + width <= source.width &&\n y + height <= source.height\n );\n}\n","/**\n * The formats the probe recognises, by their signature bytes (ADR 0001).\n *\n * @public\n */\nexport type ImageFormat = \"png\" | \"jpeg\" | \"webp\" | \"gif\" | \"avif\" | \"heif\" | \"bmp\";\n\n/**\n * An EXIF orientation, 1 to 8: how the stored pixels must be turned to be\n * upright. 1 means they already are (ADR 0005).\n *\n * @public\n */\nexport type ExifOrientation = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;\n\n/**\n * A width and a height, in whole pixels.\n *\n * @public\n */\nexport interface ImageSize {\n readonly width: number;\n readonly height: number;\n}\n\n/**\n * Which kinds of metadata a file carries, as presence flags, never values,\n * so the editor can say what an export removes (ADR 0005).\n *\n * @public\n */\nexport interface ImageMetadataPresence {\n readonly location: boolean;\n readonly camera: boolean;\n readonly timestamps: boolean;\n readonly thumbnail: boolean;\n readonly colourProfile: boolean;\n /** Any other field, such as maker notes or unknown tags. */\n readonly other: boolean;\n}\n\n/**\n * The metadata fields a user may keep on export (ADR 0005). Empty strings\n * mean the field isn't written.\n *\n * @public\n */\nexport interface ImageKeepableMetadata {\n readonly title: string;\n readonly description: string;\n readonly artist: string;\n readonly copyright: string;\n}\n\n/**\n * What the probe learned about a file before anything decodes it (ADR 0001,\n * ADR 0004, ADR 0005). Limits are checked against it.\n *\n * @public\n */\nexport interface ImageProbe {\n readonly format: ImageFormat;\n /** The size of the stored pixels, before orientation. */\n readonly stored: ImageSize;\n /** The upright size, after orientation: the size the decoder must return. */\n readonly oriented: ImageSize;\n /** The EXIF or `irot`/`imir` orientation; 1 when there's none. */\n readonly orientation: ExifOrientation;\n /** 1 for a still image, otherwise the number of frames the probe walked. */\n readonly frames: number;\n readonly hasAlpha: boolean;\n /**\n * The most pixels the decoder can produce for the file: frames × the\n * oriented size for most formats, and for AVIF and HEIF the sum over every\n * item decoded with the primary, such as grid tiles and auxiliary planes.\n * A file with an orientation counts one more oriented frame, which the\n * worker needs when it applies the orientation itself (ADR 0005).\n * Never a count declared by one header (ADR 0001).\n */\n readonly decodedPixelBound: number;\n readonly metadata: ImageMetadataPresence;\n /** The keepable fields the file carries, length-limited, shown only as text. */\n readonly keepable: ImageKeepableMetadata;\n}\n\n/**\n * A source the session holds, without its pixels: what the snapshot shows\n * (ADR 0003). Its size is the oriented size.\n *\n * @public\n */\nexport interface ImageSourceInfo {\n readonly id: string;\n readonly format: ImageFormat;\n readonly width: number;\n readonly height: number;\n readonly frames: number;\n readonly hasAlpha: boolean;\n /** The bytes the decoded source takes in the worker: frames × width × height × 4. */\n readonly decodedBytes: number;\n}\n\n/**\n * A small rendering of a source for lists and frame strips. An `ImageBitmap`\n * is one; tests can supply their own. Close it when it's no longer shown.\n *\n * @public\n */\nexport interface ImageThumbnail {\n readonly width: number;\n readonly height: number;\n close(): void;\n}\n\n/**\n * Metadata presence with nothing present.\n *\n * @public\n */\nexport const NO_METADATA: ImageMetadataPresence = Object.freeze({\n location: false,\n camera: false,\n timestamps: false,\n thumbnail: false,\n colourProfile: false,\n other: false,\n});\n\n/**\n * Keepable metadata with every field empty.\n *\n * @public\n */\nexport const EMPTY_KEEPABLE_METADATA: ImageKeepableMetadata = Object.freeze({\n title: \"\",\n description: \"\",\n artist: \"\",\n copyright: \"\",\n});\n\n/**\n * The longest a kept metadata value may be, in Unicode code points, as JSON\n * Schema and every language count them (ADR 0005, sdk-core ADR 0045).\n *\n * @public\n */\nexport const MAX_METADATA_LENGTH = 2_000;\n\n/**\n * Whether text has more than `max` Unicode code points: the length JSON\n * Schema's `maxLength` and other languages count, where JavaScript's\n * `length` counts UTF-16 units (sdk-core ADR 0045). It stops counting at\n * `max + 1`.\n *\n * @internal\n */\nexport function longerThan(text: string, max: number): boolean {\n // Every code point is one or two UTF-16 units.\n if (text.length <= max) return false;\n let count = 0;\n for (const _ of text) {\n count += 1;\n if (count > max) return true;\n }\n return false;\n}\n","/**\n * The checks the reducer and the plan reader share: both refuse exactly what\n * the format's schemas refuse (sdk-core ADR 0045).\n */\n\nimport { type ImageCrop, isValidCrop } from \"../model/plan.js\";\nimport type { ImageSize } from \"../model/source.js\";\n\n/**\n * A refusal while checking a command or a document, which the reducer and\n * the plan reader turn into their own codes.\n *\n * @internal\n */\nexport class Invalid extends Error {\n readonly reason: string;\n constructor(reason: string, message: string) {\n super(message);\n this.reason = reason;\n }\n}\n\n/** @internal */\nexport function invalid(reason: string, message: string): never {\n throw new Invalid(reason, message);\n}\n\n/** Whether a value is a plain object: not `null`, and not a list. @internal */\nexport const isRecord = <T>(value: unknown): value is T =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * Refuses a field the object's type doesn't have, as the schemas do with\n * `additionalProperties: false`, rather than dropping it.\n *\n * @internal\n */\nexport function onlyFields(value: object, fields: readonly string[], what: string): void {\n for (const name of Object.keys(value)) {\n if (!fields.includes(name)) invalid(\"malformed-command\", `${what} has no field \"${name}\"`);\n }\n}\n\n/** Requires every field, and no other, as the schemas' `required` does. @internal */\nexport function allFields(value: object, fields: readonly string[], what: string): void {\n onlyFields(value, fields, what);\n for (const name of fields) {\n if (!Object.hasOwn(value, name)) invalid(\"malformed-command\", `${what} needs \"${name}\"`);\n }\n}\n\n/** Whether a value is a whole number in a range. @internal */\nexport const isWhole = (\n value: unknown,\n min: number,\n max = Number.MAX_SAFE_INTEGER,\n): value is number =>\n Number.isSafeInteger(value) && (value as number) >= min && (value as number) <= max;\n\n/**\n * A crop's shape: whole pixels from 0, at least 1 × 1. Whether it fits its\n * source depends on the source, which a schema can't see.\n *\n * @internal\n */\nexport function checkCrop(value: unknown): ImageCrop {\n if (!isRecord<ImageCrop>(value)) invalid(\"malformed-command\", \"a crop is an object\");\n allFields(value, [\"x\", \"y\", \"width\", \"height\"], \"a crop\");\n const { x, y, width, height } = value;\n if (!isWhole(x, 0) || !isWhole(y, 0) || !isWhole(width, 1) || !isWhole(height, 1)) {\n invalid(\"malformed-command\", \"a crop is whole pixels from 0, at least 1 × 1\");\n }\n return { x, y, width, height };\n}\n\n/** @internal */\nexport function checkCropInSource(crop: ImageCrop, source: ImageSize): void {\n if (!isValidCrop(crop, source)) {\n invalid(\"crop-outside-source\", \"a crop must fit inside its source\");\n }\n}\n","import { MAX_KEY_LENGTH } from \"../model/plan.js\";\nimport { longerThan } from \"../model/source.js\";\nimport { allFields, invalid, isRecord, isWhole } from \"./checks.js\";\n\n/**\n * Edits to a list of keyed items, each with what undoes it exactly (ADR\n * 0009). The plan's layers, redactions and frames are such lists, and their\n * commands are these functions under their own names.\n *\n * Every function is pure, takes untrusted input, and refuses what it can't\n * apply by throwing through `invalid`, never by correcting it.\n */\n\n/** An item with an identity. @internal */\nexport interface Keyed {\n readonly key: string;\n}\n\n/** An item and the index it's put back at. @internal */\nexport interface KeyedEntry<T> {\n readonly at: number;\n readonly item: T;\n}\n\n/** What a list calls its items in refusals, such as `unknown-redaction`. @internal */\nexport interface KeyedListNames {\n /** The reason for a key the list doesn't have. */\n readonly unknown: string;\n /** What one item is called in messages, such as \"redaction\". */\n readonly item: string;\n}\n\n/**\n * A key: text of 1 to `MAX_KEY_LENGTH` code points. Keys are data, so\n * `__proto__` is as good as any (sdk-core ADR 0045).\n *\n * @internal\n */\nexport function checkKey(value: unknown): string {\n if (typeof value !== \"string\") invalid(\"malformed-command\", \"a key is text\");\n if (value === \"\" || longerThan(value, MAX_KEY_LENGTH)) {\n invalid(\"invalid-key\", `a key has 1 to ${MAX_KEY_LENGTH} code points`);\n }\n return value;\n}\n\n/** A list with at least one item. */\nfunction checkList(value: unknown, what: string): readonly unknown[] {\n if (!Array.isArray(value)) invalid(\"malformed-command\", `${what} is a list`);\n if (value.length === 0) invalid(\"malformed-command\", `${what} has at least one item`);\n return value;\n}\n\n/** At least one key, none repeated. @internal */\nexport function checkKeys(value: unknown): readonly string[] {\n const keys = checkList(value, \"keys\").map(checkKey);\n // The schema's uniqueItems refuses it too, so it's malformed, not a clash\n // with the plan.\n if (new Set(keys).size !== keys.length) invalid(\"malformed-command\", \"a key is listed twice\");\n return keys;\n}\n\n/** An index from 0 to `max`. */\nfunction checkIndex(value: unknown, max: number): number {\n if (!isWhole(value, 0)) invalid(\"malformed-command\", \"an index is a whole number from 0\");\n if (value > max) invalid(\"invalid-index\", `an index is from 0 to ${max}`);\n return value;\n}\n\n/** Each key's index in the list, refusing a key it doesn't have. */\nfunction indexes<T extends Keyed>(\n list: readonly T[],\n keys: readonly string[],\n names: KeyedListNames,\n): number[] {\n return keys.map((key) => {\n const index = list.findIndex((item) => item.key === key);\n if (index < 0) invalid(names.unknown, `there's no ${names.item} \"${key}\"`);\n return index;\n });\n}\n\n/** Refuses a new key that another item already has. */\nfunction checkUnused(keys: readonly string[], taken: ReadonlySet<string>): void {\n const seen = new Set(taken);\n for (const key of keys) {\n if (seen.has(key)) invalid(\"duplicate-key\", `the key \"${key}\" is already used`);\n seen.add(key);\n }\n}\n\n/**\n * Inserts items at an index. Undone by removing them.\n *\n * @param list - The list.\n * @param at - The index, from 0 to the list's length.\n * @param items - The items, already checked.\n * @param taken - Every key the plan already uses.\n * @internal\n */\nexport function insertItems<T extends Keyed>(\n list: readonly T[],\n at: unknown,\n items: readonly T[],\n taken: ReadonlySet<string>,\n): { readonly list: readonly T[]; readonly keys: readonly string[] } {\n const index = checkIndex(at, list.length);\n const keys = items.map((item) => item.key);\n checkUnused(keys, taken);\n return { list: [...list.slice(0, index), ...items, ...list.slice(index)], keys };\n}\n\n/**\n * Removes items. Undone by putting each back at its index, in rising order.\n *\n * @internal\n */\nexport function removeItems<T extends Keyed>(\n list: readonly T[],\n keys: unknown,\n names: KeyedListNames,\n): { readonly list: readonly T[]; readonly entries: readonly KeyedEntry<T>[] } {\n const removed = new Set(indexes(list, checkKeys(keys), names));\n const entries: KeyedEntry<T>[] = [];\n list.forEach((item, at) => {\n if (removed.has(at)) entries.push({ at, item });\n });\n return { list: list.filter((_, at) => !removed.has(at)), entries };\n}\n\n/**\n * Puts items back, each at its index in the list as it then is, so the\n * indexes rise. Undone by removing them.\n *\n * @param entries - The entries, with their items already checked.\n * @internal\n */\nexport function restoreItems<T extends Keyed>(\n list: readonly T[],\n entries: readonly KeyedEntry<T>[],\n taken: ReadonlySet<string>,\n): { readonly list: readonly T[]; readonly keys: readonly string[] } {\n const keys = entries.map(({ item }) => item.key);\n checkUnused(keys, taken);\n const next = [...list];\n let last = -1;\n for (const { at, item } of entries) {\n const index = checkIndex(at, next.length);\n if (index <= last) invalid(\"invalid-index\", \"restored items are listed by rising index\");\n last = index;\n next.splice(index, 0, item);\n }\n return { list: next, keys };\n}\n\n/**\n * Moves items to an index of the list without them, keeping the order they\n * had. Undone by setting the whole previous order.\n *\n * @internal\n */\nexport function moveItems<T extends Keyed>(\n list: readonly T[],\n keys: unknown,\n to: unknown,\n names: KeyedListNames,\n): { readonly list: readonly T[]; readonly order: readonly string[] } {\n const moving = new Set(indexes(list, checkKeys(keys), names));\n const moved = list.filter((_, at) => moving.has(at));\n const rest = list.filter((_, at) => !moving.has(at));\n const index = checkIndex(to, rest.length);\n return {\n list: [...rest.slice(0, index), ...moved, ...rest.slice(index)],\n order: list.map((item) => item.key),\n };\n}\n\n/**\n * Sets the list's whole order: every key it has, once. Undone by the same,\n * with the previous order.\n *\n * @internal\n */\nexport function orderItems<T extends Keyed>(\n list: readonly T[],\n keys: unknown,\n names: KeyedListNames,\n): { readonly list: readonly T[]; readonly order: readonly string[] } {\n const order = indexes(list, checkKeys(keys), names);\n if (order.length !== list.length) invalid(\"invalid-order\", \"an order lists every key once\");\n return { list: order.map((at) => list[at] as T), order: list.map((item) => item.key) };\n}\n\n/**\n * Sets some fields of some items. Undone by the same, with what `patch`\n * says restores each.\n *\n * @param patch - Applies one item's changes, and returns the item and the\n * changes that undo them.\n * @internal\n */\nexport function updateItems<T extends Keyed, Props>(\n list: readonly T[],\n updates: unknown,\n names: KeyedListNames,\n patch: (item: T, props: unknown) => { readonly item: T; readonly previous: Props },\n): {\n readonly list: readonly T[];\n readonly previous: readonly { readonly key: string; readonly props: Props }[];\n} {\n const entries = checkList(updates, \"updates\").map((update) => {\n if (!isRecord<{ key: unknown; props: unknown }>(update)) {\n invalid(\"malformed-command\", \"an update is an object\");\n }\n allFields(update, [\"key\", \"props\"], \"an update\");\n return { key: checkKey(update.key), props: update.props };\n });\n const keys = entries.map(({ key }) => key);\n if (new Set(keys).size !== keys.length) invalid(\"duplicate-key\", \"a key is updated twice\");\n const at = indexes(list, keys, names);\n const next = [...list];\n const previous = entries.map(({ key, props }, i) => {\n const index = at[i] as number;\n const patched = patch(next[index] as T, props);\n next[index] = patched.item;\n return { key, props: patched.previous };\n });\n return { list: next, previous };\n}\n","import { type ImageRedaction, MAX_SCENE_COORDINATE, REDACTION_MODES } from \"../model/plan.js\";\nimport { allFields, invalid, isRecord, isWhole, onlyFields } from \"./checks.js\";\nimport { checkKey, type KeyedListNames } from \"./keyed-list.js\";\n\n/**\n * The fields of a redaction that `image.updateRedactions` may set: any but\n * its key. Setting `mode` to `pixelate` drops the colour, and setting it to\n * `solid` needs one in the same update.\n *\n * @public\n */\nexport interface ImageRedactionProps {\n readonly mode?: ImageRedaction[\"mode\"];\n readonly x?: number;\n readonly y?: number;\n readonly width?: number;\n readonly height?: number;\n readonly colour?: string;\n}\n\n/** @internal */\nexport const REDACTION_NAMES: KeyedListNames = { unknown: \"unknown-redaction\", item: \"redaction\" };\n\nconst MODES: readonly string[] = REDACTION_MODES;\nconst REGION = [\"x\", \"y\", \"width\", \"height\"] as const;\nconst PROPS = [\"mode\", ...REGION, \"colour\"];\n/** The pattern the schema uses too. */\nconst COLOUR = /^#[0-9a-f]{6}$/;\n\n/** A colour as `#rrggbb`, in lower case. @internal */\nexport function checkColour(value: unknown): string {\n if (typeof value !== \"string\") invalid(\"malformed-command\", \"a colour is text\");\n if (!COLOUR.test(value)) invalid(\"invalid-colour\", \"a colour is #rrggbb, in lower case\");\n return value;\n}\n\n/** A redaction, with exactly its mode's fields. @internal */\nexport function checkRedaction(value: unknown): ImageRedaction {\n if (!isRecord<Record<string, unknown>>(value)) {\n invalid(\"malformed-command\", \"a redaction is an object\");\n }\n const { mode } = value;\n if (typeof mode !== \"string\") invalid(\"malformed-command\", \"a redaction's mode is text\");\n if (!MODES.includes(mode)) {\n invalid(\"unknown-redaction-mode\", `a redaction's mode is one of ${REDACTION_MODES.join(\", \")}`);\n }\n const solid = mode === \"solid\";\n allFields(value, [\"key\", \"mode\", ...REGION, ...(solid ? [\"colour\"] : [])], \"a redaction\");\n const key = checkKey(value[\"key\"]);\n const { x, y, width, height } = value;\n if (![x, y, width, height].every(Number.isInteger)) {\n invalid(\"malformed-command\", \"a redaction's region is whole pixels\");\n }\n if (\n !isWhole(x, -MAX_SCENE_COORDINATE, MAX_SCENE_COORDINATE) ||\n !isWhole(y, -MAX_SCENE_COORDINATE, MAX_SCENE_COORDINATE) ||\n !isWhole(width, 1, MAX_SCENE_COORDINATE) ||\n !isWhole(height, 1, MAX_SCENE_COORDINATE)\n ) {\n invalid(\n \"invalid-region\",\n `a redaction's region is at least 1 × 1, within ${MAX_SCENE_COORDINATE} pixels of the scene's origin`,\n );\n }\n return solid\n ? { key, mode: \"solid\", x, y, width, height, colour: checkColour(value[\"colour\"]) }\n : { key, mode: \"pixelate\", x, y, width, height };\n}\n\n/**\n * Applies an update's fields to a redaction, and gives the fields that undo\n * it: the previous value of each one set, and the colour a change to\n * `pixelate` dropped.\n *\n * @internal\n */\nexport function patchRedaction(\n item: ImageRedaction,\n props: unknown,\n): { readonly item: ImageRedaction; readonly previous: ImageRedactionProps } {\n if (!isRecord<Record<string, unknown>>(props)) {\n invalid(\"malformed-command\", \"an update's props are an object\");\n }\n onlyFields(props, PROPS, \"a redaction's props\");\n const merged: Record<string, unknown> = { ...item };\n const previous: Record<string, unknown> = {};\n const before = item as unknown as Readonly<Record<string, unknown>>;\n for (const name of PROPS) {\n if (!Object.hasOwn(props, name)) continue;\n merged[name] = props[name];\n if (Object.hasOwn(before, name)) previous[name] = before[name];\n }\n if (merged[\"mode\"] === \"pixelate\") {\n if (Object.hasOwn(props, \"colour\")) {\n invalid(\"unexpected-colour\", \"a pixelated redaction has no colour\");\n }\n if (item.mode === \"solid\") previous[\"colour\"] = item.colour;\n delete merged[\"colour\"];\n } else if (merged[\"mode\"] === \"solid\" && !Object.hasOwn(merged, \"colour\")) {\n invalid(\"missing-colour\", \"a redaction set to solid needs a colour in the same update\");\n }\n return { item: checkRedaction(merged), previous: previous as ImageRedactionProps };\n}\n","import {\n type ImageLayer,\n type ImageLayerKind,\n type ImageScenePoint,\n type ImageStroke,\n LAYER_ALIGNMENTS,\n LAYER_FONTS,\n LAYER_KINDS,\n LAYER_SHAPES,\n MAX_DRAWING_STROKES,\n MAX_LAYER_NAME_LENGTH,\n MAX_LAYER_TEXT_LENGTH,\n MAX_RUN_POINTS,\n MAX_SCENE_COORDINATE,\n MAX_STROKE_RUNS,\n MAX_STROKE_WIDTH,\n} from \"../model/plan.js\";\nimport { type ImageSize, longerThan } from \"../model/source.js\";\nimport { allFields, checkCrop, checkCropInSource, invalid, isRecord, isWhole } from \"./checks.js\";\nimport { checkKey, type KeyedListNames } from \"./keyed-list.js\";\nimport { checkColour } from \"./redactions.js\";\n\n/** @internal */\nexport const LAYER_NAMES: KeyedListNames = { unknown: \"unknown-layer\", item: \"layer\" };\n\nconst COMMON = [\"key\", \"kind\", \"name\", \"visible\", \"opacity\"] as const;\nconst BOX = [\"x\", \"y\", \"width\", \"height\", \"rotation\", \"flipX\"] as const;\n/** Each kind's fields, after those every layer has: a box and its own, or its own alone. */\nconst OWN: Readonly<Record<ImageLayerKind, readonly string[]>> = {\n text: [...BOX, \"text\", \"font\", \"bold\", \"colour\", \"align\"],\n shape: [...BOX, \"shape\", \"fill\", \"stroke\"],\n image: [...BOX, \"source\", \"crop\"],\n drawing: [\"x\", \"y\", \"strokes\"],\n arrow: [\"from\", \"to\", \"colour\", \"width\"],\n};\n/**\n * The fields of a kind that `image.updateLayers` doesn't set: a drawing's\n * strokes change only through the stroke commands, so an undo step holds\n * the strokes it removed and no others (docs/adr/0014).\n */\nconst NOT_UPDATED: Readonly<Partial<Record<ImageLayerKind, readonly string[]>>> = {\n drawing: [\"strokes\"],\n};\n/** The kinds each format version has (ADR 0009): a reader takes no later version's kind. */\nconst KINDS_BY_VERSION: Readonly<Record<2 | 3, readonly string[]>> = {\n 2: [\"text\", \"shape\", \"image\"],\n 3: LAYER_KINDS,\n};\n/** Every field some kind has, for telling another kind's field from an unknown one. */\nconst ANY_OWN = new Set(Object.values(OWN).flat());\n\n/**\n * The characters text can't hold: the C0 controls other than a line feed,\n * DEL, and the bidirectional embedding, override and isolate controls, which\n * can make text read differently from what's stored. The schema's pattern is\n * the same set.\n */\n// biome-ignore lint/suspicious/noControlCharactersInRegex: the controls are what it refuses\nexport const FORBIDDEN_IN_TEXT = /[\\u0000-\\u0009\\u000B-\\u001F\\u007F--]/u;\n\n/** Text of at most `max` code points, with none of the forbidden characters. */\nfunction checkText(value: unknown, max: number, what: string): string {\n if (typeof value !== \"string\") invalid(\"malformed-command\", `${what} is text`);\n if (longerThan(value, max)) invalid(\"text-too-long\", `${what} has at most ${max} code points`);\n if (FORBIDDEN_IN_TEXT.test(value)) {\n invalid(\n \"invalid-text\",\n `${what} can't hold control characters other than a line feed, or bidirectional controls`,\n );\n }\n return value;\n}\n\nfunction checkOneOf<T extends string>(value: unknown, options: readonly T[], what: string): T {\n if (typeof value !== \"string\" || !(options as readonly string[]).includes(value)) {\n invalid(\"malformed-command\", `${what} is one of ${options.join(\", \")}`);\n }\n return value as T;\n}\n\nfunction checkBoolean(value: unknown, what: string): boolean {\n if (typeof value !== \"boolean\") invalid(\"malformed-command\", `${what} is true or false`);\n return value;\n}\n\n/** A whole number of scene pixels within the scene's coordinates. */\nconst isCoordinate = (value: unknown): value is number =>\n isWhole(value, -MAX_SCENE_COORDINATE, MAX_SCENE_COORDINATE);\n\n/** A stroke's or an arrow's width. */\nfunction checkWidth(value: unknown, what: string): number {\n if (!isWhole(value, 1, MAX_STROKE_WIDTH)) {\n invalid(\"malformed-command\", `${what}'s width is from 1 to ${MAX_STROKE_WIDTH} pixels`);\n }\n return value;\n}\n\n/**\n * One stroke of a drawing at an origin: its colour, its width, and 1 to 64\n * runs of 1 to 2,000 points, each point within the scene's coordinates once\n * the origin is added (docs/adr/0014).\n *\n * @internal\n */\nexport function checkStroke(value: unknown, origin: ImageScenePoint): ImageStroke {\n if (!isRecord<{ colour: unknown; width: unknown; runs: unknown }>(value)) {\n invalid(\"malformed-command\", \"a stroke is an object\");\n }\n allFields(value, [\"colour\", \"width\", \"runs\"], \"a stroke\");\n const colour = checkColour(value.colour);\n const width = checkWidth(value.width, \"a stroke\");\n const { runs } = value;\n if (!Array.isArray(runs) || runs.length < 1 || runs.length > MAX_STROKE_RUNS) {\n invalid(\"malformed-command\", `a stroke has 1 to ${MAX_STROKE_RUNS} runs`);\n }\n return {\n colour,\n width,\n runs: runs.map((run: unknown) => {\n if (!Array.isArray(run) || run.length < 2 || run.length > 2 * MAX_RUN_POINTS) {\n invalid(\"malformed-command\", `a run has 1 to ${MAX_RUN_POINTS} points`);\n }\n // From the origin, which may be at one end of the scene, to a point at the other.\n const numbers = run as number[];\n if (\n !numbers.every((value) =>\n isWhole(value, -2 * MAX_SCENE_COORDINATE, 2 * MAX_SCENE_COORDINATE),\n )\n ) {\n invalid(\"malformed-command\", \"a run's coordinates are whole numbers of pixels\");\n }\n // What a schema can't state: a pair for each point, and each point in the scene.\n if (run.length % 2 !== 0) invalid(\"invalid-points\", \"a run has an x and a y for each point\");\n for (let i = 0; i < run.length; i += 2) {\n if (\n !isCoordinate(origin.x + (numbers[i] as number)) ||\n !isCoordinate(origin.y + (numbers[i + 1] as number))\n ) {\n invalid(\n \"invalid-points\",\n `a point is within ${MAX_SCENE_COORDINATE} pixels of the scene's origin`,\n );\n }\n }\n return [...numbers];\n }),\n };\n}\n\n/** A list of strokes, each checked at the drawing's origin. */\nfunction checkStrokes(value: unknown, origin: ImageScenePoint): ImageStroke[] {\n if (!Array.isArray(value) || value.length > MAX_DRAWING_STROKES) {\n invalid(\"malformed-command\", `a drawing has at most ${MAX_DRAWING_STROKES} strokes`);\n }\n return value.map((stroke) => checkStroke(stroke, origin));\n}\n\n/** A point of the scene. */\nfunction checkPoint(value: unknown, what: string): ImageScenePoint {\n if (!isRecord<{ x: unknown; y: unknown }>(value)) {\n invalid(\"malformed-command\", `${what} is a point`);\n }\n allFields(value, [\"x\", \"y\"], what);\n const { x, y } = value;\n // Stated by the schema, as a box's place is.\n if (!isCoordinate(x) || !isCoordinate(y)) {\n invalid(\n \"malformed-command\",\n `${what} is in whole pixels, within ${MAX_SCENE_COORDINATE} of the scene's origin`,\n );\n }\n return { x, y };\n}\n\n/**\n * A layer, with exactly its kind's fields. An image layer's source must be\n * registered, and its crop must fit inside it.\n *\n * @param version - The format version whose kinds are allowed: a version 2\n * document has no drawing and no arrow (ADR 0009).\n * @internal\n */\nexport function checkLayer(\n value: unknown,\n sourceSize: (id: string) => ImageSize | undefined,\n version: 2 | 3 = 3,\n): ImageLayer {\n if (!isRecord<Record<string, unknown>>(value)) {\n invalid(\"malformed-command\", \"a layer is an object\");\n }\n const { kind } = value;\n if (typeof kind !== \"string\") invalid(\"malformed-command\", \"a layer's kind is text\");\n const kinds = KINDS_BY_VERSION[version];\n if (!kinds.includes(kind)) {\n invalid(\"unknown-layer-kind\", `a layer's kind is one of ${kinds.join(\", \")}`);\n }\n const own = OWN[kind as ImageLayerKind];\n allFields(value, [...COMMON, ...own], `a ${kind} layer`);\n\n const key = checkKey(value[\"key\"]);\n const name = checkText(value[\"name\"], MAX_LAYER_NAME_LENGTH, \"a layer's name\");\n const visible = checkBoolean(value[\"visible\"], \"a layer's visible\");\n const { opacity } = value;\n if (!Number.isInteger(opacity)) {\n invalid(\"malformed-command\", \"a layer's opacity is a whole number\");\n }\n if (!isWhole(opacity, 0, 100)) invalid(\"invalid-opacity\", \"a layer's opacity is from 0 to 100\");\n const shared = { key, name, visible, opacity };\n\n if (kind === \"drawing\") {\n const { x, y } = value;\n if (!isCoordinate(x) || !isCoordinate(y)) {\n invalid(\n \"malformed-command\",\n `a drawing's origin is in whole pixels, within ${MAX_SCENE_COORDINATE} of the scene's origin`,\n );\n }\n const strokes = checkStrokes(value[\"strokes\"], { x, y });\n if (strokes.length === 0) invalid(\"empty-drawing\", \"a drawing has at least one stroke\");\n return { ...shared, kind, x, y, strokes };\n }\n if (kind === \"arrow\") {\n const from = checkPoint(value[\"from\"], \"an arrow's from\");\n const to = checkPoint(value[\"to\"], \"an arrow's to\");\n if (from.x === to.x && from.y === to.y) {\n invalid(\"empty-arrow\", \"an arrow's ends differ\");\n }\n return {\n ...shared,\n kind,\n from,\n to,\n colour: checkColour(value[\"colour\"]),\n width: checkWidth(value[\"width\"], \"an arrow\"),\n };\n }\n\n const { x, y, width, height, rotation } = value;\n if (![x, y, width, height, rotation].every(Number.isInteger)) {\n invalid(\"malformed-command\", \"a layer's box is in whole numbers\");\n }\n if (\n !isCoordinate(x) ||\n !isCoordinate(y) ||\n !isWhole(width, 1, MAX_SCENE_COORDINATE) ||\n !isWhole(height, 1, MAX_SCENE_COORDINATE) ||\n !isWhole(rotation, 0, 3_599)\n ) {\n invalid(\n \"invalid-box\",\n `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`,\n );\n }\n const flipX = checkBoolean(value[\"flipX\"], \"a layer's flipX\");\n const common = { ...shared, x, y, width, height, rotation, flipX };\n\n if (kind === \"text\") {\n return {\n ...common,\n kind,\n text: checkText(value[\"text\"], MAX_LAYER_TEXT_LENGTH, \"a layer's text\"),\n font: checkOneOf(value[\"font\"], LAYER_FONTS, \"a layer's font\"),\n bold: checkBoolean(value[\"bold\"], \"a layer's bold\"),\n colour: checkColour(value[\"colour\"]),\n align: checkOneOf(value[\"align\"], LAYER_ALIGNMENTS, \"a layer's align\"),\n };\n }\n if (kind === \"shape\") {\n const shape = checkOneOf(value[\"shape\"], LAYER_SHAPES, \"a layer's shape\");\n const fill = value[\"fill\"] === null ? null : checkColour(value[\"fill\"]);\n let stroke: { colour: string; width: number } | null = null;\n if (value[\"stroke\"] !== null) {\n const given = value[\"stroke\"];\n if (!isRecord<{ colour: unknown; width: unknown }>(given)) {\n invalid(\"malformed-command\", \"a stroke is an object or null\");\n }\n allFields(given, [\"colour\", \"width\"], \"a stroke\");\n stroke = { colour: checkColour(given.colour), width: checkWidth(given.width, \"a stroke\") };\n }\n if (fill === null && stroke === null) {\n invalid(\"empty-shape\", \"a shape has a fill or a stroke\");\n }\n return { ...common, kind, shape, fill, stroke };\n }\n const source = value[\"source\"];\n if (typeof source !== \"string\" || source === \"\") {\n invalid(\"malformed-command\", \"an image layer's source is a source id\");\n }\n const size = sourceSize(source);\n if (size === undefined) invalid(\"unknown-source\", `unknown source \"${source}\"`);\n const crop = value[\"crop\"] === null ? null : checkCrop(value[\"crop\"]);\n if (crop !== null) checkCropInSource(crop, size);\n return { ...common, kind: \"image\", source, crop };\n}\n\n/**\n * Applies an update's fields to a layer, and gives the fields that undo it:\n * the previous value of each one set. Any field of the layer's kind may be\n * set, except its key and its kind.\n *\n * @internal\n */\nexport function patchLayer(\n item: ImageLayer,\n props: unknown,\n sourceSize: (id: string) => ImageSize | undefined,\n): { readonly item: ImageLayer; readonly previous: Readonly<Record<string, unknown>> } {\n if (!isRecord<Record<string, unknown>>(props)) {\n invalid(\"malformed-command\", \"an update's props are an object\");\n }\n const notUpdated = NOT_UPDATED[item.kind] ?? [];\n const allowed = new Set<string>(\n [...COMMON.slice(2), ...OWN[item.kind]].filter((name) => !notUpdated.includes(name)),\n );\n const before = item as unknown as Readonly<Record<string, unknown>>;\n const merged: Record<string, unknown> = { ...item };\n const previous: Record<string, unknown> = {};\n for (const name of Object.keys(props)) {\n if (notUpdated.includes(name)) {\n invalid(\"malformed-command\", `a ${item.kind} layer's \"${name}\" isn't set by an update`);\n }\n if (!allowed.has(name)) {\n // Another kind's field is a mistake about the layer; anything else,\n // including its key and kind, isn't a field an update has.\n if (ANY_OWN.has(name)) {\n invalid(\"wrong-kind\", `a ${item.kind} layer has no \"${name}\"`);\n }\n invalid(\"malformed-command\", `a layer's props have no field \"${name}\"`);\n }\n merged[name] = props[name];\n previous[name] = before[name];\n }\n return { item: checkLayer(merged, sourceSize), previous };\n}\n","import {\n type ImageDrawingLayer,\n type ImagePlan,\n type ImageStroke,\n MAX_DRAWING_STROKES,\n} from \"../model/plan.js\";\nimport { allFields, invalid, isRecord } from \"./checks.js\";\nimport { checkStroke } from \"./layers.js\";\n\n/** The drawing a stroke command names, and its place among the layers. */\nfunction drawingOf(plan: ImagePlan, key: unknown): { at: number; drawing: ImageDrawingLayer } {\n if (typeof key !== \"string\") invalid(\"malformed-command\", \"a key is text\");\n const at = plan.layers.findIndex((layer) => layer.key === key);\n const layer = plan.layers[at];\n if (layer === undefined) invalid(\"unknown-layer\", `no layer has the key \"${key}\"`);\n if (layer.kind !== \"drawing\") {\n invalid(\"wrong-kind\", `a ${layer.kind} layer has no strokes`);\n }\n return { at, drawing: layer };\n}\n\n/** The plan with a drawing's strokes replaced. */\nfunction withStrokes(plan: ImagePlan, at: number, strokes: readonly ImageStroke[]): ImagePlan {\n return {\n ...plan,\n layers: plan.layers.map((layer, index) =>\n index === at && layer.kind === \"drawing\" ? { ...layer, strokes } : layer,\n ),\n };\n}\n\n/** A list with at least one item. */\nfunction some(value: unknown, what: string): unknown[] {\n if (!Array.isArray(value) || value.length === 0) {\n invalid(\"malformed-command\", `${what} is a list of at least one`);\n }\n return value;\n}\n\n/**\n * Appends strokes to a drawing (ADR 0009, docs/adr/0014). What undoes it\n * removes that many from the end.\n *\n * @internal\n */\nexport function addStrokes(plan: ImagePlan, key: unknown, value: unknown) {\n const { at, drawing } = drawingOf(plan, key);\n const strokes = some(value, \"strokes\").map((stroke) => checkStroke(stroke, drawing));\n const before = drawing.strokes.length;\n if (before + strokes.length > MAX_DRAWING_STROKES) {\n invalid(\"too-many-strokes\", `a drawing has at most ${MAX_DRAWING_STROKES} strokes`);\n }\n return {\n state: withStrokes(plan, at, [...drawing.strokes, ...strokes]),\n inverse: {\n type: \"image.removeStrokes\" as const,\n key: drawing.key,\n indexes: strokes.map((_, index) => before + index),\n },\n };\n}\n\n/**\n * Removes strokes from a drawing, by index, leaving at least one. What\n * undoes it puts each back at its index.\n *\n * @internal\n */\nexport function removeStrokes(plan: ImagePlan, key: unknown, value: unknown) {\n const { at, drawing } = drawingOf(plan, key);\n const indexes = some(value, \"indexes\");\n if (!indexes.every((index) => Number.isSafeInteger(index) && (index as number) >= 0)) {\n invalid(\"malformed-command\", \"an index is a whole number from 0\");\n }\n const chosen = new Set(indexes as number[]);\n if (chosen.size !== indexes.length) invalid(\"invalid-index\", \"an index is listed once\");\n for (const index of chosen) {\n if (index >= drawing.strokes.length) {\n invalid(\"invalid-index\", `the drawing has no stroke ${index}`);\n }\n }\n if (chosen.size === drawing.strokes.length) {\n invalid(\"empty-drawing\", \"a drawing keeps at least one stroke; remove the layer instead\");\n }\n return {\n state: withStrokes(\n plan,\n at,\n drawing.strokes.filter((_, index) => !chosen.has(index)),\n ),\n inverse: {\n type: \"image.restoreStrokes\" as const,\n key: drawing.key,\n // By rising index, so each goes back where it was.\n entries: [...chosen]\n .sort((a, b) => a - b)\n .map((index) => ({ at: index, stroke: drawing.strokes[index] as ImageStroke })),\n },\n };\n}\n\n/**\n * Puts removed strokes back, each at its index, by rising index. It's what\n * undoes {@link removeStrokes}: the reducer applies it, but it isn't part\n * of the portable command format.\n *\n * @internal\n */\nexport function restoreStrokes(plan: ImagePlan, key: unknown, value: unknown) {\n const { at, drawing } = drawingOf(plan, key);\n const strokes = [...drawing.strokes];\n let last = -1;\n const indexes: number[] = [];\n for (const entry of some(value, \"entries\")) {\n if (!isRecord<{ at: unknown; stroke: unknown }>(entry)) {\n invalid(\"malformed-command\", \"an entry is an object\");\n }\n allFields(entry, [\"at\", \"stroke\"], \"an entry\");\n const index = entry.at;\n if (!Number.isSafeInteger(index) || (index as number) < 0) {\n invalid(\"malformed-command\", \"an index is a whole number from 0\");\n }\n if ((index as number) <= last || (index as number) > strokes.length) {\n invalid(\"invalid-index\", \"entries are by rising index, each within the drawing\");\n }\n last = index as number;\n strokes.splice(last, 0, checkStroke(entry.stroke, drawing));\n indexes.push(last);\n }\n if (strokes.length > MAX_DRAWING_STROKES) {\n invalid(\"too-many-strokes\", `a drawing has at most ${MAX_DRAWING_STROKES} strokes`);\n }\n return {\n state: withStrokes(plan, at, strokes),\n inverse: { type: \"image.removeStrokes\" as const, key: drawing.key, indexes },\n };\n}\n","import type { Reducer } from \"@hussmartinez/sdk-core\";\nimport { ImageError } from \"../errors/image-error.js\";\nimport type { ImageLayer, ImageStroke } from \"../model/plan.js\";\nimport {\n DEVELOP_ADJUSTMENTS,\n FILTER_PRESETS,\n type ImageCrop,\n type ImageDevelop,\n type ImageFilter,\n type ImageOrientation,\n type ImageOutput,\n type ImagePlan,\n type ImageRedaction,\n MAX_PLAN_ITEMS,\n} from \"../model/plan.js\";\nimport {\n type ImageKeepableMetadata,\n type ImageSize,\n longerThan,\n MAX_METADATA_LENGTH,\n} from \"../model/source.js\";\nimport {\n allFields,\n checkCrop,\n checkCropInSource,\n Invalid,\n invalid,\n isRecord,\n isWhole,\n} from \"./checks.js\";\nimport {\n insertItems,\n type KeyedEntry,\n moveItems,\n orderItems,\n removeItems,\n restoreItems,\n updateItems,\n} from \"./keyed-list.js\";\nimport { checkLayer, LAYER_NAMES, patchLayer } from \"./layers.js\";\nimport {\n checkRedaction,\n type ImageRedactionProps,\n patchRedaction,\n REDACTION_NAMES,\n} from \"./redactions.js\";\nimport { addStrokes, removeStrokes, restoreStrokes } from \"./strokes.js\";\n\nexport { checkCrop, checkCropInSource, Invalid, invalid, isRecord, onlyFields } from \"./checks.js\";\n\n/**\n * Sets or removes the base's crop, in whole pixels of the oriented source.\n *\n * @public\n */\nexport interface SetCropCommand {\n readonly type: \"image.setCrop\";\n readonly crop: ImageCrop | null;\n}\n\n/**\n * Sets the base's rotation and flips.\n *\n * @public\n */\nexport interface SetOrientationCommand {\n readonly type: \"image.setOrientation\";\n readonly orientation: ImageOrientation;\n}\n\n/**\n * Sets the export's size.\n *\n * @public\n */\nexport interface SetOutputCommand {\n readonly type: \"image.setOutput\";\n readonly output: ImageOutput;\n}\n\n/**\n * Sets one metadata field to keep on export. An empty value keeps nothing.\n *\n * @public\n */\nexport interface SetMetadataCommand {\n readonly type: \"image.setMetadata\";\n readonly field: keyof ImageKeepableMetadata;\n readonly value: string;\n}\n\n/**\n * Sets some of the base's develop adjustments; the others keep their values\n * (ADR 0006).\n *\n * @public\n */\nexport interface SetDevelopCommand {\n readonly type: \"image.setDevelop\";\n readonly values: Partial<ImageDevelop>;\n}\n\n/**\n * Sets the base's filter preset and strength, or removes it with `null`.\n *\n * @public\n */\nexport interface SetFilterCommand {\n readonly type: \"image.setFilter\";\n readonly filter: ImageFilter | null;\n}\n\n/**\n * Inserts layers at an index of the plan's layers, which are drawn bottom\n * to top (ADR 0009). Each needs a key no layer or redaction of the plan has.\n *\n * @public\n */\nexport interface InsertLayersCommand {\n readonly type: \"image.insertLayers\";\n /** From 0, under every layer, to the number of layers, over them all. */\n readonly at: number;\n readonly layers: readonly ImageLayer[];\n}\n\n/**\n * Removes layers, by key.\n *\n * @public\n */\nexport interface RemoveLayersCommand {\n readonly type: \"image.removeLayers\";\n readonly keys: readonly string[];\n}\n\n/**\n * Moves layers to an index of the list without them, keeping the order they\n * had: up or down the stack.\n *\n * @public\n */\nexport interface MoveLayersCommand {\n readonly type: \"image.moveLayers\";\n readonly keys: readonly string[];\n readonly to: number;\n}\n\n/**\n * Sets some fields of some layers: their boxes after a move, their opacity,\n * a text layer's text. `props` may hold any field of the layer's kind except\n * `key` and `kind`.\n *\n * @public\n */\nexport interface UpdateLayersCommand {\n readonly type: \"image.updateLayers\";\n readonly updates: readonly {\n readonly key: string;\n readonly props: Readonly<Record<string, unknown>>;\n }[];\n}\n\n/**\n * Puts removed layers back, each at its index, by rising index. It's what\n * undoes {@link RemoveLayersCommand}: the reducer applies it, but it isn't\n * part of the portable command format (ADR 0009).\n *\n * @public\n */\nexport interface RestoreLayersCommand {\n readonly type: \"image.restoreLayers\";\n readonly entries: readonly { readonly at: number; readonly layer: ImageLayer }[];\n}\n\n/**\n * Sets the whole order of the layers: every key, once. It's what undoes\n * {@link MoveLayersCommand}: the reducer applies it, but it isn't part of\n * the portable command format (ADR 0009).\n *\n * @public\n */\nexport interface SetLayerOrderCommand {\n readonly type: \"image.setLayerOrder\";\n readonly keys: readonly string[];\n}\n\n/**\n * Inserts redactions at an index of the plan's redactions (ADR 0010). Each\n * needs a key no layer or redaction of the plan has.\n *\n * @public\n */\nexport interface InsertRedactionsCommand {\n readonly type: \"image.insertRedactions\";\n /** From 0 to the number of redactions. */\n readonly at: number;\n readonly redactions: readonly ImageRedaction[];\n}\n\n/**\n * Removes redactions, by key.\n *\n * @public\n */\nexport interface RemoveRedactionsCommand {\n readonly type: \"image.removeRedactions\";\n readonly keys: readonly string[];\n}\n\n/**\n * Moves redactions to an index of the list without them, keeping the order\n * they had. The order only decides how overlapping redactions look.\n *\n * @public\n */\nexport interface MoveRedactionsCommand {\n readonly type: \"image.moveRedactions\";\n readonly keys: readonly string[];\n readonly to: number;\n}\n\n/**\n * Sets some fields of some redactions, such as their regions after a move.\n *\n * @public\n */\nexport interface UpdateRedactionsCommand {\n readonly type: \"image.updateRedactions\";\n readonly updates: readonly { readonly key: string; readonly props: ImageRedactionProps }[];\n}\n\n/**\n * Puts removed redactions back, each at its index, by rising index. It's\n * what undoes {@link RemoveRedactionsCommand}: the reducer applies it, but\n * it isn't part of the portable command format (ADR 0009).\n *\n * @public\n */\nexport interface RestoreRedactionsCommand {\n readonly type: \"image.restoreRedactions\";\n readonly entries: readonly { readonly at: number; readonly redaction: ImageRedaction }[];\n}\n\n/**\n * Sets the whole order of the redactions: every key, once. It's what undoes\n * {@link MoveRedactionsCommand}: the reducer applies it, but it isn't part\n * of the portable command format (ADR 0009).\n *\n * @public\n */\nexport interface SetRedactionOrderCommand {\n readonly type: \"image.setRedactionOrder\";\n readonly keys: readonly string[];\n}\n\n/**\n * Appends strokes to a drawing layer (ADR 0009, docs/adr/0014): one stroke\n * for each gesture, however many runs it has.\n *\n * @public\n */\nexport interface AddStrokesCommand {\n readonly type: \"image.addStrokes\";\n /** The drawing's key. */\n readonly key: string;\n readonly strokes: readonly ImageStroke[];\n}\n\n/**\n * Removes strokes from a drawing layer, by index. A drawing keeps at least\n * one stroke: to remove the last, remove the layer.\n *\n * @public\n */\nexport interface RemoveStrokesCommand {\n readonly type: \"image.removeStrokes\";\n readonly key: string;\n readonly indexes: readonly number[];\n}\n\n/**\n * Puts removed strokes back, each at its index, by rising index. It's what\n * undoes {@link RemoveStrokesCommand}: the reducer applies it, but it isn't\n * part of the portable command format (ADR 0009).\n *\n * @public\n */\nexport interface RestoreStrokesCommand {\n readonly type: \"image.restoreStrokes\";\n readonly key: string;\n readonly entries: readonly { readonly at: number; readonly stroke: ImageStroke }[];\n}\n\n/**\n * The commands that exist only to undo others. The reducer applies them, and\n * they're plain data like every command, but the `hm-image-command` format\n * doesn't include them: an inverse's shape may change between releases\n * (sdk-core ADR 0045).\n *\n * @public\n */\nexport type ImageInverseCommand =\n | RestoreStrokesCommand\n | RestoreLayersCommand\n | SetLayerOrderCommand\n | RestoreRedactionsCommand\n | SetRedactionOrderCommand;\n\n/**\n * Every edit to an {@link ImagePlan}: plain, structured-cloneable data\n * (ADR 0003, ADR 0009).\n *\n * @public\n */\nexport type ImageCommand =\n | SetCropCommand\n | SetOrientationCommand\n | SetOutputCommand\n | SetMetadataCommand\n | SetDevelopCommand\n | SetFilterCommand\n | InsertLayersCommand\n | RemoveLayersCommand\n | MoveLayersCommand\n | UpdateLayersCommand\n | AddStrokesCommand\n | RemoveStrokesCommand\n | InsertRedactionsCommand\n | RemoveRedactionsCommand\n | MoveRedactionsCommand\n | UpdateRedactionsCommand\n | ImageInverseCommand;\n\n/**\n * Why a command was refused, as a stable token: `details.reason` on the\n * `INVALID_COMMAND` error (sdk-core ADR 0045).\n *\n * - `malformed-command`: not shaped as the `hm-image-command` schema says,\n * such as a missing field, a field of the wrong type, an unknown field, or\n * a crop that isn't whole pixels of at least 1 × 1.\n * - `unknown-command`: a `type` the reducer doesn't know.\n * - `unknown-source`: a crop for a plan whose source isn't registered, or\n * an image layer whose source isn't.\n * - `crop-outside-source`: a crop that doesn't fit inside its source.\n * - `invalid-orientation`: a rotation other than 0, 90, 180 or 270.\n * - `invalid-output`: a scale outside (0, 1], or a box under 1 pixel.\n * - `unknown-metadata-field`: a field other than title, description, artist\n * and copyright.\n * - `metadata-too-long`: a value over `MAX_METADATA_LENGTH` code points.\n * - `unknown-adjustment`: a develop value that isn't an adjustment.\n * - `invalid-level`: a develop value that isn't a whole number from -100 to 100.\n * - `unknown-preset`: a filter that isn't one of `FILTER_PRESETS`.\n * - `invalid-strength`: a filter strength that isn't a whole number from 0 to 100.\n * - `invalid-key`: a key that's empty or over `MAX_KEY_LENGTH` code points.\n * - `duplicate-key`: a new item with a key the plan already uses, or two\n * new items or two updates with the same key.\n * - `invalid-index`: an index past the end of the list.\n * - `invalid-order`: an order that doesn't list every key.\n * - `unknown-layer`: a key no layer has.\n * - `unknown-layer-kind`: a kind other than `text`, `shape` and `image`.\n * - `invalid-box`: a layer's box under 1 × 1 pixel, further than\n * `MAX_SCENE_COORDINATE` from the scene's origin, or turned by other than\n * 0 to 3599 tenths of a degree.\n * - `invalid-opacity`: an opacity that isn't from 0 to 100.\n * - `invalid-text`: text or a name with a control character other than a\n * line feed, or a bidirectional embedding, override or isolate control.\n * - `text-too-long`: text over `MAX_LAYER_TEXT_LENGTH` code points, or a\n * name over `MAX_LAYER_NAME_LENGTH`.\n * - `empty-shape`: a shape with neither a fill nor a stroke.\n * - `wrong-kind`: an update that sets a field another kind of layer has.\n * - `unknown-redaction`: a key no redaction has.\n * - `unknown-redaction-mode`: a mode other than `solid` and `pixelate`.\n * - `invalid-region`: a redaction under 1 × 1 pixel, or further than\n * `MAX_SCENE_COORDINATE` from the scene's origin.\n * - `invalid-colour`: a colour that isn't `#rrggbb` in lower case.\n * - `unexpected-colour`: an update that sets a colour on a pixelated\n * redaction, which has none.\n * - `missing-colour`: an update that sets a redaction to solid without a\n * colour.\n * - `too-many-layers`: more layers and redactions than `MAX_PLAN_ITEMS`,\n * the format's ceiling. The file policy's `maxLayers` is checked by the\n * session, with its own error code.\n *\n * @public\n */\nexport type ImageCommandRejection =\n | \"malformed-command\"\n | \"unknown-command\"\n | \"unknown-source\"\n | \"crop-outside-source\"\n | \"invalid-orientation\"\n | \"invalid-output\"\n | \"unknown-metadata-field\"\n | \"metadata-too-long\"\n | \"unknown-adjustment\"\n | \"invalid-level\"\n | \"unknown-preset\"\n | \"invalid-strength\"\n | \"invalid-key\"\n | \"duplicate-key\"\n | \"invalid-index\"\n | \"invalid-order\"\n | \"unknown-layer\"\n | \"unknown-layer-kind\"\n | \"invalid-box\"\n | \"invalid-opacity\"\n | \"invalid-text\"\n | \"text-too-long\"\n | \"empty-shape\"\n | \"empty-drawing\"\n | \"empty-arrow\"\n | \"invalid-points\"\n | \"too-many-strokes\"\n | \"wrong-kind\"\n | \"unknown-redaction\"\n | \"unknown-redaction-mode\"\n | \"invalid-region\"\n | \"invalid-colour\"\n | \"unexpected-colour\"\n | \"missing-colour\"\n | \"too-many-layers\";\n\n/** @internal */\nexport function checkOrientation(value: unknown): ImageOrientation {\n if (!isRecord<ImageOrientation>(value))\n invalid(\"malformed-command\", \"an orientation is an object\");\n allFields(value, [\"rotate\", \"flipX\", \"flipY\"], \"an orientation\");\n const { rotate, flipX, flipY } = value;\n if (typeof flipX !== \"boolean\" || typeof flipY !== \"boolean\") {\n invalid(\"malformed-command\", \"an orientation's flips are booleans\");\n }\n if (![0, 90, 180, 270].includes(rotate)) {\n invalid(\"invalid-orientation\", \"a rotation is 0, 90, 180 or 270 degrees\");\n }\n return { rotate, flipX, flipY };\n}\n\n/** @internal */\nexport function checkOutput(value: unknown): ImageOutput {\n if (!isRecord<ImageOutput>(value)) invalid(\"malformed-command\", \"an output is an object\");\n if (value.kind === \"scale\") {\n allFields(value, [\"kind\", \"scale\"], \"a scale output\");\n if (typeof value.scale !== \"number\") invalid(\"malformed-command\", \"a scale is a number\");\n if (!(Number.isFinite(value.scale) && value.scale > 0 && value.scale <= 1)) {\n invalid(\"invalid-output\", \"an output scale is more than 0 and at most 1\");\n }\n return { kind: \"scale\", scale: value.scale };\n }\n if (value.kind === \"fit\") {\n allFields(value, [\"kind\", \"width\", \"height\"], \"a box output\");\n const { width, height } = value;\n if (!Number.isInteger(width) || !Number.isInteger(height)) {\n invalid(\"malformed-command\", \"a box's width and height are whole numbers\");\n }\n if (!isWhole(width, 1) || !isWhole(height, 1)) {\n invalid(\"invalid-output\", \"an output box is at least 1 × 1 pixel\");\n }\n return { kind: \"fit\", width, height };\n }\n return invalid(\"malformed-command\", \"an output is either a scale or a box to fit\");\n}\n\nconst METADATA_FIELDS: readonly (keyof ImageKeepableMetadata)[] = [\n \"title\",\n \"description\",\n \"artist\",\n \"copyright\",\n];\n\n/** @internal */\nexport function checkMetadataValue(field: string, value: unknown): string {\n if (typeof value !== \"string\") invalid(\"malformed-command\", `metadata.${field} is text`);\n if (longerThan(value, MAX_METADATA_LENGTH)) {\n invalid(\n \"metadata-too-long\",\n `metadata.${field} has more than ${MAX_METADATA_LENGTH} code points`,\n );\n }\n return value;\n}\n\n/** @internal */\nexport function checkMetadata(value: unknown): ImageKeepableMetadata {\n if (!isRecord<ImageKeepableMetadata>(value))\n invalid(\"malformed-command\", \"metadata is an object\");\n allFields(value, METADATA_FIELDS, \"metadata\");\n return Object.fromEntries(\n METADATA_FIELDS.map((field) => [field, checkMetadataValue(field, value[field])]),\n ) as unknown as ImageKeepableMetadata;\n}\n\nconst ADJUSTMENTS: readonly string[] = DEVELOP_ADJUSTMENTS;\nconst PRESETS: readonly string[] = FILTER_PRESETS;\n\n/** Develop values: some adjustments, or with `all`, every one. @internal */\nexport function checkDevelop(value: unknown, all = false): Partial<ImageDevelop> {\n if (!isRecord<Record<string, unknown>>(value)) {\n invalid(\"malformed-command\", \"develop values are an object\");\n }\n const values: Partial<Record<keyof ImageDevelop, number>> = {};\n for (const [name, level] of Object.entries(value)) {\n if (!ADJUSTMENTS.includes(name)) {\n invalid(\"unknown-adjustment\", `\"${name}\" isn't a develop adjustment`);\n }\n if (typeof level !== \"number\") invalid(\"malformed-command\", `${name} is a number`);\n if (!isWhole(level, -100, 100)) {\n invalid(\"invalid-level\", `${name} is a whole number from -100 to 100`);\n }\n values[name as keyof ImageDevelop] = level;\n }\n if (all) allFields(value, ADJUSTMENTS, \"develop\");\n // In the adjustments' order, whatever the input's.\n return Object.fromEntries(\n DEVELOP_ADJUSTMENTS.filter((name) => name in values).map((name) => [name, values[name]]),\n ) as Partial<ImageDevelop>;\n}\n\n/** @internal */\nexport function checkFilter(value: unknown): ImageFilter | null {\n if (value === null) return null;\n if (!isRecord<ImageFilter>(value)) invalid(\"malformed-command\", \"a filter is an object or null\");\n allFields(value, [\"preset\", \"strength\"], \"a filter\");\n if (typeof value.preset !== \"string\") invalid(\"malformed-command\", \"a filter's preset is text\");\n if (!PRESETS.includes(value.preset)) {\n invalid(\"unknown-preset\", `a filter's preset is one of ${FILTER_PRESETS.join(\", \")}`);\n }\n if (typeof value.strength !== \"number\") {\n invalid(\"malformed-command\", \"a filter's strength is a number\");\n }\n if (!isWhole(value.strength, 0, 100)) {\n invalid(\"invalid-strength\", \"a filter's strength is a whole number from 0 to 100\");\n }\n return { preset: value.preset, strength: value.strength };\n}\n\n/** Each command's fields, which are all required. */\nconst COMMAND_FIELDS: Readonly<Record<ImageCommand[\"type\"], readonly string[]>> = {\n \"image.setCrop\": [\"type\", \"crop\"],\n \"image.setOrientation\": [\"type\", \"orientation\"],\n \"image.setOutput\": [\"type\", \"output\"],\n \"image.setMetadata\": [\"type\", \"field\", \"value\"],\n \"image.setDevelop\": [\"type\", \"values\"],\n \"image.setFilter\": [\"type\", \"filter\"],\n \"image.insertLayers\": [\"type\", \"at\", \"layers\"],\n \"image.removeLayers\": [\"type\", \"keys\"],\n \"image.moveLayers\": [\"type\", \"keys\", \"to\"],\n \"image.updateLayers\": [\"type\", \"updates\"],\n \"image.restoreLayers\": [\"type\", \"entries\"],\n \"image.setLayerOrder\": [\"type\", \"keys\"],\n \"image.addStrokes\": [\"type\", \"key\", \"strokes\"],\n \"image.removeStrokes\": [\"type\", \"key\", \"indexes\"],\n \"image.restoreStrokes\": [\"type\", \"key\", \"entries\"],\n \"image.insertRedactions\": [\"type\", \"at\", \"redactions\"],\n \"image.removeRedactions\": [\"type\", \"keys\"],\n \"image.moveRedactions\": [\"type\", \"keys\", \"to\"],\n \"image.updateRedactions\": [\"type\", \"updates\"],\n \"image.restoreRedactions\": [\"type\", \"entries\"],\n \"image.setRedactionOrder\": [\"type\", \"keys\"],\n};\n\n/** Every key the plan uses: a new item needs one that isn't among them. */\nfunction planKeys(plan: ImagePlan): Set<string> {\n return new Set([...plan.layers, ...plan.redactions].map((item: { key: string }) => item.key));\n}\n\n/** Refuses more layers and redactions than the format holds. */\nfunction checkRoom(plan: ImagePlan, added: number): void {\n if (plan.layers.length + plan.redactions.length + added > MAX_PLAN_ITEMS) {\n invalid(\n \"too-many-layers\",\n `a plan holds at most ${MAX_PLAN_ITEMS} layers and redactions together`,\n );\n }\n}\n\ntype SourceSize = (id: string) => ImageSize | undefined;\n\n/** A list of at least one layer. */\nfunction checkLayers(value: unknown, sourceSize: SourceSize): ImageLayer[] {\n if (!Array.isArray(value)) invalid(\"malformed-command\", \"layers is a list\");\n if (value.length === 0) invalid(\"malformed-command\", \"layers has at least one item\");\n return value.map((layer) => checkLayer(layer, sourceSize));\n}\n\n/** The entries of `image.restoreLayers`. */\nfunction checkLayerEntries(value: unknown, sourceSize: SourceSize): KeyedEntry<ImageLayer>[] {\n if (!Array.isArray(value)) invalid(\"malformed-command\", \"entries is a list\");\n if (value.length === 0) invalid(\"malformed-command\", \"entries has at least one item\");\n return value.map((entry) => {\n if (!isRecord<{ at: unknown; layer: unknown }>(entry)) {\n invalid(\"malformed-command\", \"an entry is an object\");\n }\n allFields(entry, [\"at\", \"layer\"], \"an entry\");\n return { at: entry.at as number, item: checkLayer(entry.layer, sourceSize) };\n });\n}\n\n/** A list of at least one redaction. */\nfunction checkRedactions(value: unknown): ImageRedaction[] {\n if (!Array.isArray(value)) invalid(\"malformed-command\", \"redactions is a list\");\n if (value.length === 0) invalid(\"malformed-command\", \"redactions has at least one item\");\n return value.map(checkRedaction);\n}\n\n/** The entries of `image.restoreRedactions`. */\nfunction checkRedactionEntries(value: unknown): KeyedEntry<ImageRedaction>[] {\n if (!Array.isArray(value)) invalid(\"malformed-command\", \"entries is a list\");\n if (value.length === 0) invalid(\"malformed-command\", \"entries has at least one item\");\n return value.map((entry) => {\n if (!isRecord<{ at: unknown; redaction: unknown }>(entry)) {\n invalid(\"malformed-command\", \"an entry is an object\");\n }\n allFields(entry, [\"at\", \"redaction\"], \"an entry\");\n return { at: entry.at as number, item: checkRedaction(entry.redaction) };\n });\n}\n\nfunction apply(\n plan: ImagePlan,\n input: unknown,\n sourceSize: (id: string) => ImageSize | undefined,\n): { state: ImagePlan; inverse: ImageCommand } {\n if (!isRecord<{ type: unknown }>(input)) invalid(\"malformed-command\", \"a command is an object\");\n const { type } = input;\n if (typeof type !== \"string\") invalid(\"malformed-command\", \"a command's type is text\");\n if (!Object.hasOwn(COMMAND_FIELDS, type)) {\n invalid(\"unknown-command\", `\"${type}\" isn't a command`);\n }\n const command = input as ImageCommand;\n allFields(command, COMMAND_FIELDS[command.type], `${command.type}`);\n switch (command.type) {\n case \"image.setCrop\": {\n const crop = command.crop === null ? null : checkCrop(command.crop);\n if (crop !== null) {\n const size = sourceSize(plan.base.source);\n if (size === undefined) invalid(\"unknown-source\", `unknown source \"${plan.base.source}\"`);\n checkCropInSource(crop, size);\n }\n return {\n state: { ...plan, base: { ...plan.base, crop } },\n inverse: { type: \"image.setCrop\", crop: plan.base.crop },\n };\n }\n case \"image.setOrientation\": {\n const orientation = checkOrientation(command.orientation);\n return {\n state: { ...plan, base: { ...plan.base, orientation } },\n inverse: { type: \"image.setOrientation\", orientation: plan.base.orientation },\n };\n }\n case \"image.setOutput\": {\n const output = checkOutput(command.output);\n return {\n state: { ...plan, output },\n inverse: { type: \"image.setOutput\", output: plan.output },\n };\n }\n case \"image.setMetadata\": {\n const { field } = command;\n if (typeof field !== \"string\") invalid(\"malformed-command\", \"a metadata field is text\");\n if (!(METADATA_FIELDS as readonly string[]).includes(field)) {\n invalid(\"unknown-metadata-field\", \"only title, description, artist and copyright are kept\");\n }\n const value = checkMetadataValue(field, command.value);\n return {\n state: { ...plan, metadata: { ...plan.metadata, [field]: value } },\n inverse: { type: \"image.setMetadata\", field, value: plan.metadata[field] },\n };\n }\n case \"image.setDevelop\": {\n const values = checkDevelop(command.values);\n const previous: Partial<Record<keyof ImageDevelop, number>> = {};\n for (const name of Object.keys(values) as (keyof ImageDevelop)[]) {\n previous[name] = plan.base.develop[name];\n }\n return {\n state: { ...plan, base: { ...plan.base, develop: { ...plan.base.develop, ...values } } },\n inverse: { type: \"image.setDevelop\", values: previous },\n };\n }\n case \"image.setFilter\": {\n const filter = checkFilter(command.filter);\n return {\n state: { ...plan, base: { ...plan.base, filter } },\n inverse: { type: \"image.setFilter\", filter: plan.base.filter },\n };\n }\n case \"image.insertLayers\": {\n const layers = checkLayers(command.layers, sourceSize);\n const { list, keys } = insertItems(plan.layers, command.at, layers, planKeys(plan));\n checkRoom(plan, layers.length);\n return { state: { ...plan, layers: list }, inverse: { type: \"image.removeLayers\", keys } };\n }\n case \"image.removeLayers\": {\n const { list, entries } = removeItems(plan.layers, command.keys, LAYER_NAMES);\n return {\n state: { ...plan, layers: list },\n inverse: {\n type: \"image.restoreLayers\",\n entries: entries.map(({ at, item }) => ({ at, layer: item })),\n },\n };\n }\n case \"image.restoreLayers\": {\n const entries = checkLayerEntries(command.entries, sourceSize);\n const { list, keys } = restoreItems(plan.layers, entries, planKeys(plan));\n checkRoom(plan, entries.length);\n return { state: { ...plan, layers: list }, inverse: { type: \"image.removeLayers\", keys } };\n }\n case \"image.moveLayers\": {\n const { list, order } = moveItems(plan.layers, command.keys, command.to, LAYER_NAMES);\n return {\n state: { ...plan, layers: list },\n inverse: { type: \"image.setLayerOrder\", keys: order },\n };\n }\n case \"image.setLayerOrder\": {\n const { list, order } = orderItems(plan.layers, command.keys, LAYER_NAMES);\n return {\n state: { ...plan, layers: list },\n inverse: { type: \"image.setLayerOrder\", keys: order },\n };\n }\n case \"image.updateLayers\": {\n const { list, previous } = updateItems(\n plan.layers,\n command.updates,\n LAYER_NAMES,\n (item, props) => patchLayer(item, props, sourceSize),\n );\n return {\n state: { ...plan, layers: list },\n inverse: { type: \"image.updateLayers\", updates: previous },\n };\n }\n case \"image.addStrokes\":\n return addStrokes(plan, command.key, command.strokes);\n case \"image.removeStrokes\":\n return removeStrokes(plan, command.key, command.indexes);\n case \"image.restoreStrokes\":\n return restoreStrokes(plan, command.key, command.entries);\n case \"image.insertRedactions\": {\n const redactions = checkRedactions(command.redactions);\n const { list, keys } = insertItems(plan.redactions, command.at, redactions, planKeys(plan));\n checkRoom(plan, redactions.length);\n return {\n state: { ...plan, redactions: list },\n inverse: { type: \"image.removeRedactions\", keys },\n };\n }\n case \"image.removeRedactions\": {\n const { list, entries } = removeItems(plan.redactions, command.keys, REDACTION_NAMES);\n return {\n state: { ...plan, redactions: list },\n inverse: {\n type: \"image.restoreRedactions\",\n entries: entries.map(({ at, item }) => ({ at, redaction: item })),\n },\n };\n }\n case \"image.restoreRedactions\": {\n const entries = checkRedactionEntries(command.entries);\n const { list, keys } = restoreItems(plan.redactions, entries, planKeys(plan));\n checkRoom(plan, entries.length);\n return {\n state: { ...plan, redactions: list },\n inverse: { type: \"image.removeRedactions\", keys },\n };\n }\n case \"image.moveRedactions\": {\n const { list, order } = moveItems(plan.redactions, command.keys, command.to, REDACTION_NAMES);\n return {\n state: { ...plan, redactions: list },\n inverse: { type: \"image.setRedactionOrder\", keys: order },\n };\n }\n case \"image.setRedactionOrder\": {\n const { list, order } = orderItems(plan.redactions, command.keys, REDACTION_NAMES);\n return {\n state: { ...plan, redactions: list },\n inverse: { type: \"image.setRedactionOrder\", keys: order },\n };\n }\n case \"image.updateRedactions\": {\n const { list, previous } = updateItems(\n plan.redactions,\n command.updates,\n REDACTION_NAMES,\n patchRedaction,\n );\n return {\n state: { ...plan, redactions: list },\n inverse: { type: \"image.updateRedactions\", updates: previous },\n };\n }\n }\n}\n\n/**\n * Creates the reducer for {@link ImageCommand}s: a pure function that\n * applies one command and returns the command that undoes it (ADR 0003,\n * ADR 0029). It needs the oriented size of each source, to check crops.\n *\n * Commands are strict, as the `hm-image-command` schema is (sdk-core ADR\n * 0045): an invalid command, including one with a field its type doesn't\n * have, throws `ImageError` with `INVALID_COMMAND` and an\n * {@link ImageCommandRejection} as `details.reason`. The reducer never\n * silently corrects one.\n *\n * @public\n */\nexport function createImageReducer(\n sourceSize: (id: string) => ImageSize | undefined,\n): Reducer<ImagePlan, ImageCommand> {\n return (plan, command) => {\n try {\n return apply(plan, command, sourceSize);\n } catch (error) {\n if (!(error instanceof Invalid)) throw error;\n throw new ImageError(\"INVALID_COMMAND\", `Invalid command: ${error.message}.`, {\n details: { reason: error.reason },\n });\n }\n };\n}\n","import type { ImageCrop, ImageOrientation, ImageOutput, ImagePlan } from \"./plan.js\";\nimport type { ExifOrientation, ImageSize } from \"./source.js\";\n\n/**\n * A point in pixels, which may be fractional.\n *\n * @public\n */\nexport interface ImagePoint {\n readonly x: number;\n readonly y: number;\n}\n\n/**\n * The upright size of stored pixels with an EXIF orientation: orientations 5\n * to 8 swap width and height (ADR 0005).\n *\n * @public\n */\nexport function orientedSize(stored: ImageSize, orientation: ExifOrientation): ImageSize {\n return orientation >= 5 ? { width: stored.height, height: stored.width } : stored;\n}\n\n/**\n * The cropped area of a source, or the whole source when there's no crop.\n *\n * @public\n */\nexport function cropRect(crop: ImageCrop | null, source: ImageSize): ImageCrop {\n return crop ?? { x: 0, y: 0, width: source.width, height: source.height };\n}\n\n/**\n * The size of the composition: the cropped source, turned by the plan's own\n * rotation (ADR 0003).\n *\n * @public\n */\nexport function compositionSize(plan: ImagePlan, source: ImageSize): ImageSize {\n const { width, height } = cropRect(plan.base.crop, source);\n const turned = plan.base.orientation.rotate % 180 !== 0;\n return turned ? { width: height, height: width } : { width, height };\n}\n\n/**\n * The size an export produces: the composition scaled down or fitted inside\n * a box, never enlarged, rounded to whole pixels and at least 1 × 1.\n *\n * @public\n */\nexport function outputSize(output: ImageOutput, composition: ImageSize): ImageSize {\n const factor =\n output.kind === \"scale\"\n ? output.scale\n : Math.min(1, output.width / composition.width, output.height / composition.height);\n return {\n width: Math.max(1, Math.round(composition.width * factor)),\n height: Math.max(1, Math.round(composition.height * factor)),\n };\n}\n\n/**\n * Maps a point in the cropped source to the composition, through the plan's\n * rotation and then its flips. Points are continuous coordinates, so the\n * cropped rectangle's corners map to the composition's corners.\n *\n * @public\n */\nexport function sourceToComposition(\n point: ImagePoint,\n crop: ImageCrop,\n orientation: ImageOrientation,\n): ImagePoint {\n const x = point.x - crop.x;\n const y = point.y - crop.y;\n const { width, height } = crop;\n let turned: ImagePoint;\n switch (orientation.rotate) {\n case 90:\n turned = { x: height - y, y: x };\n break;\n case 180:\n turned = { x: width - x, y: height - y };\n break;\n case 270:\n turned = { x: y, y: width - x };\n break;\n default:\n turned = { x, y };\n }\n const size =\n orientation.rotate % 180 === 0 ? { width, height } : { width: height, height: width };\n return {\n x: orientation.flipX ? size.width - turned.x : turned.x,\n y: orientation.flipY ? size.height - turned.y : turned.y,\n };\n}\n\n/**\n * The inverse of {@link sourceToComposition}: maps a point in the\n * composition, such as the pointer, back to the source.\n *\n * @public\n */\nexport function compositionToSource(\n point: ImagePoint,\n crop: ImageCrop,\n orientation: ImageOrientation,\n): ImagePoint {\n const { width, height } = crop;\n const size =\n orientation.rotate % 180 === 0 ? { width, height } : { width: height, height: width };\n const x = orientation.flipX ? size.width - point.x : point.x;\n const y = orientation.flipY ? size.height - point.y : point.y;\n let source: ImagePoint;\n switch (orientation.rotate) {\n case 90:\n source = { x: y, y: height - x };\n break;\n case 180:\n source = { x: width - x, y: height - y };\n break;\n case 270:\n source = { x: width - y, y: x };\n break;\n default:\n source = { x, y };\n }\n return { x: source.x + crop.x, y: source.y + crop.y };\n}\n","import { compositionToSource, sourceToComposition } from \"./geometry.js\";\nimport type { ImageCrop, ImageOrientation } from \"./plan.js\";\nimport type { ImageSize } from \"./source.js\";\n\n/**\n * The crop frame's geometry (docs/adr/0007): pure functions over crops in\n * whole pixels of the oriented source, which the editor's frame, keys and\n * fields share, so every way of cropping gives the same result.\n */\n\n/**\n * An aspect ratio the crop panel offers: free, the source's own, or width\n * over height.\n *\n * @public\n */\nexport type ImageAspect = \"free\" | \"original\" | readonly [number, number];\n\n/**\n * The crop panel's presets, landscape then portrait (docs/adr/0007).\n *\n * @public\n */\nexport const ASPECT_PRESETS: readonly ImageAspect[] = [\n \"free\",\n \"original\",\n [1, 1],\n [4, 3],\n [3, 2],\n [16, 9],\n [3, 4],\n [2, 3],\n [9, 16],\n];\n\n/**\n * The ratio of an aspect, width over height, or `undefined` for free.\n *\n * @public\n */\nexport function aspectRatio(aspect: ImageAspect, source: ImageSize): number | undefined {\n if (aspect === \"free\") return undefined;\n if (aspect === \"original\") return source.width / source.height;\n return aspect[0] / aspect[1];\n}\n\n/** The whole source as a crop. */\nexport const wholeCrop = (source: ImageSize): ImageCrop => ({\n x: 0,\n y: 0,\n width: source.width,\n height: source.height,\n});\n\n/**\n * The largest crop of a ratio inside `within`, centred in it, in whole\n * pixels and at least 1 × 1. With no ratio, `within` as it is.\n *\n * @public\n */\nexport function fitAspect(within: ImageCrop, ratio: number | undefined): ImageCrop {\n if (ratio === undefined) return within;\n let width = within.width;\n let height = Math.round(width / ratio);\n if (height > within.height) {\n height = within.height;\n width = Math.round(height * ratio);\n }\n width = Math.max(1, Math.min(within.width, width));\n height = Math.max(1, Math.min(within.height, height));\n return {\n x: within.x + Math.floor((within.width - width) / 2),\n y: within.y + Math.floor((within.height - height) / 2),\n width,\n height,\n };\n}\n\n/**\n * A crop moved by whole pixels, kept inside the source.\n *\n * @public\n */\nexport function moveCrop(crop: ImageCrop, dx: number, dy: number, source: ImageSize): ImageCrop {\n return {\n ...crop,\n x: Math.min(source.width - crop.width, Math.max(0, crop.x + Math.round(dx))),\n y: Math.min(source.height - crop.height, Math.max(0, crop.y + Math.round(dy))),\n };\n}\n\n/**\n * The edges a handle moves: `n`, `s`, `e` and `w`, and the corners that\n * combine two.\n *\n * @public\n */\nexport type CropHandle = \"n\" | \"s\" | \"e\" | \"w\" | \"ne\" | \"nw\" | \"se\" | \"sw\";\n\n/**\n * A crop with a handle dragged by a distance in source pixels, kept inside\n * the source and at least 1 × 1, in whole pixels. With a ratio, the opposite\n * edge or corner stays put and the other side follows the ratio.\n *\n * @public\n */\nexport function dragHandle(\n crop: ImageCrop,\n handle: CropHandle,\n dx: number,\n dy: number,\n source: ImageSize,\n ratio?: number,\n): ImageCrop {\n let left = crop.x;\n let top = crop.y;\n let right = crop.x + crop.width;\n let bottom = crop.y + crop.height;\n if (handle.includes(\"w\")) left = Math.min(right - 1, Math.max(0, left + dx));\n if (handle.includes(\"e\")) right = Math.max(left + 1, Math.min(source.width, right + dx));\n if (handle.includes(\"n\")) top = Math.min(bottom - 1, Math.max(0, top + dy));\n if (handle.includes(\"s\")) bottom = Math.max(top + 1, Math.min(source.height, bottom + dy));\n left = Math.round(left);\n right = Math.round(right);\n top = Math.round(top);\n bottom = Math.round(bottom);\n if (ratio === undefined) {\n return { x: left, y: top, width: right - left, height: bottom - top };\n }\n // Keep the ratio from the moved size, anchored at the opposite side, and\n // within the room the source leaves there.\n const horizontal = handle.includes(\"e\") || handle.includes(\"w\");\n const vertical = handle.includes(\"n\") || handle.includes(\"s\");\n let width = right - left;\n let height = bottom - top;\n if (horizontal && !vertical) height = width / ratio;\n else if (vertical && !horizontal) width = height * ratio;\n else if (width / height > ratio) width = height * ratio;\n else height = width / ratio;\n const roomRight = handle.includes(\"w\") ? right : source.width - left;\n const roomDown = handle.includes(\"n\") ? bottom : source.height - top;\n const scale = Math.min(1, roomRight / width, roomDown / height);\n width = Math.max(1, Math.round(width * scale));\n height = Math.max(1, Math.round(height * scale));\n const x = handle.includes(\"w\") ? right - width : left;\n let y = handle.includes(\"n\") ? bottom - height : top;\n // A side handle keeps the crop centred across it.\n let cx = x;\n if (vertical && !horizontal) cx = Math.round(crop.x + (crop.width - width) / 2);\n if (horizontal && !vertical) y = Math.round(crop.y + (crop.height - height) / 2);\n return {\n x: Math.min(source.width - width, Math.max(0, cx)),\n y: Math.min(source.height - height, Math.max(0, y)),\n width,\n height,\n };\n}\n\n/**\n * Where a crop of the oriented source appears in the composition of the\n * whole source under an orientation: an axis-aligned rectangle, since the\n * plan turns in quarter turns.\n *\n * @public\n */\nexport function cropInComposition(\n crop: ImageCrop,\n orientation: ImageOrientation,\n source: ImageSize,\n): ImageCrop {\n const whole = wholeCrop(source);\n const a = sourceToComposition({ x: crop.x, y: crop.y }, whole, orientation);\n const b = sourceToComposition(\n { x: crop.x + crop.width, y: crop.y + crop.height },\n whole,\n orientation,\n );\n return {\n x: Math.min(a.x, b.x),\n y: Math.min(a.y, b.y),\n width: Math.abs(b.x - a.x),\n height: Math.abs(b.y - a.y),\n };\n}\n\n/**\n * A distance in the composition of the whole source, as a distance in the\n * oriented source: what a pointer drag on the stage moves the crop by.\n *\n * @public\n */\nexport function compositionDeltaToSource(\n dx: number,\n dy: number,\n orientation: ImageOrientation,\n source: ImageSize,\n): { readonly dx: number; readonly dy: number } {\n const whole = wholeCrop(source);\n const origin = compositionToSource({ x: 0, y: 0 }, whole, orientation);\n const moved = compositionToSource({ x: dx, y: dy }, whole, orientation);\n return { dx: moved.x - origin.x, dy: moved.y - origin.y };\n}\n\n/**\n * Which source edges a handle on screen moves, under an orientation: the\n * handle's compass point in the composition, mapped back to the source.\n *\n * @public\n */\nexport function handleInSource(handle: CropHandle, orientation: ImageOrientation): CropHandle {\n const vector = { x: 0, y: 0 };\n if (handle.includes(\"e\")) vector.x = 1;\n if (handle.includes(\"w\")) vector.x = -1;\n if (handle.includes(\"s\")) vector.y = 1;\n if (handle.includes(\"n\")) vector.y = -1;\n const unit = compositionDeltaToSource(vector.x, vector.y, orientation, { width: 2, height: 2 });\n const ns = unit.dy > 0 ? \"s\" : unit.dy < 0 ? \"n\" : \"\";\n const ew = unit.dx > 0 ? \"e\" : unit.dx < 0 ? \"w\" : \"\";\n return `${ns}${ew}` as CropHandle;\n}\n\n/**\n * Moves or resizes a crop from the keyboard as it's seen on screen\n * (docs/adr/0007): an arrow moves it that way on screen, by `step` pixels of\n * the source; with `resize`, Left and Right move its right edge on screen,\n * and Up and Down its bottom edge, keeping a ratio if one is set.\n *\n * @public\n */\nexport function nudgeCropOnScreen(\n crop: ImageCrop,\n key: \"ArrowLeft\" | \"ArrowRight\" | \"ArrowUp\" | \"ArrowDown\",\n step: number,\n resize: boolean,\n orientation: ImageOrientation,\n source: ImageSize,\n ratio?: number,\n): ImageCrop {\n const dx = key === \"ArrowLeft\" ? -step : key === \"ArrowRight\" ? step : 0;\n const dy = key === \"ArrowUp\" ? -step : key === \"ArrowDown\" ? step : 0;\n const moved = compositionDeltaToSource(dx, dy, orientation, source);\n if (!resize) return moveCrop(crop, moved.dx, moved.dy, source);\n const handle = handleInSource(dx === 0 ? \"s\" : \"e\", orientation);\n return dragHandle(crop, handle, moved.dx, moved.dy, source, ratio);\n}\n","import {\n type ImageArrowLayer,\n type ImageDrawingLayer,\n type ImagePlan,\n type ImageScenePoint,\n MAX_RUN_POINTS,\n MAX_STROKE_RUNS,\n} from \"./plan.js\";\nimport type { ImageRect } from \"./redaction-geometry.js\";\n\n/**\n * Simplifies one run in place of its kept points: Ramer–Douglas–Peucker on\n * whole pixels, with distance to the segment (docs/adr/0014). Every\n * comparison is between whole numbers. A squared cross product reaches\n * 2⁷⁰, past what a double holds, so those are `BigInt`s; everything else is\n * exact in doubles.\n */\nfunction simplifyRun(xs: readonly number[], ys: readonly number[], tolerance: number): number[] {\n const count = xs.length;\n const keep = new Uint8Array(count);\n keep[0] = 1;\n keep[count - 1] = 1;\n const limit = BigInt(tolerance) * BigInt(tolerance);\n // Its own stack, so a long run can't exhaust the call stack.\n const stack = [0, count - 1];\n while (stack.length > 0) {\n const last = stack.pop() as number;\n const first = stack.pop() as number;\n if (last - first < 2) continue;\n const ax = xs[first] as number;\n const ay = ys[first] as number;\n const dx = (xs[last] as number) - ax;\n const dy = (ys[last] as number) - ay;\n // Under 2³⁶: exact.\n const length = dx * dx + dy * dy;\n let farthest = -1;\n let most = -1n;\n for (let index = first + 1; index < last; index += 1) {\n const px = (xs[index] as number) - ax;\n const py = (ys[index] as number) - ay;\n let measure: bigint;\n if (length === 0) {\n // A closed loop: the distance to the point both ends are.\n measure = BigInt(px * px + py * py);\n } else {\n const along = px * dx + py * dy;\n if (along <= 0) {\n // Before the segment's start: as far as it is from the start.\n measure = BigInt(px * px + py * py) * BigInt(length);\n } else if (along >= length) {\n const qx = px - dx;\n const qy = py - dy;\n measure = BigInt(qx * qx + qy * qy) * BigInt(length);\n } else {\n const cross = BigInt(px * dy - py * dx);\n measure = cross * cross;\n }\n }\n // Among points equally far, the first.\n if (measure > most) {\n most = measure;\n farthest = index;\n }\n }\n if (most > (length === 0 ? limit : limit * BigInt(length))) {\n keep[farthest] = 1;\n stack.push(first, farthest, farthest, last);\n }\n }\n const points: number[] = [];\n for (let index = 0; index < count; index += 1) {\n if (keep[index] === 1) points.push(xs[index] as number, ys[index] as number);\n }\n return points;\n}\n\n/**\n * A pointer's samples as one stroke's `runs` (docs/adr/0014): repeats\n * dropped, long input cut into runs of at most 2,000 points that share\n * their end points, and each run simplified by Ramer–Douglas–Peucker with\n * distance to the segment. The same samples give the same runs in every\n * engine: every comparison is between whole numbers.\n *\n * A tolerance of 0 drops only repeats and points exactly on a segment.\n *\n * @param points - `[x0, y0, x1, y1, …]`, in whole pixels from the drawing's\n * origin: at least one point.\n * @param tolerance - In whole scene pixels, from 0. The draw tool passes one\n * screen pixel's worth.\n * @returns 1 to 64 runs, each `[x0, y0, …]` of 1 to 2,000 points.\n * @throws `RangeError` for no points, an odd number of coordinates, a\n * coordinate or a tolerance that isn't a whole number, or more points\n * than 64 runs hold: a caller's mistake, since samples aren't a file's.\n * @public\n */\nexport function simplifyStroke(points: readonly number[], tolerance: number): number[][] {\n if (points.length < 2 || points.length % 2 !== 0) {\n throw new RangeError(\"A stroke's samples are an x and a y for each of at least one point.\");\n }\n if (!Number.isSafeInteger(tolerance) || tolerance < 0) {\n throw new RangeError(\"A tolerance is a whole number of pixels, from 0.\");\n }\n // Repeats go first.\n const xs: number[] = [];\n const ys: number[] = [];\n for (let index = 0; index < points.length; index += 2) {\n const x = points[index] as number;\n const y = points[index + 1] as number;\n if (!Number.isSafeInteger(x) || !Number.isSafeInteger(y)) {\n throw new RangeError(\"A stroke's samples are in whole pixels.\");\n }\n const previous = xs.length - 1;\n if (previous >= 0 && xs[previous] === x && ys[previous] === y) continue;\n xs.push(x);\n ys.push(y);\n }\n if (xs.length === 1) return [[xs[0] as number, ys[0] as number]];\n // Each run starts on the last point of the one before, so the runs join:\n // a run after the first adds 1,999 new points.\n const runs: number[][] = [];\n for (let start = 0; start < xs.length - 1; start += MAX_RUN_POINTS - 1) {\n if (runs.length === MAX_STROKE_RUNS) {\n throw new RangeError(`A stroke holds at most ${MAX_STROKE_RUNS} runs of samples.`);\n }\n const end = Math.min(start + MAX_RUN_POINTS, xs.length);\n runs.push(simplifyRun(xs.slice(start, end), ys.slice(start, end), tolerance));\n }\n return runs;\n}\n\n/**\n * An arrow's outline (docs/adr/0014): seven points of a polygon, in scene\n * pixels, which the renderer fills. Its tip is exactly on `to`. The head is\n * a triangle `4 × width` long and `4 × width` across at its base; the shaft\n * is a rectangle `width` across from `from` to the middle of the head's\n * base. An arrow shorter than its head is all head: the triangle keeps its\n * proportions, as long as the arrow, and the shaft's four points are on its\n * base.\n *\n * In order: the shaft's tail, left then right as the arrow points; the\n * shaft's end on the base, right; the head's right corner; the tip; the\n * head's left corner; the shaft's end on the base, left.\n *\n * @throws `RangeError` when `from` equals `to`: there's no direction.\n * @public\n */\nexport function arrowOutline(\n from: ImageScenePoint,\n to: ImageScenePoint,\n width: number,\n): ImageScenePoint[] {\n const dx = to.x - from.x;\n const dy = to.y - from.y;\n const length = Math.hypot(dx, dy);\n if (!(length > 0)) throw new RangeError(\"An arrow's ends differ.\");\n // Along the arrow, and to its left as it points.\n const ux = dx / length;\n const uy = dy / length;\n const lx = uy;\n const ly = -ux;\n const head = Math.min(4 * width, length);\n // The head keeps its proportions when it's shortened.\n const half = head / 2;\n const shaft = Math.min(width / 2, half);\n const base = { x: to.x - ux * head, y: to.y - uy * head };\n const at = (origin: { x: number; y: number }, left: number): ImageScenePoint => ({\n x: origin.x + lx * left || 0,\n y: origin.y + ly * left || 0,\n });\n return [\n at(from, shaft),\n at(from, -shaft),\n at(base, -shaft),\n at(base, -half),\n { x: to.x, y: to.y },\n at(base, half),\n at(base, shaft),\n ];\n}\n\n/** The smallest whole-pixel rectangle around a box given by its edges. */\nconst around = (left: number, top: number, right: number, bottom: number): ImageRect => {\n const x = Math.floor(left);\n const y = Math.floor(top);\n return { x, y, width: Math.ceil(right) - x, height: Math.ceil(bottom) - y };\n};\n\n/**\n * The smallest whole-pixel rectangle of the scene that holds everything a\n * drawing draws: its points, and half of each stroke's width around them\n * (docs/adr/0014). The editor places a drawing's frame with it.\n *\n * @public\n */\nexport function drawingBounds(drawing: Pick<ImageDrawingLayer, \"x\" | \"y\" | \"strokes\">): ImageRect {\n let left = Number.POSITIVE_INFINITY;\n let top = Number.POSITIVE_INFINITY;\n let right = Number.NEGATIVE_INFINITY;\n let bottom = Number.NEGATIVE_INFINITY;\n for (const stroke of drawing.strokes) {\n const reach = stroke.width / 2;\n for (const run of stroke.runs) {\n for (let index = 0; index + 1 < run.length; index += 2) {\n const x = drawing.x + (run[index] as number);\n const y = drawing.y + (run[index + 1] as number);\n left = Math.min(left, x - reach);\n top = Math.min(top, y - reach);\n right = Math.max(right, x + reach);\n bottom = Math.max(bottom, y + reach);\n }\n }\n }\n // A drawing has a stroke; one with none, which the plan refuses, is a point.\n if (left > right) return { x: drawing.x, y: drawing.y, width: 0, height: 0 };\n return around(left, top, right, bottom);\n}\n\n/**\n * The smallest whole-pixel rectangle of the scene that holds an arrow's\n * outline.\n *\n * @public\n */\nexport function arrowBounds(arrow: Pick<ImageArrowLayer, \"from\" | \"to\" | \"width\">): ImageRect {\n const outline = arrowOutline(arrow.from, arrow.to, arrow.width);\n const xs = outline.map((point) => point.x);\n const ys = outline.map((point) => point.y);\n return around(Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys));\n}\n\n/**\n * How many points a plan's drawings hold, across every run of every stroke:\n * what `maxDrawingPoints` limits (ADR 0009).\n *\n * @public\n */\nexport function drawingPoints(plan: Pick<ImagePlan, \"layers\">): number {\n let points = 0;\n for (const layer of plan.layers) {\n if (layer.kind !== \"drawing\") continue;\n for (const stroke of layer.strokes) {\n for (const run of stroke.runs) points += run.length / 2;\n }\n }\n return points;\n}\n","/**\n * A new key for a layer, a redaction or a frame (ADR 0009): 24 hexadecimal\n * digits from the platform's random source, so a key is never reused, even\n * one a removed item had and the history may put back.\n *\n * Commands carry their keys, so the reducer stays pure: whatever builds an\n * `image.insertRedactions` command calls this first.\n *\n * @param used - Keys to avoid, such as the plan's. A clash is not expected:\n * it's checked so that a broken random source can't produce one.\n * @public\n */\nexport function createImageKey(used?: ReadonlySet<string>): string {\n for (;;) {\n const bytes = globalThis.crypto.getRandomValues(new Uint8Array(12));\n const key = Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n if (!used?.has(key)) return key;\n }\n}\n","import { sourceToComposition } from \"./geometry.js\";\nimport type { ImageCrop, ImageLayerBox, ImageOrientation } from \"./plan.js\";\nimport type { ImageSize } from \"./source.js\";\n\n/**\n * A 2D affine transform, as the canvas takes it: `x' = a·x + c·y + e` and\n * `y' = b·x + d·y + f`.\n *\n * @public\n */\nexport type ImageMatrix = readonly [\n a: number,\n b: number,\n c: number,\n d: number,\n e: number,\n f: number,\n];\n\n/** `first` then `second`: the transform that applies `first`, then `second`. */\nfunction then(first: ImageMatrix, second: ImageMatrix): ImageMatrix {\n const [a1, b1, c1, d1, e1, f1] = first;\n const [a2, b2, c2, d2, e2, f2] = second;\n return [\n a2 * a1 + c2 * b1,\n b2 * a1 + d2 * b1,\n a2 * c1 + c2 * d1,\n b2 * c1 + d2 * d1,\n a2 * e1 + c2 * f1 + e2,\n b2 * e1 + d2 * f1 + f2,\n ];\n}\n\n/**\n * The transform from the scene to an output of the given size: through the\n * crop, the rotation and the flips, then the output's scale (ADR 0009). The\n * renderer draws layers through it, and the base through the same mapping,\n * so a layer stays on the pixels it was placed on.\n *\n * It's built from three points mapped by `sourceToComposition`, so it can't\n * disagree with the geometry the editor places frames with. Its entries are\n * exact for an output at the composition's own size.\n *\n * @param crop - The crop, or the whole source: `cropRect(plan.base.crop, source)`.\n * @public\n */\nexport function sceneToOutput(\n crop: ImageCrop,\n orientation: ImageOrientation,\n output: ImageSize,\n): ImageMatrix {\n const turned = orientation.rotate % 180 !== 0;\n const composition = turned\n ? { width: crop.height, height: crop.width }\n : { width: crop.width, height: crop.height };\n const scaleX = output.width / composition.width;\n const scaleY = output.height / composition.height;\n const at = (x: number, y: number) => {\n const point = sourceToComposition({ x, y }, crop, orientation);\n return { x: point.x * scaleX, y: point.y * scaleY };\n };\n const origin = at(0, 0);\n const alongX = at(1, 0);\n const alongY = at(0, 1);\n return [\n alongX.x - origin.x,\n alongX.y - origin.y,\n alongY.x - origin.x,\n alongY.y - origin.y,\n origin.x,\n origin.y,\n ];\n}\n\n/**\n * The transform from a layer's own box to the scene: the box's top-left\n * corner is the origin, one unit is one scene pixel, and the box is mirrored\n * left to right when it's flipped, then turned about its centre by its\n * rotation, clockwise, in tenths of a degree (ADR 0009).\n *\n * @public\n */\nexport function layerToScene(box: ImageLayerBox): ImageMatrix {\n const radians = (box.rotation * Math.PI) / 1_800;\n // Quarter turns are exact: Math.cos(Math.PI / 2) isn't quite 0.\n const quarter = box.rotation % 900 === 0 ? (box.rotation / 900) % 4 : -1;\n const cos = quarter >= 0 ? ([1, 0, -1, 0][quarter] as number) : Math.cos(radians);\n const sin = quarter >= 0 ? ([0, 1, 0, -1][quarter] as number) : Math.sin(radians);\n // Never a negative zero, which JSON can't carry.\n const negative = (value: number) => (value === 0 ? 0 : -value);\n // A flipped box's own x axis runs the other way, before the turn.\n const a = box.flipX ? negative(cos) : cos;\n const b = box.flipX ? negative(sin) : sin;\n const c = negative(sin);\n const d = cos;\n // The box's centre stays where it is: flipped and turned about it.\n return [\n a,\n b,\n c,\n d,\n box.x + box.width / 2 - (a * box.width + c * box.height) / 2,\n box.y + box.height / 2 - (b * box.width + d * box.height) / 2,\n ];\n}\n\n/**\n * The transform from a layer's own box to an output: {@link layerToScene},\n * then {@link sceneToOutput}. The renderer sets it on the canvas and draws\n * the layer in its box's own pixels.\n *\n * @public\n */\nexport function layerToOutput(\n box: ImageLayerBox,\n crop: ImageCrop,\n orientation: ImageOrientation,\n output: ImageSize,\n): ImageMatrix {\n return then(layerToScene(box), sceneToOutput(crop, orientation, output));\n}\n\n/**\n * The inverse of a transform that has one: every transform here does, since\n * a box and an output have at least one pixel.\n *\n * @public\n */\nexport function invertMatrix(matrix: ImageMatrix): ImageMatrix {\n const [a, b, c, d, e, f] = matrix;\n const determinant = a * d - b * c;\n return [\n d / determinant,\n -b / determinant,\n -c / determinant,\n a / determinant,\n (c * f - d * e) / determinant,\n (b * e - a * f) / determinant,\n ];\n}\n\n/**\n * The transform from the scene to an image layer's source pixels: where a\n * point of the scene falls in the bitmap the layer draws. The renderer uses\n * it to replace, in a copy of that bitmap, the pixels a redaction covers\n * (ADR 0010).\n *\n * @param crop - The part of the source the layer draws: its crop, or all of it.\n * @public\n */\nexport function sceneToLayerSource(box: ImageLayerBox, crop: ImageCrop): ImageMatrix {\n // The box's pixels to the crop's, then to the crop's place in the source.\n const boxToSource: ImageMatrix = [\n crop.width / box.width,\n 0,\n 0,\n crop.height / box.height,\n crop.x,\n crop.y,\n ];\n return then(invertMatrix(layerToScene(box)), boxToSource);\n}\n\n/**\n * Where a point goes under a transform.\n *\n * @public\n */\nexport function applyMatrix(\n matrix: ImageMatrix,\n point: { readonly x: number; readonly y: number },\n): { readonly x: number; readonly y: number } {\n const [a, b, c, d, e, f] = matrix;\n return { x: a * point.x + c * point.y + e, y: b * point.x + d * point.y + f };\n}\n\n/**\n * What a line of text measures at the size it's laid out at.\n *\n * @public\n */\nexport interface ImageTextLine {\n /** Its advance: how far the pen moves. */\n readonly width: number;\n}\n\n/**\n * Where a text layer's lines go: the block of lines scaled uniformly to the\n * largest size that fits the box, centred in its height, and each line\n * placed by the alignment (ADR 0009). The layout is in the box's own\n * pixels, so it's the same for the preview and for every export.\n *\n * @param lines - Each line's advance, at the size they were measured at.\n * @param lineHeight - The height of one line at that size: the font's ascent\n * and descent.\n * @param ascent - The font's ascent at that size: from a line's top to its baseline.\n * @param box - The layer's box: its width and height.\n * @param align - `start`, `center` or `end`, by the text's direction.\n * @param rightToLeft - Whether the text's direction is right to left, so\n * `start` is the box's right edge.\n * @returns The scale from the measured size to the drawn size, and for each\n * line the x of its left edge and the y of its baseline, in the box's\n * pixels. `null` when there's nothing to draw: no line has a width.\n * @public\n */\nexport function fitTextLines(\n lines: readonly ImageTextLine[],\n lineHeight: number,\n ascent: number,\n box: ImageSize,\n align: \"start\" | \"center\" | \"end\",\n rightToLeft: boolean,\n): {\n readonly scale: number;\n readonly lines: readonly { readonly x: number; readonly baseline: number }[];\n} | null {\n const widest = Math.max(0, ...lines.map((line) => line.width));\n if (!(widest > 0) || !(lineHeight > 0)) return null;\n const scale = Math.min(box.width / widest, box.height / (lineHeight * lines.length));\n const top = (box.height - lineHeight * lines.length * scale) / 2;\n // Which edge of the box the lines sit against: 0 the left, 1 the right.\n const side = align === \"center\" ? 0.5 : (align === \"start\") === rightToLeft ? 1 : 0;\n return {\n scale,\n lines: lines.map((line, index) => ({\n x: (box.width - line.width * scale) * side,\n baseline: top + (index * lineHeight + ascent) * scale,\n })),\n };\n}\n\n/**\n * Whether text reads right to left: whether its first strongly directional\n * character is from a right-to-left script, such as Hebrew or Arabic. Text\n * with no such character reads left to right.\n *\n * @public\n */\nexport function isRightToLeft(text: string): boolean {\n for (const character of text) {\n if (RIGHT_TO_LEFT.test(character)) return true;\n if (LEFT_TO_RIGHT.test(character)) return false;\n }\n return false;\n}\n\n// Hebrew, Arabic, Syriac, Thaana, N'Ko, Samaritan, Mandaic and their\n// presentation forms; then every other letter, which reads left to right.\nconst RIGHT_TO_LEFT = /[-ࣿיִ-﷿ﹰ-\\u{10800}-\\u{10FFF}\\u{1E800}-\\u{1EFFF}]/u;\nconst LEFT_TO_RIGHT = /\\p{L}/u;\n","import { compositionToSource, sourceToComposition } from \"./geometry.js\";\nimport { type ImageCrop, type ImageOrientation, MAX_SCENE_COORDINATE } from \"./plan.js\";\nimport type { ImageSize } from \"./source.js\";\n\n/**\n * A rectangle in whole pixels.\n *\n * @public\n */\nexport interface ImageRect {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n\n/** The smallest side of a pixelation block, in scene pixels (ADR 0010). */\nconst MIN_BLOCK = 8;\n/** The most blocks along a pixelated region's longer side (ADR 0010). */\nconst MAX_BLOCKS = 12;\n\n/**\n * The side of a pixelated region's square blocks, in scene pixels: the\n * larger of 8 and a twelfth of the region's longer side, rounded up (ADR\n * 0010). So a region has at most 12 blocks along its longer side, and a\n * strip over a line of text is one row of them. It isn't a setting.\n *\n * @public\n */\nexport function redactionBlockSize(region: ImageSize): number {\n return Math.max(MIN_BLOCK, Math.ceil(Math.max(region.width, region.height) / MAX_BLOCKS));\n}\n\n/** The boundaries of a region's blocks along one axis: its start, each block's end, its end. */\nfunction boundaries(start: number, length: number, block: number): number[] {\n const edges = [start];\n for (let at = start + block; at < start + length; at += block) edges.push(at);\n edges.push(start + length);\n return edges;\n}\n\n/** The rectangles between consecutive boundaries, leaving out any with no pixels. */\nfunction cells(xs: readonly number[], ys: readonly number[]): ImageRect[] {\n const rects: ImageRect[] = [];\n for (let row = 0; row + 1 < ys.length; row += 1) {\n const y = ys[row] as number;\n const height = (ys[row + 1] as number) - y;\n if (height <= 0) continue;\n for (let column = 0; column + 1 < xs.length; column += 1) {\n const x = xs[column] as number;\n const width = (xs[column + 1] as number) - x;\n if (width > 0) rects.push({ x, y, width, height });\n }\n }\n return rects;\n}\n\nconst clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value));\n\n/**\n * A pixelated region's blocks in the scene, each clipped to `within`: the\n * part of the source that's rendered, its crop. Blocks are aligned to the\n * region's top-left corner, and one that falls wholly outside `within` is\n * left out. They're listed row by row.\n *\n * @public\n */\nexport function redactionBlocksInScene(region: ImageRect, within: ImageRect): ImageRect[] {\n const block = redactionBlockSize(region);\n const clip = (edges: number[], min: number, max: number) =>\n edges.map((edge) => clamp(edge, min, max));\n return cells(\n clip(boundaries(region.x, region.width, block), within.x, within.x + within.width),\n clip(boundaries(region.y, region.height, block), within.y, within.y + within.height),\n );\n}\n\n/**\n * Where the scene's vertical and horizontal lines fall in the output:\n * through the crop, the rotation and the flips, then scaled. A quarter turn\n * maps the scene's x axis to the output's y axis.\n */\nfunction toOutput(crop: ImageCrop, orientation: ImageOrientation, output: ImageSize) {\n const turned = orientation.rotate % 180 !== 0;\n const composition = turned\n ? { width: crop.height, height: crop.width }\n : { width: crop.width, height: crop.height };\n const scaleX = output.width / composition.width;\n const scaleY = output.height / composition.height;\n const at = (x: number, y: number) => {\n const point = sourceToComposition({ x, y }, crop, orientation);\n return { x: point.x * scaleX, y: point.y * scaleY };\n };\n return {\n turned,\n /** The output coordinate of the scene line `x = value`. */\n fromX: (value: number) => (turned ? at(value, crop.y).y : at(value, crop.y).x),\n /** The output coordinate of the scene line `y = value`. */\n fromY: (value: number) => (turned ? at(crop.x, value).x : at(crop.x, value).y),\n };\n}\n\n/**\n * Output boundaries from scene boundaries: in rising order, the outer two\n * rounded outward so every output pixel the region touches is inside, the\n * others to the nearest pixel, all within the output and never decreasing.\n */\nfunction outputEdges(values: readonly number[], size: number): number[] {\n const sorted = [...values].sort((a, b) => a - b);\n const last = sorted.length - 1;\n let previous = 0;\n return sorted.map((value, index) => {\n const rounded =\n index === 0 ? Math.floor(value) : index === last ? Math.ceil(value) : Math.round(value);\n previous = Math.max(previous, clamp(rounded, 0, size));\n return previous;\n });\n}\n\n/**\n * The output pixels a region covers: the region mapped through the crop,\n * the rotation, the flips and the output's scale, rounded outward so that\n * every pixel it touches is covered whole, and clipped to the output (ADR\n * 0010). `null` when it covers none.\n *\n * @param region - The region, in scene pixels.\n * @param crop - The crop, or the whole source: `cropRect(plan.base.crop, source)`.\n * @param orientation - The plan's rotation and flips.\n * @param output - The size being rendered.\n * @public\n */\nexport function redactionRectInOutput(\n region: ImageRect,\n crop: ImageCrop,\n orientation: ImageOrientation,\n output: ImageSize,\n): ImageRect | null {\n const { turned, fromX, fromY } = toOutput(crop, orientation, output);\n const alongX = [fromX(region.x), fromX(region.x + region.width)];\n const alongY = [fromY(region.y), fromY(region.y + region.height)];\n const [left, right] = outputEdges(turned ? alongY : alongX, output.width) as [number, number];\n const [top, bottom] = outputEdges(turned ? alongX : alongY, output.height) as [number, number];\n if (right <= left || bottom <= top) return null;\n return { x: left, y: top, width: right - left, height: bottom - top };\n}\n\n/**\n * A pixelated region's blocks in the output: the scene's block boundaries\n * mapped as {@link redactionRectInOutput} maps the region. The region's own\n * edges are rounded outward and the boundaries between blocks to the\n * nearest pixel, so the blocks tile exactly the pixels the region covers. A\n * block with no output pixel is left out. They're listed row by row.\n *\n * @public\n */\nexport function redactionBlocksInOutput(\n region: ImageRect,\n crop: ImageCrop,\n orientation: ImageOrientation,\n output: ImageSize,\n): ImageRect[] {\n const block = redactionBlockSize(region);\n const { turned, fromX, fromY } = toOutput(crop, orientation, output);\n const alongX = boundaries(region.x, region.width, block).map(fromX);\n const alongY = boundaries(region.y, region.height, block).map(fromY);\n return cells(\n outputEdges(turned ? alongY : alongX, output.width),\n outputEdges(turned ? alongX : alongY, output.height),\n );\n}\n\n/** The rectangle between two opposite corners, in either order. */\nfunction between(a: { x: number; y: number }, b: { x: number; y: number }): ImageRect {\n const x = Math.min(a.x, b.x);\n const y = Math.min(a.y, b.y);\n return { x, y, width: Math.max(a.x, b.x) - x, height: Math.max(a.y, b.y) - y };\n}\n\n/**\n * A rectangle of the scene as the composition shows it: through the crop,\n * the rotation and the flips, in composition pixels, without clipping. The\n * plan turns by quarters, so it's still a rectangle in whole pixels. The\n * editor places a region's frame with it.\n *\n * @public\n */\nexport function sceneRectToComposition(\n rect: ImageRect,\n crop: ImageCrop,\n orientation: ImageOrientation,\n): ImageRect {\n return between(\n sourceToComposition({ x: rect.x, y: rect.y }, crop, orientation),\n sourceToComposition({ x: rect.x + rect.width, y: rect.y + rect.height }, crop, orientation),\n );\n}\n\n/**\n * The inverse of {@link sceneRectToComposition}: a rectangle drawn on the\n * composition, such as a region dragged out on screen, in scene pixels.\n *\n * @public\n */\nexport function compositionRectToScene(\n rect: ImageRect,\n crop: ImageCrop,\n orientation: ImageOrientation,\n): ImageRect {\n return between(\n compositionToSource({ x: rect.x, y: rect.y }, crop, orientation),\n compositionToSource({ x: rect.x + rect.width, y: rect.y + rect.height }, crop, orientation),\n );\n}\n\n/**\n * A rectangle as a redaction's region: whole pixels, rounded outward so it\n * covers everything the rectangle touched, at least 1 × 1, and within\n * `MAX_SCENE_COORDINATE` of the scene's origin. The editor fits what's\n * dragged or typed with it before it builds a command, so the reducer never\n * has to refuse it.\n *\n * @public\n */\nexport function fitRedactionRegion(rect: ImageRect): ImageRect {\n const limit = MAX_SCENE_COORDINATE;\n const x = clamp(Math.floor(rect.x), -limit, limit - 1);\n const y = clamp(Math.floor(rect.y), -limit, limit - 1);\n const right = clamp(Math.ceil(rect.x + rect.width), x + 1, limit);\n const bottom = clamp(Math.ceil(rect.y + rect.height), y + 1, limit);\n return { x, y, width: right - x, height: bottom - y };\n}\n","import { compositionSize, compositionToSource, cropRect } from \"./geometry.js\";\nimport { layerToOutput } from \"./layer-geometry.js\";\nimport { type ImageLayerBox, type ImagePlan, MAX_SCENE_COORDINATE } from \"./plan.js\";\nimport type { ImageSize } from \"./source.js\";\n\nconst QUARTERS = [0, 900, 1_800, 2_700] as const;\nconst clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value));\n\n/**\n * A box for a new layer (ADR 0009, docs/adr/0013): of the given size as it's seen,\n * in the middle of the image as it's shown, and the right way round on\n * screen whatever the plan's rotation and flips. Layers live in the scene,\n * which the plan turns and mirrors with the image; a new one is turned and\n * mirrored back, so text added to a mirrored image reads as text.\n */\nexport function newLayerBox(plan: ImagePlan, source: ImageSize, seen: ImageSize): ImageLayerBox {\n const crop = cropRect(plan.base.crop, source);\n const { orientation } = plan.base;\n const composition = compositionSize(plan, source);\n const width = clamp(Math.round(seen.width), 1, MAX_SCENE_COORDINATE);\n const height = clamp(Math.round(seen.height), 1, MAX_SCENE_COORDINATE);\n // The quarter turn and the flip after which the box's own right is right\n // on screen, and its own down is down: one of the eight always is.\n const asSeen = (rotation: number, flipX: boolean) => {\n const [a, , , d] = layerToOutput(\n { x: 0, y: 0, width, height, rotation, flipX },\n crop,\n orientation,\n composition,\n );\n return a > 0.5 && d > 0.5;\n };\n const flipX = !QUARTERS.some((rotation) => asSeen(rotation, false));\n const rotation = QUARTERS.find((quarter) => asSeen(quarter, flipX)) ?? 0;\n const centre = compositionToSource(\n { x: composition.width / 2, y: composition.height / 2 },\n crop,\n orientation,\n );\n return {\n // A box is flipped and turned about its centre, so its place is its centre's.\n x: Math.round(centre.x - width / 2) || 0,\n y: Math.round(centre.y - height / 2) || 0,\n width,\n height,\n rotation,\n flipX,\n };\n}\n\n/**\n * The size a new image layer is seen at: its own, or fitted in half of the\n * image as it's shown if that's smaller. It's never enlarged.\n */\nexport function fittedImageSize(plan: ImagePlan, source: ImageSize, image: ImageSize): ImageSize {\n const { width, height } = compositionSize(plan, source);\n const scale = Math.min(1, width / 2 / image.width, height / 2 / image.height);\n return { width: image.width * scale, height: image.height * scale };\n}\n","import {\n applyCommands,\n createHistory,\n createStore,\n type HistoryStep,\n withProcessingTime,\n} from \"@hussmartinez/sdk-core\";\nimport { asImageError, throwIfAborted } from \"../errors/error-helpers.js\";\nimport { ImageError, isImageError } from \"../errors/image-error.js\";\nimport {\n checkFileLimits,\n checkOutputLimits,\n type ImageFilePolicy,\n type ImageFilePolicyOverrides,\n type ImageLimitName,\n imageLimits,\n} from \"../errors/image-limits.js\";\nimport { drawingPoints } from \"../model/drawing-geometry.js\";\nimport { compositionSize, outputSize } from \"../model/geometry.js\";\nimport { createImageKey } from \"../model/keys.js\";\nimport { fittedImageSize, newLayerBox } from \"../model/layer-placement.js\";\nimport {\n createPlan,\n type ImageImageLayer,\n type ImageLayer,\n type ImagePlan,\n type ImageStroke,\n} from \"../model/plan.js\";\nimport type {\n ImageKeepableMetadata,\n ImageMetadataPresence,\n ImageProbe,\n ImageSourceInfo,\n} from \"../model/source.js\";\nimport { createImageReducer, type ImageCommand } from \"../operations/commands.js\";\nimport type { ImageEngine } from \"../ports/image-engine.js\";\nimport type { ImageExportFormat, ImageProcessor } from \"../ports/image-processor.js\";\n\n/**\n * The document's source, as the editor shows it: its size and format, and\n * what metadata the file carried, which the export summary reports as\n * removed unless the user kept it (ADR 0005).\n *\n * @public\n */\nexport interface ImageSessionSource extends ImageSourceInfo {\n /** The file's size in bytes, as it was opened. Never its name. */\n readonly fileSize: number;\n /** Which kinds of metadata the file carried, never their values. */\n readonly metadata: ImageMetadataPresence;\n /** The fields the user may choose to keep, as the file had them. */\n readonly keepable: ImageKeepableMetadata;\n}\n\n/**\n * The session's state, for `useSyncExternalStore`: a new object on every\n * change (ADR 0003).\n *\n * @public\n */\nexport interface ImageSessionSnapshot {\n /** `empty` until a file opens; `opening` while the first one is; then `ready`. */\n readonly status: \"empty\" | \"opening\" | \"ready\";\n /** The document, or `null` before a file is open. */\n readonly plan: ImagePlan | null;\n /** The document's source, or `null` before a file is open. */\n readonly source: ImageSessionSource | null;\n /**\n * Every source the session holds: the document's, then those of image\n * layers, including ones only the history still refers to (ADR 0004).\n */\n readonly sources: readonly ImageSessionSource[];\n readonly canUndo: boolean;\n readonly canRedo: boolean;\n /**\n * Whether undo steps were dropped to make room for an image, since the\n * document was opened: they can no longer be undone.\n */\n readonly historyTrimmed: boolean;\n /** Whether an image is being added as a layer. */\n readonly inserting: boolean;\n /** Whether a file is being opened. The current document stays until it's ready. */\n readonly opening: boolean;\n /** Whether an export is in progress. */\n readonly exporting: boolean;\n /** The limits the last open, edit or export came near: at or above their warnings. */\n readonly warnings: readonly ImageLimitName[];\n /** The last failure, until the next successful open, edit or export. */\n readonly error: ImageError | null;\n}\n\n/**\n * An anonymous usage event for the host's `onEvent` (ADR 0003). It never\n * carries file names, pixels, text the user typed or metadata values.\n *\n * @public\n */\nexport interface ImageSessionEvent {\n readonly type: \"open\" | \"insert\" | \"execute\" | \"undo\" | \"redo\" | \"export\";\n readonly outcome: \"done\" | \"failed\" | \"cancelled\";\n /** The types of the commands applied or undone. */\n readonly commands: readonly ImageCommand[\"type\"][];\n}\n\n/**\n * Options for {@link createImageSession}.\n *\n * @public\n */\nexport interface ImageSessionOptions {\n /** Probes, decodes and holds sources. The session releases the sources it registered, never the engine. */\n readonly engine: ImageEngine;\n /** Renders and encodes exports, over the same engine's sources. */\n readonly processor: ImageProcessor;\n /** The host's limits, over `imageLimits`' defaults (ADR 0004). */\n readonly filePolicy?: ImageFilePolicyOverrides;\n readonly onEvent?: (event: ImageSessionEvent) => void;\n}\n\n/**\n * What an export produced, and what the summary before a download shows\n * (ADR 0003, ADR 0005).\n *\n * @public\n */\nexport interface ImageSessionExport {\n readonly blob: Blob;\n readonly width: number;\n readonly height: number;\n /**\n * The kinds of metadata the source carried that the file doesn't: every\n * kind, since exports keep only the fields the user chose, which are\n * never these. Empty when the source carried none.\n */\n readonly removed: readonly (keyof ImageMetadataPresence)[];\n /** The fields the user kept, which the file carries. */\n readonly kept: readonly (keyof ImageKeepableMetadata)[];\n}\n\n/**\n * An image editing session (ADR 0003, ADR 0008): one document, its plan\n * over the source it opened, edited by commands with undo and redo, and\n * exported through its processor.\n *\n * @public\n */\nexport interface ImageSession {\n getSnapshot(): ImageSessionSnapshot;\n /** Calls the listener after every change. Returns a function that unsubscribes. */\n subscribe(listener: () => void): () => void;\n /**\n * Probes, checks and decodes a file, and makes it the document, with a new\n * plan and an empty history; the previous source is released (ADR 0003,\n * ADR 0004). The newest open wins: an open that finishes after a later one\n * started applies nothing, releases its source and rejects with\n * `ABORTED`. A failed or cancelled open leaves the current document as it\n * was. Probing and registration share the policy's `maxProcessingTime`\n * deadline, which aborts their signal with `PROCESSING_TIME_EXCEEDED`.\n */\n open(file: Blob, options?: { readonly signal?: AbortSignal }): Promise<ImageSessionSource>;\n /**\n * Probes, checks and decodes another file, and adds it to the document as\n * an image layer, as one undoable step (ADR 0003, ADR 0004).\n *\n * - **Limits:** the file's own, as for `open`; `maxFiles`, counting every\n * source the session holds; and `maxSessionSize`, counting their decoded\n * bytes. When the image doesn't fit, the session first drops the oldest\n * undo steps that alone keep another image, and marks the history as\n * trimmed. If that isn't enough, nothing is dropped and it fails with\n * `SESSION_TOO_LARGE`.\n * - **Placement:** by default the image is centred on what's shown, at\n * its own size or half the composition's, whichever is smaller, over\n * every layer, and turned and mirrored back against the plan's\n * rotation and flips, so it's seen as the file is. `place` returns other commands; they must refer to the\n * source, or it's released.\n * - **Lifetime:** the session holds the source while the plan, an undo\n * or redo step, or an export in progress refers to it, and releases it\n * then.\n *\n * A failure, a cancellation, or another file opened meanwhile adds\n * nothing and releases the source.\n */\n insertImage(file: Blob, options?: ImageInsertOptions): Promise<ImageSessionSource>;\n /**\n * Applies commands as one undoable step. They're checked by the reducer,\n * then the output against `maxImageDimension` and `maxImagePixels`; a\n * failure throws `ImageError` and changes nothing.\n */\n execute(commands: ImageCommand | readonly ImageCommand[]): void;\n /**\n * Makes the document's plan equal to `plan`, as one undoable step of the\n * commands that reach it, checked as `execute` checks them (ADR 0003). A\n * plan equal to the current one changes nothing. A plan over another\n * source is `INVALID_COMMAND`, and so is one without `layers`,\n * `redactions` and `animation`, such as a plan stored before format\n * version 2. For editors whose host holds the plan.\n */\n applyPlan(plan: ImagePlan): void;\n /**\n * Runs `fn`, and records every step it executes as one undoable step, for\n * a gesture such as dragging a crop handle (ADR 0003). `fn` must be\n * synchronous.\n */\n group<T>(fn: () => T): T;\n /** Undoes the last step. Returns whether there was one. */\n undo(): boolean;\n /** Redoes the last undone step. Returns whether there was one. */\n redo(): boolean;\n /**\n * Renders and encodes the document (ADR 0003). An export that finishes\n * after another file was opened rejects with `ABORTED`. The policy's\n * `maxProcessingTime` aborts the processor's signal with\n * `PROCESSING_TIME_EXCEEDED`. Custom adapters must observe that signal;\n * a session cannot preempt an arbitrary adapter that ignores it.\n */\n export(\n format: ImageExportFormat,\n options?: { readonly signal?: AbortSignal; readonly onProgress?: (fraction: number) => void },\n ): Promise<ImageSessionExport>;\n /** Releases every source the session holds. Later calls throw. */\n destroy(): Promise<void>;\n}\n\n/**\n * Options for {@link ImageSession.insertImage}.\n *\n * @public\n */\nexport interface ImageInsertOptions {\n readonly signal?: AbortSignal;\n /**\n * The commands that add the image to the plan, instead of the default\n * layer: given the new source and the plan as it is.\n */\n readonly place?: (\n source: ImageSessionSource,\n plan: ImagePlan,\n ) => ImageCommand | readonly ImageCommand[];\n}\n\n/** The ids of the sources a command's image layers name. */\nfunction sourcesIn(command: ImageCommand): string[] {\n const of = (layer: { kind?: unknown; source?: unknown }) =>\n layer.kind === \"image\" && typeof layer.source === \"string\" ? [layer.source] : [];\n switch (command.type) {\n case \"image.insertLayers\":\n return command.layers.flatMap(of);\n case \"image.restoreLayers\":\n return command.entries.flatMap(({ layer }) => of(layer));\n case \"image.updateLayers\":\n // An update may point a layer at another source.\n return command.updates.flatMap(({ props }) =>\n typeof props[\"source\"] === \"string\" ? [props[\"source\"]] : [],\n );\n default:\n return [];\n }\n}\n\n/**\n * The most drawing points the history's steps may hold between them (ADR\n * 0009): removing a large drawing leaves its points in the step that undoes\n * it. Above this, the oldest steps are dropped.\n */\nconst MAX_HISTORY_POINTS = 1_000_000;\n\n/** How many points the strokes a command carries hold. */\nfunction pointsIn(command: ImageCommand): number {\n const ofStrokes = (strokes: readonly ImageStroke[]) =>\n strokes.reduce(\n (points, stroke) => points + stroke.runs.reduce((sum, run) => sum + run.length / 2, 0),\n 0,\n );\n const ofLayers = (layers: readonly ImageLayer[]) =>\n layers.reduce(\n (points, layer) => points + (layer.kind === \"drawing\" ? ofStrokes(layer.strokes) : 0),\n 0,\n );\n switch (command.type) {\n case \"image.addStrokes\":\n return ofStrokes(command.strokes);\n case \"image.restoreStrokes\":\n return ofStrokes(command.entries.map((entry) => entry.stroke));\n case \"image.insertLayers\":\n return ofLayers(command.layers);\n case \"image.restoreLayers\":\n return ofLayers(command.entries.map((entry) => entry.layer));\n default:\n return 0;\n }\n}\n\n/** The ids of the sources a plan's image layers name. */\nconst sourcesOf = (plan: ImagePlan) =>\n plan.layers.flatMap((layer) => (layer.kind === \"image\" ? [layer.source] : []));\n\n/**\n * The default layer for an inserted image: centred on what's shown, at its\n * own size or half the composition's, whichever is smaller, keeping its\n * shape, and neither turned nor mirrored as it's seen, whatever the plan's\n * rotation and flips.\n */\nfunction defaultLayer(\n source: ImageSourceInfo,\n plan: ImagePlan,\n base: ImageSourceInfo,\n): ImageImageLayer {\n const used = new Set([...plan.layers, ...plan.redactions].map((item) => item.key));\n return {\n key: createImageKey(used),\n kind: \"image\",\n name: \"\",\n visible: true,\n opacity: 100,\n // Turned and mirrored back against the plan's orientation, so it's seen\n // as the file is, in the preview and in every export.\n ...newLayerBox(plan, base, fittedImageSize(plan, base, source)),\n source: source.id,\n crop: null,\n };\n}\n\nconst same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);\n\n/** The commands that turn `from` into `to`, field by field. */\nexport function commandsBetween(from: ImagePlan, to: ImagePlan): ImageCommand[] {\n const commands: ImageCommand[] = [];\n if (!same(from.base.crop, to.base.crop)) {\n commands.push({ type: \"image.setCrop\", crop: to.base.crop });\n }\n if (!same(from.base.orientation, to.base.orientation)) {\n commands.push({ type: \"image.setOrientation\", orientation: to.base.orientation });\n }\n const develop = Object.fromEntries(\n Object.entries(to.base.develop).filter(\n ([name, value]) => from.base.develop[name as keyof typeof from.base.develop] !== value,\n ),\n );\n if (Object.keys(develop).length > 0) {\n commands.push({ type: \"image.setDevelop\", values: develop });\n }\n if (!same(from.base.filter, to.base.filter)) {\n commands.push({ type: \"image.setFilter\", filter: to.base.filter });\n }\n if (!same(from.output, to.output)) {\n commands.push({ type: \"image.setOutput\", output: to.output });\n }\n for (const field of Object.keys(to.metadata) as (keyof ImageKeepableMetadata)[]) {\n if (from.metadata[field] !== to.metadata[field]) {\n commands.push({ type: \"image.setMetadata\", field, value: to.metadata[field] });\n }\n }\n if (!same(from.layers, to.layers)) {\n // The whole list is replaced: one step, whatever changed in it.\n if (from.layers.length > 0) {\n commands.push({ type: \"image.removeLayers\", keys: from.layers.map((layer) => layer.key) });\n }\n if (to.layers.length > 0) {\n commands.push({ type: \"image.insertLayers\", at: 0, layers: to.layers });\n }\n }\n if (!same(from.redactions, to.redactions)) {\n // The whole list is replaced: one step, whatever changed in it.\n if (from.redactions.length > 0) {\n commands.push({\n type: \"image.removeRedactions\",\n keys: from.redactions.map((redaction) => redaction.key),\n });\n }\n if (to.redactions.length > 0) {\n commands.push({ type: \"image.insertRedactions\", at: 0, redactions: to.redactions });\n }\n }\n return commands;\n}\n\nconst PRESENCE: readonly (keyof ImageMetadataPresence)[] = [\n \"location\",\n \"camera\",\n \"timestamps\",\n \"thumbnail\",\n \"colourProfile\",\n \"other\",\n];\n\n/** A probed image's decoded bytes, as the session counts them (ADR 0004). */\nconst decodedBytes = (probe: ImageProbe) => probe.oriented.width * probe.oriented.height * 4;\n\n/** The source's own limits, and what holding it costs against `maxSessionSize`. */\nfunction checkSource(\n policy: ImageFilePolicy,\n file: Blob,\n probe: ImageProbe,\n): readonly ImageLimitName[] {\n const near = checkFileLimits(policy, file.size, probe);\n // A new document holds this one source: the previous one's are released.\n const bytes = decodedBytes(probe);\n if (policy.check(\"maxSessionSize\", bytes) === \"warning\") near.push(\"maxSessionSize\");\n return near;\n}\n\n/**\n * Creates an {@link ImageSession} (ADR 0003): its store and history are\n * sdk-core's (ADR 0029), its reducer is {@link createImageReducer}, and it\n * reaches files only through its engine and processor.\n *\n * @example\n * ```ts\n * const engine = createImageEngine();\n * const session = createImageSession({ engine, processor: createImageProcessor(engine) });\n * await session.open(file);\n * session.execute({ type: \"image.setDevelop\", values: { exposure: 20 } });\n * const { blob, removed } = await session.export({ type: \"jpeg\", quality: 0.9 });\n * ```\n *\n * @public\n */\nexport function createImageSession(options: ImageSessionOptions): ImageSession {\n const { engine, processor } = options;\n const policy: ImageFilePolicy = imageLimits.resolve(options.filePolicy);\n const history = createHistory<ImageCommand>();\n let source: ImageSessionSource | null = null;\n /** The sources of image layers, by id, in the order they were added. */\n const extras = new Map<string, ImageSessionSource>();\n /** The plans of exports in progress, whose sources must outlive them. */\n const exports = new Set<ImagePlan>();\n const sourceOf = (id: string) => (source?.id === id ? source : extras.get(id));\n const reducer = createImageReducer(sourceOf);\n let plan: ImagePlan | null = null;\n /** Each open's number: only the latest may become the document. */\n let opens = 0;\n let opening = 0;\n let exporting = 0;\n let inserting = 0;\n /** Which document an async result belongs to. */\n let generation = 0;\n let warnings: readonly ImageLimitName[] = [];\n let error: ImageError | null = null;\n let nextId = 0;\n let destroyed = false;\n\n const snapshot = (): ImageSessionSnapshot => ({\n status: plan !== null ? \"ready\" : !destroyed && opening > 0 ? \"opening\" : \"empty\",\n plan,\n source,\n sources: source ? [source, ...extras.values()] : [],\n canUndo: history.canUndo,\n canRedo: history.canRedo,\n historyTrimmed: history.trimmed,\n inserting: !destroyed && inserting > 0,\n opening: !destroyed && opening > 0,\n exporting: !destroyed && exporting > 0,\n warnings,\n error,\n });\n const store = createStore<ImageSessionSnapshot>(snapshot());\n const publish = () => store.set(snapshot());\n const emit = (event: ImageSessionEvent) => {\n try {\n options.onEvent?.(event);\n } catch {\n // A host's handler can't break the session.\n }\n };\n const assertAlive = () => {\n if (destroyed) throw new Error(\"The image session has been destroyed.\");\n };\n const fail = (reason: unknown): ImageError => {\n error = isImageError(reason) ? reason : asImageError(reason);\n return error;\n };\n const superseded = () =>\n new ImageError(\"ABORTED\", \"A later open replaced this one.\", {\n details: { reason: \"superseded\" },\n });\n\n /**\n * The ids of the sources something still refers to: the plan, exports in\n * progress, and history steps, leaving out the first `dropped` of the\n * order they'd be dropped in.\n */\n const referenced = (dropped = 0): Set<string> => {\n const ids = new Set<string>();\n for (const held of [plan, ...exports]) {\n if (held) for (const id of sourcesOf(held)) ids.add(id);\n }\n const gone = new Set(history.dropOrder.slice(0, dropped));\n for (const step of history.steps) {\n if (gone.has(step)) continue;\n for (const command of [...step.commands, ...step.inverses]) {\n for (const id of sourcesIn(command)) ids.add(id);\n }\n }\n return ids;\n };\n\n /** Releases every layer source nothing refers to any more (ADR 0003). */\n const releaseUnreferenced = () => {\n const kept = referenced();\n for (const id of [...extras.keys()]) {\n if (kept.has(id)) continue;\n extras.delete(id);\n void engine.release(id).catch(() => {});\n }\n };\n\n /** The decoded bytes of every source held, leaving out the layer sources `without` names. */\n const heldBytes = (without: ReadonlySet<string> = new Set()) => {\n let bytes = source?.decodedBytes ?? 0;\n for (const [id, extra] of extras) if (!without.has(id)) bytes += extra.decodedBytes;\n return bytes;\n };\n\n /** Whether the session may hold this many decoded bytes: `false`, or the check's outcome. */\n const fits = (bytes: number) => {\n try {\n return policy.check(\"maxSessionSize\", bytes);\n } catch {\n return false;\n }\n };\n\n /**\n * Makes room for an image of `bytes` (ADR 0004). If it doesn't fit, drops\n * the fewest of the oldest history steps whose going frees enough: steps\n * that alone keep another image. If no number of them is enough, drops\n * nothing, and throws `SESSION_TOO_LARGE`.\n */\n const makeRoom = (bytes: number): readonly ImageLimitName[] => {\n const warned = (outcome: unknown): ImageLimitName[] =>\n outcome === \"warning\" ? [\"maxSessionSize\"] : [];\n const now = fits(heldBytes() + bytes);\n if (now !== false) return warned(now);\n for (let dropped = 1; dropped <= history.dropOrder.length; dropped += 1) {\n const kept = referenced(dropped);\n const freed = new Set([...extras.keys()].filter((id) => !kept.has(id)));\n const after = fits(heldBytes(freed) + bytes);\n if (after === false) continue;\n history.drop(dropped);\n releaseUnreferenced();\n return warned(after);\n }\n // Throws the limit's own error, with what it would take.\n policy.check(\"maxSessionSize\", heldBytes() + bytes);\n return [];\n };\n\n /** The plan after `commands`, with its output checked, and the step. */\n const attempt = (from: ImagePlan, commands: readonly ImageCommand[]) => {\n const { state, inverses } = applyCommands(reducer, from, commands);\n if (source) {\n checkOutputLimits(policy, outputSize(state.output, compositionSize(state, source)));\n }\n // Only a step that adds items is checked, so a plan already over a\n // lowered limit can still be edited and emptied (ADR 0004).\n const items = state.layers.length + state.redactions.length;\n if (items > from.layers.length + from.redactions.length) policy.check(\"maxLayers\", items);\n // The same for drawn points: only a step that adds some is checked.\n const points = drawingPoints(state);\n if (points > drawingPoints(from)) policy.check(\"maxDrawingPoints\", points);\n const step: HistoryStep<ImageCommand> = { commands: [...commands], inverses: [...inverses] };\n return { state, step };\n };\n\n /**\n * Says the plan is near its points limit while it is, and stops when it\n * isn't: after every change of plan, an undo and a redo included.\n */\n const notePoints = () => {\n let near = false;\n try {\n near = plan !== null && policy.check(\"maxDrawingPoints\", drawingPoints(plan)) === \"warning\";\n } catch {\n // Over a lowered limit, which the plan may still be edited under: near, at least.\n near = true;\n }\n const noted = warnings.includes(\"maxDrawingPoints\");\n if (near && !noted) warnings = [...warnings, \"maxDrawingPoints\"];\n if (!near && noted) warnings = warnings.filter((name) => name !== \"maxDrawingPoints\");\n };\n\n /**\n * Bounds what the history holds in drawn points (ADR 0009): above the\n * ceiling, drops the oldest steps, never the newest, and the history says\n * it was trimmed.\n */\n const trimPoints = () => {\n const held = () =>\n history.steps.reduce(\n (points, step) =>\n points + [...step.commands, ...step.inverses].reduce((sum, c) => sum + pointsIn(c), 0),\n 0,\n );\n while (history.dropOrder.length > 1 && held() > MAX_HISTORY_POINTS) history.drop(1);\n };\n\n const replay = (direction: \"undo\" | \"redo\"): boolean => {\n assertAlive();\n const step = direction === \"undo\" ? history.undo() : history.redo();\n if (!step || plan === null) return false;\n const commands = direction === \"undo\" ? step.inverses : step.commands;\n try {\n plan = applyCommands(reducer, plan, commands).state;\n } catch (reason) {\n history.restore(direction);\n publish();\n emit({ type: direction, outcome: \"failed\", commands: commands.map((c) => c.type) });\n throw fail(reason);\n }\n error = null;\n notePoints();\n // A step that moved from one stack to the other still refers to its sources.\n releaseUnreferenced();\n publish();\n emit({ type: direction, outcome: \"done\", commands: commands.map((c) => c.type) });\n return true;\n };\n\n /** Applies commands as one undoable step: `execute`, which `applyPlan` shares. */\n const executeCommands = (input: ImageCommand | readonly ImageCommand[]) => {\n assertAlive();\n const commands = Array.isArray(input)\n ? (input as readonly ImageCommand[])\n : [input as ImageCommand];\n try {\n if (plan === null) {\n throw new ImageError(\"INVALID_COMMAND\", \"There's nothing to edit before a file is open.\");\n }\n const result = attempt(plan, commands);\n plan = result.state;\n history.push(result.step);\n trimPoints();\n notePoints();\n error = null;\n // A new step drops what could be redone, and with it what only that kept.\n releaseUnreferenced();\n emit({ type: \"execute\", outcome: \"done\", commands: commands.map((c) => c.type) });\n } catch (reason) {\n emit({ type: \"execute\", outcome: \"failed\", commands: commands.map((c) => c.type) });\n throw fail(reason);\n } finally {\n publish();\n }\n };\n\n return {\n getSnapshot: () => store.getSnapshot(),\n subscribe: (listener) => store.subscribe(listener),\n\n async open(file, openOptions = {}) {\n assertAlive();\n opens += 1;\n const ticket = opens;\n nextId += 1;\n const id = `source-${nextId}`;\n let registered = false;\n opening += 1;\n publish();\n try {\n const { probe, near, info } = await withProcessingTime(\n policy,\n async (signal) => {\n throwIfAborted(signal);\n // One deadline covers both probing and decoding (sdk-core ADR 0020).\n policy.check(\"maxFileSize\", file.size);\n const probe = await engine.probe(file, { signal });\n throwIfAborted(signal);\n const near = checkSource(policy, file, probe);\n if (ticket !== opens) throw superseded();\n const info = await engine.register(id, file, probe, { filePolicy: policy, signal });\n registered = true;\n throwIfAborted(signal);\n return { probe, near, info };\n },\n openOptions,\n );\n assertAlive();\n if (ticket !== opens) throw superseded();\n\n // From here to the end nothing awaits, so nothing can change under us.\n const previous = source;\n source = {\n ...info,\n fileSize: file.size,\n metadata: probe.metadata,\n keepable: probe.keepable,\n };\n plan = createPlan(id);\n history.clear();\n generation += 1;\n warnings = near;\n error = null;\n if (previous) void engine.release(previous.id).catch(() => {});\n // The previous document's layer sources go with it, unless an\n // export of it is still running.\n releaseUnreferenced();\n emit({ type: \"open\", outcome: \"done\", commands: [] });\n return source;\n } catch (reason) {\n if (registered && source?.id !== id) await engine.release(id).catch(() => {});\n const failure = isImageError(reason) ? reason : asImageError(reason);\n const cancelled = failure.code === \"ABORTED\";\n // A superseded or cancelled open isn't the document's failure.\n if (!cancelled && !destroyed && ticket === opens) fail(failure);\n emit({ type: \"open\", outcome: cancelled ? \"cancelled\" : \"failed\", commands: [] });\n throw failure;\n } finally {\n opening -= 1;\n if (!destroyed) publish();\n }\n },\n\n async insertImage(file, insertOptions = {}) {\n assertAlive();\n if (plan === null || source === null) {\n throw new ImageError(\"INVALID_COMMAND\", \"There's no image to add a layer to yet.\");\n }\n const started = generation;\n nextId += 1;\n const id = `source-${nextId}`;\n let registered = false;\n /** Once the session holds the source, only `releaseUnreferenced` releases it. */\n let held = false;\n inserting += 1;\n publish();\n try {\n const { probe, info } = await withProcessingTime(\n policy,\n async (signal) => {\n throwIfAborted(signal);\n policy.check(\"maxFileSize\", file.size);\n const probe = await engine.probe(file, { signal });\n throwIfAborted(signal);\n checkFileLimits(policy, file.size, probe);\n const info = await engine.register(id, file, probe, { filePolicy: policy, signal });\n registered = true;\n throwIfAborted(signal);\n return { probe, info };\n },\n insertOptions,\n );\n assertAlive();\n if (started !== generation || plan === null || source === null) throw superseded();\n\n // From here to the end nothing awaits, so nothing can change under us.\n const near = checkFileLimits(policy, file.size, probe);\n // Every source held, and this one.\n if (policy.check(\"maxFiles\", extras.size + 2) === \"warning\") near.push(\"maxFiles\");\n near.push(...makeRoom(info.decodedBytes));\n const added: ImageSessionSource = {\n ...info,\n fileSize: file.size,\n metadata: probe.metadata,\n keepable: probe.keepable,\n };\n extras.set(id, added);\n held = true;\n try {\n const placed = insertOptions.place?.(added, plan) ?? {\n type: \"image.insertLayers\",\n at: plan.layers.length,\n layers: [defaultLayer(added, plan, source)],\n };\n const commands = Array.isArray(placed)\n ? (placed as readonly ImageCommand[])\n : [placed as ImageCommand];\n // Checked before anything runs: commands that never name the\n // source would change the plan and leave the image out of it.\n if (!commands.some((command) => sourcesIn(command).includes(id))) {\n throw new ImageError(\n \"INVALID_COMMAND\",\n \"The commands don't add the image to the plan.\",\n );\n }\n executeCommands(commands);\n } finally {\n // Commands that failed, or that don't name the source, leave it\n // unreferenced: it's released here.\n releaseUnreferenced();\n }\n warnings = near;\n emit({ type: \"insert\", outcome: \"done\", commands: [] });\n return added;\n } catch (reason) {\n if (registered && !held) await engine.release(id).catch(() => {});\n const failure = isImageError(reason) ? reason : asImageError(reason);\n const cancelled = failure.code === \"ABORTED\";\n if (!cancelled && !destroyed && started === generation) fail(failure);\n emit({ type: \"insert\", outcome: cancelled ? \"cancelled\" : \"failed\", commands: [] });\n throw failure;\n } finally {\n inserting -= 1;\n if (!destroyed) publish();\n }\n },\n\n execute: (input) => executeCommands(input),\n\n applyPlan(next) {\n assertAlive();\n // A plan from before format version 2 has no lists: it's read with\n // `readImagePlanDocument`, which migrates it, not applied as it is.\n const shaped =\n Array.isArray(next.redactions) && Array.isArray(next.layers) && next.animation === null;\n if (plan === null || !shaped || next.base.source !== plan.base.source) {\n const failure = new ImageError(\n \"INVALID_COMMAND\",\n shaped\n ? \"The plan isn't for the open image.\"\n : \"The plan needs layers, redactions and animation, as createPlan gives them.\",\n );\n error = failure;\n publish();\n throw failure;\n }\n const commands = commandsBetween(plan, next);\n if (commands.length > 0) executeCommands(commands);\n },\n\n group(fn) {\n assertAlive();\n return history.group(fn);\n },\n\n undo: () => replay(\"undo\"),\n redo: () => replay(\"redo\"),\n\n async export(format, exportOptions = {}) {\n assertAlive();\n const { onProgress } = exportOptions;\n if (plan === null || source === null) {\n throw new ImageError(\"INVALID_COMMAND\", \"There's nothing to export before a file is open.\");\n }\n const started = generation;\n const exported = plan;\n const from = source;\n exporting += 1;\n // Its sources outlive it: a layer removed, or another file opened,\n // while it runs releases nothing it draws.\n exports.add(exported);\n publish();\n try {\n const size = outputSize(exported.output, compositionSize(exported, from));\n const blob = await withProcessingTime(\n policy,\n async (signal) => {\n throwIfAborted(signal);\n const blob = await processor.export(\n { plan: exported, format },\n {\n filePolicy: policy,\n signal,\n ...(onProgress ? { onProgress } : {}),\n },\n );\n throwIfAborted(signal);\n return blob;\n },\n exportOptions,\n );\n // The document was replaced while this export ran: it applies nothing.\n if (started !== generation || destroyed) {\n throw new ImageError(\"ABORTED\", \"Another file was opened during the export.\", {\n details: { reason: \"superseded\" },\n });\n }\n error = null;\n emit({ type: \"export\", outcome: \"done\", commands: [] });\n return {\n blob,\n width: size.width,\n height: size.height,\n removed: PRESENCE.filter((kind) => from.metadata[kind]),\n kept: (Object.keys(exported.metadata) as (keyof ImageKeepableMetadata)[]).filter(\n (field) => exported.metadata[field] !== \"\",\n ),\n };\n } catch (reason) {\n const failure = isImageError(reason) ? reason : asImageError(reason);\n const cancelled = failure.code === \"ABORTED\";\n if (!cancelled && !destroyed && started === generation) fail(failure);\n emit({ type: \"export\", outcome: cancelled ? \"cancelled\" : \"failed\", commands: [] });\n throw failure;\n } finally {\n exporting -= 1;\n exports.delete(exported);\n if (!destroyed) {\n releaseUnreferenced();\n publish();\n }\n }\n },\n\n async destroy() {\n if (destroyed) return;\n destroyed = true;\n const held = [...(source ? [source.id] : []), ...extras.keys()];\n source = null;\n extras.clear();\n plan = null;\n history.clear();\n publish();\n await Promise.all(held.map((id) => engine.release(id).catch(() => {})));\n },\n };\n}\n","import { defineMessages, type MessageValue, plural, sdkCoreMessages } from \"@hussmartinez/sdk-core\";\nimport type { ImageErrorCode } from \"../core/errors/image-error.js\";\nimport type { ImageLimitName } from \"../core/errors/image-limits.js\";\n\n/**\n * The image SDK's English message catalogue for the server-safe entry:\n * sdk-core's messages, and text for every {@link ImageErrorCode} and every\n * limit's warning, which the headless session produces and a host shows.\n * Pass it to `createMessages` from `@hussmartinez/sdk-core`, with the host's\n * locale and overrides.\n *\n * It holds no interface text: the editor's labels, states, announcements\n * and tool names are in `imageEditorMessages`, from the React entry, so\n * hosts of this entry, servers included, don't carry text nothing here\n * shows (docs/adr/0012).\n *\n * Error text is looked up by code, with the error's `details` as\n * parameters, and never taken from `error.message` (ADR 0019).\n *\n * @example\n * ```ts\n * const messages = createMessages(imageMessages, { locale: \"en\", overrides: props.messages });\n * messages.error(error); // \"This animation has 400 frames, which is over the 300-frame limit.\"\n * messages.t(\"warnings.maxSessionSize\", { actual: 600e6 });\n * ```\n *\n * @public\n */\nexport const imageMessages = /* @__PURE__ */ defineMessages({\n ...sdkCoreMessages,\n \"errors.INVALID_IMAGE\": \"This file isn't a valid image, or it's too damaged to open.\",\n \"errors.UNSUPPORTED_FORMAT\":\n \"This image format isn't supported. Try converting the file to PNG or JPEG, then open it again.\",\n \"errors.DECODE_FAILED\":\n \"This browser can't open this kind of image. Try another browser, or convert the file to PNG or JPEG.\",\n \"errors.INVALID_COMMAND\": \"This edit couldn't be made. Please try again.\",\n \"errors.INVALID_DOCUMENT\": \"This project is damaged, or it isn't an image project.\",\n \"errors.UNSUPPORTED_PLAN\":\n \"This image has edits this version can't show. Update the application and try again.\",\n \"errors.IMAGE_TOO_LARGE\":\n \"This image has more pixels than the editor can handle. Try a smaller version of it.\",\n \"errors.IMAGE_DIMENSION_TOO_LARGE\":\n \"This image is {actual, number} pixels across, which is over the {maximum, number}-pixel limit.\",\n \"errors.TOO_MANY_FRAMES\": /* @__PURE__ */ plural(\"maximum\", {\n one: \"This animation has {actual, number} frames, which is over the {maximum}-frame limit.\",\n other:\n \"This animation has {actual, number} frames, which is over the {maximum, number}-frame limit.\",\n }),\n \"errors.SESSION_TOO_LARGE\":\n \"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.\",\n \"errors.TOO_MANY_LAYERS\": /* @__PURE__ */ plural(\"maximum\", {\n one: \"An image can have {maximum} layer. Merge or delete layers, and try again.\",\n other:\n \"An image can have up to {maximum, number} layers. Merge or delete layers, and try again.\",\n }),\n \"errors.TOO_MANY_POINTS\":\n \"This image's drawings would have {actual, number} points, which is over the limit of {maximum, number}. Remove some strokes, and try again.\",\n \"warnings.maxImagePixels\": \"This image is large, and may be slow to edit on some devices.\",\n \"warnings.maxImageDimension\": \"This image is very wide or tall, and may be slow to edit.\",\n \"warnings.maxFrames\": /* @__PURE__ */ plural(\"actual\", {\n one: \"This animation has {actual} frame.\",\n other: \"This animation has {actual, number} frames, and may be slow to edit and export.\",\n }),\n \"warnings.maxSessionSize\":\n \"The open images use {actual, fileSize} of memory. Clearing the undo history frees memory.\",\n \"warnings.maxLayers\": /* @__PURE__ */ plural(\"actual\", {\n one: \"This image has {actual} layer.\",\n other: \"This image has {actual, number} layers, and may be slow to edit and export.\",\n }),\n \"warnings.maxDrawingPoints\":\n \"This image has a lot of drawing, and may be slow to edit and export.\",\n}) satisfies Record<`errors.${ImageErrorCode}`, MessageValue> &\n Record<`warnings.${ImageLimitName}`, MessageValue>;\n\n/**\n * The type of {@link imageMessages}, for typing a host's overrides with\n * `MessageOverrides<ImageMessageCatalogue>`.\n *\n * @public\n */\nexport type ImageMessageCatalogue = typeof imageMessages;\n"],"mappings":";;AA+EA,IAAa,aAAb,cAAgC,SAAyB;CAEvD,OAAyB;AAC3B;AAcA,SAAgB,aACd,OACA,MAC+C;CAC/C,OAAO,WAAW,OAAO,IAAI,KAAK,MAAM,SAAS;AACnD;;ACpFA,IAAa,EACX,OAAO,cACP,YACA,mBACE,mBAAmB,YAAY;CACjC,cAAc;CACd,iBAAiB;AACnB,CAAC;;ACSD,IAAa,wBAAwB;CACnC,GAAG;CACH,gBAAgB;EAAE,GAAG,WAAW;EAAgB,SAAS;EAAe,SAAS;CAAY;CAC7F,gBAAgB;EACd,MAAM;EACN,MAAM;EACN,SAAS;EACT,SAAS;CACX;CACA,mBAAmB;EAAE,MAAM;EAA6B,MAAM;EAAU,SAAS;CAAO;CACxF,WAAW;EAAE,MAAM;EAAmB,MAAM;EAAS,SAAS;EAAK,SAAS;CAAI;CAChF,gBAAgB;EACd,MAAM;EACN,MAAM;EACN,SAAS;EACT,SAAS;CACX;CACA,WAAW;EA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