@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.
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"]}
package/dist/plan.d.ts CHANGED
@@ -7,7 +7,7 @@ export type { ColorStage, CropStage, Fit, Rect as PlanRect, RenderPlan, ResizeSt
7
7
  export declare const PLAN_VERSION = 1;
8
8
  /**
9
9
  * Builds the plan for `log` executed on a buffer of `actual` size. Until the
10
- * plugin registry lands (S1.9) every log compiles to the identity plan.
10
+ * plugin registry lands, every log compiles to the identity plan.
11
11
  */
12
12
  export declare function toRenderPlan(log: EditLog, actual: {
13
13
  width: number;
package/dist/plan.js CHANGED
@@ -2,7 +2,7 @@
2
2
  export const PLAN_VERSION = 1;
3
3
  /**
4
4
  * Builds the plan for `log` executed on a buffer of `actual` size. Until the
5
- * plugin registry lands (S1.9) every log compiles to the identity plan.
5
+ * plugin registry lands, every log compiles to the identity plan.
6
6
  */
7
7
  export function toRenderPlan(log, actual, stages = []) {
8
8
  return {
package/dist/plan.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"plan.js","sourceRoot":"","sources":["../src/plan.ts"],"names":[],"mappings":"AAoBA,oDAAoD;AACpD,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,CAAC;AAE9B;;;GAGG;AACH,MAAM,UAAU,YAAY,CAC1B,GAAY,EACZ,MAAyC,EACzC,SAAkB,EAAE;IAEpB,OAAO;QACL,OAAO,EAAE,YAAY;QACrB,MAAM,EAAE,EAAE,KAAK,EAAE,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,MAAM,EAAE;QAC9D,WAAW,EAAE,MAAM,CAAC,KAAK,GAAG,GAAG,CAAC,MAAM,CAAC,KAAK;QAC5C,MAAM;KACP,CAAC;AACJ,CAAC","sourcesContent":["import type { RenderPlan, Stage } from './generated/plan.js';\nimport type { EditLog } from './types.js';\n\nexport type { Geometry, Size, StageGeometry } from './generated/geometry.js';\nexport type {\n ChromaSubsampling,\n Format as CoreFormat,\n OutputOptions as CoreOutputOptions,\n} from './generated/output.js';\nexport type {\n ColorStage,\n CropStage,\n Fit,\n Rect as PlanRect,\n RenderPlan,\n ResizeStage,\n SourceInfo,\n Stage,\n} from './generated/plan.js';\n\n/** Mirrors `sealpixel_core::plan::PLAN_VERSION`. */\nexport const PLAN_VERSION = 1;\n\n/**\n * Builds the plan for `log` executed on a buffer of `actual` size. Until the\n * plugin registry lands (S1.9) every log compiles to the identity plan.\n */\nexport function toRenderPlan(\n log: EditLog,\n actual: { width: number; height: number },\n stages: Stage[] = [],\n): RenderPlan {\n return {\n version: PLAN_VERSION,\n source: { width: log.source.width, height: log.source.height },\n bufferScale: actual.width / log.source.width,\n stages,\n };\n}\n"]}
1
+ {"version":3,"file":"plan.js","sourceRoot":"","sources":["../src/plan.ts"],"names":[],"mappings":"AAoBA,oDAAoD;AACpD,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,CAAC;AAE9B;;;GAGG;AACH,MAAM,UAAU,YAAY,CAC1B,GAAY,EACZ,MAAyC,EACzC,SAAkB,EAAE;IAEpB,OAAO;QACL,OAAO,EAAE,YAAY;QACrB,MAAM,EAAE,EAAE,KAAK,EAAE,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,MAAM,EAAE;QAC9D,WAAW,EAAE,MAAM,CAAC,KAAK,GAAG,GAAG,CAAC,MAAM,CAAC,KAAK;QAC5C,MAAM;KACP,CAAC;AACJ,CAAC","sourcesContent":["import type { RenderPlan, Stage } from './generated/plan.js';\nimport type { EditLog } from './types.js';\n\nexport type { Geometry, Size, StageGeometry } from './generated/geometry.js';\nexport type {\n ChromaSubsampling,\n Format as CoreFormat,\n OutputOptions as CoreOutputOptions,\n} from './generated/output.js';\nexport type {\n ColorStage,\n CropStage,\n Fit,\n Rect as PlanRect,\n RenderPlan,\n ResizeStage,\n SourceInfo,\n Stage,\n} from './generated/plan.js';\n\n/** Mirrors `sealpixel_core::plan::PLAN_VERSION`. */\nexport const PLAN_VERSION = 1;\n\n/**\n * Builds the plan for `log` executed on a buffer of `actual` size. Until the\n * plugin registry lands, every log compiles to the identity plan.\n */\nexport function toRenderPlan(\n log: EditLog,\n actual: { width: number; height: number },\n stages: Stage[] = [],\n): RenderPlan {\n return {\n version: PLAN_VERSION,\n source: { width: log.source.width, height: log.source.height },\n bufferScale: actual.width / log.source.width,\n stages,\n };\n}\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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GAAG,CAAC,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 } 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;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AAC;AAED,SAAS,aAAa,CAAC,KAAc;IACnC,IAAI,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,QAAQ,IAAI,KAAK,EAAE,CAAC;QAC5D,MAAM,MAAM,GAAI,KAAgE,CAAC,MAAM,CAAC;QACxF,OAAO,MAAM,CAAC,GAAG,CAAC,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"]}
package/dist/render.js CHANGED
@@ -213,7 +213,7 @@ async function executeStages(wasm, stages, image, logical, options) {
213
213
  scale: current.width / currentLogical.width,
214
214
  mode: options.mode,
215
215
  asset: (id) => {
216
- throw new SealpixelError('INVALID_EDIT_LOG', `asset "${id}" requested but assets are not supported yet (S3.3)`);
216
+ throw new SealpixelError('INVALID_EDIT_LOG', `asset "${id}" requested but assets are not supported yet`);
217
217
  },
218
218
  signal: options.signal ?? new AbortController().signal,
219
219
  };
@@ -1 +1 @@
1
- {"version":3,"file":"render.js","sourceRoot":"","sources":["../src/render.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,iBAAiB,GAGlB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,OAAO,EAAsB,YAAY,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AACrF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O,MAAM,CAAC;AAChB,CAAC;AAED,SAAS,OAAO,CAAI,EAAW;IAC7B,IAAI,CAAC;QACH,OAAO,EAAE,EAAE,CAAC;IACd,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACnC,CAAC;AACH,CAAC;AAED,SAAS,cAAc,CAAC,MAA+B;IACrD,IAAI,MAAM,EAAE,OAAO;QAAE,MAAM,IAAI,cAAc,CAAC,SAAS,EAAE,gBAAgB,CAAC,CAAC;AAC7E,CAAC;AAED,SAAS,GAAG;IACV,OAAO,OAAO,WAAW,KAAK,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,WAAW,CAAC,GAAG,EAAE,CAAC;AAC7E,CAAC","sourcesContent":["import {\n type DecodedImage,\n loadSealpixelWasm,\n type RgbaBuffer,\n type SealpixelWasm,\n} from '@sealpixel/wasm';\nimport { withAssets } from './assets.js';\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 { editLogHash, MANIFEST_VERSION, type RenderManifest, renderHash } from './manifest.js';\nimport { type Geometry, PLAN_VERSION, type RenderPlan, type Stage } from './plan.js';\nimport type { KernelContext, PlanContext } from './plugin.js';\nimport { createRegistry, type Registry } from './registry.js';\nimport type {\n EditLog,\n OutputFormat,\n OutputOptions,\n RenderOptions,\n RenderResult,\n RenderSource,\n} from './types.js';\n\nconst FORMAT_TO_CORE: Record<OutputFormat, string> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpeg',\n 'image/webp': 'webp',\n};\n\nconst EMPTY_REGISTRY = createRegistry([]);\n\n/**\n * Renders `log` against `source` and encodes the result.\n *\n * Pure with respect to its inputs: same bytes, same log, same options, same\n * plugins and the same core version produce the same output bytes on every\n * runtime. Core stages run inside the wasm; JS kernels run between them\n * through the same orchestrator on every runtime.\n */\nexport async function render(\n source: RenderSource,\n log: EditLog,\n options: RenderOptions,\n): Promise<RenderResult> {\n const wasm = options.wasm ?? (await loadSealpixelWasm());\n const registry = options.registry ?? EMPTY_REGISTRY;\n throwIfAborted(options.signal);\n\n const mode = options.mode ?? 'truth';\n // What a manifest needs is checked before the hash and the decode, the\n // expensive steps. A buffer source names its hash explicitly: the log's\n // `source.hash` is a claim about bytes this call never saw.\n if (options.manifest && mode !== 'truth') {\n throw new SealpixelError(\n 'INVALID_REQUEST',\n 'a manifest describes a truth render; a preview cannot be verified',\n );\n }\n const sourceHash = !options.manifest\n ? undefined\n : source instanceof Uint8Array\n ? wasm.sha256Hex(source)\n : options.sourceHash;\n if (options.manifest && sourceHash === undefined) {\n throw new SealpixelError(\n 'INVALID_REQUEST',\n 'a manifest needs the hash of the original: pass the bytes as source, or sourceHash with a buffer',\n );\n }\n\n const t0 = now();\n const image = source instanceof Uint8Array ? tryCore(() => wasm.decode(source)) : source;\n const decodeMs = now() - t0;\n\n if (\n mode === 'truth' &&\n (image.width !== log.source.width || image.height !== log.source.height)\n ) {\n throw new SealpixelError(\n 'SOURCE_MISMATCH',\n `truth render expects ${log.source.width}x${log.source.height}, got ${image.width}x${image.height}`,\n );\n }\n if (log.ops.length > 0 && registry === EMPTY_REGISTRY) {\n throw new SealpixelError('INVALID_EDIT_LOG', 'log has ops but no registry was given');\n }\n throwIfAborted(options.signal);\n\n const t1 = now();\n const { stages, logical } = compileStages(registry, image, log, mode, options.upTo);\n const rendered = await withAssets(\n () =>\n executeStages(wasm, stages, image, logical, {\n mode,\n ...(options.manifest ? { pixelHash: true } : {}),\n ...(options.signal === undefined ? {} : { signal: options.signal }),\n }),\n options.assets,\n (id, bytes) => wasm.assetPut(id, bytes),\n );\n const renderMs = now() - t1;\n throwIfAborted(options.signal);\n\n const t2 = now();\n const coreOutput = toCoreOutput(options.output);\n if (options.embedEditLog) {\n coreOutput['embed'] = canonicalJson({ log, index: options.upTo ?? log.ops.length });\n }\n // A decoded source carries its ICC profile; pixels given by the caller carry\n // what the caller attached, if anything. No `instanceof`: a typed array from\n // another realm is still a profile.\n const icc = (image as Partial<DecodedImage>).icc;\n const bytes = tryCore(() => wasm.encode(rendered, JSON.stringify(coreOutput), icc));\n const encodeMs = now() - t2;\n\n const result: RenderResult = {\n bytes,\n mimeType: options.output.format,\n width: rendered.width,\n height: rendered.height,\n hash: wasm.sha256Hex(bytes),\n coreVersion: wasm.version(),\n timings: { decode: decodeMs, render: renderMs, encode: encodeMs },\n };\n if (options.manifest && sourceHash !== undefined) {\n const t3 = now();\n result.manifest = buildManifest(wasm, registry, stages, logical, log, options, {\n sourceHash,\n rendered,\n bytes: result.hash,\n output: toCoreOutput(options.output),\n mimeType: (image as Partial<DecodedImage>).mimeType,\n });\n result.timings['manifest'] = now() - t3;\n }\n return result;\n}\n\n/**\n * The manifest of a finished render, from the stages that rendered. The plan\n * is the single core plan of a render whose stages all ran in the core; a\n * pipeline with a plugin kernel outside the core lists the kernels instead,\n * and only a JavaScript runtime can verify it. `output.options` never\n * carries `embed`: the log is in `editLog`, and `embedEditLog` says whether\n * the file holds it too.\n */\nfunction buildManifest(\n wasm: SealpixelWasm,\n registry: Registry,\n stages: readonly PipelineStage[],\n logical: { width: number; height: number },\n log: EditLog,\n options: RenderOptions,\n result: {\n sourceHash: string;\n rendered: RgbaBuffer & { pixelHash?: string };\n bytes: string;\n output: Record<string, unknown>;\n mimeType: string | undefined;\n },\n): RenderManifest {\n const index = options.upTo ?? log.ops.length;\n const kernels = stages.filter((s) => s.kind !== 'core').map((s) => s.name);\n const plan: RenderPlan | undefined =\n kernels.length === 0\n ? { version: PLAN_VERSION, source: logical, bufferScale: 1, stages: toCoreStages(stages) }\n : undefined;\n const plugins = registry.pluginVersions();\n const renderer = wasm.identity();\n // From the core when the last stage ran there; a kernel outside the core\n // leaves its buffer in JavaScript, which is then hashed from there.\n const pixelHash = result.rendered.pixelHash ?? wasm.pixelHash(result.rendered);\n const logHash = editLogHash(wasm.sha256Hex, log, index);\n return {\n version: MANIFEST_VERSION,\n source: {\n width: log.source.width,\n height: log.source.height,\n hash: result.sourceHash,\n ...(result.mimeType === undefined ? {} : { mimeType: result.mimeType }),\n },\n editLog: { log, index },\n editLogHash: logHash,\n ...(plan ? { plan } : { kernels }),\n plugins,\n renderer,\n output: {\n options: result.output,\n ...(options.embedEditLog ? { embedEditLog: true } : {}),\n width: result.rendered.width,\n height: result.rendered.height,\n pixelHash,\n byteHash: result.bytes,\n },\n renderHash: renderHash(wasm.sha256Hex, {\n sourceHash: result.sourceHash,\n editsHash: logHash,\n plugins,\n renderer,\n pixelHash,\n byteHash: result.bytes,\n }),\n };\n}\n\nexport interface PipelineOptions {\n mode: 'truth' | 'preview';\n upTo?: number;\n signal?: AbortSignal;\n}\n\n/**\n * Compiles the log and executes it: consecutive core stages become one wasm\n * call, every external kernel runs in between on the RGBA buffer.\n */\nexport async function runPipeline(\n wasm: SealpixelWasm,\n registry: Registry,\n image: RgbaBuffer,\n log: EditLog,\n options: PipelineOptions,\n): Promise<RgbaBuffer> {\n const { stages, logical } = compileStages(registry, image, log, options.mode, options.upTo);\n return executeStages(wasm, stages, image, logical, options);\n}\n\n/**\n * The core plan of a truth render of `ops[0..upTo)`, when every stage runs in\n * the core, and otherwise the stages that run outside it. What a render\n * manifest records, and what a C2PA manifest definition is made from.\n */\nexport function compileCorePlan(\n log: EditLog,\n registry: Registry,\n upTo?: number,\n): {\n /** The one core plan, when every stage runs in the core. */\n plan?: RenderPlan;\n /** The core stages in order, whatever runs between them. */\n coreStages: Stage[];\n kernels: { name: string; order: number }[];\n} {\n const logical = { width: log.source.width, height: log.source.height };\n const { stages } = compileStages(registry, { ...logical, data: EMPTY }, log, 'truth', upTo);\n const kernels = stages\n .filter((s) => s.kind !== 'core')\n .map((s) => ({ name: s.name, order: s.order }));\n const coreStages = toCoreStages(stages.filter((s) => s.kind === 'core'));\n return kernels.length === 0\n ? {\n plan: { version: PLAN_VERSION, source: logical, bufferScale: 1, stages: coreStages },\n coreStages,\n kernels,\n }\n : { coreStages, kernels };\n}\n\nconst EMPTY = new Uint8Array(0);\n\n/** Compiles `ops[0..upTo)` into the ordered stages for a buffer of `image`'s size. */\nfunction compileStages(\n registry: Registry,\n image: RgbaBuffer,\n log: EditLog,\n mode: 'truth' | 'preview',\n upTo: number | undefined,\n): { stages: PipelineStage[]; logical: { width: number; height: number } } {\n const doc = compile(log, registry, upTo);\n const logical = { width: log.source.width, height: log.source.height };\n const ctx: PlanContext = {\n logical,\n actual: { width: image.width, height: image.height },\n scale: image.width / log.source.width,\n mode,\n };\n return { stages: toPipeline(doc, registry, ctx), logical };\n}\n\n/** Runs the stages: consecutive core stages as one wasm call, every external kernel in between. */\nasync function executeStages(\n wasm: SealpixelWasm,\n stages: readonly PipelineStage[],\n image: RgbaBuffer,\n logical: { width: number; height: number },\n options: Pick<PipelineOptions, 'mode' | 'signal'> & { pixelHash?: boolean },\n): Promise<RgbaBuffer & { pixelHash?: string }> {\n let current: RgbaBuffer & { pixelHash?: string } = image;\n let currentLogical = logical;\n const all = [...segments(stages)];\n for (const [i, segment] of all.entries()) {\n throwIfAborted(options.signal);\n if (segment.kind === 'core') {\n const plan: RenderPlan = {\n version: PLAN_VERSION,\n source: currentLogical,\n bufferScale: current.width / currentLogical.width,\n stages: toCoreStages(segment.stages),\n };\n const planJson = JSON.stringify(plan);\n const geometry = JSON.parse(\n tryCore(() => wasm.resolveGeometry(planJson, current.width, current.height)),\n ) as Geometry;\n const last = i === all.length - 1;\n current = tryCore(() =>\n wasm.renderRgba(current, planJson, options.pixelHash && last ? { pixelHash: true } : {}),\n );\n currentLogical = geometry.logicalOut;\n } else {\n const stage = segment.stage;\n const kctx: KernelContext = {\n logical: currentLogical,\n actual: { width: current.width, height: current.height },\n scale: current.width / currentLogical.width,\n mode: options.mode,\n asset: (id) => {\n throw new SealpixelError(\n 'INVALID_EDIT_LOG',\n `asset \"${id}\" requested but assets are not supported yet (S3.3)`,\n );\n },\n signal: options.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 }\n return current;\n}\n\ntype Segment =\n | { kind: 'core'; stages: PipelineStage[] }\n | { kind: 'external'; stage: Extract<PipelineStage, { kind: 'js' | 'wasm' }> };\n\nfunction* segments(stages: readonly PipelineStage[]): Generator<Segment> {\n let run: PipelineStage[] = [];\n for (const stage of stages) {\n if (stage.kind === 'core') {\n run.push(stage);\n continue;\n }\n if (run.length > 0) {\n yield { kind: 'core', stages: run };\n run = [];\n }\n yield { kind: 'external', stage };\n }\n if (run.length > 0) yield { kind: 'core', stages: run };\n}\n\n/** Maps the public output options onto the Rust `OutputOptions` JSON. */\nexport function toCoreOutput(output: OutputOptions): Record<string, unknown> {\n const core: Record<string, unknown> = { format: FORMAT_TO_CORE[output.format] };\n if (output.quality !== undefined) core['quality'] = output.quality;\n if (output.progressive !== undefined) core['progressive'] = output.progressive;\n if (output.chromaSubsampling !== undefined) core['chromaSubsampling'] = output.chromaSubsampling;\n if (output.lossless !== undefined) core['lossless'] = output.lossless;\n if (output.background !== undefined) core['background'] = output.background;\n return core;\n}\n\n/**\n * The inverse of `toCoreOutput`, for the options a render manifest records.\n * `embed` is not an option here: `embedEditLog` regenerates it from the log.\n */\nexport function fromCoreOutput(core: Record<string, unknown>): OutputOptions {\n const format = (Object.keys(FORMAT_TO_CORE) as OutputFormat[]).find(\n (f) => FORMAT_TO_CORE[f] === core['format'],\n );\n if (format === undefined) {\n throw new SealpixelError('INVALID_REQUEST', `unknown output format ${String(core['format'])}`);\n }\n const output: OutputOptions = { format };\n if (typeof core['quality'] === 'number') output.quality = core['quality'];\n if (typeof core['progressive'] === 'boolean') output.progressive = core['progressive'];\n if (core['chromaSubsampling'] === '4:2:0' || core['chromaSubsampling'] === '4:4:4')\n output.chromaSubsampling = core['chromaSubsampling'];\n if (typeof core['lossless'] === 'boolean') output.lossless = core['lossless'];\n if (Array.isArray(core['background']) && core['background'].length === 3)\n output.background = core['background'] as [number, number, number];\n return output;\n}\n\nfunction tryCore<T>(fn: () => T): T {\n try {\n return fn();\n } catch (error) {\n throw SealpixelError.from(error);\n }\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted) throw new SealpixelError('ABORTED', 'render aborted');\n}\n\nfunction now(): number {\n return typeof performance === 'undefined' ? Date.now() : performance.now();\n}\n"]}
1
+ {"version":3,"file":"render.js","sourceRoot":"","sources":["../src/render.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,iBAAiB,GAGlB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,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,EAAE,WAAW,EAAE,gBAAgB,EAAuB,UAAU,EAAE,MAAM,eAAe,CAAC;AAC/F,OAAO,EAAiB,YAAY,EAA+B,MAAM,WAAW,CAAC;AAErF,OAAO,EAAE,cAAc,EAAiB,MAAM,eAAe,CAAC;AAU9D,MAAM,cAAc,GAAiC;IACnD,WAAW,EAAE,KAAK;IAClB,YAAY,EAAE,MAAM;IACpB,YAAY,EAAE,MAAM;CACrB,CAAC;AAEF,MAAM,cAAc,GAAG,cAAc,CAAC,EAAE,CAAC,CAAC;AAE1C;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,MAAM,CAC1B,MAAoB,EACpB,GAAY,EACZ,OAAsB;IAEtB,MAAM,IAAI,GAAG,O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Buffer,\n type SealpixelWasm,\n} from '@sealpixel/wasm';\nimport { withAssets } from './assets.js';\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 { editLogHash, MANIFEST_VERSION, type RenderManifest, renderHash } from './manifest.js';\nimport { type Geometry, PLAN_VERSION, type RenderPlan, type Stage } from './plan.js';\nimport type { KernelContext, PlanContext } from './plugin.js';\nimport { createRegistry, type Registry } from './registry.js';\nimport type {\n EditLog,\n OutputFormat,\n OutputOptions,\n RenderOptions,\n RenderResult,\n RenderSource,\n} from './types.js';\n\nconst FORMAT_TO_CORE: Record<OutputFormat, string> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpeg',\n 'image/webp': 'webp',\n};\n\nconst EMPTY_REGISTRY = createRegistry([]);\n\n/**\n * Renders `log` against `source` and encodes the result.\n *\n * Pure with respect to its inputs: same bytes, same log, same options, same\n * plugins and the same core version produce the same output bytes on every\n * runtime. Core stages run inside the wasm; JS kernels run between them\n * through the same orchestrator on every runtime.\n */\nexport async function render(\n source: RenderSource,\n log: EditLog,\n options: RenderOptions,\n): Promise<RenderResult> {\n const wasm = options.wasm ?? (await loadSealpixelWasm());\n const registry = options.registry ?? EMPTY_REGISTRY;\n throwIfAborted(options.signal);\n\n const mode = options.mode ?? 'truth';\n // What a manifest needs is checked before the hash and the decode, the\n // expensive steps. A buffer source names its hash explicitly: the log's\n // `source.hash` is a claim about bytes this call never saw.\n if (options.manifest && mode !== 'truth') {\n throw new SealpixelError(\n 'INVALID_REQUEST',\n 'a manifest describes a truth render; a preview cannot be verified',\n );\n }\n const sourceHash = !options.manifest\n ? undefined\n : source instanceof Uint8Array\n ? wasm.sha256Hex(source)\n : options.sourceHash;\n if (options.manifest && sourceHash === undefined) {\n throw new SealpixelError(\n 'INVALID_REQUEST',\n 'a manifest needs the hash of the original: pass the bytes as source, or sourceHash with a buffer',\n );\n }\n\n const t0 = now();\n const image = source instanceof Uint8Array ? tryCore(() => wasm.decode(source)) : source;\n const decodeMs = now() - t0;\n\n if (\n mode === 'truth' &&\n (image.width !== log.source.width || image.height !== log.source.height)\n ) {\n throw new SealpixelError(\n 'SOURCE_MISMATCH',\n `truth render expects ${log.source.width}x${log.source.height}, got ${image.width}x${image.height}`,\n );\n }\n if (log.ops.length > 0 && registry === EMPTY_REGISTRY) {\n throw new SealpixelError('INVALID_EDIT_LOG', 'log has ops but no registry was given');\n }\n throwIfAborted(options.signal);\n\n const t1 = now();\n const { stages, logical } = compileStages(registry, image, log, mode, options.upTo);\n const rendered = await withAssets(\n () =>\n executeStages(wasm, stages, image, logical, {\n mode,\n ...(options.manifest ? { pixelHash: true } : {}),\n ...(options.signal === undefined ? {} : { signal: options.signal }),\n }),\n options.assets,\n (id, bytes) => wasm.assetPut(id, bytes),\n );\n const renderMs = now() - t1;\n throwIfAborted(options.signal);\n\n const t2 = now();\n const coreOutput = toCoreOutput(options.output);\n if (options.embedEditLog) {\n coreOutput['embed'] = canonicalJson({ log, index: options.upTo ?? log.ops.length });\n }\n // A decoded source carries its ICC profile; pixels given by the caller carry\n // what the caller attached, if anything. No `instanceof`: a typed array from\n // another realm is still a profile.\n const icc = (image as Partial<DecodedImage>).icc;\n const bytes = tryCore(() => wasm.encode(rendered, JSON.stringify(coreOutput), icc));\n const encodeMs = now() - t2;\n\n const result: RenderResult = {\n bytes,\n mimeType: options.output.format,\n width: rendered.width,\n height: rendered.height,\n hash: wasm.sha256Hex(bytes),\n coreVersion: wasm.version(),\n timings: { decode: decodeMs, render: renderMs, encode: encodeMs },\n };\n if (options.manifest && sourceHash !== undefined) {\n const t3 = now();\n result.manifest = buildManifest(wasm, registry, stages, logical, log, options, {\n sourceHash,\n rendered,\n bytes: result.hash,\n output: toCoreOutput(options.output),\n mimeType: (image as Partial<DecodedImage>).mimeType,\n });\n result.timings['manifest'] = now() - t3;\n }\n return result;\n}\n\n/**\n * The manifest of a finished render, from the stages that rendered. The plan\n * is the single core plan of a render whose stages all ran in the core; a\n * pipeline with a plugin kernel outside the core lists the kernels instead,\n * and only a JavaScript runtime can verify it. `output.options` never\n * carries `embed`: the log is in `editLog`, and `embedEditLog` says whether\n * the file holds it too.\n */\nfunction buildManifest(\n wasm: SealpixelWasm,\n registry: Registry,\n stages: readonly PipelineStage[],\n logical: { width: number; height: number },\n log: EditLog,\n options: RenderOptions,\n result: {\n sourceHash: string;\n rendered: RgbaBuffer & { pixelHash?: string };\n bytes: string;\n output: Record<string, unknown>;\n mimeType: string | undefined;\n },\n): RenderManifest {\n const index = options.upTo ?? log.ops.length;\n const kernels = stages.filter((s) => s.kind !== 'core').map((s) => s.name);\n const plan: RenderPlan | undefined =\n kernels.length === 0\n ? { version: PLAN_VERSION, source: logical, bufferScale: 1, stages: toCoreStages(stages) }\n : undefined;\n const plugins = registry.pluginVersions();\n const renderer = wasm.identity();\n // From the core when the last stage ran there; a kernel outside the core\n // leaves its buffer in JavaScript, which is then hashed from there.\n const pixelHash = result.rendered.pixelHash ?? wasm.pixelHash(result.rendered);\n const logHash = editLogHash(wasm.sha256Hex, log, index);\n return {\n version: MANIFEST_VERSION,\n source: {\n width: log.source.width,\n height: log.source.height,\n hash: result.sourceHash,\n ...(result.mimeType === undefined ? {} : { mimeType: result.mimeType }),\n },\n editLog: { log, index },\n editLogHash: logHash,\n ...(plan ? { plan } : { kernels }),\n plugins,\n renderer,\n output: {\n options: result.output,\n ...(options.embedEditLog ? { embedEditLog: true } : {}),\n width: result.rendered.width,\n height: result.rendered.height,\n pixelHash,\n byteHash: result.bytes,\n },\n renderHash: renderHash(wasm.sha256Hex, {\n sourceHash: result.sourceHash,\n editsHash: logHash,\n plugins,\n renderer,\n pixelHash,\n byteHash: result.bytes,\n }),\n };\n}\n\nexport interface PipelineOptions {\n mode: 'truth' | 'preview';\n upTo?: number;\n signal?: AbortSignal;\n}\n\n/**\n * Compiles the log and executes it: consecutive core stages become one wasm\n * call, every external kernel runs in between on the RGBA buffer.\n */\nexport async function runPipeline(\n wasm: SealpixelWasm,\n registry: Registry,\n image: RgbaBuffer,\n log: EditLog,\n options: PipelineOptions,\n): Promise<RgbaBuffer> {\n const { stages, logical } = compileStages(registry, image, log, options.mode, options.upTo);\n return executeStages(wasm, stages, image, logical, options);\n}\n\n/**\n * The core plan of a truth render of `ops[0..upTo)`, when every stage runs in\n * the core, and otherwise the stages that run outside it. What a render\n * manifest records, and what a C2PA manifest definition is made from.\n */\nexport function compileCorePlan(\n log: EditLog,\n registry: Registry,\n upTo?: number,\n): {\n /** The one core plan, when every stage runs in the core. */\n plan?: RenderPlan;\n /** The core stages in order, whatever runs between them. */\n coreStages: Stage[];\n kernels: { name: string; order: number }[];\n} {\n const logical = { width: log.source.width, height: log.source.height };\n const { stages } = compileStages(registry, { ...logical, data: EMPTY }, log, 'truth', upTo);\n const kernels = stages\n .filter((s) => s.kind !== 'core')\n .map((s) => ({ name: s.name, order: s.order }));\n const coreStages = toCoreStages(stages.filter((s) => s.kind === 'core'));\n return kernels.length === 0\n ? {\n plan: { version: PLAN_VERSION, source: logical, bufferScale: 1, stages: coreStages },\n coreStages,\n kernels,\n }\n : { coreStages, kernels };\n}\n\nconst EMPTY = new Uint8Array(0);\n\n/** Compiles `ops[0..upTo)` into the ordered stages for a buffer of `image`'s size. */\nfunction compileStages(\n registry: Registry,\n image: RgbaBuffer,\n log: EditLog,\n mode: 'truth' | 'preview',\n upTo: number | undefined,\n): { stages: PipelineStage[]; logical: { width: number; height: number } } {\n const doc = compile(log, registry, upTo);\n const logical = { width: log.source.width, height: log.source.height };\n const ctx: PlanContext = {\n logical,\n actual: { width: image.width, height: image.height },\n scale: image.width / log.source.width,\n mode,\n };\n return { stages: toPipeline(doc, registry, ctx), logical };\n}\n\n/** Runs the stages: consecutive core stages as one wasm call, every external kernel in between. */\nasync function executeStages(\n wasm: SealpixelWasm,\n stages: readonly PipelineStage[],\n image: RgbaBuffer,\n logical: { width: number; height: number },\n options: Pick<PipelineOptions, 'mode' | 'signal'> & { pixelHash?: boolean },\n): Promise<RgbaBuffer & { pixelHash?: string }> {\n let current: RgbaBuffer & { pixelHash?: string } = image;\n let currentLogical = logical;\n const all = [...segments(stages)];\n for (const [i, segment] of all.entries()) {\n throwIfAborted(options.signal);\n if (segment.kind === 'core') {\n const plan: RenderPlan = {\n version: PLAN_VERSION,\n source: currentLogical,\n bufferScale: current.width / currentLogical.width,\n stages: toCoreStages(segment.stages),\n };\n const planJson = JSON.stringify(plan);\n const geometry = JSON.parse(\n tryCore(() => wasm.resolveGeometry(planJson, current.width, current.height)),\n ) as Geometry;\n const last = i === all.length - 1;\n current = tryCore(() =>\n wasm.renderRgba(current, planJson, options.pixelHash && last ? { pixelHash: true } : {}),\n );\n currentLogical = geometry.logicalOut;\n } else {\n const stage = segment.stage;\n const kctx: KernelContext = {\n logical: currentLogical,\n actual: { width: current.width, height: current.height },\n scale: current.width / currentLogical.width,\n mode: options.mode,\n asset: (id) => {\n throw new SealpixelError(\n 'INVALID_EDIT_LOG',\n `asset \"${id}\" requested but assets are not supported yet`,\n );\n },\n signal: options.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 }\n return current;\n}\n\ntype Segment =\n | { kind: 'core'; stages: PipelineStage[] }\n | { kind: 'external'; stage: Extract<PipelineStage, { kind: 'js' | 'wasm' }> };\n\nfunction* segments(stages: readonly PipelineStage[]): Generator<Segment> {\n let run: PipelineStage[] = [];\n for (const stage of stages) {\n if (stage.kind === 'core') {\n run.push(stage);\n continue;\n }\n if (run.length > 0) {\n yield { kind: 'core', stages: run };\n run = [];\n }\n yield { kind: 'external', stage };\n }\n if (run.length > 0) yield { kind: 'core', stages: run };\n}\n\n/** Maps the public output options onto the Rust `OutputOptions` JSON. */\nexport function toCoreOutput(output: OutputOptions): Record<string, unknown> {\n const core: Record<string, unknown> = { format: FORMAT_TO_CORE[output.format] };\n if (output.quality !== undefined) core['quality'] = output.quality;\n if (output.progressive !== undefined) core['progressive'] = output.progressive;\n if (output.chromaSubsampling !== undefined) core['chromaSubsampling'] = output.chromaSubsampling;\n if (output.lossless !== undefined) core['lossless'] = output.lossless;\n if (output.background !== undefined) core['background'] = output.background;\n return core;\n}\n\n/**\n * The inverse of `toCoreOutput`, for the options a render manifest records.\n * `embed` is not an option here: `embedEditLog` regenerates it from the log.\n */\nexport function fromCoreOutput(core: Record<string, unknown>): OutputOptions {\n const format = (Object.keys(FORMAT_TO_CORE) as OutputFormat[]).find(\n (f) => FORMAT_TO_CORE[f] === core['format'],\n );\n if (format === undefined) {\n throw new SealpixelError('INVALID_REQUEST', `unknown output format ${String(core['format'])}`);\n }\n const output: OutputOptions = { format };\n if (typeof core['quality'] === 'number') output.quality = core['quality'];\n if (typeof core['progressive'] === 'boolean') output.progressive = core['progressive'];\n if (core['chromaSubsampling'] === '4:2:0' || core['chromaSubsampling'] === '4:4:4')\n output.chromaSubsampling = core['chromaSubsampling'];\n if (typeof core['lossless'] === 'boolean') output.lossless = core['lossless'];\n if (Array.isArray(core['background']) && core['background'].length === 3)\n output.background = core['background'] as [number, number, number];\n return output;\n}\n\nfunction tryCore<T>(fn: () => T): T {\n try {\n return fn();\n } catch (error) {\n throw SealpixelError.from(error);\n }\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted) throw new SealpixelError('ABORTED', 'render aborted');\n}\n\nfunction now(): number {\n return typeof performance === 'undefined' ? Date.now() : performance.now();\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;