@sealpixel/core 1.0.0-rc.21 → 1.0.0-rc.23

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.
@@ -15,6 +15,12 @@ export class RendererCore {
15
15
  workingCopy = null;
16
16
  descriptor = null;
17
17
  cache = new Map();
18
+ /**
19
+ * Increments whenever the source changes. It is part of every cache key: a
20
+ * render that awaits an external kernel can outlive a load, and its output
21
+ * must not reach the cache of the new source.
22
+ */
23
+ sourceGeneration = 0;
18
24
  constructor(wasm, options) {
19
25
  this.wasm = wasm;
20
26
  this.options = options;
@@ -49,6 +55,7 @@ export class RendererCore {
49
55
  this.workingCopy = workingCopy;
50
56
  this.descriptor = descriptor;
51
57
  this.cache.clear();
58
+ this.sourceGeneration++;
52
59
  return {
53
60
  descriptor,
54
61
  resident,
@@ -66,6 +73,7 @@ export class RendererCore {
66
73
  this.workingCopy = workingCopy;
67
74
  this.descriptor = descriptor;
68
75
  this.cache.clear();
76
+ this.sourceGeneration++;
69
77
  return {
70
78
  descriptor,
71
79
  resident: false,
@@ -84,6 +92,7 @@ export class RendererCore {
84
92
  this.workingCopy = null;
85
93
  this.descriptor = null;
86
94
  this.cache.clear();
95
+ this.sourceGeneration++;
87
96
  }
88
97
  /** Renders the log. Preview renders are split per stage and cached by prefix. */
89
98
  async render(req) {
@@ -155,7 +164,8 @@ export class RendererCore {
155
164
  async runStages(stages, image, logical, mode, signal, useCache) {
156
165
  let current = image;
157
166
  let currentLogical = logical;
158
- let prefix = `${image.width}x${image.height}`;
167
+ const generation = this.sourceGeneration;
168
+ let prefix = `${generation}:${image.width}x${image.height}`;
159
169
  for (const stage of stages) {
160
170
  if (signal?.aborted)
161
171
  throw new SealpixelError('ABORTED', 'render aborted');
@@ -198,7 +208,8 @@ export class RendererCore {
198
208
  }
199
209
  current = out;
200
210
  }
201
- if (useCache)
211
+ // A stale entry would only push a live one out of the cache.
212
+ if (useCache && generation === this.sourceGeneration)
202
213
  this.remember(prefix, current);
203
214
  }
204
215
  return current;
@@ -1 +1 @@
1
- {"version":3,"file":"renderer-core.js","sourceRoot":"","sources":["../src/renderer-core.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,OAAO,EAAsB,YAAY,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AACrF,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAiB,YAAY,EAAmB,MAAM,WAAW,CAAC;AAEzE,OAAO,EAAE,cAAc,EAAiB,MAAM,eAAe,CAAC;AAC9D,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAkD3C,MAAM,OAAO,YAAY;IAWZ;IAVF,QAAQ,CAAW;IACX,OAAO,CAAsB;IACtC,IAAI,GAAsB,IAAI,CAAC;IACvC,8EAA8E;IACtE,GAAG,CAAyB;IAC5B,WAAW,GAAsB,IAAI,CAAC;IACtC,UAAU,GAA4B,IAAI,CAAC;IAClC,KAAK,GAAG,IAAI,GAAG,EAAsB,CAAC;IAEvD,YACW,IAAmB,EAC5B,OAA4B;QADnB,SAAI,GAAJ,IAAI,CAAe;QAG5B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,QAAQ,GAAG,cAAc,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IAClD,CAAC;IAED,QAAQ,CAAC,EAAU,EAAE,KAAiB;QACpC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;IAChC,CAAC;IAED,QAAQ,CAAC,EAAU;QACjB,OAAO,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;IAChC,CAAC;IAED,IAAI;QACF,OAAO,EAAE,WAAW,EAAE,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,EAAE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CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QAC3B,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,GAAG,KAAK,EAAE,CAAC;YAC/B,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC;YAC9C,IAAI,MAAM,KAAK,SAAS;gBAAE,MAAM;YAChC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QAC5B,CAAC;IACH,CAAC;IAED,iDAAiD;IACjD,SAAS;QACP,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC;IACzB,CAAC;CACF","sourcesContent":["/**\n * The renderer's logic, independent of where it runs. `startSealpixelWorker`\n * wraps it behind a message protocol; `InlineRenderer` calls it directly.\n * It owns the decoded source, the working copy, and a per-stage preview cache.\n */\nimport type { RgbaBuffer, SealpixelWasm } from '@sealpixel/wasm';\nimport { canonicalJson } from './canonical-json.js';\nimport { compile, type PipelineStage, toCoreStages, toPipeline } from './compile.js';\nimport { SealpixelError } from './errors.js';\nimport { runExternalKernel } from './external-kernel.js';\nimport { type Geometry, PLAN_VERSION, type RenderPlan } from './plan.js';\nimport type { AnyPlugin, KernelContext, PlanContext } from './plugin.js';\nimport { createRegistry, type Registry } from './registry.js';\nimport { toCoreOutput } from './render.js';\nimport type { EditLog, OutputOptions, SourceDescriptor } from './types.js';\n\nexport interface LoadedSource {\n descriptor: SourceDescriptor;\n /** Full-resolution pixels are kept only when under the megapixel limit. */\n resident: boolean;\n workingCopy: RgbaBuffer;\n}\n\nexport interface RenderRequest {\n log: EditLog;\n /** `workingCopy` renders on the working copy in preview mode; `full` renders the resident source in truth mode. */\n target: 'workingCopy' | 'full';\n upTo?: number;\n signal?: AbortSignal;\n}\n\nexport interface ExportRequest {\n log: EditLog;\n output: OutputOptions;\n upTo?: number;\n embedEditLog?: boolean;\n}\n\nexport interface ExportResult {\n /** Backed by a plain `ArrayBuffer`, so it is a `BlobPart`. */\n bytes: Uint8Array<ArrayBuffer>;\n mimeType: OutputOptions['format'];\n width: number;\n height: number;\n hash: string;\n}\n\nexport interface RendererCoreOptions {\n plugins: readonly AnyPlugin[];\n /** Full-resolution pixels above this are not kept after loading. `RendererLoadOptions` overrides it per load. */\n maxClientMegapixels: number;\n /** Longest side of the preview working copy. */\n workingCopyMaxSide: number;\n /** Cached stage outputs kept for the preview pipeline. */\n cacheEntries?: number;\n}\n\n/** Per-load overrides of `RendererCoreOptions`. The session passes its `limits` here. */\nexport interface RendererLoadOptions {\n /** Full-resolution pixels above this are not kept after loading. Defaults to the renderer's option. */\n maxClientMegapixels?: number;\n}\n\nexport class RendererCore {\n readonly registry: Registry;\n private readonly options: RendererCoreOptions;\n private full: RgbaBuffer | null = null;\n /** The source's ICC profile, kept with the resident pixels for the export. */\n private icc: Uint8Array | undefined;\n private workingCopy: RgbaBuffer | null = null;\n private descriptor: SourceDescriptor | null = null;\n private readonly cache = new Map<string, RgbaBuffer>();\n\n constructor(\n readonly wasm: SealpixelWasm,\n options: RendererCoreOptions,\n ) {\n this.options = options;\n this.registry = createRegistry(options.plugins);\n }\n\n putAsset(id: string, bytes: Uint8Array): void {\n this.wasm.assetPut(id, bytes);\n }\n\n hasAsset(id: string): boolean {\n return this.wasm.assetHas(id);\n }\n\n info(): { coreVersion: string; plugins: Record<string, number> } {\n return { coreVersion: this.wasm.version(), plugins: this.registry.pluginVersions() };\n }\n\n /** Decodes `bytes`, derives the descriptor and working copy, and drops the full image when too large. */\n load(bytes: Uint8Array, id: string, loadOptions: RendererLoadOptions = {}): LoadedSource {\n const decoded = this.wasm.decode(bytes);\n const hash = this.wasm.sha256Hex(bytes);\n const descriptor: SourceDescriptor = {\n id,\n width: decoded.width,\n height: decoded.height,\n hash,\n mimeType: decoded.mimeType,\n };\n const megapixels = (decoded.width * decoded.height) / 1e6;\n const maxClientMegapixels = loadOptions.maxClientMegapixels ?? this.options.maxClientMegapixels;\n const resident = megapixels <= maxClientMegapixels;\n const workingCopy = this.wasm.resizeWorkingCopy(decoded, this.options.workingCopyMaxSide);\n this.full = resident ? decoded : null;\n this.icc = resident ? decoded.icc : undefined;\n this.workingCopy = workingCopy;\n this.descriptor = descriptor;\n this.cache.clear();\n return {\n descriptor,\n resident,\n workingCopy: { ...workingCopy, data: new Uint8Array(workingCopy.data) },\n };\n }\n\n /** Decodes an encoded working copy (for example one the host built elsewhere) and uses it as the preview source. */\n loadWorkingCopyEncoded(bytes: Uint8Array, descriptor: SourceDescriptor): LoadedSource {\n return this.loadWorkingCopy(this.wasm.decode(bytes), descriptor);\n }\n\n /** Accepts pixels decoded elsewhere, for example by a native decoder. Never resident. */\n loadWorkingCopy(workingCopy: RgbaBuffer, descriptor: SourceDescriptor): LoadedSource {\n this.full = null;\n this.icc = undefined;\n this.workingCopy = workingCopy;\n this.descriptor = descriptor;\n this.cache.clear();\n return {\n descriptor,\n resident: false,\n workingCopy: { ...workingCopy, data: new Uint8Array(workingCopy.data) },\n };\n }\n\n hasSource(): boolean {\n return this.descriptor !== null;\n }\n\n isResident(): boolean {\n return this.full !== null;\n }\n\n unload(): void {\n this.full = null;\n this.icc = undefined;\n this.workingCopy = null;\n this.descriptor = null;\n this.cache.clear();\n }\n\n /** Renders the log. Preview renders are split per stage and cached by prefix. */\n async render(req: RenderRequest): Promise<RgbaBuffer> {\n const { descriptor } = this.require();\n const image = req.target === 'full' ? this.full : this.workingCopy;\n if (!image) {\n throw new SealpixelError(\n 'SOURCE_MISMATCH',\n req.target === 'full'\n ? 'full-resolution pixels are not resident; render the original outside the browser'\n : 'no source loaded',\n );\n }\n const mode = req.target === 'full' ? 'truth' : 'preview';\n const doc = compile(req.log, this.registry, req.upTo);\n const logical = { width: descriptor.width, height: descriptor.height };\n const ctx: PlanContext = {\n logical,\n actual: { width: image.width, height: image.height },\n scale: image.width / logical.width,\n mode,\n };\n const stages = toPipeline(doc, this.registry, ctx);\n return this.runStages(stages, image, logical, mode, req.signal, mode === 'preview');\n }\n\n async export(req: ExportRequest): Promise<ExportResult> {\n const rendered = await this.render({\n log: req.log,\n target: 'full',\n ...(req.upTo === undefined ? {} : { upTo: req.upTo }),\n });\n const coreOutput = toCoreOutput(req.output);\n if (req.embedEditLog) {\n coreOutput['embed'] = canonicalJson({ log: req.log, index: req.upTo ?? req.log.ops.length });\n }\n const bytes = this.wasm.encode(rendered, JSON.stringify(coreOutput), this.icc);\n return {\n bytes,\n mimeType: req.output.format,\n width: rendered.width,\n height: rendered.height,\n hash: this.wasm.sha256Hex(bytes),\n };\n }\n\n geometry(log: EditLog, target: 'workingCopy' | 'full', upTo?: number): Geometry {\n const { descriptor } = this.require();\n const image = (target === 'full' ? this.full : this.workingCopy) ?? this.workingCopy;\n if (!image) throw new SealpixelError('SOURCE_MISMATCH', 'no source loaded');\n const logical = { width: descriptor.width, height: descriptor.height };\n const doc = compile(log, this.registry, upTo);\n const stages = toPipeline(doc, this.registry, {\n logical,\n actual: { width: image.width, height: image.height },\n scale: image.width / logical.width,\n mode: target === 'full' ? 'truth' : 'preview',\n });\n const core = stages.filter((s) => s.kind === 'core');\n const plan: RenderPlan = {\n version: PLAN_VERSION,\n source: logical,\n bufferScale: image.width / logical.width,\n stages: toCoreStages(core),\n };\n return JSON.parse(\n this.wasm.resolveGeometry(JSON.stringify(plan), image.width, image.height),\n ) as Geometry;\n }\n\n private require(): { descriptor: SourceDescriptor } {\n if (!this.descriptor) throw new SealpixelError('SOURCE_MISMATCH', 'no source loaded');\n return { descriptor: this.descriptor };\n }\n\n private async runStages(\n stages: PipelineStage[],\n image: RgbaBuffer,\n logical: { width: number; height: number },\n mode: 'truth' | 'preview',\n signal: AbortSignal | undefined,\n useCache: boolean,\n ): Promise<RgbaBuffer> {\n let current = image;\n let currentLogical = logical;\n let prefix = `${image.width}x${image.height}`;\n for (const stage of stages) {\n if (signal?.aborted) throw new SealpixelError('ABORTED', 'render aborted');\n prefix += `|${canonicalJson({ n: stage.name, p: stage.params })}`;\n const cached = useCache ? this.cache.get(prefix) : undefined;\n if (cached) {\n current = cached;\n currentLogical = this.logicalAfter(stage, currentLogical, current, image, logical);\n continue;\n }\n if (stage.kind === 'core') {\n const plan: RenderPlan = {\n version: PLAN_VERSION,\n source: currentLogical,\n bufferScale: current.width / currentLogical.width,\n stages: toCoreStages([stage]),\n };\n const planJson = JSON.stringify(plan);\n const geometry = JSON.parse(\n this.wasm.resolveGeometry(planJson, current.width, current.height),\n ) as Geometry;\n current = this.wasm.renderRgba(current, planJson);\n currentLogical = geometry.logicalOut;\n } else {\n const kctx: KernelContext = {\n logical: currentLogical,\n actual: { width: current.width, height: current.height },\n scale: current.width / currentLogical.width,\n mode,\n asset: (id) => {\n throw new SealpixelError(\n 'MISSING_ASSET',\n `asset \"${id}\" is not available to JS kernels yet`,\n { assetId: id },\n );\n },\n signal: signal ?? new AbortController().signal,\n };\n const out = await runExternalKernel(stage.plugin, current, stage.params, kctx);\n if (out.width !== current.width || out.height !== current.height) {\n currentLogical = {\n width: Math.round(currentLogical.width * (out.width / current.width)),\n height: Math.round(currentLogical.height * (out.height / current.height)),\n };\n }\n current = out;\n }\n if (useCache) this.remember(prefix, current);\n }\n return current;\n }\n\n /** Recomputes the logical size after a cached stage by asking the core for its geometry. */\n private logicalAfter(\n stage: PipelineStage,\n logicalIn: { width: number; height: number },\n out: RgbaBuffer,\n _image: RgbaBuffer,\n _sourceLogical: { width: number; height: number },\n ): { width: number; height: number } {\n if (stage.kind !== 'core') {\n return {\n width: Math.round(logicalIn.width * (out.width / out.width)),\n height: logicalIn.height,\n };\n }\n // The cached buffer already has the output size; the logical size is the\n // geometry of this single stage on a buffer with the input's logical size.\n const plan: RenderPlan = {\n version: PLAN_VERSION,\n source: logicalIn,\n bufferScale: 1,\n stages: toCoreStages([stage]),\n };\n const g = JSON.parse(\n this.wasm.resolveGeometry(JSON.stringify(plan), logicalIn.width, logicalIn.height),\n ) as Geometry;\n return g.logicalOut;\n }\n\n private remember(key: string, value: RgbaBuffer): void {\n const limit = this.options.cacheEntries ?? 6;\n if (this.cache.has(key)) this.cache.delete(key);\n this.cache.set(key, value);\n while (this.cache.size > limit) {\n const oldest = this.cache.keys().next().value;\n if (oldest === undefined) break;\n this.cache.delete(oldest);\n }\n }\n\n /** For tests: number of cached stage outputs. */\n cacheSize(): number {\n return this.cache.size;\n }\n}\n"]}
1
+ {"version":3,"file":"renderer-core.js","sourceRoot":"","sources":["../src/renderer-core.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,OAAO,EAAsB,YAAY,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AACrF,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAiB,YAAY,EAAmB,MAAM,WAAW,CAAC;AAEzE,OAAO,EAAE,cAAc,EAAiB,MAAM,eAAe,CAAC;AAC9D,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAkD3C,MAAM,OAAO,YAAY;IAiBZ;IAhBF,QAAQ,CAAW;IACX,OAAO,CAAsB;IACtC,IAAI,GAAsB,IAAI,CAAC;IACvC,8EAA8E;IACtE,GAAG,CAAyB;IAC5B,WAAW,GAAsB,IAAI,CAAC;IACtC,UAAU,GAA4B,IAAI,CAAC;IAClC,KAAK,GAAG,IAAI,GAAG,EAAsB,CAAC;IACvD;;;;OAIG;IACK,gBAAgB,GAAG,CAAC,CAAC;IAE7B,YACW,IAAmB,EAC5B,OAA4B;QADnB,SAAI,GAAJ,IAAI,CAAe;QAG5B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,QAAQ,GAAG,cAAc,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IAClD,CAAC;IAED,QAAQ,CAAC,EAAU,EAAE,KAAiB;QACpC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,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AI,CAAC,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,SAAS,CAAC,KAAK,EAAE,SAAS,CAAC,MAAM,CAAC,CACvE,CAAC;QACd,OAAO,CAAC,CAAC,UAAU,CAAC;IACtB,CAAC;IAEO,QAAQ,CAAC,GAAW,EAAE,KAAiB;QAC7C,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,YAAY,IAAI,CAAC,CAAC;QAC7C,IAAI,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC;YAAE,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QAChD,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QAC3B,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,GAAG,KAAK,EAAE,CAAC;YAC/B,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC;YAC9C,IAAI,MAAM,KAAK,SAAS;gBAAE,MAAM;YAChC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QAC5B,CAAC;IACH,CAAC;IAED,iDAAiD;IACjD,SAAS;QACP,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC;IACzB,CAAC;CACF","sourcesContent":["/**\n * The renderer's logic, independent of where it runs. `startSealpixelWorker`\n * wraps it behind a message protocol; `InlineRenderer` calls it directly.\n * It owns the decoded source, the working copy, and a per-stage preview cache.\n */\nimport type { RgbaBuffer, SealpixelWasm } from '@sealpixel/wasm';\nimport { canonicalJson } from './canonical-json.js';\nimport { compile, type PipelineStage, toCoreStages, toPipeline } from './compile.js';\nimport { SealpixelError } from './errors.js';\nimport { runExternalKernel } from './external-kernel.js';\nimport { type Geometry, PLAN_VERSION, type RenderPlan } from './plan.js';\nimport type { AnyPlugin, KernelContext, PlanContext } from './plugin.js';\nimport { createRegistry, type Registry } from './registry.js';\nimport { toCoreOutput } from './render.js';\nimport type { EditLog, OutputOptions, SourceDescriptor } from './types.js';\n\nexport interface LoadedSource {\n descriptor: SourceDescriptor;\n /** Full-resolution pixels are kept only when under the megapixel limit. */\n resident: boolean;\n workingCopy: RgbaBuffer;\n}\n\nexport interface RenderRequest {\n log: EditLog;\n /** `workingCopy` renders on the working copy in preview mode; `full` renders the resident source in truth mode. */\n target: 'workingCopy' | 'full';\n upTo?: number;\n signal?: AbortSignal;\n}\n\nexport interface ExportRequest {\n log: EditLog;\n output: OutputOptions;\n upTo?: number;\n embedEditLog?: boolean;\n}\n\nexport interface ExportResult {\n /** Backed by a plain `ArrayBuffer`, so it is a `BlobPart`. */\n bytes: Uint8Array<ArrayBuffer>;\n mimeType: OutputOptions['format'];\n width: number;\n height: number;\n hash: string;\n}\n\nexport interface RendererCoreOptions {\n plugins: readonly AnyPlugin[];\n /** Full-resolution pixels above this are not kept after loading. `RendererLoadOptions` overrides it per load. */\n maxClientMegapixels: number;\n /** Longest side of the preview working copy. */\n workingCopyMaxSide: number;\n /** Cached stage outputs kept for the preview pipeline. */\n cacheEntries?: number;\n}\n\n/** Per-load overrides of `RendererCoreOptions`. The session passes its `limits` here. */\nexport interface RendererLoadOptions {\n /** Full-resolution pixels above this are not kept after loading. Defaults to the renderer's option. */\n maxClientMegapixels?: number;\n}\n\nexport class RendererCore {\n readonly registry: Registry;\n private readonly options: RendererCoreOptions;\n private full: RgbaBuffer | null = null;\n /** The source's ICC profile, kept with the resident pixels for the export. */\n private icc: Uint8Array | undefined;\n private workingCopy: RgbaBuffer | null = null;\n private descriptor: SourceDescriptor | null = null;\n private readonly cache = new Map<string, RgbaBuffer>();\n /**\n * Increments whenever the source changes. It is part of every cache key: a\n * render that awaits an external kernel can outlive a load, and its output\n * must not reach the cache of the new source.\n */\n private sourceGeneration = 0;\n\n constructor(\n readonly wasm: SealpixelWasm,\n options: RendererCoreOptions,\n ) {\n this.options = options;\n this.registry = createRegistry(options.plugins);\n }\n\n putAsset(id: string, bytes: Uint8Array): void {\n this.wasm.assetPut(id, bytes);\n }\n\n hasAsset(id: string): boolean {\n return this.wasm.assetHas(id);\n }\n\n info(): { coreVersion: string; plugins: Record<string, number> } {\n return { coreVersion: this.wasm.version(), plugins: this.registry.pluginVersions() };\n }\n\n /** Decodes `bytes`, derives the descriptor and working copy, and drops the full image when too large. */\n load(bytes: Uint8Array, id: string, loadOptions: RendererLoadOptions = {}): LoadedSource {\n const decoded = this.wasm.decode(bytes);\n const hash = this.wasm.sha256Hex(bytes);\n const descriptor: SourceDescriptor = {\n id,\n width: decoded.width,\n height: decoded.height,\n hash,\n mimeType: decoded.mimeType,\n };\n const megapixels = (decoded.width * decoded.height) / 1e6;\n const maxClientMegapixels = loadOptions.maxClientMegapixels ?? this.options.maxClientMegapixels;\n const resident = megapixels <= maxClientMegapixels;\n const workingCopy = this.wasm.resizeWorkingCopy(decoded, this.options.workingCopyMaxSide);\n this.full = resident ? decoded : null;\n this.icc = resident ? decoded.icc : undefined;\n this.workingCopy = workingCopy;\n this.descriptor = descriptor;\n this.cache.clear();\n this.sourceGeneration++;\n return {\n descriptor,\n resident,\n workingCopy: { ...workingCopy, data: new Uint8Array(workingCopy.data) },\n };\n }\n\n /** Decodes an encoded working copy (for example one the host built elsewhere) and uses it as the preview source. */\n loadWorkingCopyEncoded(bytes: Uint8Array, descriptor: SourceDescriptor): LoadedSource {\n return this.loadWorkingCopy(this.wasm.decode(bytes), descriptor);\n }\n\n /** Accepts pixels decoded elsewhere, for example by a native decoder. Never resident. */\n loadWorkingCopy(workingCopy: RgbaBuffer, descriptor: SourceDescriptor): LoadedSource {\n this.full = null;\n this.icc = undefined;\n this.workingCopy = workingCopy;\n this.descriptor = descriptor;\n this.cache.clear();\n this.sourceGeneration++;\n return {\n descriptor,\n resident: false,\n workingCopy: { ...workingCopy, data: new Uint8Array(workingCopy.data) },\n };\n }\n\n hasSource(): boolean {\n return this.descriptor !== null;\n }\n\n isResident(): boolean {\n return this.full !== null;\n }\n\n unload(): void {\n this.full = null;\n this.icc = undefined;\n this.workingCopy = null;\n this.descriptor = null;\n this.cache.clear();\n this.sourceGeneration++;\n }\n\n /** Renders the log. Preview renders are split per stage and cached by prefix. */\n async render(req: RenderRequest): Promise<RgbaBuffer> {\n const { descriptor } = this.require();\n const image = req.target === 'full' ? this.full : this.workingCopy;\n if (!image) {\n throw new SealpixelError(\n 'SOURCE_MISMATCH',\n req.target === 'full'\n ? 'full-resolution pixels are not resident; render the original outside the browser'\n : 'no source loaded',\n );\n }\n const mode = req.target === 'full' ? 'truth' : 'preview';\n const doc = compile(req.log, this.registry, req.upTo);\n const logical = { width: descriptor.width, height: descriptor.height };\n const ctx: PlanContext = {\n logical,\n actual: { width: image.width, height: image.height },\n scale: image.width / logical.width,\n mode,\n };\n const stages = toPipeline(doc, this.registry, ctx);\n return this.runStages(stages, image, logical, mode, req.signal, mode === 'preview');\n }\n\n async export(req: ExportRequest): Promise<ExportResult> {\n const rendered = await this.render({\n log: req.log,\n target: 'full',\n ...(req.upTo === undefined ? {} : { upTo: req.upTo }),\n });\n const coreOutput = toCoreOutput(req.output);\n if (req.embedEditLog) {\n coreOutput['embed'] = canonicalJson({ log: req.log, index: req.upTo ?? req.log.ops.length });\n }\n const bytes = this.wasm.encode(rendered, JSON.stringify(coreOutput), this.icc);\n return {\n bytes,\n mimeType: req.output.format,\n width: rendered.width,\n height: rendered.height,\n hash: this.wasm.sha256Hex(bytes),\n };\n }\n\n geometry(log: EditLog, target: 'workingCopy' | 'full', upTo?: number): Geometry {\n const { descriptor } = this.require();\n const image = (target === 'full' ? this.full : this.workingCopy) ?? this.workingCopy;\n if (!image) throw new SealpixelError('SOURCE_MISMATCH', 'no source loaded');\n const logical = { width: descriptor.width, height: descriptor.height };\n const doc = compile(log, this.registry, upTo);\n const stages = toPipeline(doc, this.registry, {\n logical,\n actual: { width: image.width, height: image.height },\n scale: image.width / logical.width,\n mode: target === 'full' ? 'truth' : 'preview',\n });\n const core = stages.filter((s) => s.kind === 'core');\n const plan: RenderPlan = {\n version: PLAN_VERSION,\n source: logical,\n bufferScale: image.width / logical.width,\n stages: toCoreStages(core),\n };\n return JSON.parse(\n this.wasm.resolveGeometry(JSON.stringify(plan), image.width, image.height),\n ) as Geometry;\n }\n\n private require(): { descriptor: SourceDescriptor } {\n if (!this.descriptor) throw new SealpixelError('SOURCE_MISMATCH', 'no source loaded');\n return { descriptor: this.descriptor };\n }\n\n private async runStages(\n stages: PipelineStage[],\n image: RgbaBuffer,\n logical: { width: number; height: number },\n mode: 'truth' | 'preview',\n signal: AbortSignal | undefined,\n useCache: boolean,\n ): Promise<RgbaBuffer> {\n let current = image;\n let currentLogical = logical;\n const generation = this.sourceGeneration;\n let prefix = `${generation}:${image.width}x${image.height}`;\n for (const stage of stages) {\n if (signal?.aborted) throw new SealpixelError('ABORTED', 'render aborted');\n prefix += `|${canonicalJson({ n: stage.name, p: stage.params })}`;\n const cached = useCache ? this.cache.get(prefix) : undefined;\n if (cached) {\n current = cached;\n currentLogical = this.logicalAfter(stage, currentLogical, current, image, logical);\n continue;\n }\n if (stage.kind === 'core') {\n const plan: RenderPlan = {\n version: PLAN_VERSION,\n source: currentLogical,\n bufferScale: current.width / currentLogical.width,\n stages: toCoreStages([stage]),\n };\n const planJson = JSON.stringify(plan);\n const geometry = JSON.parse(\n this.wasm.resolveGeometry(planJson, current.width, current.height),\n ) as Geometry;\n current = this.wasm.renderRgba(current, planJson);\n currentLogical = geometry.logicalOut;\n } else {\n const kctx: KernelContext = {\n logical: currentLogical,\n actual: { width: current.width, height: current.height },\n scale: current.width / currentLogical.width,\n mode,\n asset: (id) => {\n throw new SealpixelError(\n 'MISSING_ASSET',\n `asset \"${id}\" is not available to JS kernels yet`,\n { assetId: id },\n );\n },\n signal: signal ?? new AbortController().signal,\n };\n const out = await runExternalKernel(stage.plugin, current, stage.params, kctx);\n if (out.width !== current.width || out.height !== current.height) {\n currentLogical = {\n width: Math.round(currentLogical.width * (out.width / current.width)),\n height: Math.round(currentLogical.height * (out.height / current.height)),\n };\n }\n current = out;\n }\n // A stale entry would only push a live one out of the cache.\n if (useCache && generation === this.sourceGeneration) this.remember(prefix, current);\n }\n return current;\n }\n\n /** Recomputes the logical size after a cached stage by asking the core for its geometry. */\n private logicalAfter(\n stage: PipelineStage,\n logicalIn: { width: number; height: number },\n out: RgbaBuffer,\n _image: RgbaBuffer,\n _sourceLogical: { width: number; height: number },\n ): { width: number; height: number } {\n if (stage.kind !== 'core') {\n return {\n width: Math.round(logicalIn.width * (out.width / out.width)),\n height: logicalIn.height,\n };\n }\n // The cached buffer already has the output size; the logical size is the\n // geometry of this single stage on a buffer with the input's logical size.\n const plan: RenderPlan = {\n version: PLAN_VERSION,\n source: logicalIn,\n bufferScale: 1,\n stages: toCoreStages([stage]),\n };\n const g = JSON.parse(\n this.wasm.resolveGeometry(JSON.stringify(plan), logicalIn.width, logicalIn.height),\n ) as Geometry;\n return g.logicalOut;\n }\n\n private remember(key: string, value: RgbaBuffer): void {\n const limit = this.options.cacheEntries ?? 6;\n if (this.cache.has(key)) this.cache.delete(key);\n this.cache.set(key, value);\n while (this.cache.size > limit) {\n const oldest = this.cache.keys().next().value;\n if (oldest === undefined) break;\n this.cache.delete(oldest);\n }\n }\n\n /** For tests: number of cached stage outputs. */\n cacheSize(): number {\n return this.cache.size;\n }\n}\n"]}
package/dist/session.d.ts CHANGED
@@ -103,6 +103,11 @@ export interface EditorSession {
103
103
  * with `ABORTED` and the newer one wins.
104
104
  */
105
105
  load(source: LoadSource, options?: LoadOptions): Promise<SourceDescriptor>;
106
+ /**
107
+ * Appends `op` at the current position. Checks it like a log parse does
108
+ * and throws `SealpixelError` with the same code. An op without an `id` is
109
+ * an error. An op whose `id` is already in the log is a no-op.
110
+ */
106
111
  dispatch(op: Operation): void;
107
112
  undo(): void;
108
113
  redo(): void;
@@ -119,7 +124,7 @@ export interface EditorSession {
119
124
  subscribe(listener: (state: SessionState) => void): () => void;
120
125
  /** Forces a preview render now and resolves when it is applied. */
121
126
  renderPreview(): Promise<PreviewState>;
122
- /** Resolves when no preview render is pending. */
127
+ /** Resolves when no preview render is pending. Resolves at once after `dispose`. */
123
128
  whenIdle(): Promise<void>;
124
129
  /**
125
130
  * Replaces the history with a saved state for the loaded image (controlled
@@ -161,6 +166,10 @@ export interface EditorSession {
161
166
  filename: string;
162
167
  result: ExportResult;
163
168
  }>;
169
+ /**
170
+ * Stops the previews and settles every pending `whenIdle`. After it, every
171
+ * method that needs the renderer fails with `ABORTED`.
172
+ */
164
173
  dispose(): void;
165
174
  }
166
175
  export declare function createEditorSession(options: SessionOptions): EditorSession;
package/dist/session.js CHANGED
@@ -3,9 +3,10 @@ import { compile } from './compile.js';
3
3
  import { SealpixelError } from './errors.js';
4
4
  import * as hist from './history.js';
5
5
  import { InlineRenderer } from './inline-renderer.js';
6
- import { createRegistry } from './registry.js';
6
+ import { createRegistry, parseAppendedOperation } from './registry.js';
7
7
  const hashMismatch = () => new SealpixelError('SOURCE_MISMATCH', 'the saved edit log belongs to a different image (hash differs)');
8
8
  const supersededError = () => new SealpixelError('ABORTED', 'a newer load() replaced this one');
9
+ const disposedError = () => new SealpixelError('ABORTED', 'the session is disposed; create a new session');
9
10
  const EXT = {
10
11
  'image/png': 'png',
11
12
  'image/jpeg': 'jpg',
@@ -66,6 +67,12 @@ export function createEditorSession(options) {
66
67
  let inflight = null;
67
68
  let idleResolvers = [];
68
69
  let disposed = false;
70
+ /**
71
+ * The version at which a load failed. The preview of the restored image
72
+ * keeps the load error on the stage. A later edit changes the version, and
73
+ * its preview clears the error as before.
74
+ */
75
+ let failedLoadVersion = -1;
69
76
  const emit = () => {
70
77
  for (const l of listeners)
71
78
  l(state);
@@ -93,7 +100,7 @@ export function createEditorSession(options) {
93
100
  schedulePreview();
94
101
  };
95
102
  function schedulePreview() {
96
- if (!previewEnabled || state.status !== 'ready')
103
+ if (disposed || !previewEnabled || state.status !== 'ready')
97
104
  return;
98
105
  if (timer)
99
106
  clearTimeout(timer);
@@ -134,7 +141,11 @@ export function createEditorSession(options) {
134
141
  }
135
142
  const preview = { image, geometry, viewGeometry: viewGeometry ?? geometry, version };
136
143
  inflight = null;
137
- set({ preview, previewPending: false, error: null });
144
+ set({
145
+ preview,
146
+ previewPending: false,
147
+ error: version === failedLoadVersion ? state.error : null,
148
+ });
138
149
  settleIdle();
139
150
  return preview;
140
151
  }
@@ -142,7 +153,10 @@ export function createEditorSession(options) {
142
153
  if (inflight?.controller === controller)
143
154
  inflight = null;
144
155
  const e = SealpixelError.from(error);
145
- if (e.name === 'ABORTED' || version !== state.version) {
156
+ // Only an abort that the session caused has a successor that settles
157
+ // `previewPending`. An abort from elsewhere, such as a shared renderer
158
+ // that its host disposed, is reported like any other failure.
159
+ if ((e.name === 'ABORTED' && controller.signal.aborted) || version !== state.version) {
146
160
  settleIdle();
147
161
  return null;
148
162
  }
@@ -152,6 +166,7 @@ export function createEditorSession(options) {
152
166
  }
153
167
  }
154
168
  async function renderDetached(transform, options) {
169
+ ensureAlive();
155
170
  if (state.status !== 'ready') {
156
171
  throw new SealpixelError('NO_SOURCE', 'renderDetached needs a loaded image');
157
172
  }
@@ -173,9 +188,13 @@ export function createEditorSession(options) {
173
188
  throw new SealpixelError('DECODE_FAILED', `${source}: HTTP ${res.status}`);
174
189
  return {
175
190
  bytes: new Uint8Array(await res.arrayBuffer()),
176
- name: source.split('/').pop() ?? null,
191
+ // The query and the fragment are not part of the file name.
192
+ name: source.split(/[?#]/, 1)[0]?.split('/').pop() ?? null,
177
193
  };
178
194
  }
195
+ // A Blob knows its size: refuse a large one before reading it into memory.
196
+ if (source.size > maxClientBytes)
197
+ throw tooLarge(source.size);
179
198
  const name = 'name' in source && typeof source.name === 'string' ? source.name : null;
180
199
  return { bytes: new Uint8Array(await source.arrayBuffer()), name };
181
200
  }
@@ -193,6 +212,9 @@ export function createEditorSession(options) {
193
212
  const index = typeof wrapped?.index === 'number' ? wrapped.index : undefined;
194
213
  return { log, index };
195
214
  }
215
+ function tooLarge(byteLength) {
216
+ return new SealpixelError('TOO_LARGE', `${byteLength} bytes exceed the client limit of ${maxClientBytes}`);
217
+ }
196
218
  /** Runs `task` after every renderer switch that started before it. */
197
219
  function exclusive(task) {
198
220
  const run = loadQueue.then(task);
@@ -205,8 +227,9 @@ export function createEditorSession(options) {
205
227
  * that names an image the renderer does not hold renders wrong pixels.
206
228
  */
207
229
  async function restoreCommitted() {
208
- // Nothing committed: the state is `empty` and nothing renders.
209
- if (!committed)
230
+ // Nothing committed: the state is `empty` and nothing renders. A disposed
231
+ // session renders nothing either.
232
+ if (!committed || disposed)
210
233
  return;
211
234
  try {
212
235
  await loadInto(committed.bytes, committed.id);
@@ -244,6 +267,7 @@ export function createEditorSession(options) {
244
267
  const session = {
245
268
  registry,
246
269
  async load(source, loadOptions = {}) {
270
+ ensureAlive();
247
271
  const generation = ++loadGeneration;
248
272
  const superseded = () => generation !== loadGeneration;
249
273
  if (timer)
@@ -256,9 +280,8 @@ export function createEditorSession(options) {
256
280
  const { bytes, name } = await readBytes(source);
257
281
  if (superseded())
258
282
  throw supersededError();
259
- if (bytes.byteLength > maxClientBytes) {
260
- throw new SealpixelError('TOO_LARGE', `${bytes.byteLength} bytes exceed the client limit of ${maxClientBytes}`);
261
- }
283
+ if (bytes.byteLength > maxClientBytes)
284
+ throw tooLarge(bytes.byteLength);
262
285
  const id = loadOptions.id ?? (name ? name.replace(/\.[^.]+$/, '') : 'image');
263
286
  // Validate what can be validated before the renderer switches.
264
287
  const saved = loadOptions.editLog === undefined ? null : resolveSavedState(loadOptions.editLog);
@@ -271,12 +294,14 @@ export function createEditorSession(options) {
271
294
  return await exclusive(async () => {
272
295
  if (superseded())
273
296
  throw supersededError();
297
+ ensureAlive();
274
298
  const loaded = await loadInto(bytes, id);
275
299
  // The renderer holds the new image now. Until the state commits to
276
300
  // it, any failure puts the renderer back on the committed image.
277
301
  try {
278
302
  if (superseded())
279
303
  throw supersededError();
304
+ ensureAlive();
280
305
  const descriptor = loaded.descriptor;
281
306
  const history = saved
282
307
  ? savedHistory(saved, descriptor, loadOptions.index)
@@ -313,20 +338,29 @@ export function createEditorSession(options) {
313
338
  // renderer switches ahead of it, so the state never says `ready` while
314
339
  // an older load still holds the renderer on another image.
315
340
  await exclusive(async () => {
316
- if (!superseded())
317
- set({ status: state.source ? 'ready' : 'empty', error: e });
341
+ if (superseded())
342
+ return;
343
+ set({ status: state.source ? 'ready' : 'empty', error: e });
344
+ // `load` dropped the preview. The renderer holds the previous image
345
+ // again, so the stage shows it again.
346
+ failedLoadVersion = state.version;
347
+ schedulePreview();
318
348
  });
319
349
  throw e;
320
350
  }
321
351
  },
322
352
  dispatch(op) {
323
353
  ensureReady();
324
- const violation = state.source
325
- ? registry.validateOperation(op, state.document, state.source)
326
- : null;
327
- if (violation)
328
- throw new SealpixelError('OPTION_VIOLATION', `${op.type}: ${violation}`);
329
- setHistory(hist.dispatch(state.history, op));
354
+ const id = op?.id;
355
+ if (typeof id !== 'string' || id === '') {
356
+ throw new SealpixelError('INVALID_EDIT_LOG', 'op has no non-empty string "id"');
357
+ }
358
+ // A retried op is a no-op before any check: its first dispatch already
359
+ // passed them, and the state it applied to may be gone.
360
+ if (state.history.log.ops.some((existing) => existing.id === id))
361
+ return;
362
+ const parsed = parseAppendedOperation(registry, op, state.document, state.source);
363
+ setHistory(hist.dispatch(state.history, parsed));
330
364
  },
331
365
  undo() {
332
366
  setHistory(hist.undo(state.history));
@@ -359,7 +393,7 @@ export function createEditorSession(options) {
359
393
  throw state.error ?? new SealpixelError('ABORTED', 'preview superseded');
360
394
  },
361
395
  whenIdle() {
362
- if (!state.previewPending && !timer && !inflight)
396
+ if (disposed || (!state.previewPending && !timer && !inflight))
363
397
  return Promise.resolve();
364
398
  return new Promise((resolve) => idleResolvers.push(resolve));
365
399
  },
@@ -439,16 +473,28 @@ export function createEditorSession(options) {
439
473
  return { filename, result };
440
474
  },
441
475
  dispose() {
476
+ if (disposed)
477
+ return;
442
478
  disposed = true;
443
479
  if (timer)
444
480
  clearTimeout(timer);
481
+ timer = null;
445
482
  inflight?.controller.abort();
483
+ inflight = null;
446
484
  listeners.clear();
485
+ // No preview runs any more: settle every `whenIdle` that waits for one.
486
+ set({ previewPending: false });
487
+ settleIdle();
447
488
  if (ownsRenderer)
448
489
  renderer.dispose();
449
490
  },
450
491
  };
492
+ function ensureAlive() {
493
+ if (disposed)
494
+ throw disposedError();
495
+ }
451
496
  function ensureReady() {
497
+ ensureAlive();
452
498
  if (state.status !== 'ready')
453
499
  throw new SealpixelError('NO_SOURCE', 'load an image first');
454
500
  }