bm-render 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/NOTICE +38 -0
- package/README.md +51 -3
- package/README.vi.md +51 -0
- package/THIRD-PARTY-NOTICES.md +1228 -0
- package/js/addons.d.mts +13 -0
- package/js/addons.mjs +74 -0
- package/js/bm_render.core.wasm +0 -0
- package/js/bm_render.pdf.wasm +0 -0
- package/js/bm_render.standard.wasm +0 -0
- package/js/bm_render.wasm +0 -0
- package/js/bm_woff.wasm +0 -0
- package/js/build-manifest.json +46 -0
- package/js/core.d.mts +16 -0
- package/js/core.mjs +20 -0
- package/js/engine.mjs +797 -0
- package/js/full.d.mts +16 -0
- package/js/full.mjs +20 -0
- package/js/index.d.mts +381 -0
- package/js/index.mjs +64 -0
- package/js/native.d.mts +4 -0
- package/js/native.mjs +250 -0
- package/js/node-core.mjs +9 -0
- package/js/node-full.mjs +9 -0
- package/js/node-native.mjs +15 -0
- package/js/node-pdf.mjs +34 -0
- package/js/node-standard.mjs +9 -0
- package/js/node.mjs +63 -0
- package/js/pdf-api.mjs +232 -0
- package/js/pdf-resources.mjs +152 -0
- package/js/pdf-types.d.mts +211 -0
- package/js/pdf.d.mts +85 -0
- package/js/pdf.mjs +26 -0
- package/js/standard.d.mts +16 -0
- package/js/standard.mjs +20 -0
- package/js/wasm-file.mjs +93 -0
- package/js/wasm.d.mts +9 -0
- package/package.json +252 -4
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
// PDF resource preparation. Discovery is the engine's cascade-only pass, shared by native/WASM.
|
|
2
|
+
const binary = (v) => v instanceof ArrayBuffer || ArrayBuffer.isView(v);
|
|
3
|
+
|
|
4
|
+
function ranges(value) {
|
|
5
|
+
if (Array.isArray(value)) return value;
|
|
6
|
+
if (typeof value !== "string") return null;
|
|
7
|
+
return value.split(",").map((raw) => {
|
|
8
|
+
const m = /^\s*U\+([0-9a-f?]{1,6})(?:-([0-9a-f]{1,6}))?\s*$/i.exec(raw);
|
|
9
|
+
if (!m) throw new TypeError(`bm-render: invalid unicodeRange: ${raw}`);
|
|
10
|
+
return [parseInt(m[1].replaceAll("?", "0"), 16), parseInt(m[2] ?? m[1].replaceAll("?", "f"), 16)];
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function uses(text, range) {
|
|
15
|
+
const list = ranges(range);
|
|
16
|
+
if (list === null) return true;
|
|
17
|
+
for (const char of text) {
|
|
18
|
+
const cp = char.codePointAt(0);
|
|
19
|
+
if (list.some(([a, b]) => cp >= a && cp <= b)) return true;
|
|
20
|
+
}
|
|
21
|
+
return false;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const lower = (s) => String(s).toLowerCase();
|
|
25
|
+
const fontRange = (f) => f && !binary(f) && typeof f === "object" ? f.unicodeRange ?? f.ranges : undefined;
|
|
26
|
+
const imageInput = (images) => Array.isArray(images) ? { sources: images } : images && typeof images === "object" ? images : {};
|
|
27
|
+
|
|
28
|
+
function waitFor(promise, signal) {
|
|
29
|
+
if (!signal) return promise;
|
|
30
|
+
signal.throwIfAborted();
|
|
31
|
+
return new Promise((resolve, reject) => {
|
|
32
|
+
const abort = () => reject(signal.reason);
|
|
33
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
34
|
+
promise.then((value) => { signal.removeEventListener("abort", abort); resolve(value); }, (error) => { signal.removeEventListener("abort", abort); reject(error); });
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function download(url, config, signal) {
|
|
39
|
+
const fetcher = config.fetch ?? globalThis.fetch;
|
|
40
|
+
if (typeof fetcher !== "function") throw new Error(`bm-render: no fetch available for ${url}`);
|
|
41
|
+
const response = await fetcher(url, signal ? { signal } : {});
|
|
42
|
+
if (!response?.ok) throw new Error(`bm-render: fetching ${url} failed${response ? ` (${response.status})` : ""}`);
|
|
43
|
+
const limit = config.maxBytes ?? 33554432;
|
|
44
|
+
if (Number(response.headers?.get("content-length")) > limit) { await response.body?.cancel(); throw new Error(`Response exceeds ${limit} bytes`); }
|
|
45
|
+
if (!response.body?.getReader) {
|
|
46
|
+
const data = await response.arrayBuffer();
|
|
47
|
+
if (data.byteLength > limit) throw new Error(`Response exceeds ${limit} bytes`);
|
|
48
|
+
return data;
|
|
49
|
+
}
|
|
50
|
+
const reader = response.body.getReader();
|
|
51
|
+
const chunks = []; let size = 0;
|
|
52
|
+
try {
|
|
53
|
+
for (;;) {
|
|
54
|
+
signal?.throwIfAborted?.();
|
|
55
|
+
const { value, done } = await reader.read();
|
|
56
|
+
if (done) break;
|
|
57
|
+
size += value.byteLength;
|
|
58
|
+
if (size > limit) { await reader.cancel(); throw new Error(`Response exceeds ${limit} bytes`); }
|
|
59
|
+
chunks.push(value);
|
|
60
|
+
}
|
|
61
|
+
} finally { reader.releaseLock(); }
|
|
62
|
+
const data = new Uint8Array(size); let offset = 0;
|
|
63
|
+
for (const chunk of chunks) { data.set(chunk, offset); offset += chunk.byteLength; }
|
|
64
|
+
return data.buffer;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function bytes(url, config, signal) {
|
|
68
|
+
if (config.allowUrl && !config.allowUrl(url)) throw new Error(`URL blocked by allowUrl policy: ${url}`);
|
|
69
|
+
const requestSignal = config.timeout ? signal ? AbortSignal.any([signal, AbortSignal.timeout(config.timeout)]) : AbortSignal.timeout(config.timeout) : signal;
|
|
70
|
+
requestSignal?.throwIfAborted?.();
|
|
71
|
+
let pending = config.fetchCache?.get(url);
|
|
72
|
+
if (!pending) {
|
|
73
|
+
pending = download(url, config, requestSignal).catch((error) => { config.fetchCache?.delete(url); throw error; });
|
|
74
|
+
config.fetchCache?.set(url, pending);
|
|
75
|
+
}
|
|
76
|
+
const data = await waitFor(pending, requestSignal);
|
|
77
|
+
if (data.byteLength > (config.maxBytes ?? 33554432)) throw new Error(`Response exceeds ${config.maxBytes} bytes`);
|
|
78
|
+
return new Uint8Array(data);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function urls(source) {
|
|
82
|
+
return [...(source ?? "").matchAll(/url\(\s*(?:"([^"]*)"|'([^']*)'|([^)]*?))\s*\)/gi)]
|
|
83
|
+
.map((m) => m[1] ?? m[2] ?? m[3]).filter(Boolean);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function weightDistance(face, weight) {
|
|
87
|
+
const values = String(face.weight ?? "400").trim().split(/\s+/).map(Number);
|
|
88
|
+
const lo = values[0]; const hi = values[1] ?? lo;
|
|
89
|
+
return Number.isFinite(lo) && Number.isFinite(hi) ? Math.max(lo - weight, weight - hi, 0) : 0;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function usedFaces(needs, fallback) {
|
|
93
|
+
const selected = new Map();
|
|
94
|
+
for (const request of needs.requests) {
|
|
95
|
+
const families = request.families.length ? request.families : fallback ?? [];
|
|
96
|
+
for (const family of families) {
|
|
97
|
+
const candidates = needs.faces.filter((face) => lower(face.name) === lower(family) && uses(request.text, face.unicodeRange));
|
|
98
|
+
let best = Infinity;
|
|
99
|
+
for (const face of candidates) best = Math.min(best, weightDistance(face, request.weight) + (lower(face.style ?? "normal") === request.style ? 0 : 10000));
|
|
100
|
+
for (const face of candidates) if (weightDistance(face, request.weight) + (lower(face.style ?? "normal") === request.style ? 0 : 10000) === best) selected.set(JSON.stringify(face), face);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return selected.values();
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export async function resourceOptions(renderer, node, options = {}, fetchMissing = false) {
|
|
107
|
+
if (options == null || typeof options !== "object" || Array.isArray(options)) return options;
|
|
108
|
+
const signal = options.signal;
|
|
109
|
+
signal?.throwIfAborted?.();
|
|
110
|
+
const fonts = options.fonts == null ? undefined : await options.fonts;
|
|
111
|
+
if (fonts !== undefined && !Array.isArray(fonts)) throw new TypeError("bm-render: fonts takes an array");
|
|
112
|
+
const subsets = fonts?.some((f) => fontRange(f) !== undefined);
|
|
113
|
+
if (!fetchMissing && !subsets) return fonts === undefined ? options : { ...options, fonts };
|
|
114
|
+
const fallback = options.fontFamilies ?? fonts?.filter((f) => f && !binary(f) && typeof f.name === "string").map((f) => f.name);
|
|
115
|
+
const config = imageInput(options.images);
|
|
116
|
+
const knownSources = (config.sources ?? []).filter((s) => binary(s?.data));
|
|
117
|
+
let needs = renderer.needsPdfSync(node, { ...options, images: knownSources, ...(fallback?.length ? { fontFamilies: fallback } : {}) });
|
|
118
|
+
let result = fonts === undefined ? options : { ...options, fonts: fonts.filter((f) => uses(needs.text, fontRange(f))) };
|
|
119
|
+
if (fallback?.length && options.fontFamilies === undefined) result = { ...result, fontFamilies: fallback };
|
|
120
|
+
if (!fetchMissing) return result;
|
|
121
|
+
const sources = config.sources ?? [];
|
|
122
|
+
const have = new Set(sources.map((s) => s?.src));
|
|
123
|
+
const pending = needs.images.filter((url) => !have.has(url) && !url.startsWith("data:") && (config.fetch !== undefined || /^https?:\/\//i.test(url)));
|
|
124
|
+
const tasks = pending.map(async (src) => ({ src, data: await bytes(src, config, config.signal ?? signal) }));
|
|
125
|
+
const fetched = config.throwOnError === false ? (await Promise.allSettled(tasks)).filter((r) => r.status === "fulfilled").map((r) => r.value) : await Promise.all(tasks);
|
|
126
|
+
result = { ...result, images: [...sources, ...fetched] };
|
|
127
|
+
// Downloaded SVG text can add font-face requests as well as font subsets.
|
|
128
|
+
if (fetched.length) {
|
|
129
|
+
needs = renderer.needsPdfSync(node, { ...result, images: [...knownSources, ...fetched], ...(fallback?.length ? { fontFamilies: fallback } : {}) });
|
|
130
|
+
if (subsets) result.fonts = fonts.filter((f) => uses(needs.text, fontRange(f)));
|
|
131
|
+
}
|
|
132
|
+
const failed = new Set(options.failedFontFiles ?? []);
|
|
133
|
+
const loaded = new Map();
|
|
134
|
+
for (const face of usedFaces(needs, fallback)) {
|
|
135
|
+
for (const url of urls(face.src)) {
|
|
136
|
+
if (failed.has(url)) continue;
|
|
137
|
+
try {
|
|
138
|
+
if (!loaded.has(url)) loaded.set(url, bytes(url, config, signal));
|
|
139
|
+
const data = await loaded.get(url);
|
|
140
|
+
const descriptor = { name: face.name, data, ...(face.style ? { style: face.style } : {}), ...(face.unicodeRange ? { unicodeRange: face.unicodeRange } : {}) };
|
|
141
|
+
if (/^\d+$/.test(face.weight ?? "")) descriptor.weight = Number(face.weight);
|
|
142
|
+
await renderer.registerFont(descriptor);
|
|
143
|
+
break;
|
|
144
|
+
} catch (error) {
|
|
145
|
+
signal?.throwIfAborted?.();
|
|
146
|
+
failed.add(url);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
signal?.throwIfAborted?.();
|
|
151
|
+
return failed.size ? { ...result, failedFontFiles: [...failed] } : result;
|
|
152
|
+
}
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
// PDF option types of bm-render (takumi-pdf `PdfRenderOptions` and friends; names and shapes follow
|
|
2
|
+
// takumi-pdf-js 's dts-header.d.ts / export.ts). Re-exported by bm-render/pdf (pdf.d.mts); the `Renderer`
|
|
3
|
+
// methods `renderPdf` / `measurePdf` of every entry use them (they throw on builds without the `pdf` feature).
|
|
4
|
+
import type { ByteBuf, CssInput, FontLoader, ImageSource, ImagesInput, Node, Prepared } from "./index.mjs";
|
|
5
|
+
|
|
6
|
+
/** Image entries and the fetch policy used by PDF resource preparation. */
|
|
7
|
+
export type PdfImagesInput = ImagesInput | {
|
|
8
|
+
sources?: ImageSource[];
|
|
9
|
+
fetch?: typeof globalThis.fetch;
|
|
10
|
+
fetchCache?: { get(url: string): Promise<ArrayBuffer> | undefined; set(url: string, value: Promise<ArrayBuffer>): unknown; delete(url: string): unknown };
|
|
11
|
+
throwOnError?: boolean;
|
|
12
|
+
timeout?: number;
|
|
13
|
+
maxBytes?: number;
|
|
14
|
+
allowUrl?: (url: string) => boolean;
|
|
15
|
+
signal?: AbortSignal;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
/** A page size keyword CSS Paged Media defines, matched case-insensitively. Portrait. */
|
|
19
|
+
export type PageSizeName = "a3" | "a4" | "a5" | "b4" | "b5" | "jis-b4" | "jis-b5" | "ledger" | "legal" | "letter";
|
|
20
|
+
|
|
21
|
+
/** Explicit dimensions in CSS px (96 dpi). */
|
|
22
|
+
export type Dimensions = { width: number; height: number };
|
|
23
|
+
|
|
24
|
+
/** A single-page viewport. Omitting `height` sizes the page to the laid-out content. */
|
|
25
|
+
export type ViewportInput = { width: number; height?: number };
|
|
26
|
+
|
|
27
|
+
/** A page size: a preset name or explicit {@link Dimensions}. */
|
|
28
|
+
export type PageSize = PageSizeName | (string & {}) | Dimensions;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* One side of a page margin: a length in CSS px, or `"auto"` to fit the band that draws on that side.
|
|
32
|
+
* `"auto"` never goes below the 37.8 px a page starts with, and the left and right sides hold no band,
|
|
33
|
+
* so they land on it.
|
|
34
|
+
*/
|
|
35
|
+
export type PageMarginSide = number | "auto";
|
|
36
|
+
|
|
37
|
+
/** A page margin: one value for all sides, or per-side values (a side left out is `auto`). */
|
|
38
|
+
export type PageMargin = PageMarginSide | { top?: PageMarginSide; right?: PageMarginSide; bottom?: PageMarginSide; left?: PageMarginSide };
|
|
39
|
+
|
|
40
|
+
/** A band on a page: a node tree, an HTML string, or `false` for none. */
|
|
41
|
+
/**
|
|
42
|
+
* A header / footer: a node tree, HTML, or `false` (none). As takumi-pdf, anything else goes through `fromJsx`: a
|
|
43
|
+
* JSX element tree, and `true` / numbers / other objects written as their text.
|
|
44
|
+
*/
|
|
45
|
+
export type Band = Node | string | false | { $typeof: symbol; type: unknown; props: Record<string, unknown> };
|
|
46
|
+
|
|
47
|
+
/** What some pages draw instead of the document's own bands. A field left out falls through. */
|
|
48
|
+
export type PageOverride = { header?: Band; footer?: Band };
|
|
49
|
+
|
|
50
|
+
/** Overrides keyed by the pages they cover. `first` and `last` win over `odd` and `even`. */
|
|
51
|
+
export type PageRules = { first?: PageOverride; last?: PageOverride; odd?: PageOverride; even?: PageOverride };
|
|
52
|
+
|
|
53
|
+
/** A page to keep: a 1-based page number, or an inclusive span. An unset `from` starts at the first page; an unset `to` runs to the last. */
|
|
54
|
+
export type PageRange = number | { from?: number; to?: number };
|
|
55
|
+
|
|
56
|
+
/** A custom XMP namespace and the properties written under it. */
|
|
57
|
+
export type XmpSchema = {
|
|
58
|
+
/** Human-readable name, e.g. "Factur-X PDF/A Extension". */
|
|
59
|
+
name: string;
|
|
60
|
+
/** Namespace prefix the properties are written under, e.g. "fx". */
|
|
61
|
+
prefix: string;
|
|
62
|
+
/** Namespace URI. */
|
|
63
|
+
namespace: string;
|
|
64
|
+
properties: XmpProperty[];
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
export type XmpProperty = {
|
|
68
|
+
/** Property name, e.g. "DocumentFileName". */
|
|
69
|
+
name: string;
|
|
70
|
+
value: string;
|
|
71
|
+
/** What the property means. PDF/A requires one. */
|
|
72
|
+
description: string;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
export type PdfMetadata = {
|
|
76
|
+
title?: string;
|
|
77
|
+
/** The info dictionary's subject. */
|
|
78
|
+
description?: string;
|
|
79
|
+
authors?: string[];
|
|
80
|
+
keywords?: string[];
|
|
81
|
+
/** The tool that created the source document. */
|
|
82
|
+
creator?: string;
|
|
83
|
+
/** UTC creation date, `YYYY-MM-DD` or `YYYY-MM-DDTHH:MM:SS`. PDF/A output requires one when `metadata` is set. */
|
|
84
|
+
creationDate?: string;
|
|
85
|
+
/** Custom XMP schemas written into the packet. */
|
|
86
|
+
xmp?: XmpSchema[];
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
/** A file attached to the PDF, shown in the viewer's attachment panel. */
|
|
90
|
+
export type Attachment = {
|
|
91
|
+
/** File name in the PDF, e.g. "factur-x.xml". */
|
|
92
|
+
name: string;
|
|
93
|
+
/** The file's bytes, or a string encoded as UTF-8. */
|
|
94
|
+
data: ByteBuf | string;
|
|
95
|
+
/** IANA media type, e.g. "application/xml". The PDF/A-3 levels require one. */
|
|
96
|
+
mimeType?: string;
|
|
97
|
+
/** Human-readable description. The PDF/A-3 levels require one. */
|
|
98
|
+
description?: string;
|
|
99
|
+
/** How the file relates to the document (the PDF/A-3 AFRelationship). Defaults to "unspecified". */
|
|
100
|
+
relationship?: "source" | "data" | "alternative" | "supplement" | "unspecified";
|
|
101
|
+
/** UTC modification date, `YYYY-MM-DD` or `YYYY-MM-DDTHH:MM:SS`; falls back to `metadata.creationDate`. The PDF/A-3 levels require one. */
|
|
102
|
+
modificationDate?: string;
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
/** An attachment under the PDF/A-3 levels, which require the descriptive fields. */
|
|
106
|
+
export type ArchivalAttachment = Attachment & { mimeType: string; description: string };
|
|
107
|
+
|
|
108
|
+
/** PDF/A conformance level. Validation failures reject the render. */
|
|
109
|
+
export type Pdfa = "2a" | "2b" | "2u" | "3a" | "3b" | "3u" | "4" | "4f";
|
|
110
|
+
|
|
111
|
+
/** Structure-tree emission: off, on (default), or validated against an accessibility standard. */
|
|
112
|
+
export type Tagged = boolean | "ua1" | "ua2";
|
|
113
|
+
|
|
114
|
+
/** What a character no registered font covers turns into on the page. */
|
|
115
|
+
export type UncoveredText = "error" | "placeholder" | "blank";
|
|
116
|
+
|
|
117
|
+
/** Paged output (the default): content flows across pages of `size`, like Puppeteer's `page.pdf()`. */
|
|
118
|
+
type PagedOptions = {
|
|
119
|
+
viewport?: never;
|
|
120
|
+
/** Page size. Defaults to A4. */
|
|
121
|
+
size?: PageSize;
|
|
122
|
+
/** Swaps the page's width and height, including explicit sizes. */
|
|
123
|
+
landscape?: boolean;
|
|
124
|
+
/** Page margin. Defaults to `"auto"` on every side. */
|
|
125
|
+
margin?: PageMargin;
|
|
126
|
+
/** Band repeated at the top of every page. Nodes classed `pageNumber` / `totalPages` receive the counters. */
|
|
127
|
+
header?: Band;
|
|
128
|
+
/** Band repeated at the bottom of every page; same class hooks as `header`. */
|
|
129
|
+
footer?: Band;
|
|
130
|
+
/** What some pages draw differently from the rest. */
|
|
131
|
+
pages?: PageRules;
|
|
132
|
+
/** The pages the output keeps, e.g. `[1, { from: 4, to: 8 }]`. Page counters keep their full-output numbers. */
|
|
133
|
+
pageRanges?: PageRange[];
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
/** Single-page output: a fixed viewport. Mutually exclusive with the paged fields. */
|
|
137
|
+
type ViewportOptions = {
|
|
138
|
+
viewport: ViewportInput;
|
|
139
|
+
size?: never;
|
|
140
|
+
landscape?: never;
|
|
141
|
+
margin?: never;
|
|
142
|
+
header?: never;
|
|
143
|
+
footer?: never;
|
|
144
|
+
pages?: never;
|
|
145
|
+
pageRanges?: never;
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Standards conformance. Invalid combinations are type errors (and runtime errors): the `a` levels imply a
|
|
150
|
+
* structure tree so `tagged: false` is rejected, PDF/UA-1 is PDF 1.7-only and PDF/UA-2 is PDF 2.0-only so
|
|
151
|
+
* each pairs with its own PDF/A levels, and only the PDF/A-3 levels, PDF/A-4f (or plain PDF) accept attachments.
|
|
152
|
+
*/
|
|
153
|
+
type ConformanceOptions =
|
|
154
|
+
| { pdfa?: never; tagged?: Tagged; attachments?: Attachment[] }
|
|
155
|
+
| { pdfa: "2b" | "2u"; tagged?: boolean | "ua1"; attachments?: never }
|
|
156
|
+
| { pdfa: "2a"; tagged?: true | "ua1"; attachments?: never }
|
|
157
|
+
| { pdfa: "3b" | "3u"; tagged?: boolean | "ua1"; attachments?: ArchivalAttachment[] }
|
|
158
|
+
| { pdfa: "3a"; tagged?: true | "ua1"; attachments?: ArchivalAttachment[] }
|
|
159
|
+
| { pdfa: "4"; tagged?: boolean | "ua2"; attachments?: never }
|
|
160
|
+
| { pdfa: "4f"; tagged?: boolean | "ua2"; attachments?: ArchivalAttachment[] };
|
|
161
|
+
|
|
162
|
+
export type PdfRenderOptions = (PagedOptions | ViewportOptions) &
|
|
163
|
+
ConformanceOptions & {
|
|
164
|
+
/**
|
|
165
|
+
* Fonts registered before rendering, once per renderer (deduped across calls, as takumi-pdf). The sync
|
|
166
|
+
* methods take bytes and `{ data: bytes }` entries; a URL, a promise or a lazy `data()` loader needs the
|
|
167
|
+
* async API.
|
|
168
|
+
*/
|
|
169
|
+
fonts?: FontLoader[] | Promise<FontLoader[]>;
|
|
170
|
+
/** Pre-fetched images for `src` URLs in the tree (and its bands), e.g. `[{ src: "https://…/logo.png", data: bytes }]`. */
|
|
171
|
+
images?: PdfImagesInput;
|
|
172
|
+
/** CSS to apply before layout (the `css` feature: standard / full / pdf). */
|
|
173
|
+
css?: CssInput | readonly CssInput[];
|
|
174
|
+
/** CSS custom properties for `:root`. A name without the `--` prefix gains it. */
|
|
175
|
+
cssVariables?: Record<string, string>;
|
|
176
|
+
/** Per-render font stack: ordered family names used as the fallback chain. */
|
|
177
|
+
fontFamilies?: string[];
|
|
178
|
+
/** @internal The `@font-face` files `prepare` failed to download or decode. */
|
|
179
|
+
failedFontFiles?: string[];
|
|
180
|
+
/** Default BCP-47 language tag applied to the root. */
|
|
181
|
+
lang?: string;
|
|
182
|
+
/** Document metadata; `lang` doubles as the metadata language. */
|
|
183
|
+
metadata?: PdfMetadata;
|
|
184
|
+
/** Generates a PDF outline (bookmarks) from `h1`–`h6` headings. */
|
|
185
|
+
outline?: boolean;
|
|
186
|
+
/** The paper colour as a CSS colour, painted under everything on every page. Unset leaves the page empty. */
|
|
187
|
+
backgroundColor?: string;
|
|
188
|
+
/**
|
|
189
|
+
* What a character no registered font covers turns into: `"error"` (default) fails the render naming it,
|
|
190
|
+
* `"placeholder"` draws the font's glyph 0, and `"blank"` draws nothing. `"placeholder"` is rejected with
|
|
191
|
+
* any `pdfa` level or `tagged: "ua1"` / `"ua2"`, which forbid glyph 0.
|
|
192
|
+
*/
|
|
193
|
+
uncoveredText?: UncoveredText;
|
|
194
|
+
/** Stops the render before it reads the document or draws it. */
|
|
195
|
+
signal?: AbortSignal;
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
/** Options for `measurePdf` / `PdfRenderer.measure`: page geometry (or a viewport) plus layout resources. Margins do not affect the result. */
|
|
199
|
+
export type PdfMeasureOptions = (
|
|
200
|
+
| { size?: PageSize; landscape?: boolean; viewport?: never }
|
|
201
|
+
| { viewport: ViewportInput; size?: never; landscape?: never }
|
|
202
|
+
) & Pick<PdfRenderOptions, "fonts" | "images" | "css" | "cssVariables" | "fontFamilies" | "lang"> & {
|
|
203
|
+
/** `Renderer.measurePdf` stops on an aborted one; `PdfRenderer.measure` does not read it (as takumi-pdf's `measure`). */
|
|
204
|
+
signal?: AbortSignal;
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
/** A node tree's laid-out size in CSS px. */
|
|
208
|
+
export type MeasuredSize = { width: number; height: number };
|
|
209
|
+
|
|
210
|
+
/** Prepared handle accepted by the PDF render / measure methods (same handle as `Renderer.prepare`). */
|
|
211
|
+
export type PdfPrepared = Prepared;
|
package/js/pdf.d.mts
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// bm-render/pdf: the pdf build profile (bm_render.pdf.wasm = full + PDF output) with its own module instance, and the
|
|
2
|
+
// takumi-pdf style API on top of it. init() may be called without an argument (and on Node.js it already ran on import).
|
|
3
|
+
// On Node.js / Bun / Deno the engine is the native addon when it is installed (`backend` is "native": the same addon as
|
|
4
|
+
// `bm-render`, the same PDF bytes, async methods on the thread pool), else this wasm build; BM_RENDER_BACKEND=wasm | native
|
|
5
|
+
// forces one. See docs/NATIVE.md.
|
|
6
|
+
import type {
|
|
7
|
+
ByteBuf, ContainerNode, FontLoader, InitArgument, OutputBytes, Prepared, RegisteredFamily, RendererOptions, Source, Style,
|
|
8
|
+
SyncFontDetails, WasmExports,
|
|
9
|
+
} from "./index.mjs";
|
|
10
|
+
import type { MeasuredSize, PdfMeasureOptions, PdfRenderOptions } from "./pdf-types.mjs";
|
|
11
|
+
|
|
12
|
+
export * from "./index.mjs";
|
|
13
|
+
export * from "./pdf-types.mjs";
|
|
14
|
+
|
|
15
|
+
export declare function init(input?: InitArgument): Promise<WasmExports>;
|
|
16
|
+
export default init;
|
|
17
|
+
/** The URL init() loads by default (throws where `import.meta.url` is unusable). */
|
|
18
|
+
export declare function wasmUrl(): URL;
|
|
19
|
+
/** Build profile of this entry. */
|
|
20
|
+
export declare const profile: "pdf";
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* A document input: a node tree, `{ json }` (the tree as JSON text), an HTML string, a prepared handle, or (as
|
|
24
|
+
* takumi-pdf) a JSX / React element tree, laid out as the HTML it describes (components are called once, without a
|
|
25
|
+
* React dispatcher; `<style>` elements style the document).
|
|
26
|
+
*/
|
|
27
|
+
export type PdfSource = Source | Prepared | JsxElement;
|
|
28
|
+
/** A React element (`$$typeof`, `type`, `props`), as JSX creates it. */
|
|
29
|
+
export type JsxElement = { $$typeof: symbol; type: unknown; props: Record<string, unknown> };
|
|
30
|
+
|
|
31
|
+
/** takumi-pdf's `PdfRenderer` (a wrapper of one `Renderer`; registered fonts live in it). */
|
|
32
|
+
export declare class PdfRenderer {
|
|
33
|
+
constructor(options?: RendererOptions);
|
|
34
|
+
registerFont(font: ByteBuf | SyncFontDetails): RegisteredFamily[];
|
|
35
|
+
registerFont(font: FontLoader | Promise<FontLoader>): RegisteredFamily[] | Promise<RegisteredFamily[]>;
|
|
36
|
+
loadFont(font: ByteBuf | SyncFontDetails): RegisteredFamily[];
|
|
37
|
+
loadFont(font: FontLoader | Promise<FontLoader>): RegisteredFamily[] | Promise<RegisteredFamily[]>;
|
|
38
|
+
unregisterFont(family: string | { name: string }): boolean;
|
|
39
|
+
clearFonts(): void;
|
|
40
|
+
/**
|
|
41
|
+
* Discovers resources after the cascade, loads the font subsets used by the document and its bands, and
|
|
42
|
+
* fetches their missing images and `@font-face` files. Resolves lazy `images` once. Image fetches honor
|
|
43
|
+
* `sources`, `fetch`, `fetchCache`, `throwOnError`, `timeout`, `maxBytes` and `allowUrl`; without a custom
|
|
44
|
+
* `fetch`, only http(s) image URLs are fetched. Rejects on an aborted `signal`.
|
|
45
|
+
*/
|
|
46
|
+
prepare(source: Source | JsxElement, options?: PdfRenderOptions): Promise<Prepared>;
|
|
47
|
+
/** A node tree, an HTML string or a prepared document -> PDF bytes. Paged A4 by default; `viewport` renders one page. */
|
|
48
|
+
render(source: PdfSource, options?: PdfRenderOptions): Promise<OutputBytes>;
|
|
49
|
+
renderSync(source: PdfSource, options?: PdfRenderOptions): OutputBytes;
|
|
50
|
+
/** Laid-out size in CSS px; page options lay out at the full page width with unbounded height, like a band, with three-digit `pageNumber` / `totalPages` counters (add 20 px for the margin an `auto` margin reserves). */
|
|
51
|
+
measure(source: PdfSource, options?: PdfMeasureOptions): Promise<MeasuredSize>;
|
|
52
|
+
measureSync(source: PdfSource, options?: PdfMeasureOptions): MeasuredSize;
|
|
53
|
+
free(): void;
|
|
54
|
+
[Symbol.dispose](): void;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Prepares with a lazily created shared {@link PdfRenderer}. */
|
|
58
|
+
export declare function prepare(source: Source | JsxElement, options?: PdfRenderOptions): Promise<Prepared>;
|
|
59
|
+
/** Renders with a lazily created shared {@link PdfRenderer}. */
|
|
60
|
+
export declare function render(source: PdfSource, options?: PdfRenderOptions): Promise<OutputBytes>;
|
|
61
|
+
/** Measures with a lazily created shared {@link PdfRenderer}. */
|
|
62
|
+
export declare function measure(source: PdfSource, options?: PdfMeasureOptions): Promise<MeasuredSize>;
|
|
63
|
+
|
|
64
|
+
/** `@counter-style` names the page counters can format in. */
|
|
65
|
+
export type CounterStyle =
|
|
66
|
+
| "decimal" | "decimal-leading-zero" | "lower-roman" | "upper-roman" | "lower-alpha" | "lower-latin" | "upper-alpha"
|
|
67
|
+
| "upper-latin" | "lower-greek" | "hiragana" | "katakana" | "trad-chinese-informal" | "cjk-ideographic" | "cjk-decimal"
|
|
68
|
+
| "arabic-indic" | "bengali" | "cambodian" | "khmer" | "devanagari" | "gujarati" | "gurmukhi" | "kannada" | "lao"
|
|
69
|
+
| "malayalam" | "mongolian" | "myanmar" | "oriya" | "persian" | "urdu" | "tamil" | "telugu" | "thai" | "tibetan";
|
|
70
|
+
|
|
71
|
+
/** Props shared by the page counter primitives. */
|
|
72
|
+
export type CounterProps = {
|
|
73
|
+
/** Counter style the number formats in. Defaults to decimal. */
|
|
74
|
+
format?: CounterStyle;
|
|
75
|
+
className?: string;
|
|
76
|
+
style?: Style;
|
|
77
|
+
tw?: string;
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
/** The number of the page this element lands on (a `span` node classed `pageNumber`): in a `header` / `footer` band or a `position: fixed` box each page's number, in the content flow the page it lands on. */
|
|
81
|
+
export declare function PageNumber(props?: CounterProps): ContainerNode;
|
|
82
|
+
/** The document's total page count (classed `totalPages`). */
|
|
83
|
+
export declare function TotalPages(props?: CounterProps): ContainerNode;
|
|
84
|
+
/** The page number of a link's target (classed `targetPageNumber`); with `href` it renders its own link. */
|
|
85
|
+
export declare function TargetPageNumber(props?: CounterProps & { href?: string }): ContainerNode;
|
package/js/pdf.mjs
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// bm-render/pdf (browsers, bundlers, Deno, edge runtimes): the pdf build profile (bm_render.pdf.wasm = full + PDF output)
|
|
2
|
+
// with its own module instance, plus the takumi-pdf style API: `PdfRenderer`, `render`, `measure`, `prepare` and the
|
|
3
|
+
// page counter primitives. `await init()` without an argument loads bm_render.pdf.wasm from next to this file through
|
|
4
|
+
// `new URL("./bm_render.pdf.wasm", import.meta.url)`; where that cannot work (Cloudflare Workers) pass the module:
|
|
5
|
+
//
|
|
6
|
+
// import wasm from "bm-render/pdf.wasm";
|
|
7
|
+
// import { init, PdfRenderer } from "bm-render/pdf";
|
|
8
|
+
// await init(wasm);
|
|
9
|
+
// const pdf = await new PdfRenderer().render(node, { size: "a4", margin: 24 }); // Uint8Array
|
|
10
|
+
//
|
|
11
|
+
// On Node.js this subpath resolves to ./node-pdf.mjs: the native addon when it is installed (the same addon as
|
|
12
|
+
// `bm-render`, the same PDF bytes), else this wasm build, read from disk and initialised on import.
|
|
13
|
+
// API: ./pdf.d.mts. The image `Renderer` of the other entries is exported too, with `renderPdf` / `measurePdf` methods.
|
|
14
|
+
import { createBinding } from "./engine.mjs";
|
|
15
|
+
import { pdfApi } from "./pdf-api.mjs";
|
|
16
|
+
|
|
17
|
+
const binding = createBinding(() => new URL("./bm_render.pdf.wasm", import.meta.url));
|
|
18
|
+
|
|
19
|
+
export const { init, initSync, Renderer, features, setGlyphCacheMaxBytes, wasmUrl, backend } = binding;
|
|
20
|
+
export { Prepared, setWoffDecoder } from "./engine.mjs";
|
|
21
|
+
/** Build profile of this entry. */
|
|
22
|
+
export const profile = "pdf";
|
|
23
|
+
export default init;
|
|
24
|
+
|
|
25
|
+
export const { PdfRenderer, prepare, render, measure } = pdfApi(Renderer);
|
|
26
|
+
export { PageNumber, TotalPages, TargetPageNumber } from "./pdf-api.mjs";
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// bm-render/standard: the standard build profile (bm_render.standard.wasm) with its own module instance. Same API as bm-render
|
|
2
|
+
// (./index.d.mts); init() may be called without an argument (and on Node.js it already ran on import).
|
|
3
|
+
import type { InitArgument, WasmExports } from "./index.mjs";
|
|
4
|
+
|
|
5
|
+
export * from "./index.mjs";
|
|
6
|
+
/**
|
|
7
|
+
* Instantiates the standard wasm. Without an argument it loads bm_render.standard.wasm from next to the module
|
|
8
|
+
* (`new URL("./bm_render.standard.wasm", import.meta.url)`, which bundlers emit as an asset). On Cloudflare Workers pass
|
|
9
|
+
* the module: `import wasm from "bm-render/standard.wasm"; await init(wasm)`. Idempotent.
|
|
10
|
+
*/
|
|
11
|
+
export declare function init(input?: InitArgument): Promise<WasmExports>;
|
|
12
|
+
export default init;
|
|
13
|
+
/** The URL init() loads by default (throws where `import.meta.url` is unusable). */
|
|
14
|
+
export declare function wasmUrl(): URL;
|
|
15
|
+
/** Build profile of this entry. */
|
|
16
|
+
export declare const profile: "standard";
|
package/js/standard.mjs
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// bm-render/standard (browsers, bundlers, Deno, edge runtimes): the standard build profile (bm_render.standard.wasm) with its own
|
|
2
|
+
// module instance. `await init()` without an argument loads bm_render.standard.wasm from next to this file through
|
|
3
|
+
// `new URL("./bm_render.standard.wasm", import.meta.url)`, a pattern Vite, webpack 5, Rollup and Parcel turn into an emitted
|
|
4
|
+
// asset. Where that cannot work (Cloudflare Workers / workerd), pass the precompiled module instead:
|
|
5
|
+
//
|
|
6
|
+
// import wasm from "bm-render/standard.wasm"; // a WebAssembly.Module under wrangler
|
|
7
|
+
// import { init, Renderer } from "bm-render/standard";
|
|
8
|
+
// await init(wasm);
|
|
9
|
+
//
|
|
10
|
+
// On Node.js this subpath resolves to ./node-standard.mjs, which reads the file and initialises on import.
|
|
11
|
+
// API: see ./index.mjs and ./index.d.mts.
|
|
12
|
+
import { createBinding } from "./engine.mjs";
|
|
13
|
+
|
|
14
|
+
const binding = createBinding(() => new URL("./bm_render.standard.wasm", import.meta.url));
|
|
15
|
+
|
|
16
|
+
export const { init, initSync, Renderer, features, setGlyphCacheMaxBytes, wasmUrl, backend } = binding;
|
|
17
|
+
export { Prepared, setWoffDecoder } from "./engine.mjs";
|
|
18
|
+
/** Build profile of this entry. */
|
|
19
|
+
export const profile = "standard";
|
|
20
|
+
export default init;
|
package/js/wasm-file.mjs
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// bm-render internal (Node.js / Bun / Deno only): reads one of the package's wasm files from disk, for the Node
|
|
2
|
+
// entries (js/node.mjs, node-core.mjs, node-standard.mjs, node-full.mjs, node-pdf.mjs), in a way that survives bundling.
|
|
3
|
+
//
|
|
4
|
+
// Tried in order, first readable wins:
|
|
5
|
+
// 1. next to this module: new URL("./<file>", import.meta.url), written literally per file so that bundlers
|
|
6
|
+
// that understand the pattern (webpack 5, Turbopack, Rollup / Vite SSR) emit / trace the asset and give
|
|
7
|
+
// back its new location;
|
|
8
|
+
// 2. the installed package: createRequire(<this module>).resolve("bm-render/<subpath>") (the subpath exports
|
|
9
|
+
// of package.json), which still works when a bundler moved this module but node_modules is present;
|
|
10
|
+
// 3. <cwd>/node_modules/bm-render/js/<file>.
|
|
11
|
+
// When all fail the error names every location and the usual fixes (keep bm-render external to the bundler).
|
|
12
|
+
import { readFileSync } from "node:fs";
|
|
13
|
+
import { createRequire } from "node:module";
|
|
14
|
+
import { join } from "node:path";
|
|
15
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
16
|
+
|
|
17
|
+
const proc = typeof process !== "undefined" ? process : { env: {} };
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* A file: URL for this module that createRequire() accepts, even when a bundler replaced import.meta.url:
|
|
21
|
+
* import.meta.url, else the CommonJS __filename of a bundle, else a file in the working directory.
|
|
22
|
+
*/
|
|
23
|
+
export function moduleBase() {
|
|
24
|
+
try {
|
|
25
|
+
const u = import.meta.url;
|
|
26
|
+
if (typeof u === "string" && u.startsWith("file:")) return u;
|
|
27
|
+
} catch {}
|
|
28
|
+
try {
|
|
29
|
+
// eslint-disable-next-line no-undef
|
|
30
|
+
if (typeof __filename === "string" && __filename) return pathToFileURL(__filename).href;
|
|
31
|
+
} catch {}
|
|
32
|
+
try {
|
|
33
|
+
return pathToFileURL(join(proc.cwd ? proc.cwd() : ".", "bm-render-base.js")).href;
|
|
34
|
+
} catch {}
|
|
35
|
+
return "file:///bm-render-base.js";
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const SUBPATH = {
|
|
39
|
+
"bm_render.wasm": "full.wasm",
|
|
40
|
+
"bm_render.core.wasm": "core.wasm",
|
|
41
|
+
"bm_render.standard.wasm": "standard.wasm",
|
|
42
|
+
"bm_render.pdf.wasm": "pdf.wasm",
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
/** new URL(<literal>, import.meta.url) for each shipped file (literal: see 1. above). */
|
|
46
|
+
function siblingUrl(file) {
|
|
47
|
+
switch (file) {
|
|
48
|
+
case "bm_render.wasm": return new URL("./bm_render.wasm", import.meta.url);
|
|
49
|
+
case "bm_render.core.wasm": return new URL("./bm_render.core.wasm", import.meta.url);
|
|
50
|
+
case "bm_render.standard.wasm": return new URL("./bm_render.standard.wasm", import.meta.url);
|
|
51
|
+
case "bm_render.pdf.wasm": return new URL("./bm_render.pdf.wasm", import.meta.url);
|
|
52
|
+
}
|
|
53
|
+
return new URL("./" + file, moduleBase());
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** A path for whatever a bundler made of `new URL(...)` (a URL, a URL from another realm, a string). */
|
|
57
|
+
function toPath(u) {
|
|
58
|
+
const href = typeof u === "string" ? u : String((u && u.href) || u);
|
|
59
|
+
return href.startsWith("file:") ? fileURLToPath(href) : href;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Absolute path of a file relative to this module (null when import.meta.url is unusable). */
|
|
63
|
+
export function packageFile(rel) {
|
|
64
|
+
try {
|
|
65
|
+
const base = moduleBase();
|
|
66
|
+
return base.startsWith("file:") ? fileURLToPath(new URL(rel, base)) : null;
|
|
67
|
+
} catch {
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The bytes of js/<file> of the installed package; throws a precise error when it cannot be found. */
|
|
73
|
+
export function readPackageWasm(file) {
|
|
74
|
+
const tried = [];
|
|
75
|
+
const attempt = (label, where) => {
|
|
76
|
+
let p;
|
|
77
|
+
try {
|
|
78
|
+
p = where();
|
|
79
|
+
return readFileSync(p);
|
|
80
|
+
} catch (e) {
|
|
81
|
+
tried.push(`${label}${p ? " " + p : ""}: ${e && e.code ? e.code : String(e && e.message).split("\n")[0]}`.replace(/ +/g, " "));
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
const bytes = attempt("next to the module", () => toPath(siblingUrl(file)))
|
|
86
|
+
?? attempt("package resolution", () => createRequire(moduleBase()).resolve(`bm-render/${SUBPATH[file] ?? file}`))
|
|
87
|
+
?? attempt("working directory", () => join(proc.cwd(), "node_modules", "bm-render", "js", file));
|
|
88
|
+
if (bytes) return bytes;
|
|
89
|
+
throw new Error(`bm-render: cannot find ${file} (${tried.join("; ")}). This happens when a bundler moved bm-render's ` +
|
|
90
|
+
`Node.js entry away from its package: keep the package external (Next.js: serverExternalPackages: ["bm-render"]; ` +
|
|
91
|
+
`esbuild: --external:bm-render; webpack: externals) or copy node_modules/bm-render/js/${file} next to the bundle; ` +
|
|
92
|
+
`or name the file with BM_WASM=<path>.`);
|
|
93
|
+
}
|
package/js/wasm.d.mts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Typings for the raw wasm subpaths (bm-render/wasm, /core.wasm, /standard.wasm, /full.wasm, /woff.wasm).
|
|
2
|
+
// What such an import yields depends on the toolchain; this declares the Cloudflare Workers / wrangler
|
|
3
|
+
// (and esbuild `--loader:.wasm=...` / Deno `--unstable-wasm-modules`-style) form: a compiled module, the
|
|
4
|
+
// value `init(wasm)` and `loadWoff(wasm)` accept. Vite users import `bm-render/full.wasm?url` instead
|
|
5
|
+
// (typed as a string by `vite/client`).
|
|
6
|
+
import type {} from "./index.mjs"; // global WebAssembly.Module stand-in for projects without the DOM lib
|
|
7
|
+
|
|
8
|
+
declare const wasm: WebAssembly.Module;
|
|
9
|
+
export default wasm;
|