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

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/dist/errors.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export type SealpixelErrorCode = 'SOURCE_MISMATCH' | 'INVALID_EDIT_LOG' | 'UNKNOWN_PLUGIN' | 'OPTION_VIOLATION' | 'ABORTED' | 'NO_SOURCE' | 'NOT_RESIDENT' | 'DOWNLOAD_UNSUPPORTED' | 'KERNEL_FAILED' | 'INVALID_REQUEST' | 'SOURCE_UNAVAILABLE' | 'FORBIDDEN_SOURCE' | 'FORBIDDEN_DESTINATION' | 'TIMEOUT' | import('@sealpixel/wasm').SealpixelErrorCode;
1
+ export type SealpixelErrorCode = 'SOURCE_MISMATCH' | 'INVALID_EDIT_LOG' | 'UNKNOWN_PLUGIN' | 'OPTION_VIOLATION' | 'ABORTED' | 'NO_SOURCE' | 'NOT_RESIDENT' | 'DOWNLOAD_UNSUPPORTED' | 'KERNEL_FAILED' | 'INVALID_REQUEST' | 'SOURCE_UNAVAILABLE' | 'FORBIDDEN_SOURCE' | 'FORBIDDEN_DESTINATION' | 'TIMEOUT' | 'BUSY' | import('@sealpixel/wasm').SealpixelErrorCode;
2
2
  export declare class SealpixelError extends Error {
3
3
  readonly name: SealpixelErrorCode;
4
4
  readonly details: unknown;
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAiBA,MAAM,OAAO,cAAe,SAAQ,KAAK;IACrB,IAAI,CAAqB;IAClC,OAAO,CAAU;IAE1B,YAAY,IAAwB,EAAE,OAAe,EAAE,OAAiB;QACtE,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAED,iEAAiE;IACjE,MAAM,CAAC,IAAI,CAAC,KAAc;QACxB,IAAI,KAAK,YAAY,cAAc;YAAE,OAAO,KAAK,CAAC;QAClD,IAAI,KAAK,YAAY,KAAK,IAAI,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;YAC3D,OAAO,IAAI,cAAc,CACvB,KAAK,CAAC,IAA0B,EAChC,KAAK,CAAC,OAAO,EACZ,KAA+B,CAAC,OAAO,CACzC,CAAC;QACJ,CAAC;QACD,OAAO,IAAI,cAAc,CAAC,kBAAkB,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IAC/D,CAAC;CACF","sourcesContent":["export type SealpixelErrorCode =\n | 'SOURCE_MISMATCH'\n | 'INVALID_EDIT_LOG'\n | 'UNKNOWN_PLUGIN'\n | 'OPTION_VIOLATION'\n | 'ABORTED'\n | 'NO_SOURCE'\n | 'NOT_RESIDENT'\n | 'DOWNLOAD_UNSUPPORTED'\n | 'KERNEL_FAILED'\n | 'INVALID_REQUEST'\n | 'SOURCE_UNAVAILABLE'\n | 'FORBIDDEN_SOURCE'\n | 'FORBIDDEN_DESTINATION'\n | 'TIMEOUT'\n | import('@sealpixel/wasm').SealpixelErrorCode;\n\nexport class SealpixelError extends Error {\n override readonly name: SealpixelErrorCode;\n readonly details: unknown;\n\n constructor(code: SealpixelErrorCode, message: string, details?: unknown) {\n super(message);\n this.name = code;\n this.details = details;\n }\n\n /** Re-throws core errors unchanged and wraps everything else. */\n static from(error: unknown): SealpixelError {\n if (error instanceof SealpixelError) return error;\n if (error instanceof Error && /^[A-Z_]+$/.test(error.name)) {\n return new SealpixelError(\n error.name as SealpixelErrorCode,\n error.message,\n (error as { details?: unknown }).details,\n );\n }\n return new SealpixelError('INVALID_EDIT_LOG', String(error));\n }\n}\n"]}
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAkBA,MAAM,OAAO,cAAe,SAAQ,KAAK;IACrB,IAAI,CAAqB;IAClC,OAAO,CAAU;IAE1B,YAAY,IAAwB,EAAE,OAAe,EAAE,OAAiB;QACtE,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAED,iEAAiE;IACjE,MAAM,CAAC,IAAI,CAAC,KAAc;QACxB,IAAI,KAAK,YAAY,cAAc;YAAE,OAAO,KAAK,CAAC;QAClD,IAAI,KAAK,YAAY,KAAK,IAAI,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;YAC3D,OAAO,IAAI,cAAc,CACvB,KAAK,CAAC,IAA0B,EAChC,KAAK,CAAC,OAAO,EACZ,KAA+B,CAAC,OAAO,CACzC,CAAC;QACJ,CAAC;QACD,OAAO,IAAI,cAAc,CAAC,kBAAkB,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IAC/D,CAAC;CACF","sourcesContent":["export type SealpixelErrorCode =\n | 'SOURCE_MISMATCH'\n | 'INVALID_EDIT_LOG'\n | 'UNKNOWN_PLUGIN'\n | 'OPTION_VIOLATION'\n | 'ABORTED'\n | 'NO_SOURCE'\n | 'NOT_RESIDENT'\n | 'DOWNLOAD_UNSUPPORTED'\n | 'KERNEL_FAILED'\n | 'INVALID_REQUEST'\n | 'SOURCE_UNAVAILABLE'\n | 'FORBIDDEN_SOURCE'\n | 'FORBIDDEN_DESTINATION'\n | 'TIMEOUT'\n | 'BUSY'\n | import('@sealpixel/wasm').SealpixelErrorCode;\n\nexport class SealpixelError extends Error {\n override readonly name: SealpixelErrorCode;\n readonly details: unknown;\n\n constructor(code: SealpixelErrorCode, message: string, details?: unknown) {\n super(message);\n this.name = code;\n this.details = details;\n }\n\n /** Re-throws core errors unchanged and wraps everything else. */\n static from(error: unknown): SealpixelError {\n if (error instanceof SealpixelError) return error;\n if (error instanceof Error && /^[A-Z_]+$/.test(error.name)) {\n return new SealpixelError(\n error.name as SealpixelErrorCode,\n error.message,\n (error as { details?: unknown }).details,\n );\n }\n return new SealpixelError('INVALID_EDIT_LOG', String(error));\n }\n}\n"]}
@@ -95,13 +95,36 @@ export type Redaction = {
95
95
  * Pixelate or mosaic cell size, or blur diameter, in logical source pixels.
96
96
  */
97
97
  amount: number;
98
+ /**
99
+ * Width of the soft edge outside the region, in logical source pixels.
100
+ * Every pixel the region touches gets the full effect. Outside, the
101
+ * effect fades to nothing at this distance. Zero is a hard edge, and is
102
+ * left out of the JSON.
103
+ */
104
+ feather?: number;
98
105
  };
99
106
  /**
100
- * A region in normalised image space.
107
+ * A region in normalised image space: a rect or an ellipse, each turned
108
+ * about its centre, or a closed polygon.
101
109
  */
102
110
  export type Region = {
103
111
  "kind": "rect";
104
112
  rect: Rect;
113
+ /**
114
+ * Radians, clockwise, about the rect centre, in pixel space. Left
115
+ * out of the JSON at zero, so a plan without turns serialises as it
116
+ * did before the field existed.
117
+ */
118
+ rotation?: number;
119
+ } | {
120
+ "kind": "ellipse";
121
+ rect: Rect;
122
+ /**
123
+ * Radians, clockwise, about the rect centre, in pixel space. Left
124
+ * out of the JSON at zero, so a plan without turns serialises as it
125
+ * did before the field existed.
126
+ */
127
+ rotation?: number;
105
128
  } | {
106
129
  "kind": "path";
107
130
  points: Array<[number, number]>;
@@ -1 +1 @@
1
- {"version":3,"file":"plan.js","sourceRoot":"","sources":["../../src/generated/plan.ts"],"names":[],"mappings":"AAAA,kFAAkF","sourcesContent":["// Generated by scripts/gen-plan-types.sh from crates/sealpixel-core. Do not edit.\n\n// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.\n\nexport type Anchor = \"tl\" | \"tc\" | \"tr\" | \"cl\" | \"c\" | \"cr\" | \"bl\" | \"bc\" | \"br\";\n\n/**\n * Draws shapes and text over the image in image space.\n */\nexport type AnnotateStage = { shapes?: Array<Shape>, };\n\n/**\n * Colour adjustments. All parameters are identity at their defaults.\n */\nexport type ColorStage = { brightness?: number, contrast?: number, saturation?: number, exposure?: number, gamma?: number, clarity?: number, vignette?: number, \n/**\n * 4x5 colour matrix (rows r, g, b, a; columns r, g, b, a, offset). Identity when absent.\n */\nmatrix?: [[number, number, number, number, number], [number, number, number, number, number], [number, number, number, number, number], [number, number, number, number, number]], \n/**\n * Blend between identity (0) and the matrix (1).\n */\nstrength?: number, };\n\n/**\n * Shape that keeps its interior; everything outside becomes transparent.\n */\nexport type CropMask = \"circle\";\n\n/**\n * Flip, rotate about the centre, then crop a rectangle of the rotated bounding box.\n */\nexport type CropStage = { \n/**\n * Radians, clockwise positive in image space (y down).\n */\nrotation?: number, flipX?: boolean, flipY?: boolean, \n/**\n * In rotated-bounding-box space, 0..1.\n */\nrect?: Rect, \n/**\n * Colour for areas outside the source. Transparent when absent.\n */\nfill?: [number, number, number, number], \n/**\n * Alpha mask applied to the crop output, for round avatars. Absent = none.\n */\nmask?: CropMask, };\n\nexport type Fit = \"contain\" | \"cover\" | \"fill\";\n\nexport type FrameKind = \"solid\" | \"inset\" | \"polaroid\";\n\n/**\n * Draws a frame inside the image bounds. Dimensions do not change.\n */\nexport type FrameStage = { \n/**\n * Named `style` because `kind` is the stage discriminator.\n */\nstyle: FrameKind, color: [number, number, number, number], \n/**\n * Logical pixels.\n */\nthickness: number, \n/**\n * Corner radius of the inner edge, logical pixels.\n */\nradius?: number, };\n\n/**\n * Normalised rectangle, 0..1 in the space named by the stage.\n */\nexport type Rect = { x: number, y: number, width: number, height: number, };\n\nexport type RedactMode = \"pixelate\" | \"blur\" | \"mosaic\";\n\n/**\n * Pixelate, blur or mosaic regions. Coordinates are in the stage input's image space.\n */\nexport type RedactStage = { regions?: Array<Redaction>, };\n\nexport type Redaction = { region: Region, mode: RedactMode, \n/**\n * Pixelate or mosaic cell size, or blur diameter, in logical source pixels.\n */\namount: number, };\n\n/**\n * A region in normalised image space.\n */\nexport type Region = { \"kind\": \"rect\", rect: Rect, } | { \"kind\": \"path\", points: Array<[number, number]>, };\n\n/**\n * The flat, versioned plan the executor runs. This is not the edit log: the\n * TypeScript `compile()` reduces the log to this structure.\n */\nexport type RenderPlan = { version: number, source: SourceInfo, \n/**\n * 1.0 for a truth render, below 1.0 when the buffer is a working copy.\n */\nbufferScale: number, stages?: Array<Stage>, };\n\n/**\n * Scale to a target size in logical output pixels.\n */\nexport type ResizeStage = { width?: number, height?: number, fit?: Fit, upscale?: boolean, };\n\n/**\n * A vector shape in normalised image space. Lengths are logical source pixels.\n */\nexport type Shape = { \"kind\": \"rect\", rect: Rect, stroke?: Stroke, fill?: [number, number, number, number], \n/**\n * Corner radius in logical pixels.\n */\nradius?: number, \n/**\n * Radians, clockwise, about the rect centre.\n */\nrotation?: number, } | { \"kind\": \"ellipse\", rect: Rect, stroke?: Stroke, fill?: [number, number, number, number], \n/**\n * Radians, clockwise, about the rect centre.\n */\nrotation?: number, } | { \"kind\": \"line\", from: [number, number], to: [number, number], stroke: Stroke, } | { \"kind\": \"arrow\", from: [number, number], to: [number, number], stroke: Stroke, \n/**\n * Head length in logical pixels; defaults to four stroke widths.\n */\nhead?: number, } | { \"kind\": \"path\", points: Array<[number, number]>, stroke: Stroke, closed?: boolean, fill?: [number, number, number, number], } | { \"kind\": \"text\", \n/**\n * Top-left anchor and wrap width. Height is advisory for the UI.\n */\nrect: Rect, text: string, \n/**\n * Asset id of a TrueType or OpenType font.\n */\nfont: string, \n/**\n * Font size in logical pixels.\n */\nsize: number, color: [number, number, number, number], align?: TextAlign, \n/**\n * Multiplier of the font size.\n */\nlineHeight?: number, background?: [number, number, number, number], \n/**\n * Background padding in logical pixels.\n */\npadding?: number, \n/**\n * Radians, clockwise, about the rect centre.\n */\nrotation?: number, };\n\n/**\n * Logical (full-resolution) dimensions of the source image after EXIF\n * orientation. The buffer handed to the executor may be a smaller working copy.\n */\nexport type SourceInfo = { width: number, height: number, };\n\n/**\n * One stage of the fixed-order pipeline. An absent stage is the identity.\n * Order is enforced by the TypeScript compiler, not by the executor.\n */\nexport type Stage = { \"kind\": \"color\" } & ColorStage | { \"kind\": \"redact\" } & RedactStage | { \"kind\": \"annotate\" } & AnnotateStage | { \"kind\": \"crop\" } & CropStage | { \"kind\": \"sticker\" } & StickerStage | { \"kind\": \"frame\" } & FrameStage | { \"kind\": \"watermark\" } & WatermarkStage | { \"kind\": \"resize\" } & ResizeStage;\n\n/**\n * An image asset placed in crop space.\n */\nexport type Sticker = { \n/**\n * Asset id of a PNG, JPEG or WebP.\n */\nasset: string, \n/**\n * Placement in crop space, 0..1.\n */\nrect: Rect, \n/**\n * Radians, clockwise, about the rect centre.\n */\nrotation?: number, opacity?: number, flipX?: boolean, flipY?: boolean, };\n\nexport type StickerStage = { items?: Array<Sticker>, };\n\n/**\n * Stroke style. Width is in logical source pixels.\n */\nexport type Stroke = { color: [number, number, number, number], width: number, };\n\nexport type TextAlign = \"left\" | \"center\" | \"right\";\n\nexport type Tile = { \n/**\n * Gaps between tiles, logical pixels.\n */\ngapX: number, gapY: number, \n/**\n * Radians, applied to every tile about its centre.\n */\nrotation?: number, };\n\nexport type WatermarkSource = { \"kind\": \"asset\", asset: string, } | { \"kind\": \"text\", text: string, font: string, color: [number, number, number, number], };\n\n/**\n * One stamp (image or text) at an anchor, or tiled across the image.\n */\nexport type WatermarkStage = { source: WatermarkSource, anchor?: Anchor, \n/**\n * Distance from the edges, logical pixels.\n */\nmargin?: number, \n/**\n * Stamp width as a fraction of the image width (text: font size as a fraction).\n */\nscale?: number, opacity?: number, tile?: Tile, };\n"]}
1
+ {"version":3,"file":"plan.js","sourceRoot":"","sources":["../../src/generated/plan.ts"],"names":[],"mappings":"AAAA,kFAAkF","sourcesContent":["// Generated by scripts/gen-plan-types.sh from crates/sealpixel-core. Do not edit.\n\n// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.\n\nexport type Anchor = \"tl\" | \"tc\" | \"tr\" | \"cl\" | \"c\" | \"cr\" | \"bl\" | \"bc\" | \"br\";\n\n/**\n * Draws shapes and text over the image in image space.\n */\nexport type AnnotateStage = { shapes?: Array<Shape>, };\n\n/**\n * Colour adjustments. All parameters are identity at their defaults.\n */\nexport type ColorStage = { brightness?: number, contrast?: number, saturation?: number, exposure?: number, gamma?: number, clarity?: number, vignette?: number, \n/**\n * 4x5 colour matrix (rows r, g, b, a; columns r, g, b, a, offset). Identity when absent.\n */\nmatrix?: [[number, number, number, number, number], [number, number, number, number, number], [number, number, number, number, number], [number, number, number, number, number]], \n/**\n * Blend between identity (0) and the matrix (1).\n */\nstrength?: number, };\n\n/**\n * Shape that keeps its interior; everything outside becomes transparent.\n */\nexport type CropMask = \"circle\";\n\n/**\n * Flip, rotate about the centre, then crop a rectangle of the rotated bounding box.\n */\nexport type CropStage = { \n/**\n * Radians, clockwise positive in image space (y down).\n */\nrotation?: number, flipX?: boolean, flipY?: boolean, \n/**\n * In rotated-bounding-box space, 0..1.\n */\nrect?: Rect, \n/**\n * Colour for areas outside the source. Transparent when absent.\n */\nfill?: [number, number, number, number], \n/**\n * Alpha mask applied to the crop output, for round avatars. Absent = none.\n */\nmask?: CropMask, };\n\nexport type Fit = \"contain\" | \"cover\" | \"fill\";\n\nexport type FrameKind = \"solid\" | \"inset\" | \"polaroid\";\n\n/**\n * Draws a frame inside the image bounds. Dimensions do not change.\n */\nexport type FrameStage = { \n/**\n * Named `style` because `kind` is the stage discriminator.\n */\nstyle: FrameKind, color: [number, number, number, number], \n/**\n * Logical pixels.\n */\nthickness: number, \n/**\n * Corner radius of the inner edge, logical pixels.\n */\nradius?: number, };\n\n/**\n * Normalised rectangle, 0..1 in the space named by the stage.\n */\nexport type Rect = { x: number, y: number, width: number, height: number, };\n\nexport type RedactMode = \"pixelate\" | \"blur\" | \"mosaic\";\n\n/**\n * Pixelate, blur or mosaic regions. Coordinates are in the stage input's image space.\n */\nexport type RedactStage = { regions?: Array<Redaction>, };\n\nexport type Redaction = { region: Region, mode: RedactMode, \n/**\n * Pixelate or mosaic cell size, or blur diameter, in logical source pixels.\n */\namount: number, \n/**\n * Width of the soft edge outside the region, in logical source pixels.\n * Every pixel the region touches gets the full effect. Outside, the\n * effect fades to nothing at this distance. Zero is a hard edge, and is\n * left out of the JSON.\n */\nfeather?: number, };\n\n/**\n * A region in normalised image space: a rect or an ellipse, each turned\n * about its centre, or a closed polygon.\n */\nexport type Region = { \"kind\": \"rect\", rect: Rect, \n/**\n * Radians, clockwise, about the rect centre, in pixel space. Left\n * out of the JSON at zero, so a plan without turns serialises as it\n * did before the field existed.\n */\nrotation?: number, } | { \"kind\": \"ellipse\", rect: Rect, \n/**\n * Radians, clockwise, about the rect centre, in pixel space. Left\n * out of the JSON at zero, so a plan without turns serialises as it\n * did before the field existed.\n */\nrotation?: number, } | { \"kind\": \"path\", points: Array<[number, number]>, };\n\n/**\n * The flat, versioned plan the executor runs. This is not the edit log: the\n * TypeScript `compile()` reduces the log to this structure.\n */\nexport type RenderPlan = { version: number, source: SourceInfo, \n/**\n * 1.0 for a truth render, below 1.0 when the buffer is a working copy.\n */\nbufferScale: number, stages?: Array<Stage>, };\n\n/**\n * Scale to a target size in logical output pixels.\n */\nexport type ResizeStage = { width?: number, height?: number, fit?: Fit, upscale?: boolean, };\n\n/**\n * A vector shape in normalised image space. Lengths are logical source pixels.\n */\nexport type Shape = { \"kind\": \"rect\", rect: Rect, stroke?: Stroke, fill?: [number, number, number, number], \n/**\n * Corner radius in logical pixels.\n */\nradius?: number, \n/**\n * Radians, clockwise, about the rect centre.\n */\nrotation?: number, } | { \"kind\": \"ellipse\", rect: Rect, stroke?: Stroke, fill?: [number, number, number, number], \n/**\n * Radians, clockwise, about the rect centre.\n */\nrotation?: number, } | { \"kind\": \"line\", from: [number, number], to: [number, number], stroke: Stroke, } | { \"kind\": \"arrow\", from: [number, number], to: [number, number], stroke: Stroke, \n/**\n * Head length in logical pixels; defaults to four stroke widths.\n */\nhead?: number, } | { \"kind\": \"path\", points: Array<[number, number]>, stroke: Stroke, closed?: boolean, fill?: [number, number, number, number], } | { \"kind\": \"text\", \n/**\n * Top-left anchor and wrap width. Height is advisory for the UI.\n */\nrect: Rect, text: string, \n/**\n * Asset id of a TrueType or OpenType font.\n */\nfont: string, \n/**\n * Font size in logical pixels.\n */\nsize: number, color: [number, number, number, number], align?: TextAlign, \n/**\n * Multiplier of the font size.\n */\nlineHeight?: number, background?: [number, number, number, number], \n/**\n * Background padding in logical pixels.\n */\npadding?: number, \n/**\n * Radians, clockwise, about the rect centre.\n */\nrotation?: number, };\n\n/**\n * Logical (full-resolution) dimensions of the source image after EXIF\n * orientation. The buffer handed to the executor may be a smaller working copy.\n */\nexport type SourceInfo = { width: number, height: number, };\n\n/**\n * One stage of the fixed-order pipeline. An absent stage is the identity.\n * Order is enforced by the TypeScript compiler, not by the executor.\n */\nexport type Stage = { \"kind\": \"color\" } & ColorStage | { \"kind\": \"redact\" } & RedactStage | { \"kind\": \"annotate\" } & AnnotateStage | { \"kind\": \"crop\" } & CropStage | { \"kind\": \"sticker\" } & StickerStage | { \"kind\": \"frame\" } & FrameStage | { \"kind\": \"watermark\" } & WatermarkStage | { \"kind\": \"resize\" } & ResizeStage;\n\n/**\n * An image asset placed in crop space.\n */\nexport type Sticker = { \n/**\n * Asset id of a PNG, JPEG or WebP.\n */\nasset: string, \n/**\n * Placement in crop space, 0..1.\n */\nrect: Rect, \n/**\n * Radians, clockwise, about the rect centre.\n */\nrotation?: number, opacity?: number, flipX?: boolean, flipY?: boolean, };\n\nexport type StickerStage = { items?: Array<Sticker>, };\n\n/**\n * Stroke style. Width is in logical source pixels.\n */\nexport type Stroke = { color: [number, number, number, number], width: number, };\n\nexport type TextAlign = \"left\" | \"center\" | \"right\";\n\nexport type Tile = { \n/**\n * Gaps between tiles, logical pixels.\n */\ngapX: number, gapY: number, \n/**\n * Radians, applied to every tile about its centre.\n */\nrotation?: number, };\n\nexport type WatermarkSource = { \"kind\": \"asset\", asset: string, } | { \"kind\": \"text\", text: string, font: string, color: [number, number, number, number], };\n\n/**\n * One stamp (image or text) at an anchor, or tiled across the image.\n */\nexport type WatermarkStage = { source: WatermarkSource, anchor?: Anchor, \n/**\n * Distance from the edges, logical pixels.\n */\nmargin?: number, \n/**\n * Stamp width as a fraction of the image width (text: font size as a fraction).\n */\nscale?: number, opacity?: number, tile?: Tile, };\n"]}
@@ -55,3 +55,9 @@ export interface Registry {
55
55
  initialOps(source: SourceDescriptor): Omit<Operation, 'id'>[];
56
56
  }
57
57
  export declare function createRegistry(plugins: readonly AnyPlugin[]): Registry;
58
+ /**
59
+ * Checks one op that is about to be appended to a log in the current plugin
60
+ * versions, with the same checks as a log parse. Returns the parsed op. Throws
61
+ * `SealpixelError` with the code that a log parse gives for the same op.
62
+ */
63
+ export declare function parseAppendedOperation(registry: Registry, raw: unknown, document: Document, source: SourceDescriptor): Operation;
package/dist/registry.js CHANGED
@@ -76,57 +76,26 @@ export function createRegistry(plugins) {
76
76
  const ops = [];
77
77
  // Slices reduced so far, so constraints can look at the state an op applies to.
78
78
  const document = initialDocument();
79
+ const source = stripUndefined(shape.data.source);
79
80
  shape.data.ops.forEach((raw, index) => {
80
81
  const type = typeof raw === 'object' && raw !== null ? raw.type : undefined;
81
- if (typeof type !== 'string') {
82
- issues.push({ index, code: 'INVALID_EDIT_LOG', message: 'op has no string "type"' });
82
+ if (options.tolerateUnknown && typeof type === 'string' && !byOpType.has(type)) {
83
+ ops.push(raw);
83
84
  return;
84
85
  }
85
- const entry = byOpType.get(type);
86
- if (!entry) {
87
- if (options.tolerateUnknown) {
88
- ops.push(raw);
89
- return;
90
- }
91
- const pluginId = type.slice(0, type.lastIndexOf('.'));
92
- issues.push(byId.has(pluginId)
93
- ? { index, code: 'UNKNOWN_OPERATION', message: `unknown operation "${type}"` }
94
- : { index, code: 'UNKNOWN_PLUGIN', message: `plugin "${pluginId}" is not registered` });
86
+ const result = parseOperation(registry, raw, index, shape.data.plugins);
87
+ if (!result.ok) {
88
+ issues.push(result.issue);
95
89
  return;
96
90
  }
97
- const written = shape.data.plugins[entry.plugin.id];
98
- let candidate = raw;
99
- if (written !== undefined && written < entry.plugin.version) {
100
- if (!entry.def.migrate) {
101
- issues.push({
102
- index,
103
- code: 'INVALID_EDIT_LOG',
104
- message: `op "${type}" was written by ${entry.plugin.id} v${written}; v${entry.plugin.version} has no migration`,
105
- });
106
- return;
107
- }
108
- candidate = entry.def.migrate(written, raw);
109
- }
110
- const parsed = entry.def.schema.safeParse
111
- ? entry.def.schema.safeParse(candidate)
112
- : tryParse(entry.def.schema.parse, candidate);
113
- if (parsed.success) {
114
- const op = parsed.data;
115
- const violation = validateOperation(op, document, stripUndefined(shape.data.source));
116
- if (violation) {
117
- issues.push({ index, code: 'OPTION_VIOLATION', message: `op "${type}": ${violation}` });
118
- return;
119
- }
120
- ops.push(op);
121
- document[entry.plugin.id] = entry.def.reduce(document[entry.plugin.id], op);
122
- }
123
- else {
124
- issues.push({
125
- index,
126
- code: 'INVALID_EDIT_LOG',
127
- message: `op "${type}": ${describeError(parsed.error)}`,
128
- });
91
+ const violation = validateOperation(result.op, document, source);
92
+ if (violation) {
93
+ issues.push({ index, code: 'OPTION_VIOLATION', message: `op "${type}": ${violation}` });
94
+ return;
129
95
  }
96
+ ops.push(result.op);
97
+ const id = result.entry.plugin.id;
98
+ document[id] = result.entry.def.reduce(document[id], result.op);
130
99
  });
131
100
  if (issues.length > 0)
132
101
  return { ok: false, issues };
@@ -150,7 +119,7 @@ export function createRegistry(plugins) {
150
119
  };
151
120
  return { ok: true, log };
152
121
  };
153
- return {
122
+ const registry = {
154
123
  plugins: sorted,
155
124
  byId,
156
125
  byOpType,
@@ -166,14 +135,88 @@ export function createRegistry(plugins) {
166
135
  if (result.ok)
167
136
  return result.log;
168
137
  const first = result.issues[0];
169
- const code = result.issues.every((i) => i.code === 'UNKNOWN_PLUGIN')
170
- ? 'UNKNOWN_PLUGIN'
171
- : result.issues.some((i) => i.code === 'OPTION_VIOLATION')
172
- ? 'OPTION_VIOLATION'
173
- : 'INVALID_EDIT_LOG';
174
- throw new SealpixelError(code, first ? `${first.message}` : 'invalid edit log', result.issues);
138
+ throw new SealpixelError(errorCode(result.issues), first ? `${first.message}` : 'invalid edit log', result.issues);
175
139
  },
176
140
  };
141
+ return registry;
142
+ }
143
+ /** The error code of a failed parse, from its issues. */
144
+ function errorCode(issues) {
145
+ return issues.every((i) => i.code === 'UNKNOWN_PLUGIN')
146
+ ? 'UNKNOWN_PLUGIN'
147
+ : issues.some((i) => i.code === 'OPTION_VIOLATION')
148
+ ? 'OPTION_VIOLATION'
149
+ : 'INVALID_EDIT_LOG';
150
+ }
151
+ /**
152
+ * Checks the shape of one op the way a log parse checks it: a known type, the
153
+ * migration from the plugin version in `written`, then the plugin's op schema.
154
+ * The caller runs the plugin's `validate` on the result.
155
+ */
156
+ function parseOperation(registry, raw, index, written) {
157
+ const type = typeof raw === 'object' && raw !== null ? raw.type : undefined;
158
+ if (typeof type !== 'string') {
159
+ return {
160
+ ok: false,
161
+ issue: { index, code: 'INVALID_EDIT_LOG', message: 'op has no string "type"' },
162
+ };
163
+ }
164
+ const entry = registry.byOpType.get(type);
165
+ if (!entry) {
166
+ const pluginId = type.slice(0, type.lastIndexOf('.'));
167
+ return {
168
+ ok: false,
169
+ issue: registry.byId.has(pluginId)
170
+ ? { index, code: 'UNKNOWN_OPERATION', message: `unknown operation "${type}"` }
171
+ : { index, code: 'UNKNOWN_PLUGIN', message: `plugin "${pluginId}" is not registered` },
172
+ };
173
+ }
174
+ let candidate = raw;
175
+ const version = written[entry.plugin.id];
176
+ if (version !== undefined && version < entry.plugin.version) {
177
+ if (!entry.def.migrate) {
178
+ return {
179
+ ok: false,
180
+ issue: {
181
+ index,
182
+ code: 'INVALID_EDIT_LOG',
183
+ message: `op "${type}" was written by ${entry.plugin.id} v${version}; v${entry.plugin.version} has no migration`,
184
+ },
185
+ };
186
+ }
187
+ candidate = entry.def.migrate(version, raw);
188
+ }
189
+ const parsed = entry.def.schema.safeParse
190
+ ? entry.def.schema.safeParse(candidate)
191
+ : tryParse(entry.def.schema.parse, candidate);
192
+ if (!parsed.success) {
193
+ return {
194
+ ok: false,
195
+ issue: {
196
+ index,
197
+ code: 'INVALID_EDIT_LOG',
198
+ message: `op "${type}": ${describeError(parsed.error)}`,
199
+ },
200
+ };
201
+ }
202
+ return { ok: true, op: parsed.data, entry };
203
+ }
204
+ /**
205
+ * Checks one op that is about to be appended to a log in the current plugin
206
+ * versions, with the same checks as a log parse. Returns the parsed op. Throws
207
+ * `SealpixelError` with the code that a log parse gives for the same op.
208
+ */
209
+ export function parseAppendedOperation(registry, raw, document, source) {
210
+ // No plugin versions: the op is in the current schema and needs no migration.
211
+ const result = parseOperation(registry, raw, 0, {});
212
+ if (!result.ok) {
213
+ throw new SealpixelError(errorCode([result.issue]), result.issue.message, [result.issue]);
214
+ }
215
+ const violation = registry.validateOperation(result.op, document, source);
216
+ if (violation) {
217
+ throw new SealpixelError('OPTION_VIOLATION', `${result.op.type}: ${violation}`);
218
+ }
219
+ return result.op;
177
220
  }
178
221
  function tryParse(parse, value) {
179
222
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"registry.js","sourceRoot":"","sources":["../src/registry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AA0D7C,MAAM,YAAY,GAAG,CAAC,CAAC,MAAM,CAAC;IAC5B,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IACrB,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,QAAQ,EAAE;IAClC,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,QAAQ,EAAE;IACnC,IAAI,EAAE,CAAC;SACJ,MAAM,EAAE;SACR,KAAK,CAAC,gBAAgB,CAAC;SACvB,QAAQ,EAAE;IACb,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,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KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAChE,CAAC;AAED,SAAS,cAAc,CAAmB,KAAQ;IAChD,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,SAAS,CAAC,CAAM,CAAC;AAC3F,CAAC","sourcesContent":["import { z } from 'zod';\nimport { SealpixelError } from './errors.js';\nimport type { AnyPlugin, AssetDeclaration, Document, OperationDef } from './plugin.js';\nimport type { EditLog, Operation, SourceDescriptor } from './types.js';\n\nexport interface ParseOptions {\n /**\n * Keep ops whose type is unknown instead of failing. They are ignored by\n * `compile`. Only for forward-compatible previews; servers must not set it.\n */\n tolerateUnknown?: boolean;\n}\n\nexport interface ParseIssue {\n /** Index into `ops`, or -1 for a top-level problem. */\n index: number;\n code: 'INVALID_EDIT_LOG' | 'UNKNOWN_PLUGIN' | 'UNKNOWN_OPERATION' | 'OPTION_VIOLATION';\n message: string;\n}\n\nexport type ParseResult = { ok: true; log: EditLog } | { ok: false; issues: ParseIssue[] };\n\nexport interface RegisteredOperation {\n plugin: AnyPlugin;\n // biome-ignore lint/suspicious/noExplicitAny: erased at the registry boundary\n def: OperationDef<any, any>;\n}\n\n/** Plugins plus everything derived from them: schemas, reducers, stage order. */\nexport interface Registry {\n /** Sorted by stage order, then id. */\n readonly plugins: readonly AnyPlugin[];\n readonly byId: ReadonlyMap<string, AnyPlugin>;\n readonly byOpType: ReadonlyMap<string, RegisteredOperation>;\n /** `{ pluginId: version }` for every registered plugin. */\n pluginVersions(): Record<string, number>;\n initialDocument(): Document;\n /** Validates and migrates an unknown value into an `EditLog`. Throws `SealpixelError`. */\n parseEditLog(value: unknown, options?: ParseOptions): EditLog;\n safeParseEditLog(value: unknown, options?: ParseOptions): ParseResult;\n /**\n * Runs the owning plugin's `validate` for one op against the document it\n * would apply to. Returns the violation message, or null.\n */\n validateOperation(op: Operation, document: Document, source: SourceDescriptor): string | null;\n /**\n * Runs every plugin's `validateDocument` over a compiled document. Returns\n * all violations; empty when the state satisfies the configured options.\n */\n validateDocument(\n document: Document,\n source: SourceDescriptor,\n ): { plugin: string; message: string }[];\n /** `{ pluginId: options }` for every plugin with options. */\n pluginOptions(): Record<string, unknown>;\n /** Ops that seed an empty log from option defaults, in stage order. */\n initialOps(source: SourceDescriptor): Omit<Operation, 'id'>[];\n}\n\nconst SourceSchema = z.object({\n id: z.string().min(1),\n width: z.number().int().positive(),\n height: z.number().int().positive(),\n hash: z\n .string()\n .regex(/^[0-9a-f]{64}$/)\n .optional(),\n mimeType: z.string().optional(),\n});\n\nconst AssetSchema = z\n .object({\n id: z.string().min(1),\n hash: z.string().regex(/^[0-9a-f]{64}$/),\n url: z.string().min(1).optional(),\n })\n .strict();\n\nconst LogShape = z.object({\n version: z.literal(1),\n source: SourceSchema,\n plugins: z.record(z.string(), z.number().int().positive()).default({}),\n assets: z.array(AssetSchema).max(1000).optional(),\n ops: z.array(z.unknown()).default([]),\n});\n\nexport function createRegistry(plugins: readonly AnyPlugin[]): Registry {\n const byId = new Map<string, AnyPlugin>();\n const byOpType = new Map<string, RegisteredOperation>();\n for (const plugin of plugins) {\n if (byId.has(plugin.id)) {\n throw new SealpixelError('INVALID_EDIT_LOG', `plugin \"${plugin.id}\" registered twice`);\n }\n byId.set(plugin.id, plugin);\n for (const def of plugin.operations) {\n if (byOpType.has(def.type)) {\n throw new SealpixelError('INVALID_EDIT_LOG', `operation \"${def.type}\" registered twice`);\n }\n byOpType.set(def.type, { plugin, def });\n }\n }\n const sorted = [...plugins].sort(\n (a, b) => a.stage.order - b.stage.order || a.id.localeCompare(b.id),\n );\n const initialDocument = () =>\n Object.fromEntries(sorted.map((p) => [p.id, p.initialDocument])) as Document;\n\n const validateOperation = (\n op: Operation,\n document: Document,\n source: SourceDescriptor,\n ): string | null => {\n const entry = byOpType.get(op.type);\n if (!entry?.plugin.validate) return null;\n const slice = (document as Record<string, unknown>)[entry.plugin.id];\n return entry.plugin.validate(op, { options: entry.plugin.options, slice, document, source });\n };\n\n const validateDocument = (document: Document, source: SourceDescriptor) => {\n const out: { plugin: string; message: string }[] = [];\n for (const plugin of sorted) {\n if (!plugin.validateDocument) continue;\n const slice = (document as Record<string, unknown>)[plugin.id];\n const message = plugin.validateDocument(slice, { options: plugin.options, document, source });\n if (message) out.push({ plugin: plugin.id, message });\n }\n return out;\n };\n\n const safeParseEditLog = (value: unknown, options: ParseOptions = {}): ParseResult => {\n const shape = LogShape.safeParse(value);\n if (!shape.success) {\n return {\n ok: false,\n issues: shape.error.issues.map((i) => ({\n index: -1,\n code: 'INVALID_EDIT_LOG',\n message: `${i.path.join('.') || '(root)'}: ${i.message}`,\n })),\n };\n }\n const issues: ParseIssue[] = [];\n const ops: Operation[] = [];\n // Slices reduced so far, so constraints can look at the state an op applies to.\n const document = initialDocument() as Record<string, unknown>;\n shape.data.ops.forEach((raw, index) => {\n const type =\n typeof raw === 'object' && raw !== null ? (raw as { type?: unknown }).type : undefined;\n if (typeof type !== 'string') {\n issues.push({ index, code: 'INVALID_EDIT_LOG', message: 'op has no string \"type\"' });\n return;\n }\n const entry = byOpType.get(type);\n if (!entry) {\n if (options.tolerateUnknown) {\n ops.push(raw as Operation);\n return;\n }\n const pluginId = type.slice(0, type.lastIndexOf('.'));\n issues.push(\n byId.has(pluginId)\n ? { index, code: 'UNKNOWN_OPERATION', message: `unknown operation \"${type}\"` }\n : { index, code: 'UNKNOWN_PLUGIN', message: `plugin \"${pluginId}\" is not registered` },\n );\n return;\n }\n const written = shape.data.plugins[entry.plugin.id];\n let candidate: unknown = raw;\n if (written !== undefined && written < entry.plugin.version) {\n if (!entry.def.migrate) {\n issues.push({\n index,\n code: 'INVALID_EDIT_LOG',\n message: `op \"${type}\" was written by ${entry.plugin.id} v${written}; v${entry.plugin.version} has no migration`,\n });\n return;\n }\n candidate = entry.def.migrate(written, raw);\n }\n const parsed = entry.def.schema.safeParse\n ? entry.def.schema.safeParse(candidate)\n : tryParse(entry.def.schema.parse, candidate);\n if (parsed.success) {\n const op = parsed.data as Operation;\n const violation = validateOperation(\n op,\n document as Document,\n stripUndefined(shape.data.source) as SourceDescriptor,\n );\n if (violation) {\n issues.push({ index, code: 'OPTION_VIOLATION', message: `op \"${type}\": ${violation}` });\n return;\n }\n ops.push(op);\n document[entry.plugin.id] = entry.def.reduce(document[entry.plugin.id], op);\n } else {\n issues.push({\n index,\n code: 'INVALID_EDIT_LOG',\n message: `op \"${type}\": ${describeError(parsed.error)}`,\n });\n }\n });\n if (issues.length > 0) return { ok: false, issues };\n // Every op of a registered plugin is now in its current schema. Record that\n // version, or the next parse migrates the ops again, including ops appended\n // since in the current schema.\n const plugins = { ...shape.data.plugins };\n for (const [id, written] of Object.entries(plugins)) {\n const plugin = byId.get(id);\n if (plugin && written < plugin.version) plugins[id] = plugin.version;\n }\n const log: EditLog = {\n version: 1,\n source: stripUndefined(shape.data.source) as SourceDescriptor,\n plugins,\n ...(shape.data.assets\n ? { assets: shape.data.assets.map((a) => stripUndefined(a) as AssetDeclaration) }\n : {}),\n ops,\n };\n return { ok: true, log };\n };\n\n return {\n plugins: sorted,\n byId,\n byOpType,\n pluginVersions: () => Object.fromEntries(sorted.map((p) => [p.id, p.version])),\n pluginOptions: () =>\n Object.fromEntries(\n sorted.filter((p) => p.options !== undefined).map((p) => [p.id, p.options]),\n ),\n initialDocument,\n initialOps: (source) =>\n sorted.flatMap((p) => p.initialOps?.({ options: p.options, source }) ?? []),\n validateOperation,\n validateDocument,\n safeParseEditLog,\n parseEditLog: (value, options) => {\n const result = safeParseEditLog(value, options);\n if (result.ok) return result.log;\n const first = result.issues[0];\n const code = result.issues.every((i) => i.code === 'UNKNOWN_PLUGIN')\n ? 'UNKNOWN_PLUGIN'\n : result.issues.some((i) => i.code === 'OPTION_VIOLATION')\n ? 'OPTION_VIOLATION'\n : 'INVALID_EDIT_LOG';\n throw new SealpixelError(\n code,\n first ? `${first.message}` : 'invalid edit log',\n result.issues,\n );\n },\n };\n}\n\nfunction tryParse<T>(\n parse: (v: unknown) => T,\n value: unknown,\n): { success: true; data: T } | { success: false; error: unknown } {\n try {\n return { success: true, data: parse(value) };\n } catch (error) {\n return { success: false, error };\n }\n}\n\nfunction describeError(error: unknown): string {\n if (error && typeof error === 'object' && 'issues' in error) {\n const issues = (error as { issues: { path: PropertyKey[]; message: string }[] }).issues;\n return issues.map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`).join('; ');\n }\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction stripUndefined<T extends object>(value: T): T {\n return Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined)) as T;\n}\n"]}
1
+ {"version":3,"file":"registry.js","sourceRoot":"","sources":["../src/registry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,cAAc,EAA2B,MAAM,aAAa,CAAC;AA0DtE,MAAM,YAAY,GAAG,CAAC,CAAC,MAAM,CAAC;IAC5B,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IACrB,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,QAAQ,EAAE;IAClC,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,QAAQ,EAAE;IACnC,IAAI,EAAE,CAAC;SACJ,MAAM,EAAE;SACR,KAAK,CAAC,gBAAgB,CAAC;SACvB,QAAQ,EAAE;IACb,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;CAChC,CAAC,CAAC;AAEH,MAAM,WAAW,GAAG,CAAC;KAClB,MAAM,CAAC;IACN,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC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C,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,QAAQ,KAAK,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACvF,CAAC;IACD,OAAO,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAChE,CAAC;AAED,SAAS,cAAc,CAAmB,KAAQ;IAChD,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,SAAS,CAAC,CAAM,CAAC;AAC3F,CAAC","sourcesContent":["import { z } from 'zod';\nimport { SealpixelError, type SealpixelErrorCode } from './errors.js';\nimport type { AnyPlugin, AssetDeclaration, Document, OperationDef } from './plugin.js';\nimport type { EditLog, Operation, SourceDescriptor } from './types.js';\n\nexport interface ParseOptions {\n /**\n * Keep ops whose type is unknown instead of failing. They are ignored by\n * `compile`. Only for forward-compatible previews; servers must not set it.\n */\n tolerateUnknown?: boolean;\n}\n\nexport interface ParseIssue {\n /** Index into `ops`, or -1 for a top-level problem. */\n index: number;\n code: 'INVALID_EDIT_LOG' | 'UNKNOWN_PLUGIN' | 'UNKNOWN_OPERATION' | 'OPTION_VIOLATION';\n message: string;\n}\n\nexport type ParseResult = { ok: true; log: EditLog } | { ok: false; issues: ParseIssue[] };\n\nexport interface RegisteredOperation {\n plugin: AnyPlugin;\n // biome-ignore lint/suspicious/noExplicitAny: erased at the registry boundary\n def: OperationDef<any, any>;\n}\n\n/** Plugins plus everything derived from them: schemas, reducers, stage order. */\nexport interface Registry {\n /** Sorted by stage order, then id. */\n readonly plugins: readonly AnyPlugin[];\n readonly byId: ReadonlyMap<string, AnyPlugin>;\n readonly byOpType: ReadonlyMap<string, RegisteredOperation>;\n /** `{ pluginId: version }` for every registered plugin. */\n pluginVersions(): Record<string, number>;\n initialDocument(): Document;\n /** Validates and migrates an unknown value into an `EditLog`. Throws `SealpixelError`. */\n parseEditLog(value: unknown, options?: ParseOptions): EditLog;\n safeParseEditLog(value: unknown, options?: ParseOptions): ParseResult;\n /**\n * Runs the owning plugin's `validate` for one op against the document it\n * would apply to. Returns the violation message, or null.\n */\n validateOperation(op: Operation, document: Document, source: SourceDescriptor): string | null;\n /**\n * Runs every plugin's `validateDocument` over a compiled document. Returns\n * all violations; empty when the state satisfies the configured options.\n */\n validateDocument(\n document: Document,\n source: SourceDescriptor,\n ): { plugin: string; message: string }[];\n /** `{ pluginId: options }` for every plugin with options. */\n pluginOptions(): Record<string, unknown>;\n /** Ops that seed an empty log from option defaults, in stage order. */\n initialOps(source: SourceDescriptor): Omit<Operation, 'id'>[];\n}\n\nconst SourceSchema = z.object({\n id: z.string().min(1),\n width: z.number().int().positive(),\n height: z.number().int().positive(),\n hash: z\n .string()\n .regex(/^[0-9a-f]{64}$/)\n .optional(),\n mimeType: z.string().optional(),\n});\n\nconst AssetSchema = z\n .object({\n id: z.string().min(1),\n hash: z.string().regex(/^[0-9a-f]{64}$/),\n url: z.string().min(1).optional(),\n })\n .strict();\n\nconst LogShape = z.object({\n version: z.literal(1),\n source: SourceSchema,\n plugins: z.record(z.string(), z.number().int().positive()).default({}),\n assets: z.array(AssetSchema).max(1000).optional(),\n ops: z.array(z.unknown()).default([]),\n});\n\nexport function createRegistry(plugins: readonly AnyPlugin[]): Registry {\n const byId = new Map<string, AnyPlugin>();\n const byOpType = new Map<string, RegisteredOperation>();\n for (const plugin of plugins) {\n if (byId.has(plugin.id)) {\n throw new SealpixelError('INVALID_EDIT_LOG', `plugin \"${plugin.id}\" registered twice`);\n }\n byId.set(plugin.id, plugin);\n for (const def of plugin.operations) {\n if (byOpType.has(def.type)) {\n throw new SealpixelError('INVALID_EDIT_LOG', `operation \"${def.type}\" registered twice`);\n }\n byOpType.set(def.type, { plugin, def });\n }\n }\n const sorted = [...plugins].sort(\n (a, b) => a.stage.order - b.stage.order || a.id.localeCompare(b.id),\n );\n const initialDocument = () =>\n Object.fromEntries(sorted.map((p) => [p.id, p.initialDocument])) as Document;\n\n const validateOperation = (\n op: Operation,\n document: Document,\n source: SourceDescriptor,\n ): string | null => {\n const entry = byOpType.get(op.type);\n if (!entry?.plugin.validate) return null;\n const slice = (document as Record<string, unknown>)[entry.plugin.id];\n return entry.plugin.validate(op, { options: entry.plugin.options, slice, document, source });\n };\n\n const validateDocument = (document: Document, source: SourceDescriptor) => {\n const out: { plugin: string; message: string }[] = [];\n for (const plugin of sorted) {\n if (!plugin.validateDocument) continue;\n const slice = (document as Record<string, unknown>)[plugin.id];\n const message = plugin.validateDocument(slice, { options: plugin.options, document, source });\n if (message) out.push({ plugin: plugin.id, message });\n }\n return out;\n };\n\n const safeParseEditLog = (value: unknown, options: ParseOptions = {}): ParseResult => {\n const shape = LogShape.safeParse(value);\n if (!shape.success) {\n return {\n ok: false,\n issues: shape.error.issues.map((i) => ({\n index: -1,\n code: 'INVALID_EDIT_LOG',\n message: `${i.path.join('.') || '(root)'}: ${i.message}`,\n })),\n };\n }\n const issues: ParseIssue[] = [];\n const ops: Operation[] = [];\n // Slices reduced so far, so constraints can look at the state an op applies to.\n const document = initialDocument() as Record<string, unknown>;\n const source = stripUndefined(shape.data.source) as SourceDescriptor;\n shape.data.ops.forEach((raw, index) => {\n const type =\n typeof raw === 'object' && raw !== null ? (raw as { type?: unknown }).type : undefined;\n if (options.tolerateUnknown && typeof type === 'string' && !byOpType.has(type)) {\n ops.push(raw as Operation);\n return;\n }\n const result = parseOperation(registry, raw, index, shape.data.plugins);\n if (!result.ok) {\n issues.push(result.issue);\n return;\n }\n const violation = validateOperation(result.op, document as Document, source);\n if (violation) {\n issues.push({ index, code: 'OPTION_VIOLATION', message: `op \"${type}\": ${violation}` });\n return;\n }\n ops.push(result.op);\n const id = result.entry.plugin.id;\n document[id] = result.entry.def.reduce(document[id], result.op);\n });\n if (issues.length > 0) return { ok: false, issues };\n // Every op of a registered plugin is now in its current schema. Record that\n // version, or the next parse migrates the ops again, including ops appended\n // since in the current schema.\n const plugins = { ...shape.data.plugins };\n for (const [id, written] of Object.entries(plugins)) {\n const plugin = byId.get(id);\n if (plugin && written < plugin.version) plugins[id] = plugin.version;\n }\n const log: EditLog = {\n version: 1,\n source: stripUndefined(shape.data.source) as SourceDescriptor,\n plugins,\n ...(shape.data.assets\n ? { assets: shape.data.assets.map((a) => stripUndefined(a) as AssetDeclaration) }\n : {}),\n ops,\n };\n return { ok: true, log };\n };\n\n const registry: Registry = {\n plugins: sorted,\n byId,\n byOpType,\n pluginVersions: () => Object.fromEntries(sorted.map((p) => [p.id, p.version])),\n pluginOptions: () =>\n Object.fromEntries(\n sorted.filter((p) => p.options !== undefined).map((p) => [p.id, p.options]),\n ),\n initialDocument,\n initialOps: (source) =>\n sorted.flatMap((p) => p.initialOps?.({ options: p.options, source }) ?? []),\n validateOperation,\n validateDocument,\n safeParseEditLog,\n parseEditLog: (value, options) => {\n const result = safeParseEditLog(value, options);\n if (result.ok) return result.log;\n const first = result.issues[0];\n throw new SealpixelError(\n errorCode(result.issues),\n first ? `${first.message}` : 'invalid edit log',\n result.issues,\n );\n },\n };\n return registry;\n}\n\n/** The error code of a failed parse, from its issues. */\nfunction errorCode(issues: readonly ParseIssue[]): SealpixelErrorCode {\n return issues.every((i) => i.code === 'UNKNOWN_PLUGIN')\n ? 'UNKNOWN_PLUGIN'\n : issues.some((i) => i.code === 'OPTION_VIOLATION')\n ? 'OPTION_VIOLATION'\n : 'INVALID_EDIT_LOG';\n}\n\ntype OperationResult =\n | { ok: true; op: Operation; entry: RegisteredOperation }\n | { ok: false; issue: ParseIssue };\n\n/**\n * Checks the shape of one op the way a log parse checks it: a known type, the\n * migration from the plugin version in `written`, then the plugin's op schema.\n * The caller runs the plugin's `validate` on the result.\n */\nfunction parseOperation(\n registry: Registry,\n raw: unknown,\n index: number,\n written: Readonly<Record<string, number>>,\n): OperationResult {\n const type =\n typeof raw === 'object' && raw !== null ? (raw as { type?: unknown }).type : undefined;\n if (typeof type !== 'string') {\n return {\n ok: false,\n issue: { index, code: 'INVALID_EDIT_LOG', message: 'op has no string \"type\"' },\n };\n }\n const entry = registry.byOpType.get(type);\n if (!entry) {\n const pluginId = type.slice(0, type.lastIndexOf('.'));\n return {\n ok: false,\n issue: registry.byId.has(pluginId)\n ? { index, code: 'UNKNOWN_OPERATION', message: `unknown operation \"${type}\"` }\n : { index, code: 'UNKNOWN_PLUGIN', message: `plugin \"${pluginId}\" is not registered` },\n };\n }\n let candidate: unknown = raw;\n const version = written[entry.plugin.id];\n if (version !== undefined && version < entry.plugin.version) {\n if (!entry.def.migrate) {\n return {\n ok: false,\n issue: {\n index,\n code: 'INVALID_EDIT_LOG',\n message: `op \"${type}\" was written by ${entry.plugin.id} v${version}; v${entry.plugin.version} has no migration`,\n },\n };\n }\n candidate = entry.def.migrate(version, raw);\n }\n const parsed = entry.def.schema.safeParse\n ? entry.def.schema.safeParse(candidate)\n : tryParse(entry.def.schema.parse, candidate);\n if (!parsed.success) {\n return {\n ok: false,\n issue: {\n index,\n code: 'INVALID_EDIT_LOG',\n message: `op \"${type}\": ${describeError(parsed.error)}`,\n },\n };\n }\n return { ok: true, op: parsed.data as Operation, entry };\n}\n\n/**\n * Checks one op that is about to be appended to a log in the current plugin\n * versions, with the same checks as a log parse. Returns the parsed op. Throws\n * `SealpixelError` with the code that a log parse gives for the same op.\n */\nexport function parseAppendedOperation(\n registry: Registry,\n raw: unknown,\n document: Document,\n source: SourceDescriptor,\n): Operation {\n // No plugin versions: the op is in the current schema and needs no migration.\n const result = parseOperation(registry, raw, 0, {});\n if (!result.ok) {\n throw new SealpixelError(errorCode([result.issue]), result.issue.message, [result.issue]);\n }\n const violation = registry.validateOperation(result.op, document, source);\n if (violation) {\n throw new SealpixelError('OPTION_VIOLATION', `${result.op.type}: ${violation}`);\n }\n return result.op;\n}\n\nfunction tryParse<T>(\n parse: (v: unknown) => T,\n value: unknown,\n): { success: true; data: T } | { success: false; error: unknown } {\n try {\n return { success: true, data: parse(value) };\n } catch (error) {\n return { success: false, error };\n }\n}\n\nfunction describeError(error: unknown): string {\n if (error && typeof error === 'object' && 'issues' in error) {\n const issues = (error as { issues: { path: PropertyKey[]; message: string }[] }).issues;\n return issues.map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`).join('; ');\n }\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction stripUndefined<T extends object>(value: T): T {\n return Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined)) as T;\n}\n"]}
@@ -59,6 +59,12 @@ export declare class RendererCore {
59
59
  private workingCopy;
60
60
  private descriptor;
61
61
  private readonly cache;
62
+ /**
63
+ * Increments whenever the source changes. It is part of every cache key: a
64
+ * render that awaits an external kernel can outlive a load, and its output
65
+ * must not reach the cache of the new source.
66
+ */
67
+ private sourceGeneration;
62
68
  constructor(wasm: SealpixelWasm, options: RendererCoreOptions);
63
69
  putAsset(id: string, bytes: Uint8Array): void;
64
70
  hasAsset(id: string): boolean;
@@ -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,W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,SAAS;YACjB,WAAW,EAAE,CAAC;YACd,MAAM,EAAE,YAAY,CAAC,CAAC,KAAK,CAAC,CAAC;SAC9B,CAAC;QACF,MAAM,CAAC,GAAG,IAAI,CAAC,KAAK,CAClB,IAAI,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 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,YAA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E,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;