@imggion/html2realpdf 0.2.0 → 0.3.1

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 CHANGED
@@ -6,8 +6,14 @@
6
6
  <a href="https://www.npmjs.com/package/@imggion/html2realpdf">
7
7
  <img src="https://img.shields.io/npm/v/@imggion/html2realpdf.svg?style=flat-square" alt="npm version">
8
8
  </a>
9
- <a href="https://github.com/imggion/html2realpdf/releases/tag/v0.2.0">
10
- <img src="https://img.shields.io/badge/release-0.2.0-2ea44f?style=flat-square" alt="Latest release: 0.2.0">
9
+ <a href="https://github.com/imggion/html2realpdf/releases/tag/v0.3.1">
10
+ <img src="https://img.shields.io/badge/release-0.3.1-2ea44f?style=flat-square" alt="Latest release: 0.3.1">
11
+ </a>
12
+ <a href="#compliance">
13
+ <img src="https://img.shields.io/badge/PDF%2FA--3u-d32f2f?style=flat-square&amp;logo=data%3Aimage%2Fsvg%2Bxml%3Bbase64%2CPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0Ij48cGF0aCBmaWxsPSJub25lIiBzdHJva2U9IndoaXRlIiBzdHJva2Utd2lkdGg9IjEuNSIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIgZD0iTTE0IDJINXYyMGgxNFY3ek0xNCAydjVoNSIvPjx0ZXh0IHg9IjEyIiB5PSIxNyIgZmlsbD0id2hpdGUiIGZvbnQtZmFtaWx5PSJBcmlhbCxzYW5zLXNlcmlmIiBmb250LXNpemU9IjciIGZvbnQtd2VpZ2h0PSJib2xkIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIj5QREY8L3RleHQ%2BPC9zdmc%2B" alt="PDF/A-3u">
14
+ </a>
15
+ <a href="#compliance">
16
+ <img src="https://img.shields.io/badge/PDF%2FA--3b-d32f2f?style=flat-square&amp;logo=data%3Aimage%2Fsvg%2Bxml%3Bbase64%2CPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0Ij48cGF0aCBmaWxsPSJub25lIiBzdHJva2U9IndoaXRlIiBzdHJva2Utd2lkdGg9IjEuNSIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIgZD0iTTE0IDJINXYyMGgxNFY3ek0xNCAydjVoNSIvPjx0ZXh0IHg9IjEyIiB5PSIxNyIgZmlsbD0id2hpdGUiIGZvbnQtZmFtaWx5PSJBcmlhbCxzYW5zLXNlcmlmIiBmb250LXNpemU9IjciIGZvbnQtd2VpZ2h0PSJib2xkIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIj5QREY8L3RleHQ%2BPC9zdmc%2B" alt="PDF/A-3b">
11
17
  </a>
12
18
  <img src="https://img.shields.io/badge/-zig-f39b34?style=flat-square&amp;logo=zig&amp;logoColor=white" alt="Zig">
13
19
  <img src="https://img.shields.io/badge/-WASM-654ff0?style=flat-square&amp;logo=webassembly&amp;logoColor=white" alt="WebAssembly">
@@ -28,6 +34,8 @@
28
34
  - [Vue](#vue)
29
35
  - [Preview](#preview)
30
36
  - [Page layouts](#page-layouts)
37
+ - [PDF/A and attachments](#pdfa-and-attachments)
38
+ - [Compliance](#compliance)
31
39
  - [Benchmark](#benchmark)
32
40
  - [Contributing](#contributing)
33
41
  - [License](#license)
@@ -206,6 +214,85 @@ const pdf = await renderPdf(postcard, {
206
214
  });
207
215
  ```
208
216
 
217
+ ## PDF/A and attachments
218
+
219
+ Opt into PDF/A-3u independently of the CSS profile:
220
+
221
+ ```ts
222
+ const pdf = await renderPdf(invoice, {
223
+ conformance: "pdfa-3u",
224
+ metadata: { title: "Invoice" },
225
+ attachments: [{
226
+ name: "invoice.xml",
227
+ data: new TextEncoder().encode(xml),
228
+ mimeType: "application/xml",
229
+ relationship: "Data",
230
+ }],
231
+ });
232
+ ```
233
+
234
+ The writer embeds sRGB, synchronized XMP metadata and Unicode font mappings.
235
+ Incompatible resources produce an error; there is no fallback to ordinary PDF.
236
+ CMYK JPEGs, missing glyphs and fonts that forbid outline embedding are rejected.
237
+ Transparency and supported SVG remain native PDF graphics. This is PDF/A-3u,
238
+ not a claim of Tagged PDF, PDF/UA, digital signatures or Factur-X compliance.
239
+
240
+ Attachments also work without `conformance`. Their bytes are preserved, and
241
+ caller buffers stay usable in both Worker and main-thread execution. MIME type
242
+ defaults to `application/octet-stream` and relationship to `Unspecified`.
243
+ Optional `description` and `modifiedAt: Date` are supported; dates are never
244
+ invented. Empty/duplicate names, malformed MIME types and invalid dates fail.
245
+ The html2pdf.js adapter accepts the same options through `.set(...)`.
246
+
247
+ See [PDF/A implementation and validation](https://github.com/imggion/html2realpdf/blob/main/docs/pdfa.md)
248
+ for limits and the pinned veraPDF gate. Existing calls without these options
249
+ keep their ordinary PDF output.
250
+
251
+ ## Resource limits and untrusted input
252
+
253
+ The native renderer rejects documents deeper than 64 nested elements
254
+ (`DocumentTooDeep`). CSS `var()` substitution is limited to 64 KiB per value,
255
+ 8 MiB of cumulative expansion including intermediate values, and 65,536
256
+ substitutions per cascade (`CssExpansionLimitExceeded`). PNGs are limited to
257
+ 16,777,216 pixels (`ImageTooLarge`); alpha PNG decompression must fit the exact
258
+ scanline size declared by the image (`InvalidPng` otherwise). These limits
259
+ also apply to trusted documents and cannot be raised through render options.
260
+
261
+ These errors leave the renderer usable. An unexpected WASM trap instead
262
+ discards its instance: recreate an explicit `createRenderer()` instance, or
263
+ call `renderPdf()` again to create a fresh default Worker. Failed documents
264
+ are never retried automatically.
265
+
266
+ Returning `null` from `resourceResolver` denies an image, background image, or
267
+ stylesheet without fetching the original URL. `resourcePolicy: "error"`
268
+ rejects the render; `"omit"` skips the resource and returns a diagnostic.
269
+ Without a resolver, image URLs can be fetched normally. Already embedded
270
+ image data URLs bypass the resolver, and live DOM resources may already have
271
+ been loaded by the host page.
272
+
273
+ These are targeted safeguards, not a general CPU or memory quota. Keep Worker
274
+ execution for untrusted documents and apply application-level input-size and
275
+ resource allowlists; native service integrations also need process isolation
276
+ and external time/memory limits.
277
+
278
+ ## Compliance
279
+
280
+ <p align="center">
281
+ <img src="https://raw.githubusercontent.com/imggion/html2realpdf/bacb5d0c1f8e240593c4813c4e78cf529f48e710/docs/assets/pdfa-3u-validation.png" alt="veraPDF 1.30.2 report for test.pdf: PDF/A-3u validation passed, with 14,749 passed checks and zero failed checks." width="600">
282
+ </p>
283
+
284
+ Try it yourself: render a document with `conformance: "pdfa-3u"`, download it,
285
+ and open it in [veraPDF](https://verapdf.org/), or check both profiles with its
286
+ [CLI](https://docs.verapdf.org/cli/validation/):
287
+
288
+ ```sh
289
+ verapdf --flavour 3u --format text invoice.pdf
290
+ verapdf --flavour 3b --format text invoice.pdf
291
+ ```
292
+
293
+ To run the repository's PDF/A-3u validation suite, use `make test-pdfa` after
294
+ completing the [contributor setup](#contributing).
295
+
209
296
  ## Benchmark
210
297
 
211
298
  One recorded run of the deterministic 30-page stress report produced:
@@ -224,7 +311,8 @@ One recorded run of the deterministic 30-page stress report produced:
224
311
 
225
312
  ## Contributing
226
313
 
227
- You need Zig `0.16.0`, Node.js `20.16+`, npm, and Make. On a fresh checkout,
314
+ You need Zig `0.16.0`, Node.js `20.16+`, npm, and Make. The PDF/A gate
315
+ also needs Java 17+, Poppler, curl and unzip. On a fresh checkout,
228
316
  install the JavaScript dependencies once:
229
317
 
230
318
  ```sh
@@ -240,6 +328,7 @@ npm ci --prefix tests/web
240
328
  | `make wasm` | Build the default `ReleaseFast` WebAssembly and browser package |
241
329
  | `make wasm-small` | Build the optional size-oriented `ReleaseSmall` package asset |
242
330
  | `make react` | Start the React integration app |
331
+ | `make test-pdfa` | Validate PDF/A-3u with veraPDF 1.30.2 and benchmark 30 pages |
243
332
  | `make test-release` | Run the complete release gate |
244
333
 
245
334
  To open the small browser test harness:
package/dist/LICENSE.md CHANGED
@@ -463,3 +463,19 @@ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
463
463
  ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
464
464
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
465
465
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
466
+
467
+
468
+ ## ICC sRGB2014 profile
469
+
470
+ Asset: `src/assets/color/sRGB2014.icc` (unmodified, February 2015 revision).
471
+ Source: https://registry.color.org/rgb-registry/profiles/sRGB2014.icc
472
+ SHA-256: `384b832de3412066743b52a75ee906b6fb9fb8d9e09e936fc2c43223815c6e0a`
473
+ Copyright International Color Consortium.
474
+
475
+ This profile is made available by the International Color Consortium, and may
476
+ be copied, distributed, embedded, made, used, and sold without restriction.
477
+ Altered versions of this profile shall have the original identification and
478
+ copyright information removed and shall not be misrepresented as the original
479
+ profile.
480
+
481
+ License source: https://registry.color.org/profile-library/
@@ -0,0 +1,15 @@
1
+ import type { PdfAttachment, RenderOptions } from "./types.js";
2
+ export interface PreparedAttachment {
3
+ name: string;
4
+ data: Uint8Array<ArrayBuffer>;
5
+ mimeType: string;
6
+ relationship: NonNullable<PdfAttachment["relationship"]>;
7
+ description?: string;
8
+ modifiedAt?: string;
9
+ }
10
+ export interface PdfExtras {
11
+ conformance?: RenderOptions["conformance"];
12
+ attachments?: readonly PreparedAttachment[];
13
+ }
14
+ /** Copies just the supplied views, keeping caller buffers usable after Worker transfer. */
15
+ export declare function preparePdfExtras(options: Pick<RenderOptions, "conformance" | "attachments">): PdfExtras;
@@ -0,0 +1,73 @@
1
+ /** Render-local attachment ownership and validation shared by both backends. */
2
+ import { WasmRenderError } from "./errors.js";
3
+ /** Copies just the supplied views, keeping caller buffers usable after Worker transfer. */
4
+ export function preparePdfExtras(options) {
5
+ if (options.conformance !== undefined && options.conformance !== "pdfa-3u") {
6
+ fail("Unsupported PDF conformance");
7
+ }
8
+ const result = {};
9
+ if (options.conformance !== undefined)
10
+ result.conformance = options.conformance;
11
+ if (options.attachments === undefined)
12
+ return result;
13
+ if (!Array.isArray(options.attachments))
14
+ fail("Attachments must be an array");
15
+ const names = new Set();
16
+ result.attachments = options.attachments.map((attachment) => {
17
+ if (!attachment || typeof attachment.name !== "string" || !attachment.name.trim()) {
18
+ fail("Attachment name must not be empty");
19
+ }
20
+ validateString(attachment.name);
21
+ if (names.has(attachment.name))
22
+ fail(`Duplicate attachment name: ${attachment.name}`);
23
+ names.add(attachment.name);
24
+ const mimeType = attachment.mimeType === undefined ? "application/octet-stream" : attachment.mimeType;
25
+ if (typeof mimeType !== "string" ||
26
+ !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(mimeType)) {
27
+ fail("Invalid attachment MIME type");
28
+ }
29
+ const relationship = attachment.relationship === undefined ? "Unspecified" : attachment.relationship;
30
+ if (!["Source", "Data", "Alternative", "Supplement", "Unspecified"].includes(relationship)) {
31
+ fail("Invalid attachment relationship");
32
+ }
33
+ if (!(attachment.data instanceof ArrayBuffer) && !(attachment.data instanceof Uint8Array)) {
34
+ fail("Attachment data must be an ArrayBuffer or Uint8Array");
35
+ }
36
+ // Copy only the supplied view so Worker transfer cannot detach the caller's buffer.
37
+ let data;
38
+ try {
39
+ data = new Uint8Array(attachment.data instanceof Uint8Array ? attachment.data : new Uint8Array(attachment.data));
40
+ }
41
+ catch {
42
+ return fail("Attachment buffer is detached or invalid");
43
+ }
44
+ const prepared = { name: attachment.name, data, mimeType, relationship };
45
+ if (attachment.description !== undefined) {
46
+ validateString(attachment.description);
47
+ prepared.description = attachment.description;
48
+ }
49
+ if (attachment.modifiedAt !== undefined) {
50
+ const date = attachment.modifiedAt;
51
+ if (!(date instanceof Date) ||
52
+ !Number.isFinite(date.getTime()) ||
53
+ date.getUTCFullYear() < 1 ||
54
+ date.getUTCFullYear() > 9999) {
55
+ fail("Invalid attachment modification date");
56
+ }
57
+ prepared.modifiedAt = `D:${date.toISOString().slice(0, 19).replace(/[-:T]/g, "")}Z`;
58
+ }
59
+ return prepared;
60
+ });
61
+ return result;
62
+ }
63
+ function validateString(value) {
64
+ if (typeof value !== "string")
65
+ fail("Attachment text must be a string");
66
+ for (const character of value) {
67
+ const cp = character.codePointAt(0);
68
+ if (cp === 0 || cp === 0xfffe || cp === 0xffff || (cp >= 0xd800 && cp <= 0xdfff))
69
+ fail("Invalid attachment Unicode text");
70
+ }
71
+ }
72
+ function fail(message) { throw new WasmRenderError(message, -4); }
73
+ //# sourceMappingURL=attachments.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"attachments.js","sourceRoot":"","sources":["../src/attachments.ts"],"names":[],"mappings":"AAAA,gFAAgF;AAChF,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAiB9C,2FAA2F;AAC3F,MAAM,UAAU,gBAAgB,CAAC,OAA2D;IAC1F,IAAI,OAAO,CAAC,WAAW,KAAK,SAAS,IAAI,OAAO,CAAC,WAAW,KAAK,SAAS,EAAE,CAAC;QAC3E,IAAI,CAAC,6BAA6B,CAAC,CAAC;IACtC,CAAC;IAED,MAAM,MAAM,GAAc,EAAE,CAAC;IAC7B,IAAI,OAAO,CAAC,WAAW,KAAK,SAAS;QAAE,MAAM,CAAC,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC;IAEhF,IAAI,OAAO,CAAC,WAAW,KAAK,SAAS;QAAE,OAAO,MAAM,CAAC;IACrD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,WAAW,CAAC;QAAE,IAAI,CAAC,8BAA8B,CAAC,CAAC;IAE9E,MAAM,KAAK,GAAG,IAAI,GAAG,EAAU,CAAC;IAChC,MAAM,CAAC,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,UAAU,EAAsB,EAAE;QAC9E,IAAI,CAAC,UAAU,IAA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C;IACxE,KAAK,MAAM,SAAS,IAAI,KAAK,EAAE,CAAC;QAC9B,MAAM,EAAE,GAAG,SAAS,CAAC,WAAW,CAAC,CAAC,CAAE,CAAC;QACrC,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,KAAK,MAAM,IAAI,EAAE,KAAK,MAAM,IAAI,CAAC,EAAE,IAAI,MAAM,IAAI,EAAE,IAAI,MAAM,CAAC;YAAE,IAAI,CAAC,iCAAiC,CAAC,CAAC;IAC5H,CAAC;AACH,CAAC;AAED,SAAS,IAAI,CAAC,OAAe,IAAW,MAAM,IAAI,eAAe,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC","sourcesContent":["/** Render-local attachment ownership and validation shared by both backends. */\nimport { WasmRenderError } from \"./errors.js\";\nimport type { PdfAttachment, RenderOptions } from \"./types.js\";\n\nexport interface PreparedAttachment {\n name: string;\n data: Uint8Array<ArrayBuffer>;\n mimeType: string;\n relationship: NonNullable<PdfAttachment[\"relationship\"]>;\n description?: string;\n modifiedAt?: string;\n}\n\nexport interface PdfExtras {\n conformance?: RenderOptions[\"conformance\"];\n attachments?: readonly PreparedAttachment[];\n}\n\n/** Copies just the supplied views, keeping caller buffers usable after Worker transfer. */\nexport function preparePdfExtras(options: Pick<RenderOptions, \"conformance\" | \"attachments\">): PdfExtras {\n if (options.conformance !== undefined && options.conformance !== \"pdfa-3u\") {\n fail(\"Unsupported PDF conformance\");\n }\n\n const result: PdfExtras = {};\n if (options.conformance !== undefined) result.conformance = options.conformance;\n\n if (options.attachments === undefined) return result;\n if (!Array.isArray(options.attachments)) fail(\"Attachments must be an array\");\n\n const names = new Set<string>();\n result.attachments = options.attachments.map((attachment): PreparedAttachment => {\n if (!attachment || typeof attachment.name !== \"string\" || !attachment.name.trim()) {\n fail(\"Attachment name must not be empty\");\n }\n validateString(attachment.name);\n if (names.has(attachment.name)) fail(`Duplicate attachment name: ${attachment.name}`);\n names.add(attachment.name);\n\n const mimeType = attachment.mimeType === undefined ? \"application/octet-stream\" : attachment.mimeType;\n if (\n typeof mimeType !== \"string\" ||\n !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(mimeType)\n ) {\n fail(\"Invalid attachment MIME type\");\n }\n\n const relationship = attachment.relationship === undefined ? \"Unspecified\" : attachment.relationship;\n if (![\"Source\", \"Data\", \"Alternative\", \"Supplement\", \"Unspecified\"].includes(relationship)) {\n fail(\"Invalid attachment relationship\");\n }\n\n if (!(attachment.data instanceof ArrayBuffer) && !(attachment.data instanceof Uint8Array)) {\n fail(\"Attachment data must be an ArrayBuffer or Uint8Array\");\n }\n\n // Copy only the supplied view so Worker transfer cannot detach the caller's buffer.\n let data: Uint8Array<ArrayBuffer>;\n try {\n data = new Uint8Array(\n attachment.data instanceof Uint8Array ? attachment.data : new Uint8Array(attachment.data),\n );\n } catch {\n return fail(\"Attachment buffer is detached or invalid\");\n }\n\n const prepared: PreparedAttachment = { name: attachment.name, data, mimeType, relationship };\n\n if (attachment.description !== undefined) {\n validateString(attachment.description);\n prepared.description = attachment.description;\n }\n\n if (attachment.modifiedAt !== undefined) {\n const date = attachment.modifiedAt;\n if (\n !(date instanceof Date) ||\n !Number.isFinite(date.getTime()) ||\n date.getUTCFullYear() < 1 ||\n date.getUTCFullYear() > 9999\n ) {\n fail(\"Invalid attachment modification date\");\n }\n prepared.modifiedAt = `D:${date.toISOString().slice(0, 19).replace(/[-:T]/g, \"\")}Z`;\n }\n\n return prepared;\n });\n\n return result;\n}\n\nfunction validateString(value: string): void {\n if (typeof value !== \"string\") fail(\"Attachment text must be a string\");\n for (const character of value) {\n const cp = character.codePointAt(0)!;\n if (cp === 0 || cp === 0xfffe || cp === 0xffff || (cp >= 0xd800 && cp <= 0xdfff)) fail(\"Invalid attachment Unicode text\");\n }\n}\n\nfunction fail(message: string): never { throw new WasmRenderError(message, -4); }\n"]}
package/dist/compat.js CHANGED
@@ -184,6 +184,12 @@ function compatRenderOptions(options) {
184
184
  if (options.margin !== undefined)
185
185
  page.margin = options.margin;
186
186
  const renderOptions = { page };
187
+ if (options.metadata !== undefined)
188
+ renderOptions.metadata = options.metadata;
189
+ if (options.conformance !== undefined)
190
+ renderOptions.conformance = options.conformance;
191
+ if (options.attachments !== undefined)
192
+ renderOptions.attachments = options.attachments;
187
193
  if (options.enableLinks !== undefined)
188
194
  renderOptions.enableLinks = options.enableLinks;
189
195
  if (options.pagebreak) {
@@ -1 +1 @@
1
- {"version":3,"file":"compat.js","sourceRoot":"","sources":["../src/compat.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,oCAAoC,EAAE,MAAM,aAAa,CAAC;AACnE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAG1C;;;;;;;GAOG;AACH,MAAM,OAAO,YAAY;IACf,MAAM,CAAc;IACpB,OAAO,GAAoB,EAAE,CAAC;IAC9B,UAAU,CAAmC;IAC7C,IAAI,GAAqB,OAAO,CAAC,OAAO,EAAE,CAAC;IAEnD,2EAA2E;IAC3E,IAAI,CAAC,MAAkB,EAAE,IAA8C;QACrE,IAAI,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,KAAK,EAAE,CAAC;YACxC,MAAM,IAAI,oCAAoC,CAAC,aAAa,IAAI,GAAG,CAAC,CAAC;QACvE,CAAC;QACD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;QAC5B,OAAO,IAAI,CAAC;IACd,CAAC;IAED,oFAAoF;IACpF,GAAG,CAAC,OAAwB;QAC1B,IAAI,OAAO,CAAC,WAAW,KAAK,SAAS,EAAE,CAAC;YACtC,MAAM,IAAI,oCAAoC,CAAC,qBAAqB,CAAC,CAAC;QACxE,CAAC;QACD,IAAI,OAAO,CAAC,KAAK,KAAK,SAAS,EAAE,CAAC;YAChC,MA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C,OAAO,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;QAC7E,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;IAC7B,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * PDF-oriented html2pdf.js compatibility chain over the native renderer.\n *\n * @packageDocumentation\n */\n\nimport { UnsupportedCompatibilityFeatureError } from \"./errors.js\";\nimport { PdfDocument } from \"./pdf-document.js\";\nimport { renderPdf } from \"./renderer.js\";\nimport type { Html2PdfOptions, HtmlSource, PageOptions, PdfOutputType, RenderOptions } from \"./types.js\";\n\n/**\n * Stateful, Promise-like compatibility chain.\n *\n * @remarks\n * The worker caches one `PdfDocument` until its source or options change.\n * Raster-only html2pdf.js stages fail explicitly rather than silently changing\n * the native PDF model.\n */\nexport class CompatWorker implements PromiseLike<PdfDocument> {\n private source?: HtmlSource;\n private options: Html2PdfOptions = {};\n private pdfPromise: Promise<PdfDocument> | undefined;\n private tail: Promise<unknown> = Promise.resolve();\n\n /** Sets the HTML source; canvas and image input stages are unsupported. */\n from(source: HtmlSource, type?: \"string\" | \"element\" | \"canvas\" | \"img\"): this {\n if (type === \"canvas\" || type === \"img\") {\n throw new UnsupportedCompatibilityFeatureError(`from(..., ${type})`);\n }\n this.source = source;\n this.pdfPromise = undefined;\n return this;\n }\n\n /** Shallow-merges supported compatibility options and invalidates cached output. */\n set(options: Html2PdfOptions): this {\n if (options.html2canvas !== undefined) {\n throw new UnsupportedCompatibilityFeatureError(\"html2canvas options\");\n }\n if (options.image !== undefined) {\n throw new UnsupportedCompatibilityFeatureError(\"image options\");\n }\n this.options = { ...this.options, ...options };\n this.pdfPromise = undefined;\n return this;\n }\n\n /** Alias for `set`, retained for html2pdf.js chain compatibility. */\n using(options: Html2PdfOptions): this {\n return this.set(options);\n }\n\n /**\n * Advances to PDF output for `pdf` or `container` targets.\n *\n * @remarks\n * The wrapper has no public intermediate container. A `container` target\n * therefore schedules the PDF directly; canvas and image targets throw.\n */\n to(target: \"pdf\" | \"container\" | \"canvas\" | \"img\"): this {\n if (target === \"pdf\" || target === \"container\") return this.toPdf();\n throw new UnsupportedCompatibilityFeatureError(`to(${target})`);\n }\n\n /** Schedules PDF rendering while preserving the fluent chain. */\n toPdf(): this {\n this.tail = this.ensurePdf();\n return this;\n }\n\n /** Compatibility no-op; no intermediate snapshot container is exposed. */\n toContainer(): this {\n return this;\n }\n\n /** Always throws because full-page canvas output is intentionally unsupported. */\n toCanvas(): never {\n throw new UnsupportedCompatibilityFeatureError(\"toCanvas\");\n }\n\n /** Always throws because raster image output is intentionally unsupported. */\n toImg(): never {\n throw new UnsupportedCompatibilityFeatureError(\"toImg\");\n }\n\n /** Schedules a browser download using the explicit or configured filename. */\n save(filename = this.options.filename ?? \"file.pdf\"): this {\n this.tail = this.ensurePdf().then((pdf) => pdf.download(filename));\n return this;\n }\n\n /** Alias for `save`. */\n saveAs(filename?: string): this {\n return this.save(filename);\n }\n\n /**\n * Resolves PDF output in a compatibility encoding.\n *\n * @remarks\n * Blob URL outputs remain owned by the cached `PdfDocument`. Obtain it with\n * `get(\"pdf\")` to revoke the URL, or dispose the document when finished.\n */\n outputPdf(type?: \"blob\"): Promise<Blob>;\n outputPdf(type: \"arraybuffer\"): Promise<ArrayBuffer>;\n outputPdf(type: StringPdfOutputType): Promise<string>;\n outputPdf(type: PdfOutputType): Promise<ArrayBuffer | Blob | string>;\n async outputPdf(type: PdfOutputType = \"blob\"): Promise<ArrayBuffer | Blob | string> {\n const pdf = await this.ensurePdf();\n switch (type) {\n case \"arraybuffer\": return pdf.toArrayBuffer();\n case \"blob\": return pdf.toBlob();\n case \"bloburl\":\n case \"bloburi\": return pdf.createObjectURL();\n case \"datauristring\":\n case \"dataurlstring\": return blobToDataUrl(pdf.toBlob());\n }\n }\n\n /** Routes generic html2pdf.js output requests to PDF output. */\n output(type?: \"blob\", options?: unknown, source?: \"pdf\"): Promise<Blob>;\n output(type: \"arraybuffer\", options?: unknown, source?: \"pdf\"): Promise<ArrayBuffer>;\n output(type: StringPdfOutputType, options?: unknown, source?: \"pdf\"): Promise<string>;\n output(type: PdfOutputType | undefined, options: unknown, source: \"img\"): Promise<never>;\n output(type?: PdfOutputType, options?: unknown, source?: \"pdf\" | \"img\"): Promise<ArrayBuffer | Blob | string>;\n output(type?: PdfOutputType, _options?: unknown, source: \"pdf\" | \"img\" = \"pdf\"): Promise<ArrayBuffer | Blob | string> {\n if (source === \"img\") return Promise.reject(new UnsupportedCompatibilityFeatureError(\"outputImg\"));\n return type === undefined ? this.outputPdf() : this.outputPdf(type);\n }\n\n /** Alias for `output`. */\n export(type?: \"blob\", options?: unknown, source?: \"pdf\"): Promise<Blob>;\n export(type: \"arraybuffer\", options?: unknown, source?: \"pdf\"): Promise<ArrayBuffer>;\n export(type: StringPdfOutputType, options?: unknown, source?: \"pdf\"): Promise<string>;\n export(type: PdfOutputType | undefined, options: unknown, source: \"img\"): Promise<never>;\n export(type?: PdfOutputType, options?: unknown, source?: \"pdf\" | \"img\"): Promise<ArrayBuffer | Blob | string>;\n export(type?: PdfOutputType, options?: unknown, source?: \"pdf\" | \"img\"): Promise<ArrayBuffer | Blob | string> {\n return this.output(type, options, source);\n }\n\n /** Returns a rejected promise because raster image output is unsupported. */\n outputImg(): Promise<never> {\n return Promise.reject(new UnsupportedCompatibilityFeatureError(\"outputImg\"));\n }\n\n /**\n * Resolves the cached PDF for `pdf`, or a configured compatibility option for\n * any other key, then optionally invokes the legacy callback.\n */\n get(key: string, callback?: (value: unknown) => void): Promise<unknown> {\n const value = key === \"pdf\" ? this.ensurePdf() : Promise.resolve(this.options[key as keyof Html2PdfOptions]);\n return value.then((resolved) => {\n callback?.(resolved);\n return resolved;\n });\n }\n\n /** Interrupts a chain by throwing the supplied message as an `Error`. */\n error(message: string): never {\n throw new Error(message);\n }\n\n /** Makes the chain awaitable and resolves it to the cached `PdfDocument`. */\n then<TResult1 = PdfDocument, TResult2 = never>(\n onFulfilled?: ((value: PdfDocument) => TResult1 | PromiseLike<TResult1>) | null,\n onRejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n ): Promise<TResult1 | TResult2> {\n return this.tail.then(() => this.ensurePdf()).then(onFulfilled, onRejected);\n }\n\n /** Compatibility alias for `then`. */\n thenCore<TResult1 = PdfDocument, TResult2 = never>(\n onFulfilled?: ((value: PdfDocument) => TResult1 | PromiseLike<TResult1>) | null,\n onRejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n ): Promise<TResult1 | TResult2> {\n return this.then(onFulfilled, onRejected);\n }\n\n /** Compatibility alias for `then`. */\n thenExternal<TResult1 = PdfDocument, TResult2 = never>(\n onFulfilled?: ((value: PdfDocument) => TResult1 | PromiseLike<TResult1>) | null,\n onRejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n ): Promise<TResult1 | TResult2> {\n return this.then(onFulfilled, onRejected);\n }\n\n /** Compatibility alias for `then`. */\n run<TResult1 = PdfDocument, TResult2 = never>(\n onFulfilled?: ((value: PdfDocument) => TResult1 | PromiseLike<TResult1>) | null,\n onRejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n ): Promise<TResult1 | TResult2> {\n return this.then(onFulfilled, onRejected);\n }\n\n /** Handles a failed chain while preserving `PdfDocument` as the success type. */\n catch<TResult = never>(onRejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null): Promise<PdfDocument | TResult> {\n return this.then(undefined, onRejected);\n }\n\n /** Compatibility alias for `catch`. */\n catchExternal<TResult = never>(onRejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null): Promise<PdfDocument | TResult> {\n return this.catch(onRejected);\n }\n\n private ensurePdf(): Promise<PdfDocument> {\n if (!this.source) return Promise.reject(new Error(\"No HTML source was provided\"));\n this.pdfPromise ??= renderPdf(this.source, compatRenderOptions(this.options));\n return this.pdfPromise;\n }\n}\n\n/**\n * Creates an html2pdf.js-compatible PDF chain.\n *\n * @remarks\n * Passing a source directly preserves html2pdf.js shorthand behavior and also\n * schedules `save`. Call without a source when composing an explicit chain.\n *\n * @example\n * ```ts\n * await html2pdf()\n * .set({ filename: \"invoice.pdf\", margin: [10, 12] })\n * .from(element)\n * .save();\n * ```\n */\nexport default function html2pdf(source?: HtmlSource, options?: Html2PdfOptions): CompatWorker {\n const worker = new CompatWorker();\n if (options) worker.set(options);\n if (source) worker.from(source).save();\n return worker;\n}\n\nhtml2pdf.Worker = CompatWorker;\n\nfunction compatRenderOptions(options: Html2PdfOptions): RenderOptions {\n const page: PageOptions = { unit: options.jsPDF?.unit ?? \"mm\" };\n if (options.jsPDF?.format !== undefined) page.format = options.jsPDF.format;\n if (options.jsPDF?.orientation !== undefined) page.orientation = options.jsPDF.orientation;\n if (options.margin !== undefined) page.margin = options.margin;\n\n const renderOptions: RenderOptions = { page };\n if (options.enableLinks !== undefined) renderOptions.enableLinks = options.enableLinks;\n if (options.pagebreak) {\n const modes = typeof options.pagebreak.mode === \"string\"\n ? [options.pagebreak.mode]\n : options.pagebreak.mode ?? [\"css\", \"legacy\"];\n const pageBreak: NonNullable<RenderOptions[\"pageBreak\"]> = {\n legacy: modes.includes(\"legacy\"),\n avoidAll: modes.includes(\"avoid-all\"),\n };\n if (options.pagebreak.before !== undefined) pageBreak.before = options.pagebreak.before;\n if (options.pagebreak.after !== undefined) pageBreak.after = options.pagebreak.after;\n if (options.pagebreak.avoid !== undefined) pageBreak.avoid = options.pagebreak.avoid;\n renderOptions.pageBreak = pageBreak;\n }\n return renderOptions;\n}\n\ntype StringPdfOutputType = Exclude<PdfOutputType, \"arraybuffer\" | \"blob\">;\n\nfunction blobToDataUrl(blob: Blob): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.addEventListener(\"load\", () => resolve(String(reader.result)), { once: true });\n reader.addEventListener(\"error\", () => reject(reader.error), { once: true });\n reader.readAsDataURL(blob);\n });\n}\n"]}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AAE,GAAG,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;QAC7E,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;IAC7B,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * PDF-oriented html2pdf.js compatibility chain over the native renderer.\n *\n * @packageDocumentation\n */\n\nimport { UnsupportedCompatibilityFeatureError } from \"./errors.js\";\nimport { PdfDocument } from \"./pdf-document.js\";\nimport { renderPdf } from \"./renderer.js\";\nimport type { Html2PdfOptions, HtmlSource, PageOptions, PdfOutputType, RenderOptions } from \"./types.js\";\n\n/**\n * Stateful, Promise-like compatibility chain.\n *\n * @remarks\n * The worker caches one `PdfDocument` until its source or options change.\n * Raster-only html2pdf.js stages fail explicitly rather than silently changing\n * the native PDF model.\n */\nexport class CompatWorker implements PromiseLike<PdfDocument> {\n private source?: HtmlSource;\n private options: Html2PdfOptions = {};\n private pdfPromise: Promise<PdfDocument> | undefined;\n private tail: Promise<unknown> = Promise.resolve();\n\n /** Sets the HTML source; canvas and image input stages are unsupported. */\n from(source: HtmlSource, type?: \"string\" | \"element\" | \"canvas\" | \"img\"): this {\n if (type === \"canvas\" || type === \"img\") {\n throw new UnsupportedCompatibilityFeatureError(`from(..., ${type})`);\n }\n this.source = source;\n this.pdfPromise = undefined;\n return this;\n }\n\n /** Shallow-merges supported compatibility options and invalidates cached output. */\n set(options: Html2PdfOptions): this {\n if (options.html2canvas !== undefined) {\n throw new UnsupportedCompatibilityFeatureError(\"html2canvas options\");\n }\n if (options.image !== undefined) {\n throw new UnsupportedCompatibilityFeatureError(\"image options\");\n }\n this.options = { ...this.options, ...options };\n this.pdfPromise = undefined;\n return this;\n }\n\n /** Alias for `set`, retained for html2pdf.js chain compatibility. */\n using(options: Html2PdfOptions): this {\n return this.set(options);\n }\n\n /**\n * Advances to PDF output for `pdf` or `container` targets.\n *\n * @remarks\n * The wrapper has no public intermediate container. A `container` target\n * therefore schedules the PDF directly; canvas and image targets throw.\n */\n to(target: \"pdf\" | \"container\" | \"canvas\" | \"img\"): this {\n if (target === \"pdf\" || target === \"container\") return this.toPdf();\n throw new UnsupportedCompatibilityFeatureError(`to(${target})`);\n }\n\n /** Schedules PDF rendering while preserving the fluent chain. */\n toPdf(): this {\n this.tail = this.ensurePdf();\n return this;\n }\n\n /** Compatibility no-op; no intermediate snapshot container is exposed. */\n toContainer(): this {\n return this;\n }\n\n /** Always throws because full-page canvas output is intentionally unsupported. */\n toCanvas(): never {\n throw new UnsupportedCompatibilityFeatureError(\"toCanvas\");\n }\n\n /** Always throws because raster image output is intentionally unsupported. */\n toImg(): never {\n throw new UnsupportedCompatibilityFeatureError(\"toImg\");\n }\n\n /** Schedules a browser download using the explicit or configured filename. */\n save(filename = this.options.filename ?? \"file.pdf\"): this {\n this.tail = this.ensurePdf().then((pdf) => pdf.download(filename));\n return this;\n }\n\n /** Alias for `save`. */\n saveAs(filename?: string): this {\n return this.save(filename);\n }\n\n /**\n * Resolves PDF output in a compatibility encoding.\n *\n * @remarks\n * Blob URL outputs remain owned by the cached `PdfDocument`. Obtain it with\n * `get(\"pdf\")` to revoke the URL, or dispose the document when finished.\n */\n outputPdf(type?: \"blob\"): Promise<Blob>;\n outputPdf(type: \"arraybuffer\"): Promise<ArrayBuffer>;\n outputPdf(type: StringPdfOutputType): Promise<string>;\n outputPdf(type: PdfOutputType): Promise<ArrayBuffer | Blob | string>;\n async outputPdf(type: PdfOutputType = \"blob\"): Promise<ArrayBuffer | Blob | string> {\n const pdf = await this.ensurePdf();\n switch (type) {\n case \"arraybuffer\": return pdf.toArrayBuffer();\n case \"blob\": return pdf.toBlob();\n case \"bloburl\":\n case \"bloburi\": return pdf.createObjectURL();\n case \"datauristring\":\n case \"dataurlstring\": return blobToDataUrl(pdf.toBlob());\n }\n }\n\n /** Routes generic html2pdf.js output requests to PDF output. */\n output(type?: \"blob\", options?: unknown, source?: \"pdf\"): Promise<Blob>;\n output(type: \"arraybuffer\", options?: unknown, source?: \"pdf\"): Promise<ArrayBuffer>;\n output(type: StringPdfOutputType, options?: unknown, source?: \"pdf\"): Promise<string>;\n output(type: PdfOutputType | undefined, options: unknown, source: \"img\"): Promise<never>;\n output(type?: PdfOutputType, options?: unknown, source?: \"pdf\" | \"img\"): Promise<ArrayBuffer | Blob | string>;\n output(type?: PdfOutputType, _options?: unknown, source: \"pdf\" | \"img\" = \"pdf\"): Promise<ArrayBuffer | Blob | string> {\n if (source === \"img\") return Promise.reject(new UnsupportedCompatibilityFeatureError(\"outputImg\"));\n return type === undefined ? this.outputPdf() : this.outputPdf(type);\n }\n\n /** Alias for `output`. */\n export(type?: \"blob\", options?: unknown, source?: \"pdf\"): Promise<Blob>;\n export(type: \"arraybuffer\", options?: unknown, source?: \"pdf\"): Promise<ArrayBuffer>;\n export(type: StringPdfOutputType, options?: unknown, source?: \"pdf\"): Promise<string>;\n export(type: PdfOutputType | undefined, options: unknown, source: \"img\"): Promise<never>;\n export(type?: PdfOutputType, options?: unknown, source?: \"pdf\" | \"img\"): Promise<ArrayBuffer | Blob | string>;\n export(type?: PdfOutputType, options?: unknown, source?: \"pdf\" | \"img\"): Promise<ArrayBuffer | Blob | string> {\n return this.output(type, options, source);\n }\n\n /** Returns a rejected promise because raster image output is unsupported. */\n outputImg(): Promise<never> {\n return Promise.reject(new UnsupportedCompatibilityFeatureError(\"outputImg\"));\n }\n\n /**\n * Resolves the cached PDF for `pdf`, or a configured compatibility option for\n * any other key, then optionally invokes the legacy callback.\n */\n get(key: string, callback?: (value: unknown) => void): Promise<unknown> {\n const value = key === \"pdf\" ? this.ensurePdf() : Promise.resolve(this.options[key as keyof Html2PdfOptions]);\n return value.then((resolved) => {\n callback?.(resolved);\n return resolved;\n });\n }\n\n /** Interrupts a chain by throwing the supplied message as an `Error`. */\n error(message: string): never {\n throw new Error(message);\n }\n\n /** Makes the chain awaitable and resolves it to the cached `PdfDocument`. */\n then<TResult1 = PdfDocument, TResult2 = never>(\n onFulfilled?: ((value: PdfDocument) => TResult1 | PromiseLike<TResult1>) | null,\n onRejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n ): Promise<TResult1 | TResult2> {\n return this.tail.then(() => this.ensurePdf()).then(onFulfilled, onRejected);\n }\n\n /** Compatibility alias for `then`. */\n thenCore<TResult1 = PdfDocument, TResult2 = never>(\n onFulfilled?: ((value: PdfDocument) => TResult1 | PromiseLike<TResult1>) | null,\n onRejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n ): Promise<TResult1 | TResult2> {\n return this.then(onFulfilled, onRejected);\n }\n\n /** Compatibility alias for `then`. */\n thenExternal<TResult1 = PdfDocument, TResult2 = never>(\n onFulfilled?: ((value: PdfDocument) => TResult1 | PromiseLike<TResult1>) | null,\n onRejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n ): Promise<TResult1 | TResult2> {\n return this.then(onFulfilled, onRejected);\n }\n\n /** Compatibility alias for `then`. */\n run<TResult1 = PdfDocument, TResult2 = never>(\n onFulfilled?: ((value: PdfDocument) => TResult1 | PromiseLike<TResult1>) | null,\n onRejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n ): Promise<TResult1 | TResult2> {\n return this.then(onFulfilled, onRejected);\n }\n\n /** Handles a failed chain while preserving `PdfDocument` as the success type. */\n catch<TResult = never>(onRejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null): Promise<PdfDocument | TResult> {\n return this.then(undefined, onRejected);\n }\n\n /** Compatibility alias for `catch`. */\n catchExternal<TResult = never>(onRejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null): Promise<PdfDocument | TResult> {\n return this.catch(onRejected);\n }\n\n private ensurePdf(): Promise<PdfDocument> {\n if (!this.source) return Promise.reject(new Error(\"No HTML source was provided\"));\n this.pdfPromise ??= renderPdf(this.source, compatRenderOptions(this.options));\n return this.pdfPromise;\n }\n}\n\n/**\n * Creates an html2pdf.js-compatible PDF chain.\n *\n * @remarks\n * Passing a source directly preserves html2pdf.js shorthand behavior and also\n * schedules `save`. Call without a source when composing an explicit chain.\n *\n * @example\n * ```ts\n * await html2pdf()\n * .set({ filename: \"invoice.pdf\", margin: [10, 12] })\n * .from(element)\n * .save();\n * ```\n */\nexport default function html2pdf(source?: HtmlSource, options?: Html2PdfOptions): CompatWorker {\n const worker = new CompatWorker();\n if (options) worker.set(options);\n if (source) worker.from(source).save();\n return worker;\n}\n\nhtml2pdf.Worker = CompatWorker;\n\nfunction compatRenderOptions(options: Html2PdfOptions): RenderOptions {\n const page: PageOptions = { unit: options.jsPDF?.unit ?? \"mm\" };\n if (options.jsPDF?.format !== undefined) page.format = options.jsPDF.format;\n if (options.jsPDF?.orientation !== undefined) page.orientation = options.jsPDF.orientation;\n if (options.margin !== undefined) page.margin = options.margin;\n\n const renderOptions: RenderOptions = { page };\n if (options.metadata !== undefined) renderOptions.metadata = options.metadata;\n if (options.conformance !== undefined) renderOptions.conformance = options.conformance;\n if (options.attachments !== undefined) renderOptions.attachments = options.attachments;\n if (options.enableLinks !== undefined) renderOptions.enableLinks = options.enableLinks;\n if (options.pagebreak) {\n const modes = typeof options.pagebreak.mode === \"string\"\n ? [options.pagebreak.mode]\n : options.pagebreak.mode ?? [\"css\", \"legacy\"];\n const pageBreak: NonNullable<RenderOptions[\"pageBreak\"]> = {\n legacy: modes.includes(\"legacy\"),\n avoidAll: modes.includes(\"avoid-all\"),\n };\n if (options.pagebreak.before !== undefined) pageBreak.before = options.pagebreak.before;\n if (options.pagebreak.after !== undefined) pageBreak.after = options.pagebreak.after;\n if (options.pagebreak.avoid !== undefined) pageBreak.avoid = options.pagebreak.avoid;\n renderOptions.pageBreak = pageBreak;\n }\n return renderOptions;\n}\n\ntype StringPdfOutputType = Exclude<PdfOutputType, \"arraybuffer\" | \"blob\">;\n\nfunction blobToDataUrl(blob: Blob): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.addEventListener(\"load\", () => resolve(String(reader.result)), { once: true });\n reader.addEventListener(\"error\", () => reject(reader.error), { once: true });\n reader.readAsDataURL(blob);\n });\n}\n"]}
Binary file
@@ -11,7 +11,8 @@ import type { HtmlSource, RendererInit, RenderOptions } from "./types.js";
11
11
  * @remarks
12
12
  * Create instances with `createRenderer`. Fonts and execution mode belong to
13
13
  * the renderer lifetime; each returned `PdfDocument` has its own shorter
14
- * lifetime. Call `dispose` when the renderer is no longer needed.
14
+ * lifetime. Call `dispose` when the renderer is no longer needed. Input-limit
15
+ * errors leave it reusable; an unexpected WASM trap disposes it permanently.
15
16
  */
16
17
  export declare class Html2RealPdf {
17
18
  private readonly backend;
@@ -23,6 +24,7 @@ export declare class Html2RealPdf {
23
24
  * @throws {@link InvalidSourceError} when a ref is null or the source shape is invalid.
24
25
  * @throws {@link UnsupportedCssError} when strict CSS or fallback policy rejects input.
25
26
  * @throws {@link ResourceLoadError} when required resources cannot be materialized.
27
+ * @throws {@link WasmRenderError} when native limits reject input or WASM fails.
26
28
  */
27
29
  render(source: HtmlSource, options?: RenderOptions): Promise<PdfDocument>;
28
30
  /** Terminates the owned backend and rejects future renders. */
@@ -53,7 +55,9 @@ export declare function createRenderer(init?: RendererInit): Promise<Html2RealPd
53
55
  * The default renderer is cached for the application lifetime and cannot be
54
56
  * configured with custom fonts. Use `createRenderer` when deterministic
55
57
  * backend disposal or renderer-level configuration is required. The returned
56
- * document must still be disposed by the caller.
58
+ * document must still be disposed by the caller. After an unexpected WASM trap,
59
+ * the failed render is rejected and the next call creates a fresh renderer;
60
+ * the failed document is never retried automatically.
57
61
  *
58
62
  * @example
59
63
  * ```ts
package/dist/renderer.js CHANGED
@@ -7,17 +7,18 @@ import { UnsupportedEnvironmentError, WasmRenderError } from "./errors.js";
7
7
  import { normalizePage } from "./page.js";
8
8
  import { PdfDocument } from "./pdf-document.js";
9
9
  import { snapshotSource } from "./snapshot.js";
10
- import { WasmBridge } from "./wasm.js";
10
+ import { preparePdfExtras } from "./attachments.js";
11
+ import { WASM_TRAP_STATUS, WasmBridge } from "./wasm.js";
11
12
  /** Executes the synchronous bridge on the caller's browser thread. */
12
13
  class MainThreadBackend {
13
14
  bridge;
14
15
  constructor(bridge) {
15
16
  this.bridge = bridge;
16
17
  }
17
- render(html, page, metadata, cssProfile, marginBoxes, pageRules, signal) {
18
+ render(html, page, metadata, cssProfile, marginBoxes, pageRules, signal, extras) {
18
19
  if (signal?.aborted)
19
20
  return Promise.reject(abortReason(signal));
20
- return Promise.resolve(this.bridge.render(html, page, metadata, cssProfile, marginBoxes, pageRules));
21
+ return Promise.resolve(this.bridge.render(html, page, metadata, cssProfile, marginBoxes, pageRules, extras));
21
22
  }
22
23
  dispose() {
23
24
  this.bridge.dispose();
@@ -30,6 +31,7 @@ class WorkerBackend {
30
31
  ready;
31
32
  nextId = 1;
32
33
  disposed = false;
34
+ failure;
33
35
  constructor(wasmUrl, fonts) {
34
36
  this.worker = new Worker(new URL("./worker.js", import.meta.url), { type: "module", name: "html2realpdf" });
35
37
  this.ready = new Promise((resolve, reject) => {
@@ -54,21 +56,20 @@ class WorkerBackend {
54
56
  });
55
57
  this.worker.addEventListener("message", (event) => this.handleMessage(event));
56
58
  this.worker.addEventListener("error", (event) => {
57
- const error = new WasmRenderError(event.message || "PDF Worker failed", -22);
58
- for (const pending of this.pending.values()) {
59
- pending.removeAbort?.();
60
- pending.reject(error);
61
- }
62
- this.pending.clear();
59
+ this.stop(new WasmRenderError(event.message || "PDF Worker failed", WASM_TRAP_STATUS));
63
60
  });
64
61
  this.worker.postMessage({ type: "init", wasmUrl, fonts });
65
62
  }
66
- async render(html, page, metadata, cssProfile, marginBoxes, pageRules, signal) {
63
+ async render(html, page, metadata, cssProfile, marginBoxes, pageRules, signal, extras) {
67
64
  if (this.disposed)
68
- throw new Error("Renderer has been disposed");
65
+ throw this.failure;
69
66
  if (signal?.aborted)
70
67
  throw abortReason(signal);
71
68
  await this.ready;
69
+ if (this.disposed)
70
+ throw this.failure;
71
+ if (signal?.aborted)
72
+ throw abortReason(signal);
72
73
  const id = this.nextId++;
73
74
  return new Promise((resolve, reject) => {
74
75
  const pending = { resolve, reject };
@@ -81,17 +82,28 @@ class WorkerBackend {
81
82
  pending.removeAbort = () => signal.removeEventListener("abort", onAbort);
82
83
  }
83
84
  this.pending.set(id, pending);
84
- this.worker.postMessage({ type: "render", id, html, page, metadata, cssProfile, marginBoxes, pageRules });
85
+ try {
86
+ this.worker.postMessage({ type: "render", id, html, page, metadata, cssProfile, marginBoxes, pageRules, extras }, extras?.attachments?.map((attachment) => attachment.data.buffer) ?? []);
87
+ }
88
+ catch (error) {
89
+ this.pending.delete(id);
90
+ pending.removeAbort?.();
91
+ reject(error);
92
+ }
85
93
  });
86
94
  }
87
95
  dispose() {
96
+ this.stop(new Error("Renderer was disposed"));
97
+ }
98
+ stop(error) {
88
99
  if (this.disposed)
89
100
  return;
90
101
  this.disposed = true;
102
+ this.failure = error;
91
103
  this.worker.terminate();
92
104
  for (const pending of this.pending.values()) {
93
105
  pending.removeAbort?.();
94
- pending.reject(new Error("Renderer was disposed"));
106
+ pending.reject(error);
95
107
  }
96
108
  this.pending.clear();
97
109
  }
@@ -99,6 +111,11 @@ class WorkerBackend {
99
111
  const message = event.data;
100
112
  if (message?.type !== "render-result" && message?.type !== "render-error")
101
113
  return;
114
+ // Even an aborted request can report a trap that invalidates other work.
115
+ if (message.type === "render-error" && message.status === WASM_TRAP_STATUS) {
116
+ this.stop(new WasmRenderError(message.error, WASM_TRAP_STATUS));
117
+ return;
118
+ }
102
119
  const pending = this.pending.get(message.id);
103
120
  if (!pending)
104
121
  return;
@@ -122,7 +139,8 @@ class WorkerBackend {
122
139
  * @remarks
123
140
  * Create instances with `createRenderer`. Fonts and execution mode belong to
124
141
  * the renderer lifetime; each returned `PdfDocument` has its own shorter
125
- * lifetime. Call `dispose` when the renderer is no longer needed.
142
+ * lifetime. Call `dispose` when the renderer is no longer needed. Input-limit
143
+ * errors leave it reusable; an unexpected WASM trap disposes it permanently.
126
144
  */
127
145
  export class Html2RealPdf {
128
146
  backend;
@@ -140,12 +158,14 @@ export class Html2RealPdf {
140
158
  * @throws {@link InvalidSourceError} when a ref is null or the source shape is invalid.
141
159
  * @throws {@link UnsupportedCssError} when strict CSS or fallback policy rejects input.
142
160
  * @throws {@link ResourceLoadError} when required resources cannot be materialized.
161
+ * @throws {@link WasmRenderError} when native limits reject input or WASM fails.
143
162
  */
144
163
  async render(source, options = {}) {
145
164
  if (this.disposed)
146
165
  throw new Error("Renderer has been disposed");
147
166
  if (options.signal?.aborted)
148
167
  throw abortReason(options.signal);
168
+ const extras = preparePdfExtras(options);
149
169
  options.onProgress?.({ phase: "snapshot", completed: 0, total: 1 });
150
170
  const snapshotOptions = {
151
171
  resourcePolicy: options.resourcePolicy ?? "error",
@@ -183,7 +203,15 @@ export class Html2RealPdf {
183
203
  options.onProgress?.({ phase: "snapshot", completed: 1, total: 1 });
184
204
  options.onProgress?.({ phase: "wasm", completed: 0, total: 1 });
185
205
  const page = options.page !== undefined ? normalizePage(options.page) : snapshot.page ?? normalizePage();
186
- const rendered = await this.backend.render(applyPageBreakRules(snapshot.html, options.pageBreak), page, options.metadata, options.cssProfile ?? "document", snapshot.pageMarginBoxes, options.page === undefined ? snapshot.pageRules : undefined, options.signal);
206
+ let rendered;
207
+ try {
208
+ rendered = await this.backend.render(applyPageBreakRules(snapshot.html, options.pageBreak), page, options.metadata, options.cssProfile ?? "document", snapshot.pageMarginBoxes, options.page === undefined ? snapshot.pageRules : undefined, options.signal, extras);
209
+ }
210
+ catch (error) {
211
+ if (error instanceof WasmRenderError && error.status === WASM_TRAP_STATUS)
212
+ this.dispose();
213
+ throw error;
214
+ }
187
215
  options.onProgress?.({ phase: "wasm", completed: 1, total: 1 });
188
216
  options.onProgress?.({ phase: "complete", completed: 1, total: 1 });
189
217
  return PdfDocument.create(rendered.bytes, rendered.pageCount, [...snapshot.diagnostics, ...rendered.diagnostics]);
@@ -233,7 +261,9 @@ let defaultRenderer;
233
261
  * The default renderer is cached for the application lifetime and cannot be
234
262
  * configured with custom fonts. Use `createRenderer` when deterministic
235
263
  * backend disposal or renderer-level configuration is required. The returned
236
- * document must still be disposed by the caller.
264
+ * document must still be disposed by the caller. After an unexpected WASM trap,
265
+ * the failed render is rejected and the next call creates a fresh renderer;
266
+ * the failed document is never retried automatically.
237
267
  *
238
268
  * @example
239
269
  * ```ts
@@ -246,7 +276,16 @@ export async function renderPdf(source, options = {}) {
246
276
  defaultRenderer = undefined;
247
277
  throw error;
248
278
  });
249
- return (await defaultRenderer).render(source, options);
279
+ const current = defaultRenderer;
280
+ try {
281
+ return await (await current).render(source, options);
282
+ }
283
+ catch (error) {
284
+ if (error instanceof WasmRenderError && error.status === WASM_TRAP_STATUS && defaultRenderer === current) {
285
+ defaultRenderer = undefined;
286
+ }
287
+ throw error;
288
+ }
250
289
  }
251
290
  function applyPageBreakRules(html, rules) {
252
291
  if (!rules)