@overtone-art/canvas-editor-core 0.8.6 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/node.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/node.ts","../src/print.ts"],"sourcesContent":["import { FabricImage, Rect, StaticCanvas, util } from 'fabric/node';\nimport type { FabricObject, ImageFormat } from 'fabric/node';\nimport { computeCoverPlacement, computePrintAreaClip } from './export';\nimport { displaceRgba } from './displacement';\nimport { applyTextWrapToObject } from './text-wrap';\nimport type { EditorState, MockupBlendMode, MockupConfig, MockupDisplacement } from './types';\n\nexport { renderPrintPdf } from './print';\nexport type { PrintPdfOptions, PrintPdfResult } from './print';\n\nexport interface NodeRenderOptions {\n format?: 'png' | 'jpeg' | 'webp' | 'svg';\n multiplier?: number;\n quality?: number;\n /**\n * Gate every image URL referenced by the state before it is loaded. States\n * are authored in the browser and therefore untrusted on a server; the\n * default policy allows only `http:`, `https:` and `data:`. Supply a\n * narrower predicate (e.g. an origin allowlist) to also stop requests to\n * internal hosts.\n */\n allowImageUrl?: (url: string) => boolean;\n}\n\nexport interface NodeRenderResult {\n format: 'png' | 'jpeg' | 'webp' | 'svg';\n mimeType: string;\n data: Uint8Array | string;\n width: number;\n height: number;\n}\n\n// `fabric/node` resolves bare paths and `file:` URLs against the local disk, so\n// an unrestricted state is a local-file-read and SSRF primitive on a server.\nconst ALLOWED_PROTOCOLS = new Set(['http:', 'https:', 'data:']);\n\n/** Keys whose string values are fetched as images during a render. */\nconst URL_KEYS = new Set(['src', 'image']);\n\nfunction defaultAllowImageUrl(url: string): boolean {\n const scheme = /^([a-z][a-z\\d+.-]*):/i.exec(url.trim());\n return scheme !== null && ALLOWED_PROTOCOLS.has(`${scheme[1].toLowerCase()}:`);\n}\n\nfunction assertImageUrlsAllowed(value: unknown, allow: (url: string) => boolean): void {\n if (Array.isArray(value)) {\n for (const item of value) assertImageUrlsAllowed(item, allow);\n return;\n }\n if (!value || typeof value !== 'object') return;\n for (const [key, entry] of Object.entries(value)) {\n if (typeof entry === 'string') {\n if (URL_KEYS.has(key) && !allow(entry)) {\n throw new Error(`Blocked disallowed image URL: ${entry.slice(0, 120)}`);\n }\n } else {\n assertImageUrlsAllowed(entry, allow);\n }\n }\n}\n\nfunction validateState(state: EditorState): void {\n if (\n !state?.canvas ||\n !Array.isArray(state.layers) ||\n !Number.isFinite(state.canvas.width) ||\n !Number.isFinite(state.canvas.height) ||\n state.canvas.width <= 0 ||\n state.canvas.height <= 0\n ) {\n throw new Error('Invalid editor state');\n }\n const major = Number.parseInt(state.version?.split('.')[0] ?? '1', 10);\n if (!Number.isFinite(major) || major > 2) {\n throw new Error(`Unsupported editor state version: ${state.version}`);\n }\n}\n\nfunction dataUrlBytes(dataUrl: string): Uint8Array {\n const encoded = dataUrl.slice(dataUrl.indexOf(',') + 1);\n const binary = atob(encoded);\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);\n return bytes;\n}\n\nfunction validateOptions(options: NodeRenderOptions): Required<NodeRenderOptions> {\n const format = options.format ?? 'png';\n const multiplier = options.multiplier ?? 1;\n const quality = options.quality ?? 1;\n const allowImageUrl = options.allowImageUrl ?? defaultAllowImageUrl;\n if (!Number.isFinite(multiplier) || multiplier <= 0) {\n throw new Error('Render multiplier must be positive');\n }\n if (!Number.isFinite(quality) || quality < 0 || quality > 1) {\n throw new Error('Render quality must be between 0 and 1');\n }\n return { format, multiplier, quality, allowImageUrl };\n}\n\nasync function createStateCanvas(state: EditorState, transparent = false): Promise<StaticCanvas> {\n const canvas = new StaticCanvas(undefined, {\n width: state.canvas.width,\n height: state.canvas.height,\n backgroundColor: transparent ? '' : (state.background ?? ''),\n preserveObjectStacking: true,\n });\n try {\n if (!transparent && state.backgroundImage) {\n canvas.backgroundImage = (\n await util.enlivenObjects([state.backgroundImage])\n )[0] as FabricObject;\n }\n const objects = (await util.enlivenObjects(\n state.layers.map((layer) => layer.fabricObject),\n )) as FabricObject[];\n objects.forEach((object, index) => {\n const layer = state.layers[index];\n object.set({ visible: layer.visible, opacity: layer.opacity });\n // The browser's TextWrapManager derives `wordSplit` and the overflow\n // clip live as the author types; fabric serializes neither the function\n // override nor (when a mask is present) the clip's nested, space-\n // converted placement, so a freshly enlivened object needs the same\n // derivation run once here, or the engine's own print output would\n // differ from what the editor previewed.\n applyTextWrapToObject(object, layer.meta, (options) => new Rect(options));\n canvas.add(object);\n });\n canvas.renderAll();\n return canvas;\n } catch (error) {\n canvas.dispose();\n throw error;\n }\n}\n\nfunction encodeCanvas(\n canvas: StaticCanvas,\n options: Required<NodeRenderOptions>,\n): NodeRenderResult {\n const { format, multiplier, quality } = options;\n const width = Math.round(canvas.getWidth() * multiplier);\n const height = Math.round(canvas.getHeight() * multiplier);\n if (format === 'svg') {\n return { format, mimeType: 'image/svg+xml', data: canvas.toSVG(), width, height };\n }\n const dataUrl = canvas.toDataURL({ format: format as ImageFormat, multiplier, quality });\n return {\n format,\n mimeType: format === 'jpeg' ? 'image/jpeg' : `image/${format}`,\n data: dataUrlBytes(dataUrl),\n width,\n height,\n };\n}\n\nfunction compositeOperation(mode?: MockupBlendMode): GlobalCompositeOperation {\n return !mode || mode === 'normal' ? 'source-over' : mode;\n}\n\nfunction clampOpacity(value = 1): number {\n return Math.max(0, Math.min(1, value));\n}\n\nasync function coverImage(url: string, width: number, height: number): Promise<FabricImage> {\n let image: FabricImage;\n try {\n image = await FabricImage.fromURL(url);\n } catch (error) {\n throw new Error(`Failed to load mockup image: ${url}`, { cause: error });\n }\n const sourceWidth = image.width;\n const sourceHeight = image.height;\n const placement = computeCoverPlacement(sourceWidth, sourceHeight, width, height);\n image.set({\n originX: 'left',\n originY: 'top',\n left: placement.left,\n top: placement.top,\n scaleX: placement.width / sourceWidth,\n scaleY: placement.height / sourceHeight,\n selectable: false,\n evented: false,\n });\n return image;\n}\n\nasync function displacedDesignUrl(\n designCanvas: StaticCanvas,\n displacement: MockupDisplacement,\n width: number,\n height: number,\n): Promise<string> {\n const mapCanvas = new StaticCanvas(undefined, { width, height });\n const warpedCanvas = new StaticCanvas(undefined, { width, height });\n try {\n mapCanvas.add(await coverImage(displacement.image, width, height));\n mapCanvas.renderAll();\n const pixels = displaceRgba(\n designCanvas.getContext().getImageData(0, 0, width, height).data,\n mapCanvas.getContext().getImageData(0, 0, width, height).data,\n width,\n height,\n displacement,\n );\n const imageData = warpedCanvas.getContext().createImageData(width, height);\n imageData.data.set(pixels);\n warpedCanvas.getContext().putImageData(imageData, 0, 0);\n return warpedCanvas.toDataURL({ format: 'png', multiplier: 1 });\n } catch (error) {\n throw new Error('Failed to apply mockup displacement map', { cause: error });\n } finally {\n mapCanvas.dispose();\n warpedCanvas.dispose();\n }\n}\n\n/** Render browser-authored EditorState without a DOM or live editor instance. */\nexport async function renderEditorState(\n state: EditorState,\n options: NodeRenderOptions = {},\n): Promise<NodeRenderResult> {\n validateState(state);\n const resolved = validateOptions(options);\n assertImageUrlsAllowed(state, resolved.allowImageUrl);\n const canvas = await createStateCanvas(state);\n try {\n return encodeCanvas(canvas, resolved);\n } finally {\n canvas.dispose();\n }\n}\n\n/** Render a saved product mockup with the transparent design composited above it. */\nexport async function renderMockupState(\n state: EditorState,\n options: NodeRenderOptions = {},\n): Promise<NodeRenderResult> {\n validateState(state);\n const resolved = validateOptions(options);\n assertImageUrlsAllowed(state, resolved.allowImageUrl);\n if (resolved.format === 'svg') {\n throw new Error('Mockup rendering supports PNG, JPEG, and WebP output');\n }\n const mockup: MockupConfig | null | undefined = state.mockup;\n if (!mockup?.image) throw new Error('No mockup is configured');\n\n const designCanvas = await createStateCanvas(state, true);\n const output = new StaticCanvas(undefined, {\n width: state.canvas.width,\n height: state.canvas.height,\n preserveObjectStacking: true,\n });\n try {\n output.add(await coverImage(mockup.image, state.canvas.width, state.canvas.height));\n\n const designUrl = mockup.displacement\n ? await displacedDesignUrl(\n designCanvas,\n mockup.displacement,\n state.canvas.width,\n state.canvas.height,\n )\n : designCanvas.toDataURL({ format: 'png', multiplier: 1 });\n const design = await FabricImage.fromURL(designUrl);\n design.set({\n originX: 'left',\n originY: 'top',\n left: 0,\n top: 0,\n opacity: clampOpacity(mockup.designOpacity),\n globalCompositeOperation: compositeOperation(mockup.designBlendMode),\n selectable: false,\n evented: false,\n });\n if (mockup.printArea && mockup.clipToPrintArea !== false) {\n const clip = computePrintAreaClip(\n mockup.printArea,\n 1,\n 1,\n state.canvas.width,\n state.canvas.height,\n );\n design.clipPath = new Rect({\n originX: 'left',\n originY: 'top',\n left: clip.left,\n top: clip.top,\n width: clip.width,\n height: clip.height,\n absolutePositioned: true,\n });\n }\n output.add(design);\n\n if (mockup.overlay) {\n const overlay = await coverImage(\n mockup.overlay.image,\n state.canvas.width,\n state.canvas.height,\n );\n overlay.set({\n opacity: clampOpacity(mockup.overlay.opacity),\n globalCompositeOperation: compositeOperation(mockup.overlay.blendMode ?? 'multiply'),\n });\n output.add(overlay);\n }\n output.renderAll();\n return encodeCanvas(output, resolved);\n } finally {\n designCanvas.dispose();\n output.dispose();\n }\n}\n\nasync function renderBatch(\n states: EditorState[],\n options: NodeRenderOptions & { concurrency?: number },\n renderer: (state: EditorState, options: NodeRenderOptions) => Promise<NodeRenderResult>,\n): Promise<NodeRenderResult[]> {\n const concurrency = Math.max(1, Math.floor(options.concurrency ?? 2));\n const results = new Array<NodeRenderResult>(states.length);\n let nextIndex = 0;\n await Promise.all(\n Array.from({ length: Math.min(concurrency, states.length) }, async () => {\n while (nextIndex < states.length) {\n const index = nextIndex++;\n results[index] = await renderer(states[index], options);\n }\n }),\n );\n return results;\n}\n\n/** Render multiple states with bounded concurrency for fulfillment jobs. */\nexport async function renderEditorStateBatch(\n states: EditorState[],\n options: NodeRenderOptions & { concurrency?: number } = {},\n): Promise<NodeRenderResult[]> {\n return renderBatch(states, options, renderEditorState);\n}\n\n/** Render multiple mockup states with bounded concurrency for fulfillment jobs. */\nexport async function renderMockupStateBatch(\n states: EditorState[],\n options: NodeRenderOptions & { concurrency?: number } = {},\n): Promise<NodeRenderResult[]> {\n return renderBatch(states, options, renderMockupState);\n}\n","import type { EditorState } from './types';\nimport type { NodeRenderOptions } from './node';\n\nexport interface PrintPdfOptions {\n /** Rasterization density. Defaults to the document DPI, or 300. */\n dpi?: number;\n /** Bleed on every edge, in inches. Defaults to 0.125in. */\n bleed?: number;\n /** Space outside bleed reserved for printer marks, in inches. Defaults to 0.25in. */\n marksMargin?: number;\n trimMarks?: boolean;\n registrationMarks?: boolean;\n /** Optional safe-area inset in inches for preflight warnings. */\n safeArea?: number;\n /** Sharp built-in `cmyk` profile or an absolute path to a custom ICC profile. */\n iccProfile?: string;\n /** Ceiling on the rasterized bleed image, in pixels. Defaults to 250 megapixels. */\n maxPixels?: number;\n outputConditionIdentifier?: string;\n title?: string;\n allowImageUrl?: NodeRenderOptions['allowImageUrl'];\n /** Preserve SVG shapes/text over a CMYK bleed raster. Defaults to `vector`. */\n rendering?: 'vector' | 'raster';\n /** PDFKit font registrations keyed by the exact SVG font-family name. */\n fontFiles?: Record<string, string | Uint8Array>;\n /** Convert text backed by `fontFiles` into glyph paths. Defaults to true. */\n outlineFonts?: boolean;\n}\n\nexport interface PrintPdfResult {\n format: 'pdf';\n mimeType: 'application/pdf';\n data: Uint8Array;\n standard: 'PDF/X-4';\n colourSpace: 'CMYK';\n rendering: 'vector' | 'raster';\n outlinedFonts: string[];\n unoutlinedFonts: string[];\n dpi: number;\n trimWidthPoints: number;\n trimHeightPoints: number;\n bleedPoints: number;\n warnings: string[];\n}\n\nfunction svgAttributes(source: string): Record<string, string> {\n return Object.fromEntries(\n [...source.matchAll(/([\\w:-]+)=(?:\"([^\"]*)\"|'([^']*)')/g)].map((match) => [\n match[1],\n match[2] ?? match[3] ?? '',\n ]),\n );\n}\n\nfunction decodeXmlText(source: string): string {\n return source\n .replace(/<[^>]+>/g, '')\n .replace(/&#x([\\da-f]+);/gi, (_, value: string) =>\n String.fromCodePoint(Number.parseInt(value, 16)),\n )\n .replace(/&#(\\d+);/g, (_, value: string) => String.fromCodePoint(Number(value)))\n .replace(/&lt;/g, '<')\n .replace(/&gt;/g, '>')\n .replace(/&quot;/g, '\"')\n .replace(/&apos;/g, \"'\")\n .replace(/&amp;/g, '&');\n}\n\nfunction escapeXmlAttribute(value: string): string {\n return value.replace(/[<>&\"']/g, (character) => `&#${character.charCodeAt(0)};`);\n}\n\nfunction fontSource(\n files: Record<string, string | Uint8Array>,\n family: string,\n bold: boolean,\n italic: boolean,\n): string | Uint8Array | undefined {\n const suffix = bold && italic ? '-BoldItalic' : bold ? '-Bold' : italic ? '-Italic' : '';\n // `family` comes from the untrusted SVG, so plain indexing would resolve\n // `__proto__`/`constructor` to inherited members and hand a non-font to fontkit.\n const own = (key: string) =>\n Object.hasOwn(files, key) ? (files[key] as string | Uint8Array) : undefined;\n return own(`${family}${suffix}`) ?? own(family);\n}\n\nasync function outlineSvgText(\n svg: string,\n files: Record<string, string | Uint8Array>,\n outlined: Set<string>,\n): Promise<string> {\n const fontkit = await import('fontkit');\n let output = '';\n let cursor = 0;\n for (const textMatch of svg.matchAll(/<text\\b([^>]*)>([\\s\\S]*?)<\\/text>/gi)) {\n const index = textMatch.index ?? 0;\n output += svg.slice(cursor, index);\n cursor = index + textMatch[0].length;\n const textAttributes = svgAttributes(textMatch[1]);\n const spans = [...textMatch[2].matchAll(/<tspan\\b([^>]*)>([\\s\\S]*?)<\\/tspan>/gi)];\n const lines = spans.length\n ? spans.map((span) => ({ attributes: svgAttributes(span[1]), text: decodeXmlText(span[2]) }))\n : [{ attributes: textAttributes, text: decodeXmlText(textMatch[2]) }];\n const resolved = lines.map((line) => {\n const attributes = { ...textAttributes, ...line.attributes };\n const family = attributes['font-family'] ?? 'sans-serif';\n const bold = /bold|[6-9]00/i.test(attributes['font-weight'] ?? '');\n const italic = /italic|oblique/i.test(attributes['font-style'] ?? '');\n return { ...line, attributes, family, source: fontSource(files, family, bold, italic) };\n });\n if (resolved.some((line) => !line.source)) {\n output += textMatch[0];\n continue;\n }\n const paths: string[] = [];\n for (const line of resolved) {\n const source = line.source!;\n const opened =\n typeof source === 'string'\n ? fontkit.openSync(source)\n : fontkit.create(Buffer.from(source.buffer, source.byteOffset, source.byteLength));\n if (!('layout' in opened)) {\n throw new Error(`Font collection requires a named face: ${line.family}`);\n }\n const size = Number.parseFloat(line.attributes['font-size'] ?? '16');\n const scale = size / opened.unitsPerEm;\n const style = line.attributes.style ?? '';\n const run = opened.layout(line.text);\n let penX = Number.parseFloat(line.attributes.x ?? '0');\n const baseline = Number.parseFloat(line.attributes.y ?? '0');\n run.glyphs.forEach((glyph, glyphIndex) => {\n const position = run.positions[glyphIndex];\n const x = penX + position.xOffset * scale;\n const y = baseline - position.yOffset * scale;\n paths.push(\n `<path d=\"${glyph.path.toSVG()}\" transform=\"translate(${x} ${y}) scale(${scale} ${-scale})\" style=\"${escapeXmlAttribute(style)}\"/>`,\n );\n penX += position.xAdvance * scale;\n });\n outlined.add(line.family);\n }\n output += `<g data-outlined-font=\"${escapeXmlAttribute([...new Set(resolved.map((line) => line.family))].join(','))}\">${paths.join('')}</g>`;\n }\n return output + svg.slice(cursor);\n}\n\nfunction rgbToCmyk([redByte, greenByte, blueByte]: [number, number, number]): [\n number,\n number,\n number,\n number,\n] {\n const red = redByte / 255;\n const green = greenByte / 255;\n const blue = blueByte / 255;\n const black = 1 - Math.max(red, green, blue);\n if (black >= 1) return [0, 0, 0, 100];\n return [\n ((1 - red - black) / (1 - black)) * 100,\n ((1 - green - black) / (1 - black)) * 100,\n ((1 - blue - black) / (1 - black)) * 100,\n black * 100,\n ];\n}\n\nasync function imageSourceBytes(\n source: string,\n allow?: (url: string) => boolean,\n): Promise<Uint8Array> {\n if (source.startsWith('data:')) {\n const response = await fetch(source);\n if (!response.ok) throw new Error('Failed to decode an embedded SVG image');\n return new Uint8Array(await response.arrayBuffer());\n }\n const permitted = allow\n ? allow(source)\n : (() => {\n try {\n return ['http:', 'https:'].includes(new URL(source).protocol);\n } catch {\n return false;\n }\n })();\n if (!permitted) throw new Error(`Blocked disallowed vector image URL: ${source}`);\n const response = await fetch(source);\n if (!response.ok) throw new Error(`Failed to load vector image: ${source}`);\n return new Uint8Array(await response.arrayBuffer());\n}\n\nasync function convertSvgImagesToCmyk(\n svg: string,\n sharp: (typeof import('sharp'))['default'],\n profile: string,\n allow?: (url: string) => boolean,\n): Promise<string> {\n const sources = new Set<string>();\n for (const image of svg.matchAll(/<image\\b[^>]*(?:xlink:href|href)=\"([^\"]+)\"[^>]*>/gi)) {\n if (image[1]) sources.add(image[1]);\n }\n let converted = svg;\n for (const source of sources) {\n const bytes = await imageSourceBytes(source, allow);\n const jpeg = await sharp(bytes)\n .flatten({ background: '#ffffff' })\n .toColourspace('cmyk')\n .withIccProfile(profile)\n .jpeg({ quality: 100, chromaSubsampling: '4:4:4' })\n .toBuffer();\n const dataUrl = `data:image/jpeg;base64,${jpeg.toString('base64')}`;\n converted = converted.split(source).join(dataUrl);\n }\n return converted;\n}\n\nasync function renderVectorOverlay(\n state: EditorState,\n options: PrintPdfOptions,\n width: number,\n height: number,\n sharp: (typeof import('sharp'))['default'],\n warnings: string[],\n outlinedFonts: Set<string>,\n unoutlinedFonts: Set<string>,\n): Promise<Uint8Array> {\n const [{ default: PDFKit }, { default: SVGtoPDF }, { renderEditorState }] = await Promise.all([\n import('pdfkit'),\n import('svg-to-pdfkit'),\n import('./node'),\n ]);\n // The bleed image is already flattened onto white. Render the trim overlay\n // against the same opaque print substrate so semi-transparent artwork does\n // not blend a second time with the raster copy beneath it.\n const rendered = await renderEditorState(\n { ...state, background: '#ffffff' },\n {\n format: 'svg',\n allowImageUrl: options.allowImageUrl,\n },\n );\n if (typeof rendered.data !== 'string') throw new Error('Vector rendering returned raster data');\n const fontFiles = options.fontFiles ?? {};\n const outlinedSvg =\n options.outlineFonts === false\n ? rendered.data\n : await outlineSvgText(rendered.data, fontFiles, outlinedFonts);\n const svg = await convertSvgImagesToCmyk(\n outlinedSvg,\n sharp,\n options.iccProfile ?? 'cmyk',\n options.allowImageUrl,\n );\n const remainingText = [...svg.matchAll(/<text\\b([^>]*)>/gi)].map((match) =>\n svgAttributes(match[1]),\n );\n for (const attributes of remainingText) {\n const family = attributes['font-family'] ?? 'sans-serif';\n unoutlinedFonts.add(family);\n const bold = /bold|[6-9]00/i.test(attributes['font-weight'] ?? '');\n const italic = /italic|oblique/i.test(attributes['font-style'] ?? '');\n if (!fontSource(fontFiles, family, bold, italic)) {\n warnings.push(\n `Font \"${family}\" used a PDF standard fallback; supply fontFiles for exact embedding`,\n );\n }\n }\n\n const document = new PDFKit({ autoFirstPage: false, compress: false, pdfVersion: '1.7' });\n for (const [name, path] of Object.entries(fontFiles)) {\n document.registerFont(name, typeof path === 'string' ? path : Buffer.from(path));\n }\n document.addPage({ size: [width, height], margin: 0 });\n SVGtoPDF(document, svg, 0, 0, {\n width,\n height,\n preserveAspectRatio: 'none',\n colorCallback: (color) => {\n const [rgb, opacity] = color;\n return [rgbToCmyk(rgb), opacity] as unknown as typeof color;\n },\n warningCallback: (warning) => warnings.push(`Vector render: ${warning}`),\n });\n\n return new Promise<Uint8Array>((resolve, reject) => {\n const chunks: Uint8Array[] = [];\n document.on('data', (chunk: Uint8Array) => chunks.push(chunk));\n document.on('error', reject);\n document.on('end', () => resolve(new Uint8Array(Buffer.concat(chunks))));\n document.end();\n });\n}\n\n/** Beyond this no printer is served, and larger values only buy an OOM. */\nconst MAX_DPI = 2400;\n/** ~24×36in at 600dpi. Bounds the raster a hostile state can ask a server for. */\nconst DEFAULT_MAX_PIXELS = 250_000_000;\n\nfunction positive(value: number, label: string): number {\n if (!Number.isFinite(value) || value <= 0) throw new Error(`${label} must be positive`);\n return value;\n}\n\n/**\n * States are browser-authored and untrusted on a server. `documentDpi` divides\n * the render multiplier, so an unvalidated fractional value (0.001) inflates the\n * rasterization by six orders of magnitude before any size check runs.\n */\nfunction boundedDpi(value: number, label: string): number {\n const dpi = positive(value, label);\n if (dpi > MAX_DPI) throw new Error(`${label} must not exceed ${MAX_DPI}`);\n if (dpi < 1) throw new Error(`${label} must be at least 1`);\n return dpi;\n}\n\nfunction nonNegative(value: number, label: string): number {\n if (!Number.isFinite(value) || value < 0) throw new Error(`${label} cannot be negative`);\n return value;\n}\n\nfunction preflightSafeArea(state: EditorState, safePixels: number): string[] {\n if (safePixels <= 0) return [];\n const right = state.canvas.width - safePixels;\n const bottom = state.canvas.height - safePixels;\n const warnings: string[] = [];\n for (const layer of state.layers) {\n if (!layer.visible) continue;\n const object = layer.fabricObject;\n const left = Number(object.left ?? 0);\n const top = Number(object.top ?? 0);\n const width = Number(object.width ?? 0) * Math.abs(Number(object.scaleX ?? 1));\n const height = Number(object.height ?? 0) * Math.abs(Number(object.scaleY ?? 1));\n if (left < safePixels || top < safePixels || left + width > right || top + height > bottom) {\n warnings.push(`Layer \"${layer.name}\" extends outside the configured safe area`);\n }\n }\n return warnings;\n}\n\n/**\n * Render an EditorState into a print-production PDF/X-4 file.\n *\n * The design is rasterized at the requested density, converted through Sharp's\n * CMYK ICC pipeline, edge-extended into bleed, and embedded with output intent,\n * trim/bleed boxes, XMP identification, and optional printer marks.\n */\nexport async function renderPrintPdf(\n state: EditorState,\n options: PrintPdfOptions = {},\n): Promise<PrintPdfResult> {\n const dpi = boundedDpi(options.dpi ?? state.canvas.dpi ?? 300, 'Print DPI');\n const documentDpi = boundedDpi(state.canvas.dpi ?? 72, 'Document DPI');\n const maxPixels = positive(options.maxPixels ?? DEFAULT_MAX_PIXELS, 'Max pixels');\n const bleedInches = nonNegative(options.bleed ?? 0.125, 'Bleed');\n const marksMarginInches = nonNegative(options.marksMargin ?? 0.25, 'Marks margin');\n const safeAreaInches = nonNegative(options.safeArea ?? 0, 'Safe area');\n const rendering = options.rendering ?? 'vector';\n const bleedPixels = Math.round(bleedInches * dpi);\n const trimWidthPoints = (state.canvas.width / documentDpi) * 72;\n const trimHeightPoints = (state.canvas.height / documentDpi) * 72;\n const bleedPoints = bleedInches * 72;\n const marksMarginPoints = marksMarginInches * 72;\n\n const scale = dpi / documentDpi;\n const outputPixels =\n Math.round(state.canvas.width * scale + bleedPixels * 2) *\n Math.round(state.canvas.height * scale + bleedPixels * 2);\n if (!Number.isFinite(outputPixels) || outputPixels > maxPixels) {\n throw new Error(\n `Print raster of ${outputPixels} pixels exceeds the ${maxPixels} pixel budget; lower the DPI or raise maxPixels`,\n );\n }\n\n const [{ default: sharp }, pdfLib] = await Promise.all([import('sharp'), import('pdf-lib')]);\n // Keep the optional print entry free of a static cycle with `node.ts`, which\n // re-exports this function as part of the Node-only public surface.\n const { renderEditorState } = await import('./node');\n const rendered = await renderEditorState(state, {\n format: 'png',\n multiplier: scale,\n allowImageUrl: options.allowImageUrl,\n });\n if (typeof rendered.data === 'string') throw new Error('Print rasterization returned SVG data');\n\n let pipeline = sharp(rendered.data).flatten({ background: '#ffffff' });\n if (bleedPixels > 0) {\n pipeline = pipeline.extend({\n top: bleedPixels,\n right: bleedPixels,\n bottom: bleedPixels,\n left: bleedPixels,\n extendWith: 'copy',\n });\n }\n const { data: cmykJpeg, info } = await pipeline\n .toColourspace('cmyk')\n .withIccProfile(options.iccProfile ?? 'cmyk')\n .withDensity(dpi)\n .jpeg({ quality: 100, chromaSubsampling: '4:4:4' })\n .toBuffer({ resolveWithObject: true });\n const metadata = await sharp(cmykJpeg).metadata();\n if (info.channels !== 4 || metadata.space !== 'cmyk' || !metadata.icc) {\n throw new Error('CMYK conversion did not produce a four-channel image with an ICC profile');\n }\n\n const { PDFDocument, PDFDict, PDFName, PDFString, cmyk } = pdfLib;\n const document = await PDFDocument.create();\n const title = options.title ?? 'Overtone Canvas Editor print export';\n document.setTitle(title);\n document.setCreator('@overtone-art/canvas-editor-core');\n document.setProducer('@overtone-art/canvas-editor-core');\n const pageWidth = trimWidthPoints + bleedPoints * 2 + marksMarginPoints * 2;\n const pageHeight = trimHeightPoints + bleedPoints * 2 + marksMarginPoints * 2;\n const page = document.addPage([pageWidth, pageHeight]);\n const image = await document.embedJpg(cmykJpeg);\n page.drawImage(image, {\n x: marksMarginPoints,\n y: marksMarginPoints,\n width: trimWidthPoints + bleedPoints * 2,\n height: trimHeightPoints + bleedPoints * 2,\n });\n\n const trimLeft = marksMarginPoints + bleedPoints;\n const trimBottom = marksMarginPoints + bleedPoints;\n const trimRight = trimLeft + trimWidthPoints;\n const trimTop = trimBottom + trimHeightPoints;\n const warnings = preflightSafeArea(state, safeAreaInches * documentDpi);\n const outlinedFonts = new Set<string>();\n const unoutlinedFonts = new Set<string>();\n if (rendering === 'vector') {\n const vectorPdf = await renderVectorOverlay(\n state,\n options,\n trimWidthPoints,\n trimHeightPoints,\n sharp,\n warnings,\n outlinedFonts,\n unoutlinedFonts,\n );\n const [vectorPage] = await document.embedPdf(vectorPdf);\n page.drawPage(vectorPage, {\n x: trimLeft,\n y: trimBottom,\n width: trimWidthPoints,\n height: trimHeightPoints,\n });\n }\n const bleedLeft = marksMarginPoints;\n const bleedBottom = marksMarginPoints;\n const bleedRight = pageWidth - marksMarginPoints;\n const bleedTop = pageHeight - marksMarginPoints;\n const context = document.context;\n page.node.set(PDFName.of('TrimBox'), context.obj([trimLeft, trimBottom, trimRight, trimTop]));\n page.node.set(\n PDFName.of('BleedBox'),\n context.obj([bleedLeft, bleedBottom, bleedRight, bleedTop]),\n );\n page.node.set(PDFName.of('ArtBox'), context.obj([trimLeft, trimBottom, trimRight, trimTop]));\n\n const markColour = cmyk(0, 0, 0, 1);\n if (options.trimMarks !== false) {\n const offset = Math.max(3, bleedPoints / 2);\n const length = Math.max(9, marksMarginPoints - 3);\n for (const x of [trimLeft, trimRight]) {\n page.drawLine({\n start: { x, y: trimBottom - offset },\n end: { x, y: trimBottom - offset - length },\n thickness: 0.5,\n color: markColour,\n });\n page.drawLine({\n start: { x, y: trimTop + offset },\n end: { x, y: trimTop + offset + length },\n thickness: 0.5,\n color: markColour,\n });\n }\n for (const y of [trimBottom, trimTop]) {\n page.drawLine({\n start: { x: trimLeft - offset, y },\n end: { x: trimLeft - offset - length, y },\n thickness: 0.5,\n color: markColour,\n });\n page.drawLine({\n start: { x: trimRight + offset, y },\n end: { x: trimRight + offset + length, y },\n thickness: 0.5,\n color: markColour,\n });\n }\n }\n if (options.registrationMarks !== false) {\n for (const [x, y] of [\n [pageWidth / 2, marksMarginPoints / 2],\n [pageWidth / 2, pageHeight - marksMarginPoints / 2],\n [marksMarginPoints / 2, pageHeight / 2],\n [pageWidth - marksMarginPoints / 2, pageHeight / 2],\n ] as Array<[number, number]>) {\n page.drawCircle({ x, y, size: 4, borderWidth: 0.5, borderColor: markColour });\n page.drawLine({\n start: { x: x - 6, y },\n end: { x: x + 6, y },\n thickness: 0.5,\n color: markColour,\n });\n page.drawLine({\n start: { x, y: y - 6 },\n end: { x, y: y + 6 },\n thickness: 0.5,\n color: markColour,\n });\n }\n }\n\n const profileStream = context.flateStream(metadata.icc, {\n N: 4,\n Alternate: PDFName.of('DeviceCMYK'),\n });\n const profileRef = context.register(profileStream);\n const outputIntent = context.obj({\n Type: PDFName.of('OutputIntent'),\n S: PDFName.of('GTS_PDFX'),\n OutputConditionIdentifier: PDFString.of(options.outputConditionIdentifier ?? 'CMYK'),\n RegistryName: PDFString.of('https://www.color.org'),\n Info: PDFString.of(options.outputConditionIdentifier ?? 'CMYK print condition'),\n DestOutputProfile: profileRef,\n });\n document.catalog.set(PDFName.of('OutputIntents'), context.obj([context.register(outputIntent)]));\n\n const now = new Date().toISOString();\n const xmp = `<?xpacket begin=\"\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n<rdf:Description rdf:about=\"\" xmlns:pdfxid=\"http://www.npes.org/pdfx/ns/id/\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:xmp=\"http://ns.adobe.com/xap/1.0/\" pdfxid:GTS_PDFXVersion=\"PDF/X-4\" xmp:CreateDate=\"${now}\"><dc:title><rdf:Alt><rdf:li xml:lang=\"x-default\">${title.replace(/[<>&]/g, '')}</rdf:li></rdf:Alt></dc:title></rdf:Description>\n</rdf:RDF></x:xmpmeta><?xpacket end=\"w\"?>`;\n const metadataStream = context.flateStream(new TextEncoder().encode(xmp), {\n Type: PDFName.of('Metadata'),\n Subtype: PDFName.of('XML'),\n });\n document.catalog.set(PDFName.of('Metadata'), context.register(metadataStream));\n const infoRef = context.trailerInfo.Info;\n if (infoRef) {\n const infoDict = context.lookup(infoRef, PDFDict);\n infoDict.set(PDFName.of('GTS_PDFXVersion'), PDFString.of('PDF/X-4'));\n infoDict.set(PDFName.of('Trapped'), PDFName.of('False'));\n }\n\n return {\n format: 'pdf',\n mimeType: 'application/pdf',\n data: await document.save({ useObjectStreams: false }),\n standard: 'PDF/X-4',\n colourSpace: 'CMYK',\n rendering,\n outlinedFonts: [...outlinedFonts].sort(),\n unoutlinedFonts: [...unoutlinedFonts].sort(),\n dpi,\n trimWidthPoints,\n trimHeightPoints,\n bleedPoints,\n warnings,\n };\n}\n"],"mappings":";;;;;;;;AAAA,SAAS,aAAa,MAAM,cAAc,YAAY;;;AC6CtD,SAAS,cAAc,QAAwC;AAC7D,SAAO,OAAO;AAAA,IACZ,CAAC,GAAG,OAAO,SAAS,oCAAoC,CAAC,EAAE,IAAI,CAAC,UAAU;AAAA,MACxE,MAAM,CAAC;AAAA,MACP,MAAM,CAAC,KAAK,MAAM,CAAC,KAAK;AAAA,IAC1B,CAAC;AAAA,EACH;AACF;AAEA,SAAS,cAAc,QAAwB;AAC7C,SAAO,OACJ,QAAQ,YAAY,EAAE,EACtB;AAAA,IAAQ;AAAA,IAAoB,CAAC,GAAG,UAC/B,OAAO,cAAc,OAAO,SAAS,OAAO,EAAE,CAAC;AAAA,EACjD,EACC,QAAQ,aAAa,CAAC,GAAG,UAAkB,OAAO,cAAc,OAAO,KAAK,CAAC,CAAC,EAC9E,QAA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WAAO,QAAQ;AAAA,EACjB;AACF;AAEA,eAAe,YACb,QACA,SACA,UAC6B;AAC7B,QAAM,cAAc,KAAK,IAAI,GAAG,KAAK,MAAM,QAAQ,eAAe,CAAC,CAAC;AACpE,QAAM,UAAU,IAAI,MAAwB,OAAO,MAAM;AACzD,MAAI,YAAY;AAChB,QAAM,QAAQ;AAAA,IACZ,MAAM,KAAK,EAAE,QAAQ,KAAK,IAAI,aAAa,OAAO,MAAM,EAAE,GAAG,YAAY;AACvE,aAAO,YAAY,OAAO,QAAQ;AAChC,cAAM,QAAQ;AACd,gBAAQ,KAAK,IAAI,MAAM,SAAS,OAAO,KAAK,GAAG,OAAO;AAAA,MACxD;AAAA,IACF,CAAC;AAAA,EACH;AACA,SAAO;AACT;AAGA,eAAsB,uBACpB,QACA,UAAwD,CAAC,GAC5B;AAC7B,SAAO,YAAY,QAAQ,SAAS,iBAAiB;AACvD;AAGA,eAAsB,uBACpB,QACA,UAAwD,CAAC,GAC5B;AAC7B,SAAO,YAAY,QAAQ,SAAS,iBAAiB;AACvD;","names":["response","renderEditorState"]}
1
+ {"version":3,"sources":["../src/node.ts","../src/print.ts"],"sourcesContent":["import { FabricImage, Rect, StaticCanvas, util } from 'fabric/node';\nimport * as fabricNode from 'fabric/node';\nimport { registerEffects } from '@overtone-art/canvas-editor-effects';\nimport type { FabricObject, ImageFormat } from 'fabric/node';\nimport { computeCoverPlacement, computePrintAreaClip } from './export';\nimport { displaceRgba } from './displacement';\nimport { applyTextWrapToObject } from './text-wrap';\nimport type { EditorState, MockupBlendMode, MockupConfig, MockupDisplacement } from './types';\n\n// Before anything enlivens here: a serialized `Rect` carrying an `effect`\n// must restore as the effect-aware class in this renderer too (D3).\nregisterEffects(fabricNode);\n\nexport { renderPrintPdf } from './print';\n// Fabric-free, so the node entry can carry them: the D11 bench and a server\n// renderer build a state's filters from the same table the browser uses.\nexport { IMAGE_FILTER_PRESETS } from './image-effects/presets';\nexport { imageEffectsFilterSpecs } from './image-effects/specs';\nexport type { PrintPdfOptions, PrintPdfResult } from './print';\n\nexport interface NodeRenderOptions {\n format?: 'png' | 'jpeg' | 'webp' | 'svg';\n multiplier?: number;\n quality?: number;\n /**\n * Gate every image URL referenced by the state before it is loaded. States\n * are authored in the browser and therefore untrusted on a server; the\n * default policy allows only `http:`, `https:` and `data:`. Supply a\n * narrower predicate (e.g. an origin allowlist) to also stop requests to\n * internal hosts.\n */\n allowImageUrl?: (url: string) => boolean;\n}\n\nexport interface NodeRenderResult {\n format: 'png' | 'jpeg' | 'webp' | 'svg';\n mimeType: string;\n data: Uint8Array | string;\n width: number;\n height: number;\n}\n\n// `fabric/node` resolves bare paths and `file:` URLs against the local disk, so\n// an unrestricted state is a local-file-read and SSRF primitive on a server.\nconst ALLOWED_PROTOCOLS = new Set(['http:', 'https:', 'data:']);\n\n/** Keys whose string values are fetched as images during a render. */\nconst URL_KEYS = new Set(['src', 'image']);\n\nfunction defaultAllowImageUrl(url: string): boolean {\n const scheme = /^([a-z][a-z\\d+.-]*):/i.exec(url.trim());\n return scheme !== null && ALLOWED_PROTOCOLS.has(`${scheme[1].toLowerCase()}:`);\n}\n\nfunction assertImageUrlsAllowed(value: unknown, allow: (url: string) => boolean): void {\n if (Array.isArray(value)) {\n for (const item of value) assertImageUrlsAllowed(item, allow);\n return;\n }\n if (!value || typeof value !== 'object') return;\n for (const [key, entry] of Object.entries(value)) {\n if (typeof entry === 'string') {\n if (URL_KEYS.has(key) && !allow(entry)) {\n throw new Error(`Blocked disallowed image URL: ${entry.slice(0, 120)}`);\n }\n } else {\n assertImageUrlsAllowed(entry, allow);\n }\n }\n}\n\nfunction validateState(state: EditorState): void {\n if (\n !state?.canvas ||\n !Array.isArray(state.layers) ||\n !Number.isFinite(state.canvas.width) ||\n !Number.isFinite(state.canvas.height) ||\n state.canvas.width <= 0 ||\n state.canvas.height <= 0\n ) {\n throw new Error('Invalid editor state');\n }\n const major = Number.parseInt(state.version?.split('.')[0] ?? '1', 10);\n if (!Number.isFinite(major) || major > 2) {\n throw new Error(`Unsupported editor state version: ${state.version}`);\n }\n}\n\nfunction dataUrlBytes(dataUrl: string): Uint8Array {\n const encoded = dataUrl.slice(dataUrl.indexOf(',') + 1);\n const binary = atob(encoded);\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);\n return bytes;\n}\n\nfunction validateOptions(options: NodeRenderOptions): Required<NodeRenderOptions> {\n const format = options.format ?? 'png';\n const multiplier = options.multiplier ?? 1;\n const quality = options.quality ?? 1;\n const allowImageUrl = options.allowImageUrl ?? defaultAllowImageUrl;\n if (!Number.isFinite(multiplier) || multiplier <= 0) {\n throw new Error('Render multiplier must be positive');\n }\n if (!Number.isFinite(quality) || quality < 0 || quality > 1) {\n throw new Error('Render quality must be between 0 and 1');\n }\n return { format, multiplier, quality, allowImageUrl };\n}\n\nasync function createStateCanvas(state: EditorState, transparent = false): Promise<StaticCanvas> {\n const canvas = new StaticCanvas(undefined, {\n width: state.canvas.width,\n height: state.canvas.height,\n backgroundColor: transparent ? '' : (state.background ?? ''),\n preserveObjectStacking: true,\n });\n try {\n if (!transparent && state.backgroundImage) {\n canvas.backgroundImage = (\n await util.enlivenObjects([state.backgroundImage])\n )[0] as FabricObject;\n }\n const objects = (await util.enlivenObjects(\n state.layers.map((layer) => layer.fabricObject),\n )) as FabricObject[];\n objects.forEach((object, index) => {\n const layer = state.layers[index];\n object.set({ visible: layer.visible, opacity: layer.opacity });\n // The browser's TextWrapManager derives `wordSplit` and the overflow\n // clip live as the author types; fabric serializes neither the function\n // override nor (when a mask is present) the clip's nested, space-\n // converted placement, so a freshly enlivened object needs the same\n // derivation run once here, or the engine's own print output would\n // differ from what the editor previewed.\n applyTextWrapToObject(object, layer.meta, (options) => new Rect(options));\n canvas.add(object);\n });\n canvas.renderAll();\n return canvas;\n } catch (error) {\n canvas.dispose();\n throw error;\n }\n}\n\nfunction encodeCanvas(\n canvas: StaticCanvas,\n options: Required<NodeRenderOptions>,\n): NodeRenderResult {\n const { format, multiplier, quality } = options;\n const width = Math.round(canvas.getWidth() * multiplier);\n const height = Math.round(canvas.getHeight() * multiplier);\n if (format === 'svg') {\n return { format, mimeType: 'image/svg+xml', data: canvas.toSVG(), width, height };\n }\n const dataUrl = canvas.toDataURL({ format: format as ImageFormat, multiplier, quality });\n return {\n format,\n mimeType: format === 'jpeg' ? 'image/jpeg' : `image/${format}`,\n data: dataUrlBytes(dataUrl),\n width,\n height,\n };\n}\n\nfunction compositeOperation(mode?: MockupBlendMode): GlobalCompositeOperation {\n return !mode || mode === 'normal' ? 'source-over' : mode;\n}\n\nfunction clampOpacity(value = 1): number {\n return Math.max(0, Math.min(1, value));\n}\n\nasync function coverImage(url: string, width: number, height: number): Promise<FabricImage> {\n let image: FabricImage;\n try {\n image = await FabricImage.fromURL(url);\n } catch (error) {\n throw new Error(`Failed to load mockup image: ${url}`, { cause: error });\n }\n const sourceWidth = image.width;\n const sourceHeight = image.height;\n const placement = computeCoverPlacement(sourceWidth, sourceHeight, width, height);\n image.set({\n originX: 'left',\n originY: 'top',\n left: placement.left,\n top: placement.top,\n scaleX: placement.width / sourceWidth,\n scaleY: placement.height / sourceHeight,\n selectable: false,\n evented: false,\n });\n return image;\n}\n\nasync function displacedDesignUrl(\n designCanvas: StaticCanvas,\n displacement: MockupDisplacement,\n width: number,\n height: number,\n): Promise<string> {\n const mapCanvas = new StaticCanvas(undefined, { width, height });\n const warpedCanvas = new StaticCanvas(undefined, { width, height });\n try {\n mapCanvas.add(await coverImage(displacement.image, width, height));\n mapCanvas.renderAll();\n const pixels = displaceRgba(\n designCanvas.getContext().getImageData(0, 0, width, height).data,\n mapCanvas.getContext().getImageData(0, 0, width, height).data,\n width,\n height,\n displacement,\n );\n const imageData = warpedCanvas.getContext().createImageData(width, height);\n imageData.data.set(pixels);\n warpedCanvas.getContext().putImageData(imageData, 0, 0);\n return warpedCanvas.toDataURL({ format: 'png', multiplier: 1 });\n } catch (error) {\n throw new Error('Failed to apply mockup displacement map', { cause: error });\n } finally {\n mapCanvas.dispose();\n warpedCanvas.dispose();\n }\n}\n\n/** Render browser-authored EditorState without a DOM or live editor instance. */\nexport async function renderEditorState(\n state: EditorState,\n options: NodeRenderOptions = {},\n): Promise<NodeRenderResult> {\n validateState(state);\n const resolved = validateOptions(options);\n assertImageUrlsAllowed(state, resolved.allowImageUrl);\n const canvas = await createStateCanvas(state);\n try {\n return encodeCanvas(canvas, resolved);\n } finally {\n canvas.dispose();\n }\n}\n\n/** Render a saved product mockup with the transparent design composited above it. */\nexport async function renderMockupState(\n state: EditorState,\n options: NodeRenderOptions = {},\n): Promise<NodeRenderResult> {\n validateState(state);\n const resolved = validateOptions(options);\n assertImageUrlsAllowed(state, resolved.allowImageUrl);\n if (resolved.format === 'svg') {\n throw new Error('Mockup rendering supports PNG, JPEG, and WebP output');\n }\n const mockup: MockupConfig | null | undefined = state.mockup;\n if (!mockup?.image) throw new Error('No mockup is configured');\n\n const designCanvas = await createStateCanvas(state, true);\n const output = new StaticCanvas(undefined, {\n width: state.canvas.width,\n height: state.canvas.height,\n preserveObjectStacking: true,\n });\n try {\n output.add(await coverImage(mockup.image, state.canvas.width, state.canvas.height));\n\n const designUrl = mockup.displacement\n ? await displacedDesignUrl(\n designCanvas,\n mockup.displacement,\n state.canvas.width,\n state.canvas.height,\n )\n : designCanvas.toDataURL({ format: 'png', multiplier: 1 });\n const design = await FabricImage.fromURL(designUrl);\n design.set({\n originX: 'left',\n originY: 'top',\n left: 0,\n top: 0,\n opacity: clampOpacity(mockup.designOpacity),\n globalCompositeOperation: compositeOperation(mockup.designBlendMode),\n selectable: false,\n evented: false,\n });\n if (mockup.printArea && mockup.clipToPrintArea !== false) {\n const clip = computePrintAreaClip(\n mockup.printArea,\n 1,\n 1,\n state.canvas.width,\n state.canvas.height,\n );\n design.clipPath = new Rect({\n originX: 'left',\n originY: 'top',\n left: clip.left,\n top: clip.top,\n width: clip.width,\n height: clip.height,\n absolutePositioned: true,\n });\n }\n output.add(design);\n\n if (mockup.overlay) {\n const overlay = await coverImage(\n mockup.overlay.image,\n state.canvas.width,\n state.canvas.height,\n );\n overlay.set({\n opacity: clampOpacity(mockup.overlay.opacity),\n globalCompositeOperation: compositeOperation(mockup.overlay.blendMode ?? 'multiply'),\n });\n output.add(overlay);\n }\n output.renderAll();\n return encodeCanvas(output, resolved);\n } finally {\n designCanvas.dispose();\n output.dispose();\n }\n}\n\nasync function renderBatch(\n states: EditorState[],\n options: NodeRenderOptions & { concurrency?: number },\n renderer: (state: EditorState, options: NodeRenderOptions) => Promise<NodeRenderResult>,\n): Promise<NodeRenderResult[]> {\n const concurrency = Math.max(1, Math.floor(options.concurrency ?? 2));\n const results = new Array<NodeRenderResult>(states.length);\n let nextIndex = 0;\n await Promise.all(\n Array.from({ length: Math.min(concurrency, states.length) }, async () => {\n while (nextIndex < states.length) {\n const index = nextIndex++;\n results[index] = await renderer(states[index], options);\n }\n }),\n );\n return results;\n}\n\n/** Render multiple states with bounded concurrency for fulfillment jobs. */\nexport async function renderEditorStateBatch(\n states: EditorState[],\n options: NodeRenderOptions & { concurrency?: number } = {},\n): Promise<NodeRenderResult[]> {\n return renderBatch(states, options, renderEditorState);\n}\n\n/** Render multiple mockup states with bounded concurrency for fulfillment jobs. */\nexport async function renderMockupStateBatch(\n states: EditorState[],\n options: NodeRenderOptions & { concurrency?: number } = {},\n): Promise<NodeRenderResult[]> {\n return renderBatch(states, options, renderMockupState);\n}\n","import type { EditorState } from './types';\nimport type { NodeRenderOptions } from './node';\n\nexport interface PrintPdfOptions {\n /** Rasterization density. Defaults to the document DPI, or 300. */\n dpi?: number;\n /** Bleed on every edge, in inches. Defaults to 0.125in. */\n bleed?: number;\n /** Space outside bleed reserved for printer marks, in inches. Defaults to 0.25in. */\n marksMargin?: number;\n trimMarks?: boolean;\n registrationMarks?: boolean;\n /** Optional safe-area inset in inches for preflight warnings. */\n safeArea?: number;\n /** Sharp built-in `cmyk` profile or an absolute path to a custom ICC profile. */\n iccProfile?: string;\n /** Ceiling on the rasterized bleed image, in pixels. Defaults to 250 megapixels. */\n maxPixels?: number;\n outputConditionIdentifier?: string;\n title?: string;\n allowImageUrl?: NodeRenderOptions['allowImageUrl'];\n /** Preserve SVG shapes/text over a CMYK bleed raster. Defaults to `vector`. */\n rendering?: 'vector' | 'raster';\n /** PDFKit font registrations keyed by the exact SVG font-family name. */\n fontFiles?: Record<string, string | Uint8Array>;\n /** Convert text backed by `fontFiles` into glyph paths. Defaults to true. */\n outlineFonts?: boolean;\n}\n\nexport interface PrintPdfResult {\n format: 'pdf';\n mimeType: 'application/pdf';\n data: Uint8Array;\n standard: 'PDF/X-4';\n colourSpace: 'CMYK';\n rendering: 'vector' | 'raster';\n outlinedFonts: string[];\n unoutlinedFonts: string[];\n dpi: number;\n trimWidthPoints: number;\n trimHeightPoints: number;\n bleedPoints: number;\n warnings: string[];\n}\n\nfunction svgAttributes(source: string): Record<string, string> {\n return Object.fromEntries(\n [...source.matchAll(/([\\w:-]+)=(?:\"([^\"]*)\"|'([^']*)')/g)].map((match) => [\n match[1],\n match[2] ?? match[3] ?? '',\n ]),\n );\n}\n\nfunction decodeXmlText(source: string): string {\n return source\n .replace(/<[^>]+>/g, '')\n .replace(/&#x([\\da-f]+);/gi, (_, value: string) =>\n String.fromCodePoint(Number.parseInt(value, 16)),\n )\n .replace(/&#(\\d+);/g, (_, value: string) => String.fromCodePoint(Number(value)))\n .replace(/&lt;/g, '<')\n .replace(/&gt;/g, '>')\n .replace(/&quot;/g, '\"')\n .replace(/&apos;/g, \"'\")\n .replace(/&amp;/g, '&');\n}\n\nfunction escapeXmlAttribute(value: string): string {\n return value.replace(/[<>&\"']/g, (character) => `&#${character.charCodeAt(0)};`);\n}\n\nfunction fontSource(\n files: Record<string, string | Uint8Array>,\n family: string,\n bold: boolean,\n italic: boolean,\n): string | Uint8Array | undefined {\n const suffix = bold && italic ? '-BoldItalic' : bold ? '-Bold' : italic ? '-Italic' : '';\n // `family` comes from the untrusted SVG, so plain indexing would resolve\n // `__proto__`/`constructor` to inherited members and hand a non-font to fontkit.\n const own = (key: string) =>\n Object.hasOwn(files, key) ? (files[key] as string | Uint8Array) : undefined;\n return own(`${family}${suffix}`) ?? own(family);\n}\n\nasync function outlineSvgText(\n svg: string,\n files: Record<string, string | Uint8Array>,\n outlined: Set<string>,\n): Promise<string> {\n const fontkit = await import('fontkit');\n let output = '';\n let cursor = 0;\n for (const textMatch of svg.matchAll(/<text\\b([^>]*)>([\\s\\S]*?)<\\/text>/gi)) {\n const index = textMatch.index ?? 0;\n output += svg.slice(cursor, index);\n cursor = index + textMatch[0].length;\n const textAttributes = svgAttributes(textMatch[1]);\n const spans = [...textMatch[2].matchAll(/<tspan\\b([^>]*)>([\\s\\S]*?)<\\/tspan>/gi)];\n const lines = spans.length\n ? spans.map((span) => ({ attributes: svgAttributes(span[1]), text: decodeXmlText(span[2]) }))\n : [{ attributes: textAttributes, text: decodeXmlText(textMatch[2]) }];\n const resolved = lines.map((line) => {\n const attributes = { ...textAttributes, ...line.attributes };\n const family = attributes['font-family'] ?? 'sans-serif';\n const bold = /bold|[6-9]00/i.test(attributes['font-weight'] ?? '');\n const italic = /italic|oblique/i.test(attributes['font-style'] ?? '');\n return { ...line, attributes, family, source: fontSource(files, family, bold, italic) };\n });\n if (resolved.some((line) => !line.source)) {\n output += textMatch[0];\n continue;\n }\n const paths: string[] = [];\n for (const line of resolved) {\n const source = line.source!;\n const opened =\n typeof source === 'string'\n ? fontkit.openSync(source)\n : fontkit.create(Buffer.from(source.buffer, source.byteOffset, source.byteLength));\n if (!('layout' in opened)) {\n throw new Error(`Font collection requires a named face: ${line.family}`);\n }\n const size = Number.parseFloat(line.attributes['font-size'] ?? '16');\n const scale = size / opened.unitsPerEm;\n const style = line.attributes.style ?? '';\n const run = opened.layout(line.text);\n let penX = Number.parseFloat(line.attributes.x ?? '0');\n const baseline = Number.parseFloat(line.attributes.y ?? '0');\n run.glyphs.forEach((glyph, glyphIndex) => {\n const position = run.positions[glyphIndex];\n const x = penX + position.xOffset * scale;\n const y = baseline - position.yOffset * scale;\n paths.push(\n `<path d=\"${glyph.path.toSVG()}\" transform=\"translate(${x} ${y}) scale(${scale} ${-scale})\" style=\"${escapeXmlAttribute(style)}\"/>`,\n );\n penX += position.xAdvance * scale;\n });\n outlined.add(line.family);\n }\n output += `<g data-outlined-font=\"${escapeXmlAttribute([...new Set(resolved.map((line) => line.family))].join(','))}\">${paths.join('')}</g>`;\n }\n return output + svg.slice(cursor);\n}\n\nfunction rgbToCmyk([redByte, greenByte, blueByte]: [number, number, number]): [\n number,\n number,\n number,\n number,\n] {\n const red = redByte / 255;\n const green = greenByte / 255;\n const blue = blueByte / 255;\n const black = 1 - Math.max(red, green, blue);\n if (black >= 1) return [0, 0, 0, 100];\n return [\n ((1 - red - black) / (1 - black)) * 100,\n ((1 - green - black) / (1 - black)) * 100,\n ((1 - blue - black) / (1 - black)) * 100,\n black * 100,\n ];\n}\n\nasync function imageSourceBytes(\n source: string,\n allow?: (url: string) => boolean,\n): Promise<Uint8Array> {\n if (source.startsWith('data:')) {\n const response = await fetch(source);\n if (!response.ok) throw new Error('Failed to decode an embedded SVG image');\n return new Uint8Array(await response.arrayBuffer());\n }\n const permitted = allow\n ? allow(source)\n : (() => {\n try {\n return ['http:', 'https:'].includes(new URL(source).protocol);\n } catch {\n return false;\n }\n })();\n if (!permitted) throw new Error(`Blocked disallowed vector image URL: ${source}`);\n const response = await fetch(source);\n if (!response.ok) throw new Error(`Failed to load vector image: ${source}`);\n return new Uint8Array(await response.arrayBuffer());\n}\n\nasync function convertSvgImagesToCmyk(\n svg: string,\n sharp: (typeof import('sharp'))['default'],\n profile: string,\n allow?: (url: string) => boolean,\n): Promise<string> {\n const sources = new Set<string>();\n for (const image of svg.matchAll(/<image\\b[^>]*(?:xlink:href|href)=\"([^\"]+)\"[^>]*>/gi)) {\n if (image[1]) sources.add(image[1]);\n }\n let converted = svg;\n for (const source of sources) {\n const bytes = await imageSourceBytes(source, allow);\n const jpeg = await sharp(bytes)\n .flatten({ background: '#ffffff' })\n .toColourspace('cmyk')\n .withIccProfile(profile)\n .jpeg({ quality: 100, chromaSubsampling: '4:4:4' })\n .toBuffer();\n const dataUrl = `data:image/jpeg;base64,${jpeg.toString('base64')}`;\n converted = converted.split(source).join(dataUrl);\n }\n return converted;\n}\n\nasync function renderVectorOverlay(\n state: EditorState,\n options: PrintPdfOptions,\n width: number,\n height: number,\n sharp: (typeof import('sharp'))['default'],\n warnings: string[],\n outlinedFonts: Set<string>,\n unoutlinedFonts: Set<string>,\n): Promise<Uint8Array> {\n const [{ default: PDFKit }, { default: SVGtoPDF }, { renderEditorState }] = await Promise.all([\n import('pdfkit'),\n import('svg-to-pdfkit'),\n import('./node'),\n ]);\n // The bleed image is already flattened onto white. Render the trim overlay\n // against the same opaque print substrate so semi-transparent artwork does\n // not blend a second time with the raster copy beneath it.\n const rendered = await renderEditorState(\n { ...state, background: '#ffffff' },\n {\n format: 'svg',\n allowImageUrl: options.allowImageUrl,\n },\n );\n if (typeof rendered.data !== 'string') throw new Error('Vector rendering returned raster data');\n const fontFiles = options.fontFiles ?? {};\n const outlinedSvg =\n options.outlineFonts === false\n ? rendered.data\n : await outlineSvgText(rendered.data, fontFiles, outlinedFonts);\n const svg = await convertSvgImagesToCmyk(\n outlinedSvg,\n sharp,\n options.iccProfile ?? 'cmyk',\n options.allowImageUrl,\n );\n const remainingText = [...svg.matchAll(/<text\\b([^>]*)>/gi)].map((match) =>\n svgAttributes(match[1]),\n );\n for (const attributes of remainingText) {\n const family = attributes['font-family'] ?? 'sans-serif';\n unoutlinedFonts.add(family);\n const bold = /bold|[6-9]00/i.test(attributes['font-weight'] ?? '');\n const italic = /italic|oblique/i.test(attributes['font-style'] ?? '');\n if (!fontSource(fontFiles, family, bold, italic)) {\n warnings.push(\n `Font \"${family}\" used a PDF standard fallback; supply fontFiles for exact embedding`,\n );\n }\n }\n\n const document = new PDFKit({ autoFirstPage: false, compress: false, pdfVersion: '1.7' });\n for (const [name, path] of Object.entries(fontFiles)) {\n document.registerFont(name, typeof path === 'string' ? path : Buffer.from(path));\n }\n document.addPage({ size: [width, height], margin: 0 });\n SVGtoPDF(document, svg, 0, 0, {\n width,\n height,\n preserveAspectRatio: 'none',\n colorCallback: (color) => {\n const [rgb, opacity] = color;\n return [rgbToCmyk(rgb), opacity] as unknown as typeof color;\n },\n warningCallback: (warning) => warnings.push(`Vector render: ${warning}`),\n });\n\n return new Promise<Uint8Array>((resolve, reject) => {\n const chunks: Uint8Array[] = [];\n document.on('data', (chunk: Uint8Array) => chunks.push(chunk));\n document.on('error', reject);\n document.on('end', () => resolve(new Uint8Array(Buffer.concat(chunks))));\n document.end();\n });\n}\n\n/** Beyond this no printer is served, and larger values only buy an OOM. */\nconst MAX_DPI = 2400;\n/** ~24×36in at 600dpi. Bounds the raster a hostile state can ask a server for. */\nconst DEFAULT_MAX_PIXELS = 250_000_000;\n\nfunction positive(value: number, label: string): number {\n if (!Number.isFinite(value) || value <= 0) throw new Error(`${label} must be positive`);\n return value;\n}\n\n/**\n * States are browser-authored and untrusted on a server. `documentDpi` divides\n * the render multiplier, so an unvalidated fractional value (0.001) inflates the\n * rasterization by six orders of magnitude before any size check runs.\n */\nfunction boundedDpi(value: number, label: string): number {\n const dpi = positive(value, label);\n if (dpi > MAX_DPI) throw new Error(`${label} must not exceed ${MAX_DPI}`);\n if (dpi < 1) throw new Error(`${label} must be at least 1`);\n return dpi;\n}\n\nfunction nonNegative(value: number, label: string): number {\n if (!Number.isFinite(value) || value < 0) throw new Error(`${label} cannot be negative`);\n return value;\n}\n\nfunction preflightSafeArea(state: EditorState, safePixels: number): string[] {\n if (safePixels <= 0) return [];\n const right = state.canvas.width - safePixels;\n const bottom = state.canvas.height - safePixels;\n const warnings: string[] = [];\n for (const layer of state.layers) {\n if (!layer.visible) continue;\n const object = layer.fabricObject;\n const left = Number(object.left ?? 0);\n const top = Number(object.top ?? 0);\n const width = Number(object.width ?? 0) * Math.abs(Number(object.scaleX ?? 1));\n const height = Number(object.height ?? 0) * Math.abs(Number(object.scaleY ?? 1));\n if (left < safePixels || top < safePixels || left + width > right || top + height > bottom) {\n warnings.push(`Layer \"${layer.name}\" extends outside the configured safe area`);\n }\n }\n return warnings;\n}\n\n/**\n * Render an EditorState into a print-production PDF/X-4 file.\n *\n * The design is rasterized at the requested density, converted through Sharp's\n * CMYK ICC pipeline, edge-extended into bleed, and embedded with output intent,\n * trim/bleed boxes, XMP identification, and optional printer marks.\n */\nexport async function renderPrintPdf(\n state: EditorState,\n options: PrintPdfOptions = {},\n): Promise<PrintPdfResult> {\n const dpi = boundedDpi(options.dpi ?? state.canvas.dpi ?? 300, 'Print DPI');\n const documentDpi = boundedDpi(state.canvas.dpi ?? 72, 'Document DPI');\n const maxPixels = positive(options.maxPixels ?? DEFAULT_MAX_PIXELS, 'Max pixels');\n const bleedInches = nonNegative(options.bleed ?? 0.125, 'Bleed');\n const marksMarginInches = nonNegative(options.marksMargin ?? 0.25, 'Marks margin');\n const safeAreaInches = nonNegative(options.safeArea ?? 0, 'Safe area');\n const rendering = options.rendering ?? 'vector';\n const bleedPixels = Math.round(bleedInches * dpi);\n const trimWidthPoints = (state.canvas.width / documentDpi) * 72;\n const trimHeightPoints = (state.canvas.height / documentDpi) * 72;\n const bleedPoints = bleedInches * 72;\n const marksMarginPoints = marksMarginInches * 72;\n\n const scale = dpi / documentDpi;\n const outputPixels =\n Math.round(state.canvas.width * scale + bleedPixels * 2) *\n Math.round(state.canvas.height * scale + bleedPixels * 2);\n if (!Number.isFinite(outputPixels) || outputPixels > maxPixels) {\n throw new Error(\n `Print raster of ${outputPixels} pixels exceeds the ${maxPixels} pixel budget; lower the DPI or raise maxPixels`,\n );\n }\n\n const [{ default: sharp }, pdfLib] = await Promise.all([import('sharp'), import('pdf-lib')]);\n // Keep the optional print entry free of a static cycle with `node.ts`, which\n // re-exports this function as part of the Node-only public surface.\n const { renderEditorState } = await import('./node');\n const rendered = await renderEditorState(state, {\n format: 'png',\n multiplier: scale,\n allowImageUrl: options.allowImageUrl,\n });\n if (typeof rendered.data === 'string') throw new Error('Print rasterization returned SVG data');\n\n let pipeline = sharp(rendered.data).flatten({ background: '#ffffff' });\n if (bleedPixels > 0) {\n pipeline = pipeline.extend({\n top: bleedPixels,\n right: bleedPixels,\n bottom: bleedPixels,\n left: bleedPixels,\n extendWith: 'copy',\n });\n }\n const { data: cmykJpeg, info } = await pipeline\n .toColourspace('cmyk')\n .withIccProfile(options.iccProfile ?? 'cmyk')\n .withDensity(dpi)\n .jpeg({ quality: 100, chromaSubsampling: '4:4:4' })\n .toBuffer({ resolveWithObject: true });\n const metadata = await sharp(cmykJpeg).metadata();\n if (info.channels !== 4 || metadata.space !== 'cmyk' || !metadata.icc) {\n throw new Error('CMYK conversion did not produce a four-channel image with an ICC profile');\n }\n\n const { PDFDocument, PDFDict, PDFName, PDFString, cmyk } = pdfLib;\n const document = await PDFDocument.create();\n const title = options.title ?? 'Overtone Canvas Editor print export';\n document.setTitle(title);\n document.setCreator('@overtone-art/canvas-editor-core');\n document.setProducer('@overtone-art/canvas-editor-core');\n const pageWidth = trimWidthPoints + bleedPoints * 2 + marksMarginPoints * 2;\n const pageHeight = trimHeightPoints + bleedPoints * 2 + marksMarginPoints * 2;\n const page = document.addPage([pageWidth, pageHeight]);\n const image = await document.embedJpg(cmykJpeg);\n page.drawImage(image, {\n x: marksMarginPoints,\n y: marksMarginPoints,\n width: trimWidthPoints + bleedPoints * 2,\n height: trimHeightPoints + bleedPoints * 2,\n });\n\n const trimLeft = marksMarginPoints + bleedPoints;\n const trimBottom = marksMarginPoints + bleedPoints;\n const trimRight = trimLeft + trimWidthPoints;\n const trimTop = trimBottom + trimHeightPoints;\n const warnings = preflightSafeArea(state, safeAreaInches * documentDpi);\n const outlinedFonts = new Set<string>();\n const unoutlinedFonts = new Set<string>();\n if (rendering === 'vector') {\n const vectorPdf = await renderVectorOverlay(\n state,\n options,\n trimWidthPoints,\n trimHeightPoints,\n sharp,\n warnings,\n outlinedFonts,\n unoutlinedFonts,\n );\n const [vectorPage] = await document.embedPdf(vectorPdf);\n page.drawPage(vectorPage, {\n x: trimLeft,\n y: trimBottom,\n width: trimWidthPoints,\n height: trimHeightPoints,\n });\n }\n const bleedLeft = marksMarginPoints;\n const bleedBottom = marksMarginPoints;\n const bleedRight = pageWidth - marksMarginPoints;\n const bleedTop = pageHeight - marksMarginPoints;\n const context = document.context;\n page.node.set(PDFName.of('TrimBox'), context.obj([trimLeft, trimBottom, trimRight, trimTop]));\n page.node.set(\n PDFName.of('BleedBox'),\n context.obj([bleedLeft, bleedBottom, bleedRight, bleedTop]),\n );\n page.node.set(PDFName.of('ArtBox'), context.obj([trimLeft, trimBottom, trimRight, trimTop]));\n\n const markColour = cmyk(0, 0, 0, 1);\n if (options.trimMarks !== false) {\n const offset = Math.max(3, bleedPoints / 2);\n const length = Math.max(9, marksMarginPoints - 3);\n for (const x of [trimLeft, trimRight]) {\n page.drawLine({\n start: { x, y: trimBottom - offset },\n end: { x, y: trimBottom - offset - length },\n thickness: 0.5,\n color: markColour,\n });\n page.drawLine({\n start: { x, y: trimTop + offset },\n end: { x, y: trimTop + offset + length },\n thickness: 0.5,\n color: markColour,\n });\n }\n for (const y of [trimBottom, trimTop]) {\n page.drawLine({\n start: { x: trimLeft - offset, y },\n end: { x: trimLeft - offset - length, y },\n thickness: 0.5,\n color: markColour,\n });\n page.drawLine({\n start: { x: trimRight + offset, y },\n end: { x: trimRight + offset + length, y },\n thickness: 0.5,\n color: markColour,\n });\n }\n }\n if (options.registrationMarks !== false) {\n for (const [x, y] of [\n [pageWidth / 2, marksMarginPoints / 2],\n [pageWidth / 2, pageHeight - marksMarginPoints / 2],\n [marksMarginPoints / 2, pageHeight / 2],\n [pageWidth - marksMarginPoints / 2, pageHeight / 2],\n ] as Array<[number, number]>) {\n page.drawCircle({ x, y, size: 4, borderWidth: 0.5, borderColor: markColour });\n page.drawLine({\n start: { x: x - 6, y },\n end: { x: x + 6, y },\n thickness: 0.5,\n color: markColour,\n });\n page.drawLine({\n start: { x, y: y - 6 },\n end: { x, y: y + 6 },\n thickness: 0.5,\n color: markColour,\n });\n }\n }\n\n const profileStream = context.flateStream(metadata.icc, {\n N: 4,\n Alternate: PDFName.of('DeviceCMYK'),\n });\n const profileRef = context.register(profileStream);\n const outputIntent = context.obj({\n Type: PDFName.of('OutputIntent'),\n S: PDFName.of('GTS_PDFX'),\n OutputConditionIdentifier: PDFString.of(options.outputConditionIdentifier ?? 'CMYK'),\n RegistryName: PDFString.of('https://www.color.org'),\n Info: PDFString.of(options.outputConditionIdentifier ?? 'CMYK print condition'),\n DestOutputProfile: profileRef,\n });\n document.catalog.set(PDFName.of('OutputIntents'), context.obj([context.register(outputIntent)]));\n\n const now = new Date().toISOString();\n const xmp = `<?xpacket begin=\"\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n<rdf:Description rdf:about=\"\" xmlns:pdfxid=\"http://www.npes.org/pdfx/ns/id/\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:xmp=\"http://ns.adobe.com/xap/1.0/\" pdfxid:GTS_PDFXVersion=\"PDF/X-4\" xmp:CreateDate=\"${now}\"><dc:title><rdf:Alt><rdf:li xml:lang=\"x-default\">${title.replace(/[<>&]/g, '')}</rdf:li></rdf:Alt></dc:title></rdf:Description>\n</rdf:RDF></x:xmpmeta><?xpacket end=\"w\"?>`;\n const metadataStream = context.flateStream(new TextEncoder().encode(xmp), {\n Type: PDFName.of('Metadata'),\n Subtype: PDFName.of('XML'),\n });\n document.catalog.set(PDFName.of('Metadata'), context.register(metadataStream));\n const infoRef = context.trailerInfo.Info;\n if (infoRef) {\n const infoDict = context.lookup(infoRef, PDFDict);\n infoDict.set(PDFName.of('GTS_PDFXVersion'), PDFString.of('PDF/X-4'));\n infoDict.set(PDFName.of('Trapped'), PDFName.of('False'));\n }\n\n return {\n format: 'pdf',\n mimeType: 'application/pdf',\n data: await document.save({ useObjectStreams: false }),\n standard: 'PDF/X-4',\n colourSpace: 'CMYK',\n rendering,\n outlinedFonts: [...outlinedFonts].sort(),\n unoutlinedFonts: [...unoutlinedFonts].sort(),\n dpi,\n trimWidthPoints,\n trimHeightPoints,\n bleedPoints,\n warnings,\n };\n}\n"],"mappings":";;;;;;;;;;AAAA,SAAS,aAAa,MAAM,cAAc,YAAY;AACtD,YAAY,gBAAgB;AAC5B,SAAS,uBAAuB;;;AC2ChC,SAAS,cAAc,QAAwC;AAC7D,SAAO,OAAO;AAAA,IACZ,CAAC,GAAG,OAAO,SAAS,oCAAoC,CAAC,EAAE,IAAI,CAAC,UAAU;AAAA,MACxE,MAAM,CAAC;AAAA,MACP,MAAM,CAAC,KAAK,MAAM,CAAC,KAAK;AAAA,IAC1B,CAAC;AAAA,EACH;AACF;AAEA,SAAS,cAAc,QAAwB;AAC7C,SAAO,OACJ,QAAQ,YAAY,EAAE,EACtB;AAAA,IAAQ;AAAA,IAAoB,CAAC,GAAG,UAC/B,OAAO,cAAc,OAAO,SAAS,OAAO,EAAE,CAAC;AAAA,EACjD,EACC,QAAQ,aAAa,CAAC,GAAG,UAAkB,OAAO,cAAc,OAAO,KAAK,CAAC,CAAC,EAC9E,QAAQ,SAAS,GAAG,EACpB,QAAQ,SAAS,GAAG,EACpB,QAAQ,WAAW,GAAG,EACtB,QAAQ,WAAW,GAAG,EACtB,QAAQ,UAAU,GAAG;AAC1B;AAEA,SAAS,mBAAmB,OAAuB;AACjD,SAAO,MAAM,QAAQ,YAAY,CAAC,cAAc,KAAK,UAAU,WAAW,CAAC,CAAC,GAAG;AACjF;AAEA,SAAS,WACP,OACA,QACA,MACA,QACiC;AACjC,QAAM,SAAS,QAAQ,SAAS,gBAAgB,OAAO,UAAU,SAAS,YAAY;AAGtF,QAAM,MAAM,CAAC,QACX,OAAO,OAAO,OAAO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AAQ,KAAK,IAAI,MAAM,SAAS,OAAO,KAAK,GAAG,OAAO;AAAA,MACxD;AAAA,IACF,CAAC;AAAA,EACH;AACA,SAAO;AACT;AAGA,eAAsB,uBACpB,QACA,UAAwD,CAAC,GAC5B;AAC7B,SAAO,YAAY,QAAQ,SAAS,iBAAiB;AACvD;AAGA,eAAsB,uBACpB,QACA,UAAwD,CAAC,GAC5B;AAC7B,SAAO,YAAY,QAAQ,SAAS,iBAAiB;AACvD;","names":["response","renderEditorState"]}
@@ -1,5 +1,56 @@
1
1
  import { FabricObject, Gradient } from 'fabric';
2
2
 
3
+ /** The eighteen Adjust controls. Neutral is 0; ranges are pinned in `ADJUST_RANGES`. */
4
+ interface ImageAdjust {
5
+ temperature: number;
6
+ tint: number;
7
+ brightness: number;
8
+ contrast: number;
9
+ highlights: number;
10
+ shadows: number;
11
+ whites: number;
12
+ blacks: number;
13
+ invert: number;
14
+ vibrance: number;
15
+ saturation: number;
16
+ hue: number;
17
+ sharpness: number;
18
+ clarity: number;
19
+ vignette: number;
20
+ blur: number;
21
+ noise: number;
22
+ pixelate: number;
23
+ }
24
+ declare const ADJUST_KEYS: readonly ["temperature", "tint", "brightness", "contrast", "highlights", "shadows", "whites", "blacks", "invert", "vibrance", "saturation", "hue", "sharpness", "clarity", "vignette", "blur", "noise", "pixelate"];
25
+ declare const NEUTRAL_ADJUST: ImageAdjust;
26
+ /** [-1, 1] unless listed here. `invert` is 0 or 1. */
27
+ declare const ADJUST_RANGES: Partial<Record<keyof ImageAdjust, [number, number]>>;
28
+ type ImageFilterPresetId = 'original' | 'black-white' | 'sepia' | 'fade' | 'vivid' | 'fuchsia' | 'cool' | 'warm' | 'duotone' | 'nashville' | 'valencia' | 'clarendon' | 'reyes' | 'lark' | 'juno';
29
+ interface ImageFilterPreset {
30
+ id: ImageFilterPresetId;
31
+ name: string;
32
+ version: number;
33
+ /** Starting slider values; they stay editable after the pick. */
34
+ adjust: Partial<ImageAdjust>;
35
+ /** Optional 20-entry ColorMatrix applied FIRST. */
36
+ matrix?: number[];
37
+ }
38
+ /** Alpha stretched from `low..high` to `0..255`; the identity window (0, 255) means no clip. */
39
+ interface ImageAlphaClip {
40
+ low: number;
41
+ high: number;
42
+ }
43
+ interface ImageEffectsState {
44
+ preset?: {
45
+ id: ImageFilterPresetId;
46
+ version: number;
47
+ };
48
+ adjust: Partial<ImageAdjust>;
49
+ alphaClip?: ImageAlphaClip;
50
+ }
51
+ /** Long edge, in px, above which the on-canvas image filters a downscaled proxy (D5). */
52
+ declare const IMAGE_PROXY_MAX_EDGE = 2048;
53
+
3
54
  /**
4
55
  * Layer blend modes — the seventeen the canvas can composite natively, verified
5
56
  * identical in the browser and in node-canvas 3.2.3.
@@ -140,10 +191,23 @@ interface LayerMeta {
140
191
  wrapWidth?: number;
141
192
  /** Layer resizes uniformly: single-axis handles are hidden. */
142
193
  lockAspect?: boolean;
194
+ /** Filter presets and adjustments an image layer's filter array is derived from. */
195
+ imageEffects?: ImageEffectsState;
196
+ /** Identity and parameters of a parametric shape layer (see `ShapeManager`). */
197
+ shape?: ShapeState;
198
+ /** One layer effect: the authoring record behind the native props or the `effect` prop. */
199
+ effect?: LayerEffectState;
143
200
  [key: string]: unknown;
144
201
  }
145
- /** Shape the baseline follows. The two are alternatives, never combined. */
146
- type TextCurveShape = 'arc' | 'wave';
202
+ type LayerEffectKind = 'none' | 'outline' | 'hollow' | 'drop' | 'splice' | 'echo' | 'background';
203
+ /** Authoring record of an effect. The print truth is the fabric object (D1). */
204
+ interface LayerEffectState {
205
+ kind: LayerEffectKind;
206
+ params: Record<string, number | string>;
207
+ version: 1;
208
+ }
209
+ /** Shape the baseline follows. They are alternatives, never combined. */
210
+ type TextCurveShape = 'arc' | 'wave' | 'angle';
147
211
  interface TextCurveConfig {
148
212
  /**
149
213
  * Which of the two shapes is live. The parameters of the other one are kept
@@ -171,6 +235,8 @@ interface TextCurveConfig {
171
235
  * them tighter round a smaller circle.
172
236
  */
173
237
  centerOffset: number;
238
+ /** Slope of a straight baseline, in degrees, −80…80. Positive rises to the right. `angle` only. */
239
+ angle: number;
174
240
  }
175
241
  /**
176
242
  * A curve as authored: every field optional, missing ones fall back to the
@@ -272,6 +338,8 @@ interface EditorConfig {
272
338
  unit?: Unit;
273
339
  dpi?: number;
274
340
  fonts?: FontDefinition[];
341
+ /** Plugins whose layers may be restored from a saved state; registered on boot. */
342
+ shapes?: ShapePlugin[];
275
343
  license?: LicenseConfig;
276
344
  }
277
345
  type ExportFormat = 'png' | 'jpeg' | 'webp' | 'svg' | 'json';
@@ -346,16 +414,6 @@ interface DpiIssue {
346
414
  effectiveDpi: number;
347
415
  minimumDpi: number;
348
416
  }
349
- interface ImageAdjustments {
350
- /** Range -1 to 1. */
351
- brightness?: number;
352
- /** Range -1 to 1. */
353
- contrast?: number;
354
- /** Range -1 to 1. */
355
- saturation?: number;
356
- /** Range 0 to 1. */
357
- blur?: number;
358
- }
359
417
  interface FontDefinition {
360
418
  family: string;
361
419
  /** URL, data URL, or a complete CSS FontFace source such as `local(...)`. */
@@ -445,11 +503,32 @@ interface ImageProvider {
445
503
  /** Called immediately before a provider asset is inserted into the design. */
446
504
  trackUse?(image: ImageProviderResult): Promise<void>;
447
505
  }
506
+ /** One editable geometry knob of a shape plugin. */
507
+ interface ShapeParamDef {
508
+ key: string;
509
+ min: number;
510
+ max: number;
511
+ step: number;
512
+ default: number;
513
+ }
514
+ /** Authoring record of a parametric shape layer (`meta.shape`). */
515
+ interface ShapeState {
516
+ id: string;
517
+ params: Record<string, number>;
518
+ version: 1;
519
+ }
448
520
  interface ShapePlugin {
449
521
  name: string;
450
522
  icon: string;
451
523
  category?: string;
524
+ /** `options.params` carries parameter overrides; the rest are fabric options. */
452
525
  create(options?: Record<string, unknown>): FabricObject;
526
+ /** Editable geometry parameters. A plugin without any is a fixed silhouette. */
527
+ params?: ShapeParamDef[];
528
+ /** Rebuild the object's geometry in place for new parameters, at its current box. */
529
+ regenerate?(object: FabricObject, params: Record<string, number>): void;
530
+ /** Re-solve geometry after a non-uniform scale instead of stretching it (arrows). */
531
+ bakesScale?: boolean;
453
532
  }
454
533
  interface TemplateParameter {
455
534
  key: string;
@@ -691,4 +770,23 @@ interface EditorEvents {
691
770
  };
692
771
  }
693
772
 
694
- export { type ProjectState as $, type MaskPresetId as A, BLEND_GROUPS as B, type CanvasSizePreset as C, DEFAULT_GRADIENT_CONFIG as D, type EditorConfig as E, type FileAdapter as F, type GradientBox as G, type MaskRefinementPrompt as H, type ImageAdjustments as I, type MaskRefinementProvider as J, type MaskRefinementRequest as K, type LayerData as L, type MaskBrushOptions as M, type MaskRefinementResult as N, type MockupBlendMode as O, type MockupConfig as P, type MockupDisplacement as Q, type MockupDisplacementChannel as R, type MockupOverlay as S, type MockupPrintArea as T, type NormalizedLayerPosition as U, type PatternConfig as V, type PatternLocks as W, type PatternState as X, type PositioningAdapter as Y, type PrintifyPositioning as Z, type ProjectPage as _, BLEND_MODES as a, type ResizeOptions as a0, type SemanticExportOptions as a1, type SerializedBackgroundImageOptions as a2, type SerializedLayer as a3, type ShapeMaskPresetId as a4, type ShapePlugin as a5, type SvgExportOptions as a6, type TemplateDefinition as a7, type TemplateParameter as a8, type TextCurveConfig as a9, type TextCurveInput as aa, type TextCurveShape as ab, type TextOverflow as ac, type TextWrapMode as ad, type TextureMaskPresetId as ae, type TileMode as af, type Unit as ag, angleFromCoords as ah, blendModeLabel as ai, blendModeOf as aj, blendOperation as ak, linearCoords as al, readGradientConfig as am, toFabricGradient as an, type BackgroundImageOptions as b, type BlendMode as c, DEFAULT_PATTERN_CONFIG as d, type DpiIssue as e, type EditorEvents as f, type EditorState as g, type ExportFormat as h, type FontDefinition as i, type GradientConfig as j, type GradientKind as k, type GradientStop as l, type ImageAttribution as m, type ImageProvider as n, type ImageProviderResult as o, type ImageSearchOptions as p, type ImageSearchResult as q, type LayerMaskEntry as r, type LayerMaskMode as s, type LayerMeta as t, type LayerShadowConfig as u, type LayerType as v, type LicenseConfig as w, type LicensePayload as x, type LicenseStatus as y, type MaskPoint as z };
773
+ declare const IMAGE_FILTER_PRESETS: readonly ImageFilterPreset[];
774
+ declare function imageFilterPreset(id: string): ImageFilterPreset | undefined;
775
+
776
+ /** A serialized fabric filter: what `filter.toObject()` returns, and what `enlivenObjects` takes. */
777
+ type FilterSpec = {
778
+ type: string;
779
+ } & Record<string, unknown>;
780
+ declare function clampAdjust(adjust: Partial<ImageAdjust>): Partial<ImageAdjust>;
781
+ declare function clampAlphaClip(clip: Partial<ImageAlphaClip> | undefined): ImageAlphaClip | undefined;
782
+ /**
783
+ * The matrix the studio's alpha clip has always used; `colorsOnly: false` makes
784
+ * the 2D path honour row four.
785
+ */
786
+ declare function alphaClipMatrix({ low, high }: ImageAlphaClip): number[];
787
+ /** State → serialized filters in the D5 order. Neutral controls emit nothing. */
788
+ declare function imageEffectsFilterSpecs(state: ImageEffectsState): FilterSpec[];
789
+ /** Read a layer's state off its meta, lifting the pre-release `imageAdjustments` shape once. */
790
+ declare function normalizeImageEffects(meta: Record<string, unknown>): ImageEffectsState;
791
+
792
+ export { type MockupDisplacement as $, ADJUST_KEYS as A, BLEND_GROUPS as B, type CanvasSizePreset as C, DEFAULT_GRADIENT_CONFIG as D, type EditorConfig as E, type FileAdapter as F, type GradientBox as G, type LayerEffectState as H, IMAGE_FILTER_PRESETS as I, type LayerMaskEntry as J, type LayerMaskMode as K, type LayerData as L, type LayerMeta as M, type LayerShadowConfig as N, type LayerType as O, type LicenseConfig as P, type LicensePayload as Q, type LicenseStatus as R, type MaskBrushOptions as S, type MaskPoint as T, type MaskPresetId as U, type MaskRefinementPrompt as V, type MaskRefinementProvider as W, type MaskRefinementRequest as X, type MaskRefinementResult as Y, type MockupBlendMode as Z, type MockupConfig as _, ADJUST_RANGES as a, type MockupDisplacementChannel as a0, type MockupOverlay as a1, type MockupPrintArea as a2, NEUTRAL_ADJUST as a3, type NormalizedLayerPosition as a4, type PatternConfig as a5, type PatternLocks as a6, type PatternState as a7, type PositioningAdapter as a8, type PrintifyPositioning as a9, clampAdjust as aA, clampAlphaClip as aB, imageEffectsFilterSpecs as aC, imageFilterPreset as aD, linearCoords as aE, normalizeImageEffects as aF, readGradientConfig as aG, toFabricGradient as aH, type ProjectPage as aa, type ProjectState as ab, type ResizeOptions as ac, type SemanticExportOptions as ad, type SerializedBackgroundImageOptions as ae, type SerializedLayer as af, type ShapeMaskPresetId as ag, type ShapeParamDef as ah, type ShapePlugin as ai, type ShapeState as aj, type SvgExportOptions as ak, type TemplateDefinition as al, type TemplateParameter as am, type TextCurveConfig as an, type TextCurveInput as ao, type TextCurveShape as ap, type TextOverflow as aq, type TextWrapMode as ar, type TextureMaskPresetId as as, type TileMode as at, type Unit as au, alphaClipMatrix as av, angleFromCoords as aw, blendModeLabel as ax, blendModeOf as ay, blendOperation as az, BLEND_MODES as b, type BackgroundImageOptions as c, type BlendMode as d, DEFAULT_PATTERN_CONFIG as e, type DpiIssue as f, type EditorEvents as g, type EditorState as h, type ExportFormat as i, type FilterSpec as j, type FontDefinition as k, type GradientConfig as l, type GradientKind as m, type GradientStop as n, IMAGE_PROXY_MAX_EDGE as o, type ImageAdjust as p, type ImageAlphaClip as q, type ImageAttribution as r, type ImageEffectsState as s, type ImageFilterPreset as t, type ImageFilterPresetId as u, type ImageProvider as v, type ImageProviderResult as w, type ImageSearchOptions as x, type ImageSearchResult as y, type LayerEffectKind as z };
@@ -1,5 +1,56 @@
1
1
  import { FabricObject, Gradient } from 'fabric';
2
2
 
3
+ /** The eighteen Adjust controls. Neutral is 0; ranges are pinned in `ADJUST_RANGES`. */
4
+ interface ImageAdjust {
5
+ temperature: number;
6
+ tint: number;
7
+ brightness: number;
8
+ contrast: number;
9
+ highlights: number;
10
+ shadows: number;
11
+ whites: number;
12
+ blacks: number;
13
+ invert: number;
14
+ vibrance: number;
15
+ saturation: number;
16
+ hue: number;
17
+ sharpness: number;
18
+ clarity: number;
19
+ vignette: number;
20
+ blur: number;
21
+ noise: number;
22
+ pixelate: number;
23
+ }
24
+ declare const ADJUST_KEYS: readonly ["temperature", "tint", "brightness", "contrast", "highlights", "shadows", "whites", "blacks", "invert", "vibrance", "saturation", "hue", "sharpness", "clarity", "vignette", "blur", "noise", "pixelate"];
25
+ declare const NEUTRAL_ADJUST: ImageAdjust;
26
+ /** [-1, 1] unless listed here. `invert` is 0 or 1. */
27
+ declare const ADJUST_RANGES: Partial<Record<keyof ImageAdjust, [number, number]>>;
28
+ type ImageFilterPresetId = 'original' | 'black-white' | 'sepia' | 'fade' | 'vivid' | 'fuchsia' | 'cool' | 'warm' | 'duotone' | 'nashville' | 'valencia' | 'clarendon' | 'reyes' | 'lark' | 'juno';
29
+ interface ImageFilterPreset {
30
+ id: ImageFilterPresetId;
31
+ name: string;
32
+ version: number;
33
+ /** Starting slider values; they stay editable after the pick. */
34
+ adjust: Partial<ImageAdjust>;
35
+ /** Optional 20-entry ColorMatrix applied FIRST. */
36
+ matrix?: number[];
37
+ }
38
+ /** Alpha stretched from `low..high` to `0..255`; the identity window (0, 255) means no clip. */
39
+ interface ImageAlphaClip {
40
+ low: number;
41
+ high: number;
42
+ }
43
+ interface ImageEffectsState {
44
+ preset?: {
45
+ id: ImageFilterPresetId;
46
+ version: number;
47
+ };
48
+ adjust: Partial<ImageAdjust>;
49
+ alphaClip?: ImageAlphaClip;
50
+ }
51
+ /** Long edge, in px, above which the on-canvas image filters a downscaled proxy (D5). */
52
+ declare const IMAGE_PROXY_MAX_EDGE = 2048;
53
+
3
54
  /**
4
55
  * Layer blend modes — the seventeen the canvas can composite natively, verified
5
56
  * identical in the browser and in node-canvas 3.2.3.
@@ -140,10 +191,23 @@ interface LayerMeta {
140
191
  wrapWidth?: number;
141
192
  /** Layer resizes uniformly: single-axis handles are hidden. */
142
193
  lockAspect?: boolean;
194
+ /** Filter presets and adjustments an image layer's filter array is derived from. */
195
+ imageEffects?: ImageEffectsState;
196
+ /** Identity and parameters of a parametric shape layer (see `ShapeManager`). */
197
+ shape?: ShapeState;
198
+ /** One layer effect: the authoring record behind the native props or the `effect` prop. */
199
+ effect?: LayerEffectState;
143
200
  [key: string]: unknown;
144
201
  }
145
- /** Shape the baseline follows. The two are alternatives, never combined. */
146
- type TextCurveShape = 'arc' | 'wave';
202
+ type LayerEffectKind = 'none' | 'outline' | 'hollow' | 'drop' | 'splice' | 'echo' | 'background';
203
+ /** Authoring record of an effect. The print truth is the fabric object (D1). */
204
+ interface LayerEffectState {
205
+ kind: LayerEffectKind;
206
+ params: Record<string, number | string>;
207
+ version: 1;
208
+ }
209
+ /** Shape the baseline follows. They are alternatives, never combined. */
210
+ type TextCurveShape = 'arc' | 'wave' | 'angle';
147
211
  interface TextCurveConfig {
148
212
  /**
149
213
  * Which of the two shapes is live. The parameters of the other one are kept
@@ -171,6 +235,8 @@ interface TextCurveConfig {
171
235
  * them tighter round a smaller circle.
172
236
  */
173
237
  centerOffset: number;
238
+ /** Slope of a straight baseline, in degrees, −80…80. Positive rises to the right. `angle` only. */
239
+ angle: number;
174
240
  }
175
241
  /**
176
242
  * A curve as authored: every field optional, missing ones fall back to the
@@ -272,6 +338,8 @@ interface EditorConfig {
272
338
  unit?: Unit;
273
339
  dpi?: number;
274
340
  fonts?: FontDefinition[];
341
+ /** Plugins whose layers may be restored from a saved state; registered on boot. */
342
+ shapes?: ShapePlugin[];
275
343
  license?: LicenseConfig;
276
344
  }
277
345
  type ExportFormat = 'png' | 'jpeg' | 'webp' | 'svg' | 'json';
@@ -346,16 +414,6 @@ interface DpiIssue {
346
414
  effectiveDpi: number;
347
415
  minimumDpi: number;
348
416
  }
349
- interface ImageAdjustments {
350
- /** Range -1 to 1. */
351
- brightness?: number;
352
- /** Range -1 to 1. */
353
- contrast?: number;
354
- /** Range -1 to 1. */
355
- saturation?: number;
356
- /** Range 0 to 1. */
357
- blur?: number;
358
- }
359
417
  interface FontDefinition {
360
418
  family: string;
361
419
  /** URL, data URL, or a complete CSS FontFace source such as `local(...)`. */
@@ -445,11 +503,32 @@ interface ImageProvider {
445
503
  /** Called immediately before a provider asset is inserted into the design. */
446
504
  trackUse?(image: ImageProviderResult): Promise<void>;
447
505
  }
506
+ /** One editable geometry knob of a shape plugin. */
507
+ interface ShapeParamDef {
508
+ key: string;
509
+ min: number;
510
+ max: number;
511
+ step: number;
512
+ default: number;
513
+ }
514
+ /** Authoring record of a parametric shape layer (`meta.shape`). */
515
+ interface ShapeState {
516
+ id: string;
517
+ params: Record<string, number>;
518
+ version: 1;
519
+ }
448
520
  interface ShapePlugin {
449
521
  name: string;
450
522
  icon: string;
451
523
  category?: string;
524
+ /** `options.params` carries parameter overrides; the rest are fabric options. */
452
525
  create(options?: Record<string, unknown>): FabricObject;
526
+ /** Editable geometry parameters. A plugin without any is a fixed silhouette. */
527
+ params?: ShapeParamDef[];
528
+ /** Rebuild the object's geometry in place for new parameters, at its current box. */
529
+ regenerate?(object: FabricObject, params: Record<string, number>): void;
530
+ /** Re-solve geometry after a non-uniform scale instead of stretching it (arrows). */
531
+ bakesScale?: boolean;
453
532
  }
454
533
  interface TemplateParameter {
455
534
  key: string;
@@ -691,4 +770,23 @@ interface EditorEvents {
691
770
  };
692
771
  }
693
772
 
694
- export { type ProjectState as $, type MaskPresetId as A, BLEND_GROUPS as B, type CanvasSizePreset as C, DEFAULT_GRADIENT_CONFIG as D, type EditorConfig as E, type FileAdapter as F, type GradientBox as G, type MaskRefinementPrompt as H, type ImageAdjustments as I, type MaskRefinementProvider as J, type MaskRefinementRequest as K, type LayerData as L, type MaskBrushOptions as M, type MaskRefinementResult as N, type MockupBlendMode as O, type MockupConfig as P, type MockupDisplacement as Q, type MockupDisplacementChannel as R, type MockupOverlay as S, type MockupPrintArea as T, type NormalizedLayerPosition as U, type PatternConfig as V, type PatternLocks as W, type PatternState as X, type PositioningAdapter as Y, type PrintifyPositioning as Z, type ProjectPage as _, BLEND_MODES as a, type ResizeOptions as a0, type SemanticExportOptions as a1, type SerializedBackgroundImageOptions as a2, type SerializedLayer as a3, type ShapeMaskPresetId as a4, type ShapePlugin as a5, type SvgExportOptions as a6, type TemplateDefinition as a7, type TemplateParameter as a8, type TextCurveConfig as a9, type TextCurveInput as aa, type TextCurveShape as ab, type TextOverflow as ac, type TextWrapMode as ad, type TextureMaskPresetId as ae, type TileMode as af, type Unit as ag, angleFromCoords as ah, blendModeLabel as ai, blendModeOf as aj, blendOperation as ak, linearCoords as al, readGradientConfig as am, toFabricGradient as an, type BackgroundImageOptions as b, type BlendMode as c, DEFAULT_PATTERN_CONFIG as d, type DpiIssue as e, type EditorEvents as f, type EditorState as g, type ExportFormat as h, type FontDefinition as i, type GradientConfig as j, type GradientKind as k, type GradientStop as l, type ImageAttribution as m, type ImageProvider as n, type ImageProviderResult as o, type ImageSearchOptions as p, type ImageSearchResult as q, type LayerMaskEntry as r, type LayerMaskMode as s, type LayerMeta as t, type LayerShadowConfig as u, type LayerType as v, type LicenseConfig as w, type LicensePayload as x, type LicenseStatus as y, type MaskPoint as z };
773
+ declare const IMAGE_FILTER_PRESETS: readonly ImageFilterPreset[];
774
+ declare function imageFilterPreset(id: string): ImageFilterPreset | undefined;
775
+
776
+ /** A serialized fabric filter: what `filter.toObject()` returns, and what `enlivenObjects` takes. */
777
+ type FilterSpec = {
778
+ type: string;
779
+ } & Record<string, unknown>;
780
+ declare function clampAdjust(adjust: Partial<ImageAdjust>): Partial<ImageAdjust>;
781
+ declare function clampAlphaClip(clip: Partial<ImageAlphaClip> | undefined): ImageAlphaClip | undefined;
782
+ /**
783
+ * The matrix the studio's alpha clip has always used; `colorsOnly: false` makes
784
+ * the 2D path honour row four.
785
+ */
786
+ declare function alphaClipMatrix({ low, high }: ImageAlphaClip): number[];
787
+ /** State → serialized filters in the D5 order. Neutral controls emit nothing. */
788
+ declare function imageEffectsFilterSpecs(state: ImageEffectsState): FilterSpec[];
789
+ /** Read a layer's state off its meta, lifting the pre-release `imageAdjustments` shape once. */
790
+ declare function normalizeImageEffects(meta: Record<string, unknown>): ImageEffectsState;
791
+
792
+ export { type MockupDisplacement as $, ADJUST_KEYS as A, BLEND_GROUPS as B, type CanvasSizePreset as C, DEFAULT_GRADIENT_CONFIG as D, type EditorConfig as E, type FileAdapter as F, type GradientBox as G, type LayerEffectState as H, IMAGE_FILTER_PRESETS as I, type LayerMaskEntry as J, type LayerMaskMode as K, type LayerData as L, type LayerMeta as M, type LayerShadowConfig as N, type LayerType as O, type LicenseConfig as P, type LicensePayload as Q, type LicenseStatus as R, type MaskBrushOptions as S, type MaskPoint as T, type MaskPresetId as U, type MaskRefinementPrompt as V, type MaskRefinementProvider as W, type MaskRefinementRequest as X, type MaskRefinementResult as Y, type MockupBlendMode as Z, type MockupConfig as _, ADJUST_RANGES as a, type MockupDisplacementChannel as a0, type MockupOverlay as a1, type MockupPrintArea as a2, NEUTRAL_ADJUST as a3, type NormalizedLayerPosition as a4, type PatternConfig as a5, type PatternLocks as a6, type PatternState as a7, type PositioningAdapter as a8, type PrintifyPositioning as a9, clampAdjust as aA, clampAlphaClip as aB, imageEffectsFilterSpecs as aC, imageFilterPreset as aD, linearCoords as aE, normalizeImageEffects as aF, readGradientConfig as aG, toFabricGradient as aH, type ProjectPage as aa, type ProjectState as ab, type ResizeOptions as ac, type SemanticExportOptions as ad, type SerializedBackgroundImageOptions as ae, type SerializedLayer as af, type ShapeMaskPresetId as ag, type ShapeParamDef as ah, type ShapePlugin as ai, type ShapeState as aj, type SvgExportOptions as ak, type TemplateDefinition as al, type TemplateParameter as am, type TextCurveConfig as an, type TextCurveInput as ao, type TextCurveShape as ap, type TextOverflow as aq, type TextWrapMode as ar, type TextureMaskPresetId as as, type TileMode as at, type Unit as au, alphaClipMatrix as av, angleFromCoords as aw, blendModeLabel as ax, blendModeOf as ay, blendOperation as az, BLEND_MODES as b, type BackgroundImageOptions as c, type BlendMode as d, DEFAULT_PATTERN_CONFIG as e, type DpiIssue as f, type EditorEvents as g, type EditorState as h, type ExportFormat as i, type FilterSpec as j, type FontDefinition as k, type GradientConfig as l, type GradientKind as m, type GradientStop as n, IMAGE_PROXY_MAX_EDGE as o, type ImageAdjust as p, type ImageAlphaClip as q, type ImageAttribution as r, type ImageEffectsState as s, type ImageFilterPreset as t, type ImageFilterPresetId as u, type ImageProvider as v, type ImageProviderResult as w, type ImageSearchOptions as x, type ImageSearchResult as y, type LayerEffectKind as z };