@imggion/html2realpdf 0.3.1 → 0.4.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/README.md +99 -4
- package/dist/image.d.ts +83 -0
- package/dist/image.js +169 -0
- package/dist/image.js.map +1 -0
- package/dist/index.d.ts +4 -3
- package/dist/index.js +4 -3
- package/dist/index.js.map +1 -1
- package/dist/libhtml2realpdf.wasm +0 -0
- package/dist/node-source.d.ts +16 -0
- package/dist/node-source.js +155 -0
- package/dist/node-source.js.map +1 -0
- package/dist/node.d.ts +78 -0
- package/dist/node.js +105 -0
- package/dist/node.js.map +1 -0
- package/dist/renderer.d.ts +64 -1
- package/dist/renderer.js +164 -41
- package/dist/renderer.js.map +1 -1
- package/dist/snapshot.d.ts +6 -0
- package/dist/snapshot.js +177 -5
- package/dist/snapshot.js.map +1 -1
- package/dist/types.d.ts +52 -3
- package/dist/types.js.map +1 -1
- package/dist/wasm.d.ts +39 -9
- package/dist/wasm.js +83 -28
- package/dist/wasm.js.map +1 -1
- package/dist/worker.js +9 -0
- package/dist/worker.js.map +1 -1
- package/package.json +11 -2
- package/skills/html2realpdf/SKILL.md +80 -5
package/dist/types.d.ts
CHANGED
|
@@ -115,7 +115,7 @@ export interface Diagnostic {
|
|
|
115
115
|
/** Stable snapshot path to the affected node, when available. */
|
|
116
116
|
nodePath?: string;
|
|
117
117
|
/** Pipeline phase that produced the diagnostic. */
|
|
118
|
-
phase?: "snapshot" | "parse" | "cascade" | "computed" | "layout" | "fragmentation" | "paint" | "pdf";
|
|
118
|
+
phase?: "snapshot" | "parse" | "cascade" | "computed" | "layout" | "fragmentation" | "paint" | "pdf" | "raster";
|
|
119
119
|
/** Fallback that preserved output despite the unsupported input. */
|
|
120
120
|
fallback?: string;
|
|
121
121
|
}
|
|
@@ -218,6 +218,47 @@ export interface RenderOptions {
|
|
|
218
218
|
/** Receives coarse phase-boundary progress, not per-page render progress. */
|
|
219
219
|
onProgress?: (progress: RenderProgress) => void;
|
|
220
220
|
}
|
|
221
|
+
/** Encoded raster formats. Only JPEG is available; the union reserves room for more. */
|
|
222
|
+
export type ImageFormat = "jpeg";
|
|
223
|
+
/** JPEG chroma sampling: `4:2:0` is smaller, `4:4:4` keeps colored text and edges sharp. */
|
|
224
|
+
export type ChromaSubsampling = "4:2:0" | "4:4:4";
|
|
225
|
+
/**
|
|
226
|
+
* Options applied to one HTML snapshot and image render.
|
|
227
|
+
*
|
|
228
|
+
* @remarks
|
|
229
|
+
* Snapshot and resource options behave exactly as for PDF rendering. The
|
|
230
|
+
* image has the requested CSS `width` and an automatic height equal to the
|
|
231
|
+
* laid-out content; page geometry, page breaks, and PDF-only options do not
|
|
232
|
+
* apply.
|
|
233
|
+
*/
|
|
234
|
+
export interface ImageRenderOptions extends Omit<RenderOptions, "page" | "pageBreak" | "metadata" | "conformance" | "attachments" | "enableLinks" | "cssProfile"> {
|
|
235
|
+
/** Encoded format. Defaults to `jpeg`, the only supported value. */
|
|
236
|
+
format?: ImageFormat;
|
|
237
|
+
/**
|
|
238
|
+
* Canvas width in CSS pixels, from 1 to 4096. Defaults to the element's
|
|
239
|
+
* rendered width for Element/ref sources, and to `viewport.width` or 800
|
|
240
|
+
* for HTML strings.
|
|
241
|
+
*/
|
|
242
|
+
width?: number;
|
|
243
|
+
/** Device pixels per CSS pixel, from 0.5 to 4. Defaults to `1`. */
|
|
244
|
+
scale?: number;
|
|
245
|
+
/**
|
|
246
|
+
* JPEG quality from `0` to `1`, where `0.8` means 80% (the
|
|
247
|
+
* `canvas.toBlob` and Photoshop/Lightroom scale). Defaults to `0.8`.
|
|
248
|
+
* Values outside 0...1 throw a `RangeError`; `0` encodes at the minimum
|
|
249
|
+
* valid quality (1%) and reports a diagnostic.
|
|
250
|
+
*/
|
|
251
|
+
quality?: number;
|
|
252
|
+
/**
|
|
253
|
+
* Chroma sampling. Defaults to `4:2:0`, or `4:4:4` when `quality >= 0.9`.
|
|
254
|
+
* An explicit value always wins.
|
|
255
|
+
*/
|
|
256
|
+
chromaSubsampling?: ChromaSubsampling;
|
|
257
|
+
/** Opaque color behind transparent content. Defaults to `#ffffff`. */
|
|
258
|
+
background?: string;
|
|
259
|
+
/** Layout profile. Defaults to `web`, the browser-like profile used for components. */
|
|
260
|
+
cssProfile?: CssProfile;
|
|
261
|
+
}
|
|
221
262
|
/** Configuration whose lifetime matches an explicit renderer instance. */
|
|
222
263
|
export interface RendererInit {
|
|
223
264
|
/** Execution backend. Defaults to `worker`. */
|
|
@@ -231,9 +272,17 @@ export interface RendererInit {
|
|
|
231
272
|
export interface FontRegistration {
|
|
232
273
|
/** CSS family name used during font resolution. */
|
|
233
274
|
family: string;
|
|
234
|
-
/**
|
|
275
|
+
/**
|
|
276
|
+
* Complete TrueType (`glyf` outline) font bytes, copied into the native
|
|
277
|
+
* context. WOFF/WOFF2 files are rejected with a descriptive error.
|
|
278
|
+
*/
|
|
235
279
|
data: ArrayBuffer | Uint8Array;
|
|
236
|
-
/**
|
|
280
|
+
/**
|
|
281
|
+
* CSS font weight from 1 to 1000. Defaults to `400`. Faces of one family are
|
|
282
|
+
* selected with the CSS font-matching algorithm, so Medium (500) and
|
|
283
|
+
* SemiBold (600) coexist with Regular and Bold; registering the same family,
|
|
284
|
+
* weight, and style again replaces the earlier face.
|
|
285
|
+
*/
|
|
237
286
|
weight?: number | "normal" | "bold";
|
|
238
287
|
/** CSS font style. Defaults to `normal`. */
|
|
239
288
|
style?: "normal" | "italic";
|
package/dist/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG","sourcesContent":["/**\n * Public configuration and callback contracts for the browser wrapper.\n *\n * @packageDocumentation\n */\n\n/** A structural ref accepted without making React a runtime dependency. */\nexport type RefLike<T> = { readonly current: T | null };\n\n/**\n * Input accepted by the snapshot boundary.\n *\n * @remarks\n * Mounted elements and refs preserve computed styles and live browser state;\n * strings are evaluated in an inert document.\n */\nexport type HtmlSource = string | Element | RefLike<Element>;\n\n/** Units used for custom page dimensions and margins. */\nexport type LengthUnit = \"pt\" | \"px\" | \"mm\" | \"cm\" | \"in\";\n\n/** Named physical page sizes or a custom `[width, height]` in the selected unit. */\nexport type PageFormat = \"a4\" | \"letter\" | readonly [width: number, height: number];\n\n/** Orientation applied after resolving the page format. */\nexport type PageOrientation = \"portrait\" | \"landscape\";\n\n/**\n * Layout and CSS support profile.\n *\n * @remarks\n * `document` favors stable paged reports. `web` enables the broader browser\n * layout profile. `strict` uses that broader profile and rejects unsupported\n * CSS by default.\n */\nexport type CssProfile = \"document\" | \"web\" | \"strict\";\n\n/** Media environment used while resolving styles and media queries. */\nexport type MediaType = \"screen\" | \"print\";\n\n/** Containing block used for the snapshotted root element. */\nexport type LayoutContext = \"source\" | \"page\";\n\n/** Action taken when an authored CSS property is outside the selected profile. */\nexport type UnsupportedCssPolicy = \"warn\" | \"error\" | \"ignore\";\n\n/** Policy for SVG subtrees that cannot remain native PDF vectors. */\nexport type FallbackPolicy = \"error\" | \"rasterize-subtree\";\n\n/** Policy used when a canvas-to-SVG adapter intentionally returns `null`. */\nexport type CanvasFallbackPolicy = \"error\" | \"rasterize\";\n\n/** Complete SVG returned by a canvas adapter. */\nexport type CanvasSvgSource = string | Blob | SVGSVGElement;\n\n/** Context passed to a canvas-to-SVG adapter. */\nexport interface CanvasToSvgRequest {\n /** Original live canvas, suitable for chart-library export APIs. */\n canvas: HTMLCanvasElement;\n /** Stable snapshot path used to identify failures and fallbacks. */\n nodePath: string;\n /** Rendered canvas width in CSS pixels. */\n cssWidth: number;\n /** Rendered canvas height in CSS pixels. */\n cssHeight: number;\n /** Backing bitmap width. */\n bitmapWidth: number;\n /** Backing bitmap height. */\n bitmapHeight: number;\n}\n\n/**\n * Replaces a live canvas with vector SVG when the source library can export it.\n *\n * @remarks\n * Returning `null` delegates to `canvasFallback`. Throwing or returning\n * malformed SVG produces `CanvasToSvgError`.\n */\nexport type CanvasToSvg = (\n request: CanvasToSvgRequest,\n) => CanvasSvgSource | null | Promise<CanvasSvgSource | null>;\n\n/** Deterministic viewport used for responsive layout and media queries. */\nexport interface ViewportOptions {\n /** Viewport width in CSS pixels. Values below one are clamped. */\n width: number;\n /** Viewport height in CSS pixels. Values below one are clamped. */\n height: number;\n}\n\n/**\n * Page margins in the selected page unit.\n *\n * @remarks\n * Four values use html2pdf.js order `[top, left, bottom, right]`, not CSS\n * shorthand order. Two values mean `[vertical, horizontal]`.\n */\nexport type Margin =\n | number\n | readonly [vertical: number, horizontal: number]\n | readonly [top: number, left: number, bottom: number, right: number];\n\n/** Explicit page geometry. Supplying this overrides captured `@page` geometry. */\nexport interface PageOptions {\n /** Page size. Defaults to `a4`. */\n format?: PageFormat;\n /** Page orientation. Defaults to `portrait`. */\n orientation?: PageOrientation;\n /** Unit for custom dimensions and margins. Defaults to `pt`. */\n unit?: LengthUnit;\n /** Page margins. Defaults to zero on every edge. */\n margin?: Margin;\n}\n\n/** Coarse rendering phases reported at stable cancellation boundaries. */\nexport type RenderPhase = \"snapshot\" | \"wasm\" | \"complete\";\n\n/** Progress notification for a rendering phase. */\nexport interface RenderProgress {\n /** Phase producing this notification. */\n phase: RenderPhase;\n /** Completed work units within the phase. */\n completed: number;\n /** Total work units within the phase. */\n total: number;\n}\n\n/** Structured warning or error produced without losing successful PDF output. */\nexport interface Diagnostic {\n /** Stable machine-readable identifier. */\n code: string;\n /** Diagnostic severity assigned by the snapshot or native renderer. */\n severity: \"warning\" | \"error\";\n /** Human-readable explanation. */\n message: string;\n /** CSS property associated with the diagnostic, when applicable. */\n property?: string;\n /** Stable snapshot path to the affected node, when available. */\n nodePath?: string;\n /** Pipeline phase that produced the diagnostic. */\n phase?: \"snapshot\" | \"parse\" | \"cascade\" | \"computed\" | \"layout\" | \"fragmentation\" | \"paint\" | \"pdf\";\n /** Fallback that preserved output despite the unsupported input. */\n fallback?: string;\n}\n\n/** Resource requested while materializing a self-contained snapshot. */\nexport interface ResourceRequest {\n /** Resource class. Fonts are registered on `createRenderer` instead. */\n kind: \"image\" | \"stylesheet\";\n /** Absolute URL resolved against `baseUrl` or the source document. */\n url: URL;\n}\n\n/**\n * Resolves resources that cannot be fetched directly by the browser snapshot.\n *\n * @remarks\n * For stylesheets, a string is CSS source. For images, a string is a data URL\n * or replacement URL. `null` denies the resource without a fallback fetch:\n * `resourcePolicy: \"error\"` rejects the render and `\"omit\"` omits the resource.\n * Without a resolver, images may be fetched directly; HTML-string stylesheets\n * require a resolver. Already embedded image data URLs bypass the resolver.\n */\nexport type ResourceResolver = (request: ResourceRequest) => Blob | string | null | Promise<Blob | string | null>;\n\n/** Selector-driven pagination overrides compatible with html2pdf.js workflows. */\nexport interface PageBreakRules {\n /** Selectors forced to begin on a new page. */\n before?: string | readonly string[];\n /** Selectors forced to end the current page. */\n after?: string | readonly string[];\n /** Selectors whose contents should avoid internal fragmentation. */\n avoid?: string | readonly string[];\n /** Applies `break-inside: avoid` to every element. */\n avoidAll?: boolean;\n /** Honors the legacy `.html2pdf__page-break` marker. */\n legacy?: boolean;\n}\n\n/** PDF information dictionary fields written by the native renderer. */\nexport interface PdfMetadata {\n /** Document title. */\n title?: string;\n /** Document author. */\n author?: string;\n /** Document subject. */\n subject?: string;\n /** Search keywords, joined when supplied as an array. */\n keywords?: string | readonly string[];\n /** Application or service that created the document. */\n creator?: string;\n}\n\n/** Options applied to one HTML snapshot and PDF render. */\nexport interface RenderOptions {\n /** Explicit page geometry; captured `@page` rules are used when omitted. */\n page?: PageOptions;\n /**\n * Promotes unsupported snapshot CSS to errors without selecting the `web`\n * layout profile. An explicit `unsupportedCss` policy takes precedence.\n */\n strict?: boolean;\n /** Layout profile. Defaults to `document`. */\n cssProfile?: CssProfile;\n /** Media environment used for style resolution. Defaults to `screen`. */\n mediaType?: MediaType;\n /**\n * Root layout context. `source` preserves the mounted browser width;\n * `page` resolves an implicit root width and auto inline margins against the\n * PDF content box. Defaults to `source`.\n */\n layoutContext?: LayoutContext;\n /** Isolated viewport used for media queries and responsive layout. */\n viewport?: ViewportOptions;\n /** Unsupported-CSS policy; defaults to `error` for strict mode and `warn` otherwise. */\n unsupportedCss?: UnsupportedCssPolicy;\n /** Unsupported SVG policy. Defaults to `error`. */\n fallback?: FallbackPolicy;\n /** Optional bridge from live canvas content to validated SVG. */\n canvasToSvg?: CanvasToSvg;\n /** Fallback when `canvasToSvg` returns `null`. Defaults to `error`. */\n canvasFallback?: CanvasFallbackPolicy;\n /** Flattens open Shadow DOM into the snapshot. Defaults to `false`. */\n includeShadowDom?: boolean;\n /** Base URL for relative resources. Defaults to the source document URL. */\n baseUrl?: string | URL;\n /** Failed-resource policy. Defaults to `error`. */\n resourcePolicy?: \"error\" | \"omit\";\n /** Resolver for protected, virtual, or otherwise unavailable resources. */\n resourceResolver?: ResourceResolver;\n /** Selector-driven page-break overrides. */\n pageBreak?: PageBreakRules;\n /** PDF information dictionary fields. */\n metadata?: PdfMetadata;\n /** Opts into PDF/A-3u; incompatible resources reject the render without fallback. */\n conformance?: \"pdfa-3u\";\n /** Embedded files for this render only; does not implicitly enable PDF/A. */\n attachments?: readonly PdfAttachment[];\n /** Preserves HTTP(S), mail, telephone, and FTP annotations unless explicitly set to `false`. */\n enableLinks?: boolean;\n /**\n * Rejects the caller at snapshot and render boundaries when aborted.\n * An already-running synchronous WASM render cannot be preempted.\n */\n signal?: AbortSignal;\n /** Receives coarse phase-boundary progress, not per-page render progress. */\n onProgress?: (progress: RenderProgress) => void;\n}\n\n/** Configuration whose lifetime matches an explicit renderer instance. */\nexport interface RendererInit {\n /** Execution backend. Defaults to `worker`. */\n execution?: \"worker\" | \"main\";\n /** WASM asset override for deployments that cannot serve package-relative assets. */\n wasmUrl?: string | URL;\n /** Embeddable TrueType fonts registered once for every render. */\n fonts?: readonly FontRegistration[];\n}\n\n/** Embeddable TrueType font registered in a renderer-owned WASM context. */\nexport interface FontRegistration {\n /** CSS family name used during font resolution. */\n family: string;\n /** Complete TrueType font bytes, copied into the native context. */\n data: ArrayBuffer | Uint8Array;\n /** CSS font weight. Defaults to `400`. */\n weight?: number | \"normal\" | \"bold\";\n /** CSS font style. Defaults to `normal`. */\n style?: \"normal\" | \"italic\";\n}\n\n/** Page settings accepted through the html2pdf.js-compatible `jsPDF` option. */\nexport interface CompatJsPdfOptions {\n /** Unit shared by custom page geometry and margins. */\n unit?: LengthUnit;\n /** Named or custom page format forwarded to the modern page contract. */\n format?: PageFormat;\n /** Page orientation forwarded to the modern page contract. */\n orientation?: PageOrientation;\n}\n\n/** Page-break settings accepted by the html2pdf.js compatibility layer. */\nexport interface CompatPageBreakOptions {\n /** Compatibility modes. Defaults to `css` and `legacy`. */\n mode?: \"css\" | \"legacy\" | \"avoid-all\" | readonly (\"css\" | \"legacy\" | \"avoid-all\")[];\n /** Selectors forced to begin on a new page. */\n before?: string | readonly string[];\n /** Selectors forced to end the current page. */\n after?: string | readonly string[];\n /** Selectors whose contents should avoid internal fragmentation. */\n avoid?: string | readonly string[];\n}\n\n/** Options supported by the PDF-oriented html2pdf.js compatibility layer. */\nexport interface Html2PdfOptions {\n /** Same metadata and archival options as RenderOptions. */\n metadata?: PdfMetadata;\n conformance?: \"pdfa-3u\";\n attachments?: readonly PdfAttachment[];\n /** Page margins in html2pdf.js order. */\n margin?: Margin;\n /** Filename used by `save` when no method argument is supplied. */\n filename?: string;\n /** Preserves HTTP(S), mail, telephone, and FTP links unless explicitly disabled. */\n enableLinks?: boolean;\n /** Compatibility pagination rules. */\n pagebreak?: CompatPageBreakOptions;\n /** Compatibility page geometry. */\n jsPDF?: CompatJsPdfOptions;\n /** Unsupported because this renderer does not use an html2canvas pipeline. */\n html2canvas?: never;\n /** Unsupported because PDF pages are not encoded as raster images. */\n image?: never;\n}\n\n/** Output encodings supported by compatibility `output` methods. */\nexport type PdfOutputType =\n | \"arraybuffer\"\n | \"blob\"\n | \"bloburl\"\n | \"bloburi\"\n | \"datauristring\"\n | \"dataurlstring\";\n\n/** File embedded in one PDF; caller data is copied and never transferred or detached. */\nexport interface PdfAttachment {\n /** Nonempty, unique filename. Unicode is preserved. */\n name: string;\n /** Original bytes; a Uint8Array embeds only its selected view. */\n data: ArrayBuffer | Uint8Array;\n /** MIME media type without parameters. Defaults to application/octet-stream. */\n mimeType?: string;\n /** Relationship to the document. Defaults to Unspecified. */\n relationship?: \"Source\" | \"Data\" | \"Alternative\" | \"Supplement\" | \"Unspecified\";\n /** Optional human-readable attachment description. */\n description?: string;\n /** Explicit modification time, stored in UTC with second precision; no date is invented. */\n modifiedAt?: Date;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG","sourcesContent":["/**\n * Public configuration and callback contracts for the browser wrapper.\n *\n * @packageDocumentation\n */\n\n/** A structural ref accepted without making React a runtime dependency. */\nexport type RefLike<T> = { readonly current: T | null };\n\n/**\n * Input accepted by the snapshot boundary.\n *\n * @remarks\n * Mounted elements and refs preserve computed styles and live browser state;\n * strings are evaluated in an inert document.\n */\nexport type HtmlSource = string | Element | RefLike<Element>;\n\n/** Units used for custom page dimensions and margins. */\nexport type LengthUnit = \"pt\" | \"px\" | \"mm\" | \"cm\" | \"in\";\n\n/** Named physical page sizes or a custom `[width, height]` in the selected unit. */\nexport type PageFormat = \"a4\" | \"letter\" | readonly [width: number, height: number];\n\n/** Orientation applied after resolving the page format. */\nexport type PageOrientation = \"portrait\" | \"landscape\";\n\n/**\n * Layout and CSS support profile.\n *\n * @remarks\n * `document` favors stable paged reports. `web` enables the broader browser\n * layout profile. `strict` uses that broader profile and rejects unsupported\n * CSS by default.\n */\nexport type CssProfile = \"document\" | \"web\" | \"strict\";\n\n/** Media environment used while resolving styles and media queries. */\nexport type MediaType = \"screen\" | \"print\";\n\n/** Containing block used for the snapshotted root element. */\nexport type LayoutContext = \"source\" | \"page\";\n\n/** Action taken when an authored CSS property is outside the selected profile. */\nexport type UnsupportedCssPolicy = \"warn\" | \"error\" | \"ignore\";\n\n/** Policy for SVG subtrees that cannot remain native PDF vectors. */\nexport type FallbackPolicy = \"error\" | \"rasterize-subtree\";\n\n/** Policy used when a canvas-to-SVG adapter intentionally returns `null`. */\nexport type CanvasFallbackPolicy = \"error\" | \"rasterize\";\n\n/** Complete SVG returned by a canvas adapter. */\nexport type CanvasSvgSource = string | Blob | SVGSVGElement;\n\n/** Context passed to a canvas-to-SVG adapter. */\nexport interface CanvasToSvgRequest {\n /** Original live canvas, suitable for chart-library export APIs. */\n canvas: HTMLCanvasElement;\n /** Stable snapshot path used to identify failures and fallbacks. */\n nodePath: string;\n /** Rendered canvas width in CSS pixels. */\n cssWidth: number;\n /** Rendered canvas height in CSS pixels. */\n cssHeight: number;\n /** Backing bitmap width. */\n bitmapWidth: number;\n /** Backing bitmap height. */\n bitmapHeight: number;\n}\n\n/**\n * Replaces a live canvas with vector SVG when the source library can export it.\n *\n * @remarks\n * Returning `null` delegates to `canvasFallback`. Throwing or returning\n * malformed SVG produces `CanvasToSvgError`.\n */\nexport type CanvasToSvg = (\n request: CanvasToSvgRequest,\n) => CanvasSvgSource | null | Promise<CanvasSvgSource | null>;\n\n/** Deterministic viewport used for responsive layout and media queries. */\nexport interface ViewportOptions {\n /** Viewport width in CSS pixels. Values below one are clamped. */\n width: number;\n /** Viewport height in CSS pixels. Values below one are clamped. */\n height: number;\n}\n\n/**\n * Page margins in the selected page unit.\n *\n * @remarks\n * Four values use html2pdf.js order `[top, left, bottom, right]`, not CSS\n * shorthand order. Two values mean `[vertical, horizontal]`.\n */\nexport type Margin =\n | number\n | readonly [vertical: number, horizontal: number]\n | readonly [top: number, left: number, bottom: number, right: number];\n\n/** Explicit page geometry. Supplying this overrides captured `@page` geometry. */\nexport interface PageOptions {\n /** Page size. Defaults to `a4`. */\n format?: PageFormat;\n /** Page orientation. Defaults to `portrait`. */\n orientation?: PageOrientation;\n /** Unit for custom dimensions and margins. Defaults to `pt`. */\n unit?: LengthUnit;\n /** Page margins. Defaults to zero on every edge. */\n margin?: Margin;\n}\n\n/** Coarse rendering phases reported at stable cancellation boundaries. */\nexport type RenderPhase = \"snapshot\" | \"wasm\" | \"complete\";\n\n/** Progress notification for a rendering phase. */\nexport interface RenderProgress {\n /** Phase producing this notification. */\n phase: RenderPhase;\n /** Completed work units within the phase. */\n completed: number;\n /** Total work units within the phase. */\n total: number;\n}\n\n/** Structured warning or error produced without losing successful PDF output. */\nexport interface Diagnostic {\n /** Stable machine-readable identifier. */\n code: string;\n /** Diagnostic severity assigned by the snapshot or native renderer. */\n severity: \"warning\" | \"error\";\n /** Human-readable explanation. */\n message: string;\n /** CSS property associated with the diagnostic, when applicable. */\n property?: string;\n /** Stable snapshot path to the affected node, when available. */\n nodePath?: string;\n /** Pipeline phase that produced the diagnostic. */\n phase?: \"snapshot\" | \"parse\" | \"cascade\" | \"computed\" | \"layout\" | \"fragmentation\" | \"paint\" | \"pdf\" | \"raster\";\n /** Fallback that preserved output despite the unsupported input. */\n fallback?: string;\n}\n\n/** Resource requested while materializing a self-contained snapshot. */\nexport interface ResourceRequest {\n /** Resource class. Fonts are registered on `createRenderer` instead. */\n kind: \"image\" | \"stylesheet\";\n /** Absolute URL resolved against `baseUrl` or the source document. */\n url: URL;\n}\n\n/**\n * Resolves resources that cannot be fetched directly by the browser snapshot.\n *\n * @remarks\n * For stylesheets, a string is CSS source. For images, a string is a data URL\n * or replacement URL. `null` denies the resource without a fallback fetch:\n * `resourcePolicy: \"error\"` rejects the render and `\"omit\"` omits the resource.\n * Without a resolver, images may be fetched directly; HTML-string stylesheets\n * require a resolver. Already embedded image data URLs bypass the resolver.\n */\nexport type ResourceResolver = (request: ResourceRequest) => Blob | string | null | Promise<Blob | string | null>;\n\n/** Selector-driven pagination overrides compatible with html2pdf.js workflows. */\nexport interface PageBreakRules {\n /** Selectors forced to begin on a new page. */\n before?: string | readonly string[];\n /** Selectors forced to end the current page. */\n after?: string | readonly string[];\n /** Selectors whose contents should avoid internal fragmentation. */\n avoid?: string | readonly string[];\n /** Applies `break-inside: avoid` to every element. */\n avoidAll?: boolean;\n /** Honors the legacy `.html2pdf__page-break` marker. */\n legacy?: boolean;\n}\n\n/** PDF information dictionary fields written by the native renderer. */\nexport interface PdfMetadata {\n /** Document title. */\n title?: string;\n /** Document author. */\n author?: string;\n /** Document subject. */\n subject?: string;\n /** Search keywords, joined when supplied as an array. */\n keywords?: string | readonly string[];\n /** Application or service that created the document. */\n creator?: string;\n}\n\n/** Options applied to one HTML snapshot and PDF render. */\nexport interface RenderOptions {\n /** Explicit page geometry; captured `@page` rules are used when omitted. */\n page?: PageOptions;\n /**\n * Promotes unsupported snapshot CSS to errors without selecting the `web`\n * layout profile. An explicit `unsupportedCss` policy takes precedence.\n */\n strict?: boolean;\n /** Layout profile. Defaults to `document`. */\n cssProfile?: CssProfile;\n /** Media environment used for style resolution. Defaults to `screen`. */\n mediaType?: MediaType;\n /**\n * Root layout context. `source` preserves the mounted browser width;\n * `page` resolves an implicit root width and auto inline margins against the\n * PDF content box. Defaults to `source`.\n */\n layoutContext?: LayoutContext;\n /** Isolated viewport used for media queries and responsive layout. */\n viewport?: ViewportOptions;\n /** Unsupported-CSS policy; defaults to `error` for strict mode and `warn` otherwise. */\n unsupportedCss?: UnsupportedCssPolicy;\n /** Unsupported SVG policy. Defaults to `error`. */\n fallback?: FallbackPolicy;\n /** Optional bridge from live canvas content to validated SVG. */\n canvasToSvg?: CanvasToSvg;\n /** Fallback when `canvasToSvg` returns `null`. Defaults to `error`. */\n canvasFallback?: CanvasFallbackPolicy;\n /** Flattens open Shadow DOM into the snapshot. Defaults to `false`. */\n includeShadowDom?: boolean;\n /** Base URL for relative resources. Defaults to the source document URL. */\n baseUrl?: string | URL;\n /** Failed-resource policy. Defaults to `error`. */\n resourcePolicy?: \"error\" | \"omit\";\n /** Resolver for protected, virtual, or otherwise unavailable resources. */\n resourceResolver?: ResourceResolver;\n /** Selector-driven page-break overrides. */\n pageBreak?: PageBreakRules;\n /** PDF information dictionary fields. */\n metadata?: PdfMetadata;\n /** Opts into PDF/A-3u; incompatible resources reject the render without fallback. */\n conformance?: \"pdfa-3u\";\n /** Embedded files for this render only; does not implicitly enable PDF/A. */\n attachments?: readonly PdfAttachment[];\n /** Preserves HTTP(S), mail, telephone, and FTP annotations unless explicitly set to `false`. */\n enableLinks?: boolean;\n /**\n * Rejects the caller at snapshot and render boundaries when aborted.\n * An already-running synchronous WASM render cannot be preempted.\n */\n signal?: AbortSignal;\n /** Receives coarse phase-boundary progress, not per-page render progress. */\n onProgress?: (progress: RenderProgress) => void;\n}\n\n/** Encoded raster formats. Only JPEG is available; the union reserves room for more. */\nexport type ImageFormat = \"jpeg\";\n\n/** JPEG chroma sampling: `4:2:0` is smaller, `4:4:4` keeps colored text and edges sharp. */\nexport type ChromaSubsampling = \"4:2:0\" | \"4:4:4\";\n\n/**\n * Options applied to one HTML snapshot and image render.\n *\n * @remarks\n * Snapshot and resource options behave exactly as for PDF rendering. The\n * image has the requested CSS `width` and an automatic height equal to the\n * laid-out content; page geometry, page breaks, and PDF-only options do not\n * apply.\n */\nexport interface ImageRenderOptions extends Omit<RenderOptions, \"page\" | \"pageBreak\" | \"metadata\" | \"conformance\" | \"attachments\" | \"enableLinks\" | \"cssProfile\"> {\n /** Encoded format. Defaults to `jpeg`, the only supported value. */\n format?: ImageFormat;\n /**\n * Canvas width in CSS pixels, from 1 to 4096. Defaults to the element's\n * rendered width for Element/ref sources, and to `viewport.width` or 800\n * for HTML strings.\n */\n width?: number;\n /** Device pixels per CSS pixel, from 0.5 to 4. Defaults to `1`. */\n scale?: number;\n /**\n * JPEG quality from `0` to `1`, where `0.8` means 80% (the\n * `canvas.toBlob` and Photoshop/Lightroom scale). Defaults to `0.8`.\n * Values outside 0...1 throw a `RangeError`; `0` encodes at the minimum\n * valid quality (1%) and reports a diagnostic.\n */\n quality?: number;\n /**\n * Chroma sampling. Defaults to `4:2:0`, or `4:4:4` when `quality >= 0.9`.\n * An explicit value always wins.\n */\n chromaSubsampling?: ChromaSubsampling;\n /** Opaque color behind transparent content. Defaults to `#ffffff`. */\n background?: string;\n /** Layout profile. Defaults to `web`, the browser-like profile used for components. */\n cssProfile?: CssProfile;\n}\n\n/** Configuration whose lifetime matches an explicit renderer instance. */\nexport interface RendererInit {\n /** Execution backend. Defaults to `worker`. */\n execution?: \"worker\" | \"main\";\n /** WASM asset override for deployments that cannot serve package-relative assets. */\n wasmUrl?: string | URL;\n /** Embeddable TrueType fonts registered once for every render. */\n fonts?: readonly FontRegistration[];\n}\n\n/** Embeddable TrueType font registered in a renderer-owned WASM context. */\nexport interface FontRegistration {\n /** CSS family name used during font resolution. */\n family: string;\n /**\n * Complete TrueType (`glyf` outline) font bytes, copied into the native\n * context. WOFF/WOFF2 files are rejected with a descriptive error.\n */\n data: ArrayBuffer | Uint8Array;\n /**\n * CSS font weight from 1 to 1000. Defaults to `400`. Faces of one family are\n * selected with the CSS font-matching algorithm, so Medium (500) and\n * SemiBold (600) coexist with Regular and Bold; registering the same family,\n * weight, and style again replaces the earlier face.\n */\n weight?: number | \"normal\" | \"bold\";\n /** CSS font style. Defaults to `normal`. */\n style?: \"normal\" | \"italic\";\n}\n\n/** Page settings accepted through the html2pdf.js-compatible `jsPDF` option. */\nexport interface CompatJsPdfOptions {\n /** Unit shared by custom page geometry and margins. */\n unit?: LengthUnit;\n /** Named or custom page format forwarded to the modern page contract. */\n format?: PageFormat;\n /** Page orientation forwarded to the modern page contract. */\n orientation?: PageOrientation;\n}\n\n/** Page-break settings accepted by the html2pdf.js compatibility layer. */\nexport interface CompatPageBreakOptions {\n /** Compatibility modes. Defaults to `css` and `legacy`. */\n mode?: \"css\" | \"legacy\" | \"avoid-all\" | readonly (\"css\" | \"legacy\" | \"avoid-all\")[];\n /** Selectors forced to begin on a new page. */\n before?: string | readonly string[];\n /** Selectors forced to end the current page. */\n after?: string | readonly string[];\n /** Selectors whose contents should avoid internal fragmentation. */\n avoid?: string | readonly string[];\n}\n\n/** Options supported by the PDF-oriented html2pdf.js compatibility layer. */\nexport interface Html2PdfOptions {\n /** Same metadata and archival options as RenderOptions. */\n metadata?: PdfMetadata;\n conformance?: \"pdfa-3u\";\n attachments?: readonly PdfAttachment[];\n /** Page margins in html2pdf.js order. */\n margin?: Margin;\n /** Filename used by `save` when no method argument is supplied. */\n filename?: string;\n /** Preserves HTTP(S), mail, telephone, and FTP links unless explicitly disabled. */\n enableLinks?: boolean;\n /** Compatibility pagination rules. */\n pagebreak?: CompatPageBreakOptions;\n /** Compatibility page geometry. */\n jsPDF?: CompatJsPdfOptions;\n /** Unsupported because this renderer does not use an html2canvas pipeline. */\n html2canvas?: never;\n /** Unsupported because PDF pages are not encoded as raster images. */\n image?: never;\n}\n\n/** Output encodings supported by compatibility `output` methods. */\nexport type PdfOutputType =\n | \"arraybuffer\"\n | \"blob\"\n | \"bloburl\"\n | \"bloburi\"\n | \"datauristring\"\n | \"dataurlstring\";\n\n/** File embedded in one PDF; caller data is copied and never transferred or detached. */\nexport interface PdfAttachment {\n /** Nonempty, unique filename. Unicode is preserved. */\n name: string;\n /** Original bytes; a Uint8Array embeds only its selected view. */\n data: ArrayBuffer | Uint8Array;\n /** MIME media type without parameters. Defaults to application/octet-stream. */\n mimeType?: string;\n /** Relationship to the document. Defaults to Unspecified. */\n relationship?: \"Source\" | \"Data\" | \"Alternative\" | \"Supplement\" | \"Unspecified\";\n /** Optional human-readable attachment description. */\n description?: string;\n /** Explicit modification time, stored in UTC with second precision; no date is invented. */\n modifiedAt?: Date;\n}\n"]}
|
package/dist/wasm.d.ts
CHANGED
|
@@ -4,26 +4,40 @@
|
|
|
4
4
|
* @packageDocumentation
|
|
5
5
|
*/
|
|
6
6
|
import type { PdfExtras } from "./attachments.js";
|
|
7
|
+
import type { NormalizedImageOptions } from "./image.js";
|
|
7
8
|
import type { NormalizedPage } from "./page.js";
|
|
8
9
|
import type { CssProfile, Diagnostic, FontRegistration, PdfMetadata } from "./types.js";
|
|
9
10
|
import type { SnapshotPageMarginBox, SnapshotPageRule } from "./snapshot.js";
|
|
10
11
|
/** Internal status: the instance must be discarded without further WASM calls. */
|
|
11
12
|
export declare const WASM_TRAP_STATUS = -23;
|
|
13
|
+
/**
|
|
14
|
+
* External resource referenced by an HTML string, as reported by
|
|
15
|
+
* `src/resources.zig`. Offsets are UTF-8 byte positions in the input.
|
|
16
|
+
*/
|
|
17
|
+
export interface ResourceReference {
|
|
18
|
+
kind: "image" | "stylesheet" | "background";
|
|
19
|
+
/** URL text after HTML character-reference decoding. */
|
|
20
|
+
url: string;
|
|
21
|
+
/** Byte range of the URL text, without quotes. */
|
|
22
|
+
start: number;
|
|
23
|
+
end: number;
|
|
24
|
+
/** Byte range of the whole start tag for `image` and `stylesheet`. */
|
|
25
|
+
tagStart?: number;
|
|
26
|
+
tagEnd?: number;
|
|
27
|
+
}
|
|
12
28
|
/** Owned JavaScript result copied out of WASM memory. */
|
|
13
29
|
export interface WasmRenderResult {
|
|
14
30
|
bytes: Uint8Array;
|
|
15
31
|
pageCount: number;
|
|
16
32
|
diagnostics: Diagnostic[];
|
|
17
33
|
}
|
|
18
|
-
/**
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
* discarded without further calls, including cleanup against damaged state.
|
|
26
|
-
*/
|
|
34
|
+
/** Owned encoded image copied out of WASM memory. */
|
|
35
|
+
export interface WasmImageResult {
|
|
36
|
+
bytes: Uint8Array;
|
|
37
|
+
width: number;
|
|
38
|
+
height: number;
|
|
39
|
+
diagnostics: Diagnostic[];
|
|
40
|
+
}
|
|
27
41
|
export declare class WasmBridge {
|
|
28
42
|
private readonly exports;
|
|
29
43
|
private readonly context;
|
|
@@ -32,8 +46,24 @@ export declare class WasmBridge {
|
|
|
32
46
|
private constructor();
|
|
33
47
|
/** Instantiates the expected ABI, creates a context, and registers its fonts. */
|
|
34
48
|
static create(wasmUrl: string | URL, fonts?: readonly FontRegistration[]): Promise<WasmBridge>;
|
|
49
|
+
/** Instantiates from module bytes already in memory, such as a file read in Node. */
|
|
50
|
+
static fromBytes(bytes: BufferSource, fonts?: readonly FontRegistration[]): Promise<WasmBridge>;
|
|
51
|
+
private static fromInstance;
|
|
35
52
|
/** Serializes render options, invokes the native renderer, and returns owned output. */
|
|
36
53
|
render(html: string, page: NormalizedPage, metadata?: PdfMetadata, cssProfile?: CssProfile, marginBoxes?: readonly SnapshotPageMarginBox[], pageRules?: readonly SnapshotPageRule[], extras?: PdfExtras): WasmRenderResult;
|
|
54
|
+
/**
|
|
55
|
+
* Renders one auto-height image. `image.quality` must already be the
|
|
56
|
+
* encoder's 1...100 integer; the native side rejects anything else.
|
|
57
|
+
*/
|
|
58
|
+
renderImage(html: string, image: NormalizedImageOptions, cssProfile?: CssProfile): WasmImageResult;
|
|
59
|
+
/** Lists the external resources an HTML string references. */
|
|
60
|
+
resourceReferences(html: string): ResourceReference[];
|
|
61
|
+
/**
|
|
62
|
+
* Shared result-handle lifecycle: copy inputs into WASM, call the
|
|
63
|
+
* renderer, copy owned output out, then free the handle and every input
|
|
64
|
+
* allocation (unless a trap discarded the instance).
|
|
65
|
+
*/
|
|
66
|
+
private invoke;
|
|
37
67
|
/** Frees the renderer context and every font copied into it. */
|
|
38
68
|
dispose(): void;
|
|
39
69
|
/** Copies one font registration across the ABI into context-owned storage. */
|
package/dist/wasm.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* @packageDocumentation
|
|
5
5
|
*/
|
|
6
6
|
import { WasmRenderError } from "./errors.js";
|
|
7
|
-
const EXPECTED_ABI_VERSION =
|
|
7
|
+
const EXPECTED_ABI_VERSION = 3;
|
|
8
8
|
/** Internal status: the instance must be discarded without further WASM calls. */
|
|
9
9
|
export const WASM_TRAP_STATUS = -23;
|
|
10
10
|
/**
|
|
@@ -16,6 +16,23 @@ export const WASM_TRAP_STATUS = -23;
|
|
|
16
16
|
* memory invalidates borrowed views. After a WASM trap the whole instance is
|
|
17
17
|
* discarded without further calls, including cleanup against damaged state.
|
|
18
18
|
*/
|
|
19
|
+
/**
|
|
20
|
+
* WebAssembly `i32` results reach JavaScript as signed numbers, so addresses
|
|
21
|
+
* and lengths above 2 GiB would turn negative. Statuses stay signed.
|
|
22
|
+
*/
|
|
23
|
+
function withUnsignedAddresses(exports) {
|
|
24
|
+
const unsigned = (call) => (...args) => call(...args) >>> 0;
|
|
25
|
+
return {
|
|
26
|
+
...exports,
|
|
27
|
+
alloc: unsigned(exports.alloc),
|
|
28
|
+
pdf_result_data_ptr: unsigned(exports.pdf_result_data_ptr),
|
|
29
|
+
pdf_result_data_len: unsigned(exports.pdf_result_data_len),
|
|
30
|
+
pdf_result_error_ptr: unsigned(exports.pdf_result_error_ptr),
|
|
31
|
+
pdf_result_error_len: unsigned(exports.pdf_result_error_len),
|
|
32
|
+
pdf_result_diagnostics_ptr: unsigned(exports.pdf_result_diagnostics_ptr),
|
|
33
|
+
pdf_result_diagnostics_len: unsigned(exports.pdf_result_diagnostics_len),
|
|
34
|
+
};
|
|
35
|
+
}
|
|
19
36
|
export class WasmBridge {
|
|
20
37
|
exports;
|
|
21
38
|
context;
|
|
@@ -37,7 +54,15 @@ export class WasmBridge {
|
|
|
37
54
|
catch {
|
|
38
55
|
result = await WebAssembly.instantiate(await response.arrayBuffer(), {});
|
|
39
56
|
}
|
|
40
|
-
|
|
57
|
+
return WasmBridge.fromInstance(result.instance, fonts);
|
|
58
|
+
}
|
|
59
|
+
/** Instantiates from module bytes already in memory, such as a file read in Node. */
|
|
60
|
+
static async fromBytes(bytes, fonts = []) {
|
|
61
|
+
const result = await WebAssembly.instantiate(bytes, {});
|
|
62
|
+
return WasmBridge.fromInstance(result.instance, fonts);
|
|
63
|
+
}
|
|
64
|
+
static fromInstance(instance, fonts) {
|
|
65
|
+
const exports = withUnsignedAddresses(instance.exports);
|
|
41
66
|
const abiVersion = exports.html2realpdf_abi_version?.();
|
|
42
67
|
if (abiVersion !== EXPECTED_ABI_VERSION) {
|
|
43
68
|
throw new WasmRenderError(`Unsupported WASM ABI version ${String(abiVersion)}; expected ${EXPECTED_ABI_VERSION}`, -14);
|
|
@@ -62,6 +87,49 @@ export class WasmBridge {
|
|
|
62
87
|
}
|
|
63
88
|
/** Serializes render options, invokes the native renderer, and returns owned output. */
|
|
64
89
|
render(html, page, metadata, cssProfile = "document", marginBoxes, pageRules, extras) {
|
|
90
|
+
return this.invoke(html, (copy) => {
|
|
91
|
+
const attachments = extras?.attachments?.map(({ data, ...metadataFields }) => ({
|
|
92
|
+
...metadataFields, dataPointer: copy(data), dataLength: data.byteLength,
|
|
93
|
+
}));
|
|
94
|
+
return {
|
|
95
|
+
pageWidthPoints: page.widthPoints,
|
|
96
|
+
pageHeightPoints: page.heightPoints,
|
|
97
|
+
marginTopPoints: page.marginTopPoints,
|
|
98
|
+
marginRightPoints: page.marginRightPoints,
|
|
99
|
+
marginBottomPoints: page.marginBottomPoints,
|
|
100
|
+
marginLeftPoints: page.marginLeftPoints,
|
|
101
|
+
cssProfile, marginBoxes, pageRules,
|
|
102
|
+
conformance: extras?.conformance,
|
|
103
|
+
attachments,
|
|
104
|
+
metadata: metadata ? {
|
|
105
|
+
...metadata,
|
|
106
|
+
keywords: Array.isArray(metadata.keywords) ? metadata.keywords.join(", ") : metadata.keywords,
|
|
107
|
+
} : undefined,
|
|
108
|
+
};
|
|
109
|
+
}, (input, inputLength, options, optionsLength) => this.exports.render_html_to_pdf_with_context_json_options(this.context, input, inputLength, options, optionsLength), (handle, bytes, diagnostics) => ({ bytes, pageCount: this.exports.pdf_result_page_count(handle), diagnostics }));
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Renders one auto-height image. `image.quality` must already be the
|
|
113
|
+
* encoder's 1...100 integer; the native side rejects anything else.
|
|
114
|
+
*/
|
|
115
|
+
renderImage(html, image, cssProfile = "web") {
|
|
116
|
+
return this.invoke(html, () => ({ cssProfile, image }), (input, inputLength, options, optionsLength) => this.exports.render_html_to_image_with_context_json_options(this.context, input, inputLength, options, optionsLength), (handle, bytes, diagnostics) => ({
|
|
117
|
+
bytes,
|
|
118
|
+
width: this.exports.image_result_width(handle),
|
|
119
|
+
height: this.exports.image_result_height(handle),
|
|
120
|
+
diagnostics,
|
|
121
|
+
}));
|
|
122
|
+
}
|
|
123
|
+
/** Lists the external resources an HTML string references. */
|
|
124
|
+
resourceReferences(html) {
|
|
125
|
+
return this.invoke(html, () => ({}), (input, inputLength) => this.exports.html_resource_references_json(input, inputLength), (_handle, bytes) => JSON.parse(new TextDecoder().decode(bytes)));
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Shared result-handle lifecycle: copy inputs into WASM, call the
|
|
129
|
+
* renderer, copy owned output out, then free the handle and every input
|
|
130
|
+
* allocation (unless a trap discarded the instance).
|
|
131
|
+
*/
|
|
132
|
+
invoke(html, buildOptions, call, read) {
|
|
65
133
|
if (this.disposed)
|
|
66
134
|
throw new WasmRenderError("WASM bridge has been disposed", -15);
|
|
67
135
|
const allocations = [];
|
|
@@ -76,44 +144,25 @@ export class WasmBridge {
|
|
|
76
144
|
};
|
|
77
145
|
let resultHandle = 0;
|
|
78
146
|
try {
|
|
79
|
-
const
|
|
80
|
-
...metadata, dataPointer: copy(data), dataLength: data.byteLength,
|
|
81
|
-
}));
|
|
147
|
+
const options = buildOptions(copy);
|
|
82
148
|
const input = this.encoder.encode(html);
|
|
83
149
|
const inputPointer = copy(input);
|
|
84
|
-
const renderOptions = this.encoder.encode(JSON.stringify(
|
|
85
|
-
pageWidthPoints: page.widthPoints,
|
|
86
|
-
pageHeightPoints: page.heightPoints,
|
|
87
|
-
marginTopPoints: page.marginTopPoints,
|
|
88
|
-
marginRightPoints: page.marginRightPoints,
|
|
89
|
-
marginBottomPoints: page.marginBottomPoints,
|
|
90
|
-
marginLeftPoints: page.marginLeftPoints,
|
|
91
|
-
cssProfile, marginBoxes, pageRules,
|
|
92
|
-
conformance: extras?.conformance,
|
|
93
|
-
attachments,
|
|
94
|
-
metadata: metadata ? {
|
|
95
|
-
...metadata,
|
|
96
|
-
keywords: Array.isArray(metadata.keywords) ? metadata.keywords.join(", ") : metadata.keywords,
|
|
97
|
-
} : undefined,
|
|
98
|
-
}));
|
|
150
|
+
const renderOptions = this.encoder.encode(JSON.stringify(options));
|
|
99
151
|
const optionsPointer = copy(renderOptions);
|
|
100
|
-
resultHandle =
|
|
152
|
+
resultHandle = call(inputPointer, input.length, optionsPointer, renderOptions.length);
|
|
101
153
|
if (resultHandle === 0)
|
|
102
154
|
throw new WasmRenderError("WASM result allocation failed", -12);
|
|
103
155
|
const status = this.exports.pdf_result_status(resultHandle);
|
|
104
156
|
if (status !== 0) {
|
|
105
157
|
const detail = this.readResultString(resultHandle, "error");
|
|
106
|
-
throw new WasmRenderError(detail || `WASM
|
|
158
|
+
throw new WasmRenderError(detail || `WASM rendering failed with status ${status}`, status);
|
|
107
159
|
}
|
|
108
160
|
const pointer = this.exports.pdf_result_data_ptr(resultHandle);
|
|
109
161
|
const length = this.exports.pdf_result_data_len(resultHandle);
|
|
110
162
|
if (pointer === 0 || length === 0)
|
|
111
|
-
throw new WasmRenderError("WASM returned an empty
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
pageCount: this.exports.pdf_result_page_count(resultHandle),
|
|
115
|
-
diagnostics: this.readDiagnostics(resultHandle),
|
|
116
|
-
};
|
|
163
|
+
throw new WasmRenderError("WASM returned an empty result", -13);
|
|
164
|
+
const bytes = new Uint8Array(this.exports.memory.buffer, pointer, length).slice();
|
|
165
|
+
return read(resultHandle, bytes, this.readDiagnostics(resultHandle));
|
|
117
166
|
}
|
|
118
167
|
catch (error) {
|
|
119
168
|
return this.rethrow(error);
|
|
@@ -147,6 +196,12 @@ export class WasmBridge {
|
|
|
147
196
|
: new Uint8Array(registration.data);
|
|
148
197
|
if (family.length === 0 || data.length === 0)
|
|
149
198
|
throw new WasmRenderError("Font family and data must not be empty", -16);
|
|
199
|
+
// WOFF and WOFF2 wrap compressed tables that the native TrueType parser
|
|
200
|
+
// cannot read. Keep the native invalid-font status, but name the cause.
|
|
201
|
+
const signature = data.length >= 4 ? String.fromCharCode(data[0], data[1], data[2], data[3]) : "";
|
|
202
|
+
if (signature === "wOFF" || signature === "wOF2") {
|
|
203
|
+
throw new WasmRenderError(`Font "${registration.family}" is ${signature === "wOF2" ? "WOFF2" : "WOFF"}; register the TrueType (.ttf) file instead`, -6);
|
|
204
|
+
}
|
|
150
205
|
const familyPointer = this.exports.alloc(family.length);
|
|
151
206
|
const dataPointer = this.exports.alloc(data.length);
|
|
152
207
|
if (familyPointer === 0 || dataPointer === 0) {
|
package/dist/wasm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wasm.js","sourceRoot":"","sources":["../src/wasm.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAK9C,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAC/B,kFAAkF;AAClF,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,EAAE,CAAC;AAuDpC;;;;;;;;GAQG;AACH,MAAM,OAAO,UAAU;IAIgB,OAAO;IAAgC,OAAO;IAHlE,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;IACrC,QAAQ,GAAG,KAAK,CAAC;IAEzB,YAAqC,OAAoB,EAAmB,OAAe;uBAAtD,OAAO;uBAAgC,OAAO;IAAW,CAAC;IAE/F,iFAAiF;IACjF,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,OAAqB,EAAE,KAAK,GAAgC,EAAE;QAChF,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,OAAO,CAAC,CAAC;QACtC,IAAI,CAAC,QAAQ,CAAC,EAAE;YAAE,MAAM,IAAI,eAAe,CAAC,6BAA6B,QAAQ,CAAC,MAAM,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC;QAEjG,IAAI,MAAiD,CAAC;QACtD,IAAI,CAAC;YACH,MAAM,GAAG,MAAM,WAAW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K,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAsB,CAAC,CAAC,CAAC,EAAE,CAAC;QAC7D,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,CAAC,EAAE,IAAI,EAAE,0BAA0B,EAAE,QAAQ,EAAE,SAAS,EAAE,OAAO,EAAE,qCAAqC,EAAE,CAAC,CAAC;QACrH,CAAC;IACH,CAAC;CACF","sourcesContent":["/**\n * Typed ownership bridge for the renderer's handle-based WebAssembly ABI.\n *\n * @packageDocumentation\n */\n\nimport type { PdfExtras } from \"./attachments.js\";\nimport { WasmRenderError } from \"./errors.js\";\nimport type { NormalizedPage } from \"./page.js\";\nimport type { CssProfile, Diagnostic, FontRegistration, PdfMetadata } from \"./types.js\";\nimport type { SnapshotPageMarginBox, SnapshotPageRule } from \"./snapshot.js\";\n\nconst EXPECTED_ABI_VERSION = 2;\n/** Internal status: the instance must be discarded without further WASM calls. */\nexport const WASM_TRAP_STATUS = -23;\n\n/** ABI surface implemented by `src/wasm.zig`. */\ninterface WasmExports {\n html2realpdf_abi_version(): number;\n pdf_context_create(): number;\n pdf_context_free(handle: number): void;\n pdf_context_register_font(\n handle: number,\n familyPointer: number,\n familyLength: number,\n dataPointer: number,\n dataLength: number,\n weight: number,\n style: number,\n ): number;\n memory: WebAssembly.Memory;\n alloc(length: number): number;\n free(pointer: number, length: number): void;\n render_html_to_pdf_with_options(\n pointer: number,\n length: number,\n pageWidthPoints: number,\n pageHeightPoints: number,\n marginTopPoints: number,\n marginRightPoints: number,\n marginBottomPoints: number,\n marginLeftPoints: number,\n ): number;\n render_html_to_pdf_with_json_options(pointer: number, length: number, optionsPointer: number, optionsLength: number): number;\n render_html_to_pdf_with_context_json_options(\n context: number,\n pointer: number,\n length: number,\n optionsPointer: number,\n optionsLength: number,\n ): number;\n pdf_result_status(handle: number): number;\n pdf_result_data_ptr(handle: number): number;\n pdf_result_data_len(handle: number): number;\n pdf_result_page_count(handle: number): number;\n pdf_result_error_ptr(handle: number): number;\n pdf_result_error_len(handle: number): number;\n pdf_result_diagnostics_ptr(handle: number): number;\n pdf_result_diagnostics_len(handle: number): number;\n pdf_result_free(handle: number): void;\n}\n\n/** Owned JavaScript result copied out of WASM memory. */\nexport interface WasmRenderResult {\n bytes: Uint8Array;\n pageCount: number;\n diagnostics: Diagnostic[];\n}\n\n/**\n * Owns one native PDF context and its registered fonts.\n *\n * @remarks\n * All temporary allocations and result handles are freed before `render`\n * returns. PDF bytes are copied first because freeing handles or growing WASM\n * memory invalidates borrowed views. After a WASM trap the whole instance is\n * discarded without further calls, including cleanup against damaged state.\n */\nexport class WasmBridge {\n private readonly encoder = new TextEncoder();\n private disposed = false;\n\n private constructor(private readonly exports: WasmExports, private readonly context: number) {}\n\n /** Instantiates the expected ABI, creates a context, and registers its fonts. */\n static async create(wasmUrl: string | URL, fonts: readonly FontRegistration[] = []): Promise<WasmBridge> {\n const response = await fetch(wasmUrl);\n if (!response.ok) throw new WasmRenderError(`Could not load WASM: HTTP ${response.status}`, -10);\n\n let result: WebAssembly.WebAssemblyInstantiatedSource;\n try {\n result = await WebAssembly.instantiateStreaming(response.clone(), {});\n } catch {\n result = await WebAssembly.instantiate(await response.arrayBuffer(), {});\n }\n\n const exports = result.instance.exports as unknown as WasmExports;\n const abiVersion = exports.html2realpdf_abi_version?.();\n if (abiVersion !== EXPECTED_ABI_VERSION) {\n throw new WasmRenderError(`Unsupported WASM ABI version ${String(abiVersion)}; expected ${EXPECTED_ABI_VERSION}`, -14);\n }\n const context = exports.pdf_context_create();\n if (context === 0) throw new WasmRenderError(\"WASM context allocation failed\", -12);\n const bridge = new WasmBridge(exports, context);\n try {\n for (const registration of fonts) bridge.registerFont(registration);\n return bridge;\n } catch (error) {\n try {\n return bridge.rethrow(error);\n } finally {\n bridge.dispose();\n }\n }\n }\n\n /** Serializes render options, invokes the native renderer, and returns owned output. */\n render(html: string, page: NormalizedPage, metadata?: PdfMetadata, cssProfile: CssProfile = \"document\", marginBoxes?: readonly SnapshotPageMarginBox[], pageRules?: readonly SnapshotPageRule[], extras?: PdfExtras): WasmRenderResult {\n if (this.disposed) throw new WasmRenderError(\"WASM bridge has been disposed\", -15);\n const allocations: { pointer: number; length: number }[] = [];\n const copy = (bytes: Uint8Array): number => {\n const length = Math.max(bytes.length, 1);\n const pointer = this.exports.alloc(length);\n if (pointer === 0) throw new WasmRenderError(\"WASM input allocation failed\", -11);\n allocations.push({ pointer, length });\n new Uint8Array(this.exports.memory.buffer, pointer, bytes.length).set(bytes);\n return pointer;\n };\n let resultHandle = 0;\n try {\n const attachments = extras?.attachments?.map(({ data, ...metadata }) => ({\n ...metadata, dataPointer: copy(data), dataLength: data.byteLength,\n }));\n const input = this.encoder.encode(html);\n const inputPointer = copy(input);\n const renderOptions = this.encoder.encode(JSON.stringify({\n pageWidthPoints: page.widthPoints,\n pageHeightPoints: page.heightPoints,\n marginTopPoints: page.marginTopPoints,\n marginRightPoints: page.marginRightPoints,\n marginBottomPoints: page.marginBottomPoints,\n marginLeftPoints: page.marginLeftPoints,\n cssProfile, marginBoxes, pageRules,\n conformance: extras?.conformance,\n attachments,\n metadata: metadata ? {\n ...metadata,\n keywords: Array.isArray(metadata.keywords) ? metadata.keywords.join(\", \") : metadata.keywords,\n } : undefined,\n }));\n const optionsPointer = copy(renderOptions);\n resultHandle = this.exports.render_html_to_pdf_with_context_json_options(\n this.context,\n inputPointer,\n input.length,\n optionsPointer,\n renderOptions.length,\n );\n if (resultHandle === 0) throw new WasmRenderError(\"WASM result allocation failed\", -12);\n\n const status = this.exports.pdf_result_status(resultHandle);\n if (status !== 0) {\n const detail = this.readResultString(resultHandle, \"error\");\n throw new WasmRenderError(detail || `WASM PDF rendering failed with status ${status}`, status);\n }\n\n const pointer = this.exports.pdf_result_data_ptr(resultHandle);\n const length = this.exports.pdf_result_data_len(resultHandle);\n if (pointer === 0 || length === 0) throw new WasmRenderError(\"WASM returned an empty PDF\", -13);\n\n return {\n bytes: new Uint8Array(this.exports.memory.buffer, pointer, length).slice(),\n pageCount: this.exports.pdf_result_page_count(resultHandle),\n diagnostics: this.readDiagnostics(resultHandle),\n };\n } catch (error) {\n return this.rethrow(error);\n } finally {\n if (!this.disposed) {\n try {\n if (resultHandle !== 0) this.exports.pdf_result_free(resultHandle);\n for (const { pointer, length } of allocations) this.exports.free(pointer, length);\n } catch (error) {\n this.rethrow(error);\n }\n }\n }\n }\n\n /** Frees the renderer context and every font copied into it. */\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.exports.pdf_context_free(this.context);\n }\n\n /** Copies one font registration across the ABI into context-owned storage. */\n private registerFont(registration: FontRegistration): void {\n const family = this.encoder.encode(registration.family.trim());\n const data = registration.data instanceof Uint8Array\n ? registration.data\n : new Uint8Array(registration.data);\n if (family.length === 0 || data.length === 0) throw new WasmRenderError(\"Font family and data must not be empty\", -16);\n const familyPointer = this.exports.alloc(family.length);\n const dataPointer = this.exports.alloc(data.length);\n if (familyPointer === 0 || dataPointer === 0) {\n if (familyPointer !== 0) this.exports.free(familyPointer, family.length);\n if (dataPointer !== 0) this.exports.free(dataPointer, data.length);\n throw new WasmRenderError(\"WASM font allocation failed\", -11);\n }\n try {\n new Uint8Array(this.exports.memory.buffer, familyPointer, family.length).set(family);\n new Uint8Array(this.exports.memory.buffer, dataPointer, data.length).set(data);\n const numericWeight = registration.weight === \"bold\" ? 700 : registration.weight === \"normal\" || registration.weight === undefined\n ? 400\n : registration.weight;\n const status = this.exports.pdf_context_register_font(\n this.context,\n familyPointer,\n family.length,\n dataPointer,\n data.length,\n numericWeight,\n registration.style === \"italic\" ? 1 : 0,\n );\n if (status !== 0) throw new WasmRenderError(`WASM font registration failed with status ${status}`, status);\n } catch (error) {\n this.rethrow(error);\n } finally {\n if (!this.disposed) {\n try {\n this.exports.free(familyPointer, family.length);\n this.exports.free(dataPointer, data.length);\n } catch (error) {\n this.rethrow(error);\n }\n }\n }\n }\n\n private rethrow(error: unknown): never {\n if (error instanceof WebAssembly.RuntimeError) {\n // A trap may leave the stack or allocator invalid, including during free.\n this.disposed = true;\n throw new WasmRenderError(`WASM instance was discarded after a trap: ${error.message}`, WASM_TRAP_STATUS, { cause: error });\n }\n throw error;\n }\n\n private readResultString(handle: number, kind: \"error\" | \"diagnostics\"): string {\n const pointer = kind === \"error\"\n ? this.exports.pdf_result_error_ptr(handle)\n : this.exports.pdf_result_diagnostics_ptr(handle);\n const length = kind === \"error\"\n ? this.exports.pdf_result_error_len(handle)\n : this.exports.pdf_result_diagnostics_len(handle);\n if (pointer === 0 || length === 0) return \"\";\n return new TextDecoder().decode(new Uint8Array(this.exports.memory.buffer, pointer, length));\n }\n\n private readDiagnostics(handle: number): Diagnostic[] {\n const serialized = this.readResultString(handle, \"diagnostics\");\n if (!serialized) return [];\n try {\n const parsed: unknown = JSON.parse(serialized);\n return Array.isArray(parsed) ? parsed as Diagnostic[] : [];\n } catch {\n return [{ code: \"INVALID_WASM_DIAGNOSTICS\", severity: \"warning\", message: \"WASM returned malformed diagnostics\" }];\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"wasm.js","sourceRoot":"","sources":["../src/wasm.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAM9C,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAC/B,kFAAkF;AAClF,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,EAAE,CAAC;AAyFpC;;;;;;;;GAQG;AACH;;;GAGG;AACH,SAAS,qBAAqB,CAAC,OAAoB;IACjD,MAAM,QAAQ,GAAG,CAAyB,IAA+B,EAAE,EAAE,CAAC,CAAC,GAAG,IAAU,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC;IACrH,OAAO;QACL,GAAG,OAAO;QACV,KAAK,EAAE,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC;QAC9B,mBAAmB,EAAE,QAAQ,CAAC,OAAO,CAAC,mBA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n */\n\nimport type { PdfExtras } from \"./attachments.js\";\nimport { WasmRenderError } from \"./errors.js\";\nimport type { NormalizedImageOptions } from \"./image.js\";\nimport type { NormalizedPage } from \"./page.js\";\nimport type { CssProfile, Diagnostic, FontRegistration, PdfMetadata } from \"./types.js\";\nimport type { SnapshotPageMarginBox, SnapshotPageRule } from \"./snapshot.js\";\n\nconst EXPECTED_ABI_VERSION = 3;\n/** Internal status: the instance must be discarded without further WASM calls. */\nexport const WASM_TRAP_STATUS = -23;\n\n/** ABI surface implemented by `src/wasm.zig`. */\ninterface WasmExports {\n html2realpdf_abi_version(): number;\n pdf_context_create(): number;\n pdf_context_free(handle: number): void;\n pdf_context_register_font(\n handle: number,\n familyPointer: number,\n familyLength: number,\n dataPointer: number,\n dataLength: number,\n weight: number,\n style: number,\n ): number;\n memory: WebAssembly.Memory;\n alloc(length: number): number;\n free(pointer: number, length: number): void;\n render_html_to_pdf_with_options(\n pointer: number,\n length: number,\n pageWidthPoints: number,\n pageHeightPoints: number,\n marginTopPoints: number,\n marginRightPoints: number,\n marginBottomPoints: number,\n marginLeftPoints: number,\n ): number;\n render_html_to_pdf_with_json_options(pointer: number, length: number, optionsPointer: number, optionsLength: number): number;\n render_html_to_pdf_with_context_json_options(\n context: number,\n pointer: number,\n length: number,\n optionsPointer: number,\n optionsLength: number,\n ): number;\n pdf_result_status(handle: number): number;\n pdf_result_data_ptr(handle: number): number;\n pdf_result_data_len(handle: number): number;\n pdf_result_page_count(handle: number): number;\n pdf_result_error_ptr(handle: number): number;\n pdf_result_error_len(handle: number): number;\n pdf_result_diagnostics_ptr(handle: number): number;\n pdf_result_diagnostics_len(handle: number): number;\n pdf_result_free(handle: number): void;\n render_html_to_image_with_context_json_options(\n context: number,\n pointer: number,\n length: number,\n optionsPointer: number,\n optionsLength: number,\n ): number;\n image_result_width(handle: number): number;\n image_result_height(handle: number): number;\n html_resource_references_json(pointer: number, length: number): number;\n}\n\n/**\n * External resource referenced by an HTML string, as reported by\n * `src/resources.zig`. Offsets are UTF-8 byte positions in the input.\n */\nexport interface ResourceReference {\n kind: \"image\" | \"stylesheet\" | \"background\";\n /** URL text after HTML character-reference decoding. */\n url: string;\n /** Byte range of the URL text, without quotes. */\n start: number;\n end: number;\n /** Byte range of the whole start tag for `image` and `stylesheet`. */\n tagStart?: number;\n tagEnd?: number;\n}\n\n/** Owned JavaScript result copied out of WASM memory. */\nexport interface WasmRenderResult {\n bytes: Uint8Array;\n pageCount: number;\n diagnostics: Diagnostic[];\n}\n\n/** Owned encoded image copied out of WASM memory. */\nexport interface WasmImageResult {\n bytes: Uint8Array;\n width: number;\n height: number;\n diagnostics: Diagnostic[];\n}\n\n/**\n * Owns one native PDF context and its registered fonts.\n *\n * @remarks\n * All temporary allocations and result handles are freed before `render`\n * returns. PDF bytes are copied first because freeing handles or growing WASM\n * memory invalidates borrowed views. After a WASM trap the whole instance is\n * discarded without further calls, including cleanup against damaged state.\n */\n/**\n * WebAssembly `i32` results reach JavaScript as signed numbers, so addresses\n * and lengths above 2 GiB would turn negative. Statuses stay signed.\n */\nfunction withUnsignedAddresses(exports: WasmExports): WasmExports {\n const unsigned = <Args extends unknown[]>(call: (...args: Args) => number) => (...args: Args) => call(...args) >>> 0;\n return {\n ...exports,\n alloc: unsigned(exports.alloc),\n pdf_result_data_ptr: unsigned(exports.pdf_result_data_ptr),\n pdf_result_data_len: unsigned(exports.pdf_result_data_len),\n pdf_result_error_ptr: unsigned(exports.pdf_result_error_ptr),\n pdf_result_error_len: unsigned(exports.pdf_result_error_len),\n pdf_result_diagnostics_ptr: unsigned(exports.pdf_result_diagnostics_ptr),\n pdf_result_diagnostics_len: unsigned(exports.pdf_result_diagnostics_len),\n };\n}\n\nexport class WasmBridge {\n private readonly encoder = new TextEncoder();\n private disposed = false;\n\n private constructor(private readonly exports: WasmExports, private readonly context: number) {}\n\n /** Instantiates the expected ABI, creates a context, and registers its fonts. */\n static async create(wasmUrl: string | URL, fonts: readonly FontRegistration[] = []): Promise<WasmBridge> {\n const response = await fetch(wasmUrl);\n if (!response.ok) throw new WasmRenderError(`Could not load WASM: HTTP ${response.status}`, -10);\n\n let result: WebAssembly.WebAssemblyInstantiatedSource;\n try {\n result = await WebAssembly.instantiateStreaming(response.clone(), {});\n } catch {\n result = await WebAssembly.instantiate(await response.arrayBuffer(), {});\n }\n return WasmBridge.fromInstance(result.instance, fonts);\n }\n\n /** Instantiates from module bytes already in memory, such as a file read in Node. */\n static async fromBytes(bytes: BufferSource, fonts: readonly FontRegistration[] = []): Promise<WasmBridge> {\n const result = await WebAssembly.instantiate(bytes, {});\n return WasmBridge.fromInstance(result.instance, fonts);\n }\n\n private static fromInstance(instance: WebAssembly.Instance, fonts: readonly FontRegistration[]): WasmBridge {\n const exports = withUnsignedAddresses(instance.exports as unknown as WasmExports);\n const abiVersion = exports.html2realpdf_abi_version?.();\n if (abiVersion !== EXPECTED_ABI_VERSION) {\n throw new WasmRenderError(`Unsupported WASM ABI version ${String(abiVersion)}; expected ${EXPECTED_ABI_VERSION}`, -14);\n }\n const context = exports.pdf_context_create();\n if (context === 0) throw new WasmRenderError(\"WASM context allocation failed\", -12);\n const bridge = new WasmBridge(exports, context);\n try {\n for (const registration of fonts) bridge.registerFont(registration);\n return bridge;\n } catch (error) {\n try {\n return bridge.rethrow(error);\n } finally {\n bridge.dispose();\n }\n }\n }\n\n /** Serializes render options, invokes the native renderer, and returns owned output. */\n render(html: string, page: NormalizedPage, metadata?: PdfMetadata, cssProfile: CssProfile = \"document\", marginBoxes?: readonly SnapshotPageMarginBox[], pageRules?: readonly SnapshotPageRule[], extras?: PdfExtras): WasmRenderResult {\n return this.invoke(\n html,\n (copy) => {\n const attachments = extras?.attachments?.map(({ data, ...metadataFields }) => ({\n ...metadataFields, dataPointer: copy(data), dataLength: data.byteLength,\n }));\n return {\n pageWidthPoints: page.widthPoints,\n pageHeightPoints: page.heightPoints,\n marginTopPoints: page.marginTopPoints,\n marginRightPoints: page.marginRightPoints,\n marginBottomPoints: page.marginBottomPoints,\n marginLeftPoints: page.marginLeftPoints,\n cssProfile, marginBoxes, pageRules,\n conformance: extras?.conformance,\n attachments,\n metadata: metadata ? {\n ...metadata,\n keywords: Array.isArray(metadata.keywords) ? metadata.keywords.join(\", \") : metadata.keywords,\n } : undefined,\n };\n },\n (input, inputLength, options, optionsLength) => this.exports.render_html_to_pdf_with_context_json_options(\n this.context, input, inputLength, options, optionsLength,\n ),\n (handle, bytes, diagnostics) => ({ bytes, pageCount: this.exports.pdf_result_page_count(handle), diagnostics }),\n );\n }\n\n /**\n * Renders one auto-height image. `image.quality` must already be the\n * encoder's 1...100 integer; the native side rejects anything else.\n */\n renderImage(html: string, image: NormalizedImageOptions, cssProfile: CssProfile = \"web\"): WasmImageResult {\n return this.invoke(\n html,\n () => ({ cssProfile, image }),\n (input, inputLength, options, optionsLength) => this.exports.render_html_to_image_with_context_json_options(\n this.context, input, inputLength, options, optionsLength,\n ),\n (handle, bytes, diagnostics) => ({\n bytes,\n width: this.exports.image_result_width(handle),\n height: this.exports.image_result_height(handle),\n diagnostics,\n }),\n );\n }\n\n /** Lists the external resources an HTML string references. */\n resourceReferences(html: string): ResourceReference[] {\n return this.invoke(\n html,\n () => ({}),\n (input, inputLength) => this.exports.html_resource_references_json(input, inputLength),\n (_handle, bytes) => JSON.parse(new TextDecoder().decode(bytes)) as ResourceReference[],\n );\n }\n\n /**\n * Shared result-handle lifecycle: copy inputs into WASM, call the\n * renderer, copy owned output out, then free the handle and every input\n * allocation (unless a trap discarded the instance).\n */\n private invoke<T>(\n html: string,\n buildOptions: (copy: (bytes: Uint8Array) => number) => object,\n call: (inputPointer: number, inputLength: number, optionsPointer: number, optionsLength: number) => number,\n read: (handle: number, bytes: Uint8Array, diagnostics: Diagnostic[]) => T,\n ): T {\n if (this.disposed) throw new WasmRenderError(\"WASM bridge has been disposed\", -15);\n const allocations: { pointer: number; length: number }[] = [];\n const copy = (bytes: Uint8Array): number => {\n const length = Math.max(bytes.length, 1);\n const pointer = this.exports.alloc(length);\n if (pointer === 0) throw new WasmRenderError(\"WASM input allocation failed\", -11);\n allocations.push({ pointer, length });\n new Uint8Array(this.exports.memory.buffer, pointer, bytes.length).set(bytes);\n return pointer;\n };\n let resultHandle = 0;\n try {\n const options = buildOptions(copy);\n const input = this.encoder.encode(html);\n const inputPointer = copy(input);\n const renderOptions = this.encoder.encode(JSON.stringify(options));\n const optionsPointer = copy(renderOptions);\n resultHandle = call(inputPointer, input.length, optionsPointer, renderOptions.length);\n if (resultHandle === 0) throw new WasmRenderError(\"WASM result allocation failed\", -12);\n\n const status = this.exports.pdf_result_status(resultHandle);\n if (status !== 0) {\n const detail = this.readResultString(resultHandle, \"error\");\n throw new WasmRenderError(detail || `WASM rendering failed with status ${status}`, status);\n }\n\n const pointer = this.exports.pdf_result_data_ptr(resultHandle);\n const length = this.exports.pdf_result_data_len(resultHandle);\n if (pointer === 0 || length === 0) throw new WasmRenderError(\"WASM returned an empty result\", -13);\n\n const bytes = new Uint8Array(this.exports.memory.buffer, pointer, length).slice();\n return read(resultHandle, bytes, this.readDiagnostics(resultHandle));\n } catch (error) {\n return this.rethrow(error);\n } finally {\n if (!this.disposed) {\n try {\n if (resultHandle !== 0) this.exports.pdf_result_free(resultHandle);\n for (const { pointer, length } of allocations) this.exports.free(pointer, length);\n } catch (error) {\n this.rethrow(error);\n }\n }\n }\n }\n\n /** Frees the renderer context and every font copied into it. */\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.exports.pdf_context_free(this.context);\n }\n\n /** Copies one font registration across the ABI into context-owned storage. */\n private registerFont(registration: FontRegistration): void {\n const family = this.encoder.encode(registration.family.trim());\n const data = registration.data instanceof Uint8Array\n ? registration.data\n : new Uint8Array(registration.data);\n if (family.length === 0 || data.length === 0) throw new WasmRenderError(\"Font family and data must not be empty\", -16);\n // WOFF and WOFF2 wrap compressed tables that the native TrueType parser\n // cannot read. Keep the native invalid-font status, but name the cause.\n const signature = data.length >= 4 ? String.fromCharCode(data[0]!, data[1]!, data[2]!, data[3]!) : \"\";\n if (signature === \"wOFF\" || signature === \"wOF2\") {\n throw new WasmRenderError(\n `Font \"${registration.family}\" is ${signature === \"wOF2\" ? \"WOFF2\" : \"WOFF\"}; register the TrueType (.ttf) file instead`,\n -6,\n );\n }\n const familyPointer = this.exports.alloc(family.length);\n const dataPointer = this.exports.alloc(data.length);\n if (familyPointer === 0 || dataPointer === 0) {\n if (familyPointer !== 0) this.exports.free(familyPointer, family.length);\n if (dataPointer !== 0) this.exports.free(dataPointer, data.length);\n throw new WasmRenderError(\"WASM font allocation failed\", -11);\n }\n try {\n new Uint8Array(this.exports.memory.buffer, familyPointer, family.length).set(family);\n new Uint8Array(this.exports.memory.buffer, dataPointer, data.length).set(data);\n const numericWeight = registration.weight === \"bold\" ? 700 : registration.weight === \"normal\" || registration.weight === undefined\n ? 400\n : registration.weight;\n const status = this.exports.pdf_context_register_font(\n this.context,\n familyPointer,\n family.length,\n dataPointer,\n data.length,\n numericWeight,\n registration.style === \"italic\" ? 1 : 0,\n );\n if (status !== 0) throw new WasmRenderError(`WASM font registration failed with status ${status}`, status);\n } catch (error) {\n this.rethrow(error);\n } finally {\n if (!this.disposed) {\n try {\n this.exports.free(familyPointer, family.length);\n this.exports.free(dataPointer, data.length);\n } catch (error) {\n this.rethrow(error);\n }\n }\n }\n }\n\n private rethrow(error: unknown): never {\n if (error instanceof WebAssembly.RuntimeError) {\n // A trap may leave the stack or allocator invalid, including during free.\n this.disposed = true;\n throw new WasmRenderError(`WASM instance was discarded after a trap: ${error.message}`, WASM_TRAP_STATUS, { cause: error });\n }\n throw error;\n }\n\n private readResultString(handle: number, kind: \"error\" | \"diagnostics\"): string {\n const pointer = kind === \"error\"\n ? this.exports.pdf_result_error_ptr(handle)\n : this.exports.pdf_result_diagnostics_ptr(handle);\n const length = kind === \"error\"\n ? this.exports.pdf_result_error_len(handle)\n : this.exports.pdf_result_diagnostics_len(handle);\n if (pointer === 0 || length === 0) return \"\";\n return new TextDecoder().decode(new Uint8Array(this.exports.memory.buffer, pointer, length));\n }\n\n private readDiagnostics(handle: number): Diagnostic[] {\n const serialized = this.readResultString(handle, \"diagnostics\");\n if (!serialized) return [];\n try {\n const parsed: unknown = JSON.parse(serialized);\n return Array.isArray(parsed) ? parsed as Diagnostic[] : [];\n } catch {\n return [{ code: \"INVALID_WASM_DIAGNOSTICS\", severity: \"warning\", message: \"WASM returned malformed diagnostics\" }];\n }\n }\n}\n"]}
|
package/dist/worker.js
CHANGED
|
@@ -16,6 +16,15 @@ scope.addEventListener("message", (event) => {
|
|
|
16
16
|
scope.postMessage({ type: "render-error", id: message.id, error: "Worker is not initialized" });
|
|
17
17
|
return;
|
|
18
18
|
}
|
|
19
|
+
if (message.type === "render-image") {
|
|
20
|
+
bridgePromise.then((bridge) => bridge.renderImage(message.html, message.image, message.cssProfile)).then((result) => {
|
|
21
|
+
scope.postMessage({ type: "render-result", id: message.id, bytes: result.bytes, width: result.width, height: result.height, diagnostics: result.diagnostics }, [result.bytes.buffer]);
|
|
22
|
+
}, (error) => scope.postMessage({
|
|
23
|
+
type: "render-error", id: message.id, error: errorMessage(error),
|
|
24
|
+
status: error instanceof WasmRenderError ? error.status : -21,
|
|
25
|
+
}));
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
19
28
|
bridgePromise.then((bridge) => bridge.render(message.html, message.page, message.metadata, message.cssProfile, message.marginBoxes, message.pageRules, message.extras)).then((result) => {
|
|
20
29
|
scope.postMessage({ type: "render-result", id: message.id, bytes: result.bytes, pageCount: result.pageCount, diagnostics: result.diagnostics }, [result.bytes.buffer]);
|
|
21
30
|
}, (error) => scope.postMessage({
|
package/dist/worker.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker.js","sourceRoot":"","sources":["../src/worker.ts"],"names":[],"mappings":"AAAA,iCAAiC;
|
|
1
|
+
{"version":3,"file":"worker.js","sourceRoot":"","sources":["../src/worker.ts"],"names":[],"mappings":"AAAA,iCAAiC;AAUjC,OAA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cAAc,EAAE,EAAE,EAAE,OAAO,CAAC,EAAE,EAAE,KAAK,EAAE,YAAY,CAAC,KAAK,CAAC;QAChE,MAAM,EAAE,KAAK,YAAY,eAAe,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE;KAC9D,CAAC,CACH,CAAC;AACJ,CAAC,CAAC,CAAC;AAEH,SAAS,YAAY,CAAC,KAAc;IAClC,OAAO,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAChE,CAAC","sourcesContent":["/// <reference lib=\"webworker\" />\n\n/**\n * Module Worker protocol that owns a `WasmBridge` off the browser main thread.\n *\n * @packageDocumentation\n */\n\nimport type { PdfExtras } from \"./attachments.js\";\nimport type { NormalizedImageOptions } from \"./image.js\";\nimport { WasmBridge } from \"./wasm.js\";\nimport { WasmRenderError } from \"./errors.js\";\nimport type { NormalizedPage } from \"./page.js\";\nimport type { CssProfile, FontRegistration, PdfMetadata } from \"./types.js\";\nimport type { SnapshotPageMarginBox, SnapshotPageRule } from \"./snapshot.js\";\n\n/** Creates the single renderer context owned by this Worker. */\ninterface InitMessage {\n type: \"init\";\n wasmUrl: string;\n fonts: readonly FontRegistration[];\n}\n\n/** Requests one render and correlates its transferable result by `id`. */\ninterface RenderMessage {\n type: \"render\";\n extras?: PdfExtras;\n id: number;\n html: string;\n page: NormalizedPage;\n metadata?: PdfMetadata;\n cssProfile?: CssProfile;\n marginBoxes?: readonly SnapshotPageMarginBox[];\n pageRules?: readonly SnapshotPageRule[];\n}\n\n/** Requests one image render; results reuse the `render-result` envelope. */\ninterface RenderImageMessage {\n type: \"render-image\";\n id: number;\n html: string;\n image: NormalizedImageOptions;\n cssProfile?: CssProfile;\n}\n\nconst scope = self as unknown as DedicatedWorkerGlobalScope;\nlet bridgePromise: Promise<WasmBridge> | undefined;\n\n// Initialization and renders share the same promise so early render requests\n// wait for font registration instead of racing the native context.\nscope.addEventListener(\"message\", (event: MessageEvent<InitMessage | RenderMessage | RenderImageMessage>) => {\n const message = event.data;\n if (message.type === \"init\") {\n bridgePromise = WasmBridge.create(message.wasmUrl, message.fonts);\n bridgePromise.then(\n () => scope.postMessage({ type: \"ready\" }),\n (error: unknown) => scope.postMessage({ type: \"init-error\", error: errorMessage(error) }),\n );\n return;\n }\n\n if (!bridgePromise) {\n scope.postMessage({ type: \"render-error\", id: message.id, error: \"Worker is not initialized\" });\n return;\n }\n\n if (message.type === \"render-image\") {\n bridgePromise.then((bridge) => bridge.renderImage(message.html, message.image, message.cssProfile)).then(\n (result) => {\n scope.postMessage(\n { type: \"render-result\", id: message.id, bytes: result.bytes, width: result.width, height: result.height, diagnostics: result.diagnostics },\n [result.bytes.buffer],\n );\n },\n (error: unknown) => scope.postMessage({\n type: \"render-error\", id: message.id, error: errorMessage(error),\n status: error instanceof WasmRenderError ? error.status : -21,\n }),\n );\n return;\n }\n\n bridgePromise.then((bridge) => bridge.render(message.html, message.page, message.metadata, message.cssProfile, message.marginBoxes, message.pageRules, message.extras)).then(\n (result) => {\n scope.postMessage(\n { type: \"render-result\", id: message.id, bytes: result.bytes, pageCount: result.pageCount, diagnostics: result.diagnostics },\n [result.bytes.buffer],\n );\n },\n (error: unknown) => scope.postMessage({\n type: \"render-error\", id: message.id, error: errorMessage(error),\n status: error instanceof WasmRenderError ? error.status : -21,\n }),\n );\n});\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,14 +1,22 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@imggion/html2realpdf",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "HTML to real, selectable PDF and JPEG rendering in the browser and Node, powered by Zig and WebAssembly",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
7
7
|
"types": "./dist/index.d.ts",
|
|
8
8
|
"exports": {
|
|
9
9
|
".": {
|
|
10
|
+
"node": {
|
|
11
|
+
"types": "./dist/node.d.ts",
|
|
12
|
+
"import": "./dist/node.js"
|
|
13
|
+
},
|
|
10
14
|
"types": "./dist/index.d.ts",
|
|
11
15
|
"import": "./dist/index.js"
|
|
16
|
+
},
|
|
17
|
+
"./node": {
|
|
18
|
+
"types": "./dist/node.d.ts",
|
|
19
|
+
"import": "./dist/node.js"
|
|
12
20
|
}
|
|
13
21
|
},
|
|
14
22
|
"files": [
|
|
@@ -51,6 +59,7 @@
|
|
|
51
59
|
"node": ">=20.16.0"
|
|
52
60
|
},
|
|
53
61
|
"devDependencies": {
|
|
62
|
+
"jpeg-js": "0.4.4",
|
|
54
63
|
"pdfjs-dist": "5.4.624",
|
|
55
64
|
"typescript": "^7.0.2"
|
|
56
65
|
}
|