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/js/native.mjs ADDED
@@ -0,0 +1,250 @@
1
+ // bm-render internal (Node.js / Bun / Deno only): finds and loads the native Node-API addon and wraps it as an
2
+ // engine backend for js/engine.mjs. Imported by js/node.mjs (`bm-render` on Node: native when available, else
3
+ // wasm), js/node-pdf.mjs (`bm-render/pdf` on Node, likewise, with the addon's PDF output) and js/node-native.mjs
4
+ // (`bm-render/native`: native or an error). The wasm-only entries never import
5
+ // this file, so bundles for browsers / edge runtimes contain no `require` of a `.node` file.
6
+ //
7
+ // Where the addon is looked for (first that loads wins; nothing here ever throws):
8
+ // 1. $BM_RENDER_NATIVE_PATH: a `.node` file. When set, it is the ONLY candidate.
9
+ // 2. a source checkout's build output: ../native/dist/<name>/bm-render.<name>.node (scripts/build-native.mjs)
10
+ // 3. the per-platform npm package `@hunghg255/bm-render-<name>` (an optional dependency whose main is the `.node` file)
11
+ // with <name> = win32-x64-msvc | win32-arm64-msvc | linux-x64-gnu | linux-x64-musl | linux-arm64-gnu |
12
+ // linux-arm64-musl | darwin-x64 | darwin-arm64. On Linux the C library is detected (glibc / musl); the other
13
+ // variant is tried when the detected one does not load.
14
+ //
15
+ // Bundlers and output tracing: 1 and 2 are opened with process.dlopen (not a module request, so bundlers and
16
+ // file tracers ignore them: they are never part of an installed package). 3 is `require("@hunghg255/bm-render-<name>")`
17
+ // with a literal package name per platform on `createRequire(import.meta.url)`, the form @vercel/nft follows
18
+ // (Next.js with webpack + serverExternalPackages, Vercel functions of other frameworks), so the installed platform
19
+ // package is traced into deployments. The webpackIgnore / turbopackIgnore comments stop bundlers from trying to
20
+ // bundle the packages (Turbopack fails the build on the ones that are not installed; a .node file cannot be
21
+ // bundled anyway): the require happens at run time. Next.js 16 + Turbopack honours the comment in its own output
22
+ // tracing too, so there the platform package is added with outputFileTracingIncludes (docs: frameworks/nextjs).
23
+ // When the module is bundled into a CommonJS file (no import.meta.url) the require is based on __filename, then
24
+ // on the working directory; whatever fails, the caller falls back to wasm.
25
+ //
26
+ // Design, build and the internal addon interface: docs/NATIVE.md.
27
+ import { createRequire } from "node:module";
28
+ import { existsSync, readFileSync } from "node:fs";
29
+ import { resolve } from "node:path";
30
+ import { fileURLToPath } from "node:url";
31
+ import { createBinding, builtInWoffDecoder } from "./engine.mjs";
32
+ import { moduleBase } from "./wasm-file.mjs";
33
+
34
+ /** Interface version of the addon this file understands (src/native.zig `abi_version`). */
35
+ export const NATIVE_ABI = 1;
36
+
37
+ const dec = new TextDecoder();
38
+ const proc = typeof process !== "undefined" ? process : { env: {}, platform: "", arch: "" };
39
+
40
+ /** True when the process runs on musl libc (Alpine, ...). */
41
+ function isMusl() {
42
+ if (proc.platform !== "linux") return false;
43
+ try {
44
+ if (existsSync("/etc/alpine-release")) return true;
45
+ } catch {}
46
+ try {
47
+ // what the running node binary itself is linked against
48
+ if (proc.report && typeof proc.report.getReport === "function") {
49
+ const prev = proc.report.excludeNetwork;
50
+ try {
51
+ if (prev !== undefined) proc.report.excludeNetwork = true; // (the network section can be slow)
52
+ const report = proc.report.getReport();
53
+ if (report && report.header && report.header.glibcVersionRuntime) return false;
54
+ if (report && Array.isArray(report.sharedObjects) && report.sharedObjects.some((f) => /libc\.musl-|ld-musl-/.test(f))) return true;
55
+ } finally {
56
+ if (prev !== undefined) proc.report.excludeNetwork = prev;
57
+ }
58
+ }
59
+ } catch {}
60
+ try {
61
+ const ldd = readFileSync("/usr/bin/ldd", "utf8");
62
+ if (ldd.includes("musl")) return true;
63
+ } catch {}
64
+ return false;
65
+ }
66
+
67
+ /** Addon names for this process, most likely first ([] on an unsupported platform). */
68
+ export function nativeNames() {
69
+ const arch = proc.arch === "x64" || proc.arch === "arm64" ? proc.arch : null;
70
+ if (!arch) return [];
71
+ if (proc.platform === "win32") return [`win32-${arch}-msvc`];
72
+ if (proc.platform === "darwin") return [`darwin-${arch}`];
73
+ if (proc.platform === "linux") return isMusl() ? [`linux-${arch}-musl`, `linux-${arch}-gnu`] : [`linux-${arch}-gnu`, `linux-${arch}-musl`];
74
+ return [];
75
+ }
76
+
77
+ /**
78
+ * require() of the platform package `@hunghg255/bm-render-<name>`. Written the way file tracers (@vercel/nft) recognise: `createRequire(import.meta.url)` assigned to a `require`
79
+ * in the same scope as one literal request per package. Do not "simplify" into a template string or pass
80
+ * `require` around: the platform package would silently disappear from traced deployments. Throws when
81
+ * import.meta.url is unusable (a CommonJS bundle); the caller then uses requirePlatformPackageFrom().
82
+ */
83
+ function requirePlatformPackage(name) {
84
+ const require = createRequire(import.meta.url);
85
+ switch (name) {
86
+ case "win32-x64-msvc": return require(/* webpackIgnore: true */ /* turbopackIgnore: true */ "@hunghg255/bm-render-win32-x64-msvc");
87
+ case "win32-arm64-msvc": return require(/* webpackIgnore: true */ /* turbopackIgnore: true */ "@hunghg255/bm-render-win32-arm64-msvc");
88
+ case "linux-x64-gnu": return require(/* webpackIgnore: true */ /* turbopackIgnore: true */ "@hunghg255/bm-render-linux-x64-gnu");
89
+ case "linux-x64-musl": return require(/* webpackIgnore: true */ /* turbopackIgnore: true */ "@hunghg255/bm-render-linux-x64-musl");
90
+ case "linux-arm64-gnu": return require(/* webpackIgnore: true */ /* turbopackIgnore: true */ "@hunghg255/bm-render-linux-arm64-gnu");
91
+ case "linux-arm64-musl": return require(/* webpackIgnore: true */ /* turbopackIgnore: true */ "@hunghg255/bm-render-linux-arm64-musl");
92
+ case "darwin-x64": return require(/* webpackIgnore: true */ /* turbopackIgnore: true */ "@hunghg255/bm-render-darwin-x64");
93
+ case "darwin-arm64": return require(/* webpackIgnore: true */ /* turbopackIgnore: true */ "@hunghg255/bm-render-darwin-arm64");
94
+ }
95
+ throw new Error(`no package for ${name}`);
96
+ }
97
+
98
+ /** The same from moduleBase() (a bundle's __filename, or the working directory). Not traced; a fallback. */
99
+ function requirePlatformPackageFrom(base, name) {
100
+ return createRequire(base)(`@hunghg255/bm-render-${name}`);
101
+ }
102
+
103
+ /** Loads a `.node` file by path (process.dlopen: what require() does for `.node`, without a module request). */
104
+ function dlopen(file) {
105
+ const m = { exports: {} };
106
+ proc.dlopen(m, file);
107
+ return m.exports;
108
+ }
109
+
110
+ let loaded; // undefined = not tried yet; null = unavailable
111
+ const errors = [];
112
+
113
+ /** The addon's exports, or null when no usable addon is installed for this platform. Never throws. */
114
+ export function loadNative() {
115
+ if (loaded !== undefined) return loaded;
116
+ loaded = null;
117
+ try {
118
+ const names = nativeNames();
119
+ if (names.length === 0) errors.push(`no native build for ${proc.platform}-${proc.arch}`);
120
+ const candidates = []; // [label, load()]
121
+ const forced = proc.env.BM_RENDER_NATIVE_PATH;
122
+ if (forced) {
123
+ const file = resolve(forced); // (relative to the working directory)
124
+ candidates.push([file, () => dlopen(file)]);
125
+ } else {
126
+ let here = null;
127
+ try { here = fileURLToPath(moduleBase()); } catch {}
128
+ for (const name of here ? names : []) {
129
+ const dev = resolve(here, "..", "..", "native", "dist", name, `bm-render.${name}.node`);
130
+ if (existsSync(dev)) candidates.push([dev, () => dlopen(dev)]);
131
+ }
132
+ let metaUrl = false;
133
+ try {
134
+ metaUrl = String(import.meta.url).startsWith("file:");
135
+ } catch {}
136
+ for (const name of names) {
137
+ candidates.push([`@hunghg255/bm-render-${name}`, () => (metaUrl ? requirePlatformPackage(name) : requirePlatformPackageFrom(moduleBase(), name))]);
138
+ }
139
+ }
140
+ for (const [id, load] of candidates) {
141
+ try {
142
+ const addon = load();
143
+ if (!addon || addon.abi !== NATIVE_ABI || typeof addon.run !== "function") {
144
+ errors.push(`${id}: addon interface version ${addon && addon.abi}, expected ${NATIVE_ABI}`);
145
+ continue;
146
+ }
147
+ loaded = addon;
148
+ break;
149
+ } catch (e) {
150
+ const missing = e && e.code === "MODULE_NOT_FOUND" && String(e.message).includes(id);
151
+ errors.push(`${id}: ${missing ? "not installed" : String(e && e.message).split("\n")[0]}`);
152
+ }
153
+ }
154
+ } catch (e) {
155
+ errors.push(String(e && e.message));
156
+ }
157
+ return loaded;
158
+ }
159
+
160
+ /** Why loadNative() returned null (for error messages). */
161
+ export function nativeError() {
162
+ return errors.join("; ") || "not tried";
163
+ }
164
+
165
+ /** Bit of the `pdf` feature in the addon's `features` (src/config.zig `feature_bits`, js/engine.mjs FEATURE_NAMES). */
166
+ const PDF_BIT = 1 << 18;
167
+ const PDF_OPS = new Set(["pdf", "pdfMeasure", "pdfNeeds"]);
168
+
169
+ /** Whether the addon was built with PDF output (the published ones are). */
170
+ export function nativeHasPdf(addon) {
171
+ return !!addon && (addon.features & PDF_BIT) !== 0 && addon.ops.pdf !== undefined && addon.ops.pdfMeasure !== undefined;
172
+ }
173
+
174
+ /**
175
+ * The addon as a js/engine.mjs backend (see the interface there). `pdf`: expose its PDF output. One addon serves
176
+ * two entries: `bm-render` / `bm-render/native` (pdf = false: the feature set of the full wasm build, so
177
+ * `features.pdf` is false and renderPdf rejects exactly as it does on wasm) and `bm-render/pdf` (pdf = true).
178
+ */
179
+ export function nativeBackend(addon, pdf = false) {
180
+ const ops = addon.ops;
181
+ const id = (op) => {
182
+ const i = ops[op];
183
+ if (i === undefined || (!pdf && PDF_OPS.has(op))) throw new Error(`bm-render: ${op} is not supported by this native build`);
184
+ return i;
185
+ };
186
+ // V8 (Node.js, Deno, Electron) hands out zero-filled ArrayBuffers: raw frames are then painted straight into
187
+ // the result's buffer without clearing it first. Unknown engines (Bun: JavaScriptCore) keep the explicit clear.
188
+ try {
189
+ if (typeof addon.tune === "function" && proc.versions && proc.versions.v8 && !proc.versions.bun) addon.tune(0, 0, 0, 1);
190
+ } catch {}
191
+ return {
192
+ name: "native",
193
+ /** what init() / initSync() resolve to */
194
+ exports: addon,
195
+ ready: () => true,
196
+ featureBits: () => (pdf ? addon.features : addon.features & ~PDF_BIT) >>> 0,
197
+ has: (op) => ops[op] !== undefined && (pdf || !PDF_OPS.has(op)),
198
+ create: () => addon.create(),
199
+ destroy: (h) => addon.destroy(h),
200
+ memoryBytes: () => addon.memoryBytes(),
201
+ run(h, op, arg0, arg1, input, options, atts, text) {
202
+ const out = addon.run(h, id(op), arg0, arg1, input, options, atts);
203
+ return text ? dec.decode(out) : out;
204
+ },
205
+ runAsync(h, op, arg0, arg1, input, options, atts, text) {
206
+ const p = addon.runAsync(h, id(op), arg0, arg1, input, options, atts);
207
+ return text ? p.then((out) => dec.decode(out)) : p;
208
+ },
209
+ };
210
+ }
211
+
212
+ let binding; // undefined = not tried yet
213
+
214
+ /**
215
+ * The public API (`{ init, initSync, Renderer, features, setGlyphCacheMaxBytes, backend }`, see js/engine.mjs
216
+ * `createBinding`) on the native addon, or null when it is unavailable. One instance per module realm.
217
+ */
218
+ export function nativeBinding() {
219
+ if (binding !== undefined) return binding;
220
+ const addon = loadNative();
221
+ if (!addon) return (binding = null);
222
+ binding = createBinding(undefined, nativeBackend(addon));
223
+ // WOFF / WOFF2 is compiled in: wasm entries without it (bm-render/core) decode through the addon as well,
224
+ // and bm-render/woff's loadWoff() has nothing to load.
225
+ if (addon.ops.woffDecode !== undefined) {
226
+ builtInWoffDecoder((bytes) => {
227
+ const src = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes.buffer ?? bytes, bytes.byteOffset ?? 0, bytes.byteLength);
228
+ return addon.run(null, addon.ops.woffDecode, 0, 0, null, null, ["", src, 0, 0, 0]);
229
+ });
230
+ }
231
+ return binding;
232
+ }
233
+
234
+ let pdfBinding; // undefined = not tried yet
235
+
236
+ /**
237
+ * The same API on the same addon with its PDF output exposed (`bm-render/pdf` on Node: js/node-pdf.mjs), or null
238
+ * when no addon is available or it was built without the `pdf` feature (the caller then uses bm_render.pdf.wasm).
239
+ */
240
+ export function nativePdfBinding() {
241
+ if (pdfBinding !== undefined) return pdfBinding;
242
+ const addon = loadNative();
243
+ if (!addon) return (pdfBinding = null);
244
+ if (!nativeHasPdf(addon)) {
245
+ errors.push("the addon was built without PDF output");
246
+ return (pdfBinding = null);
247
+ }
248
+ nativeBinding(); // (installs the built-in WOFF decoder)
249
+ return (pdfBinding = createBinding(undefined, nativeBackend(addon, true)));
250
+ }
@@ -0,0 +1,9 @@
1
+ // bm-render/core on Node.js / Bun / Deno: the core profile (bm_render.core.wasm), read from the package (js/wasm-file.mjs: survives bundling) and
2
+ // initialised synchronously on import (shares ./core.mjs's module instance). Same API as ./index.mjs.
3
+ import { readPackageWasm } from "./wasm-file.mjs";
4
+ import { initSync } from "./core.mjs";
5
+
6
+ initSync(readPackageWasm("bm_render.core.wasm"));
7
+
8
+ export * from "./core.mjs";
9
+ export { default } from "./core.mjs";
@@ -0,0 +1,9 @@
1
+ // bm-render/full on Node.js / Bun / Deno: the full profile (bm_render.wasm), read from the package (js/wasm-file.mjs: survives bundling) and
2
+ // initialised synchronously on import (shares ./full.mjs's module instance). Same API as ./index.mjs.
3
+ import { readPackageWasm } from "./wasm-file.mjs";
4
+ import { initSync } from "./full.mjs";
5
+
6
+ initSync(readPackageWasm("bm_render.wasm"));
7
+
8
+ export * from "./full.mjs";
9
+ export { default } from "./full.mjs";
@@ -0,0 +1,15 @@
1
+ // bm-render/native (Node.js / Bun / Deno): the native Node-API addon, or an error when it is not installed for
2
+ // this platform (no wasm fallback; `bm-render` itself falls back automatically). Same API as ./index.mjs;
3
+ // init() / initSync() are no-ops. Shares its instance with `bm-render` when that entry is running natively.
4
+ import { nativeBinding, nativeError, nativeNames } from "./native.mjs";
5
+
6
+ const binding = nativeBinding();
7
+ if (!binding) {
8
+ throw new Error(`bm-render/native: the native addon is not available (${nativeError()}). Install the optional package ` +
9
+ `${nativeNames().map((n) => "@hunghg255/bm-render-" + n).join(" or ") || "for your platform (none is published for it)"}, or import "bm-render" ` +
10
+ `(falls back to WebAssembly) / "bm-render/full" (always WebAssembly).`);
11
+ }
12
+
13
+ export const { init, initSync, Renderer, features, setGlyphCacheMaxBytes, backend } = binding;
14
+ export { Prepared, setWoffDecoder } from "./engine.mjs";
15
+ export default init;
@@ -0,0 +1,34 @@
1
+ // bm-render/pdf on Node.js / Bun / Deno (the "node" condition of `import ... from "bm-render/pdf"`): ready on import.
2
+ //
3
+ // Backend (exported as `backend`: "native" | "wasm"), chosen exactly as js/node.mjs chooses it for `bm-render`:
4
+ // * the native Node-API addon when one is installed for this platform and it was built with PDF output (the
5
+ // published ones are; js/native.mjs): the same addon `bm-render` uses, the same PDF bytes as the wasm build,
6
+ // faster, and the async methods (PdfRenderer.render / measure, Renderer.renderPdf / measurePdf, ...) run on
7
+ // the libuv thread pool instead of blocking the event loop;
8
+ // * otherwise, automatically and silently, the pdf profile (bm_render.pdf.wasm = full + PDF output), read from
9
+ // the package (js/wasm-file.mjs: survives bundling) and initialised synchronously on import (./pdf.mjs's
10
+ // module instance).
11
+ // $BM_RENDER_BACKEND = wasm | native forces one (native without a usable addon = an error on import). $BM_WASM /
12
+ // $BM_PROFILE select the wasm backend here too, as they do for `bm-render` (they name binaries of the image
13
+ // entry; this entry always loads bm_render.pdf.wasm).
14
+ // Same API as ./pdf.mjs (./pdf.d.mts).
15
+ import * as wasm from "./pdf.mjs";
16
+ import { nativePdfBinding, nativeError } from "./native.mjs";
17
+ import { pdfApi } from "./pdf-api.mjs";
18
+ import { readPackageWasm } from "./wasm-file.mjs";
19
+
20
+ const env = (typeof process !== "undefined" && process.env) || {};
21
+ const want = String(env.BM_RENDER_BACKEND || "").toLowerCase();
22
+ if (want && want !== "wasm" && want !== "native") throw new Error(`bm-render: BM_RENDER_BACKEND must be "wasm" or "native", not "${env.BM_RENDER_BACKEND}"`);
23
+ const native = want === "native" || (!want && !env.BM_WASM && !env.BM_PROFILE) ? nativePdfBinding() : null;
24
+ if (!native && want === "native") throw new Error(`bm-render: BM_RENDER_BACKEND=native, but the native addon is not available for bm-render/pdf (${nativeError()})`);
25
+
26
+ if (!native) wasm.initSync(readPackageWasm("bm_render.pdf.wasm"));
27
+
28
+ // (the same names as ./pdf.mjs, bound to the active backend)
29
+ export const { init, initSync, Renderer, features, setGlyphCacheMaxBytes, backend } = native || wasm;
30
+ export const { PdfRenderer, prepare, render, measure } = native ? pdfApi(native.Renderer) : wasm;
31
+ export const { wasmUrl, profile } = wasm;
32
+ export { Prepared, setWoffDecoder } from "./engine.mjs";
33
+ export { PageNumber, TotalPages, TargetPageNumber } from "./pdf-api.mjs";
34
+ export default init;
@@ -0,0 +1,9 @@
1
+ // bm-render/standard on Node.js / Bun / Deno: the standard profile (bm_render.standard.wasm), read from the package (js/wasm-file.mjs: survives bundling) and
2
+ // initialised synchronously on import (shares ./standard.mjs's module instance). Same API as ./index.mjs.
3
+ import { readPackageWasm } from "./wasm-file.mjs";
4
+ import { initSync } from "./standard.mjs";
5
+
6
+ initSync(readPackageWasm("bm_render.standard.wasm"));
7
+
8
+ export * from "./standard.mjs";
9
+ export { default } from "./standard.mjs";
package/js/node.mjs ADDED
@@ -0,0 +1,63 @@
1
+ // bm-render on Node.js / Bun / Deno (the "node" condition of `import ... from "bm-render"`): ready on import.
2
+ //
3
+ // Backend (exported as `backend`: "native" | "wasm"):
4
+ // * the native Node-API addon when one is installed for this platform (js/native.mjs: the optional package
5
+ // @hunghg255/bm-render-<platform>-<arch>[-<abi>], or $BM_RENDER_NATIVE_PATH): same API and the same output bytes as the
6
+ // full wasm build, faster, and the async methods (render, renderSvg, measure, renderAnimation, ...) run on
7
+ // the libuv thread pool instead of blocking the event loop;
8
+ // * otherwise, automatically and silently, the wasm binary: loaded from disk, ./index.mjs's module instance
9
+ // initialised synchronously on import.
10
+ // $BM_RENDER_BACKEND = wasm | native forces one (native without an addon = an error on import). Naming a wasm
11
+ // binary with $BM_WASM / $BM_PROFILE also selects the wasm backend. Always wasm: bm-render/core, /standard,
12
+ // /full. Always native (or an error): bm-render/native.
13
+ //
14
+ // Which wasm binary:
15
+ // 1. $BM_WASM (a file path) if set;
16
+ // 2. else $BM_PROFILE = core | standard | full selects bm_render.<profile>.wasm of the package;
17
+ // 3. else, in a source checkout only (../build.zig exists), a fresh local build ../zig-out/bin/bm_render.wasm;
18
+ // 4. else bm_render.wasm of the package (the full profile; what the npm package ships).
19
+ // "Of the package" = the first readable of (js/wasm-file.mjs): next to this module (import.meta.url), the
20
+ // package resolved with createRequire (bm-render/<subpath>), <cwd>/node_modules/bm-render/js/. The later ones
21
+ // matter when a bundler moved this module away from its package (Next.js without serverExternalPackages,
22
+ // esbuild --bundle without --external:bm-render) but node_modules is still there at run time.
23
+ // Fixed-profile entries with their own instances: bm-render/core, /standard, /full (node-<profile>.mjs).
24
+ import { readFileSync, existsSync } from "node:fs";
25
+ import * as bm from "./index.mjs";
26
+ import { nativeBinding, nativeError } from "./native.mjs";
27
+ import { readPackageWasm, packageFile } from "./wasm-file.mjs";
28
+
29
+ const env = (typeof process !== "undefined" && process.env) || {};
30
+ const want = String(env.BM_RENDER_BACKEND || "").toLowerCase();
31
+ if (want && want !== "wasm" && want !== "native") throw new Error(`bm-render: BM_RENDER_BACKEND must be "wasm" or "native", not "${env.BM_RENDER_BACKEND}"`);
32
+ const native = want === "native" || (!want && !env.BM_WASM && !env.BM_PROFILE) ? nativeBinding() : null;
33
+ if (!native && want === "native") throw new Error(`bm-render: BM_RENDER_BACKEND=native, but the native addon is not available (${nativeError()})`);
34
+
35
+ if (!native) {
36
+ const profile = env.BM_PROFILE && env.BM_PROFILE !== "full" ? env.BM_PROFILE : null;
37
+ let bytes;
38
+ if (env.BM_WASM) {
39
+ try {
40
+ bytes = readFileSync(env.BM_WASM);
41
+ } catch (e) {
42
+ throw new Error(`bm-render: BM_WASM=${env.BM_WASM} cannot be read (${e && e.message})`);
43
+ }
44
+ } else {
45
+ if (!profile) {
46
+ // a source checkout: prefer the fresh local build
47
+ const checkout = packageFile("../build.zig");
48
+ const dev = checkout && existsSync(checkout) ? packageFile("../zig-out/bin/bm_render.wasm") : null;
49
+ if (dev) {
50
+ try {
51
+ bytes = readFileSync(dev);
52
+ } catch {}
53
+ }
54
+ }
55
+ bytes ??= readPackageWasm(profile ? `bm_render.${profile}.wasm` : "bm_render.wasm");
56
+ }
57
+ bm.initSync(bytes);
58
+ }
59
+
60
+ // (the same names as ./index.mjs, bound to the active backend)
61
+ export const { init, initSync, Renderer, features, setGlyphCacheMaxBytes, backend } = native || bm;
62
+ export { Prepared, setWoffDecoder } from "./engine.mjs";
63
+ export default init;
package/js/pdf-api.mjs ADDED
@@ -0,0 +1,232 @@
1
+ // bm-render internal: the takumi-pdf style API (`PdfRenderer`, `render`, `measure`, `prepare`) on top of one
2
+ // binding's `Renderer`, and the page counter primitives. Shared by js/pdf.mjs (the wasm pdf profile) and
3
+ // js/node-pdf.mjs (the native addon when it is available), so both expose exactly the same classes.
4
+ const DISPOSE = typeof Symbol.dispose === "symbol" ? Symbol.dispose : Symbol.for("nodejs.dispose");
5
+ import { resourceOptions } from "./pdf-resources.mjs";
6
+
7
+ /** @param {new (options?: object) => any} Renderer the `Renderer` of a binding with the `pdf` feature */
8
+ export function pdfApi(Renderer) {
9
+ /**
10
+ * A PDF renderer holding registered fonts (takumi-pdf `PdfRenderer`). Reuse one instance across renders.
11
+ * `prepare` discovers resources after the cascade and fetches missing images and font files.
12
+ */
13
+ class PdfRenderer {
14
+ #r;
15
+
16
+ constructor(options) {
17
+ this.#r = new Renderer(options);
18
+ }
19
+
20
+ registerFont(font) { return this.#r.registerFont(font); }
21
+ loadFont(font) { return this.#r.registerFont(font); }
22
+ /** Removes every face of a family: takumi-pdf takes `{ name }` (a registered family); a plain name works too. */
23
+ unregisterFont(family) { return this.#r.unregisterFont(family !== null && typeof family === "object" ? family.name : family); }
24
+ clearFonts() { this.#r.clearFonts(); }
25
+ /**
26
+ * Resolves `fonts` / lazy `images` once and, as takumi-pdf's `prepare` does, fetches the remote images the
27
+ * document draws that `images` does not provide (`images: { sources, fetch, ... }`); `render` and `measure`
28
+ * accept the handle (their options merge over it).
29
+ */
30
+ async prepare(node, options) {
31
+ node = resolveDocument(node);
32
+ return this.#r.prepare(node, await resourceOptions(this.#r, node, resolveBands(options), true));
33
+ }
34
+ /** A node tree, an HTML string or a prepared document -> PDF bytes (Uint8Array). */
35
+ async render(node, options) {
36
+ node = resolveDocument(node);
37
+ return this.#r.renderPdf(node, node?.[PREPARED] ? resolveBands(options) : await resourceOptions(this.#r, node, resolveBands(options), false));
38
+ }
39
+ renderSync(node, options) { return this.#r.renderPdfSync(resolveDocument(node), resolveBands(options)); }
40
+ /**
41
+ * Laid-out `{ width, height }` in CSS px (page options: at the full page width, unbounded height, like a band).
42
+ * As in takumi-pdf, `signal` is not read here.
43
+ */
44
+ async measure(node, options) {
45
+ node = resolveDocument(node);
46
+ return this.#r.measurePdf(node, node?.[PREPARED] ? measureOptions(options) : await resourceOptions(this.#r, node, measureOptions(options), false));
47
+ }
48
+ measureSync(node, options) { return this.#r.measurePdfSync(resolveDocument(node), measureOptions(options)); }
49
+ free() { this.#r.free(); }
50
+ [DISPOSE]() { this.free(); }
51
+ }
52
+
53
+ let shared;
54
+ const sharedRenderer = () => (shared ??= new PdfRenderer());
55
+
56
+ return {
57
+ PdfRenderer,
58
+ /** Prepares with a lazily created shared {@link PdfRenderer}. */
59
+ prepare: (node, options) => sharedRenderer().prepare(node, options),
60
+ /** Renders with a lazily created shared {@link PdfRenderer}. */
61
+ render: (node, options) => sharedRenderer().render(node, options),
62
+ /** Measures with a lazily created shared {@link PdfRenderer}. */
63
+ measure: (node, options) => sharedRenderer().measure(node, options),
64
+ };
65
+ }
66
+
67
+ // ---- inputs as takumi-pdf's JS wrapper reads them (takumi-bindings-js document.ts `resolveDocument`, export.ts)
68
+
69
+ const PREPARED = Symbol.for("bm-render.prepared");
70
+ const isJsxElement = (v) => typeof v === "object" && v !== null && typeof v.$$typeof === "symbol" && "props" in v;
71
+ /** takumi-bindings-js `isNode`: an object with a `type` that is not a JSX element (bm-render also reads `{ json }`). */
72
+ const isNode = (v) => typeof v === "object" && v !== null && "type" in v && !("$$typeof" in v);
73
+
74
+ /**
75
+ * A document or band as takumi-pdf's wrapper reads it: HTML strings and node trees as they are; anything else goes
76
+ * through `fromJsx`, here as HTML markup: a JSX (React element) tree, and the values fromJsx turns into text
77
+ * (`true` -> "true", `5` -> "5", `{}` -> "[object Object]"; `null` / `undefined` / `false` -> nothing, a list -> its
78
+ * items). A list at the root is passed on as is (bm rejects it, takumi-pdf throws too).
79
+ */
80
+ function resolveDocument(v) {
81
+ if (typeof v === "string" || isNode(v) || Array.isArray(v)) return v;
82
+ if (typeof v === "object" && v !== null && (v[PREPARED] || typeof v.json === "string")) return v;
83
+ return jsxToHtml(v);
84
+ }
85
+
86
+ /** A band value: `false` / `null` / `undefined` stay (no band), the rest as {@link resolveDocument} reads a document. */
87
+ const resolveBand = (v) => (v == null || v === false ? v : typeof v === "string" || isNode(v) ? v : jsxToHtml(v));
88
+
89
+ const CSS_NULL = "bm-render: data did not match any variant of untagged enum CssSource";
90
+
91
+ /** render / prepare options: bands resolved, and the input checks takumi-pdf's wrapper makes before the native side. */
92
+ function resolveBands(options) {
93
+ if (options == null || typeof options !== "object" || Array.isArray(options)) return options;
94
+ const o = { ...options };
95
+ // JSON.stringify turns NaN and infinities into null. Reject them here while
96
+ // the original JS numbers are still observable, before the native/wasm parser
97
+ // can mistake them for an omitted margin side.
98
+ if (typeof o.margin === "number") {
99
+ if (!Number.isFinite(o.margin)) throw new Error("Page size must be finite and larger than zero");
100
+ } else if (o.margin && typeof o.margin === "object" && !Array.isArray(o.margin)) {
101
+ for (const side of ["top", "right", "bottom", "left"]) {
102
+ if (typeof o.margin[side] === "number" && !Number.isFinite(o.margin[side]))
103
+ throw new Error("Page size must be finite and larger than zero");
104
+ }
105
+ }
106
+ // takumi-pdf: `css: null` becomes the sheet list `[null]`, which no `CssSource` variant reads
107
+ if (o.css === null) throw new TypeError(CSS_NULL);
108
+ if (o.fonts != null && typeof o.fonts !== "object" && typeof o.fonts !== "function") throw new TypeError("bm-render: fonts takes an array");
109
+ if ("header" in o) o.header = resolveBand(o.header);
110
+ if ("footer" in o) o.footer = resolveBand(o.footer);
111
+ if (o.pages != null && typeof o.pages === "object" && !Array.isArray(o.pages)) {
112
+ const pages = {};
113
+ for (const [rule, page] of Object.entries(o.pages)) {
114
+ if (page == null || typeof page !== "object" || Array.isArray(page)) { pages[rule] = page; continue; }
115
+ const p = { ...page };
116
+ if ("header" in p) p.header = resolveBand(p.header);
117
+ if ("footer" in p) p.footer = resolveBand(p.footer);
118
+ pages[rule] = p;
119
+ }
120
+ o.pages = pages;
121
+ }
122
+ return o;
123
+ }
124
+
125
+ /** measure options: takumi-pdf's `measure` does not read `signal`. */
126
+ function measureOptions(options) {
127
+ if (options == null || typeof options !== "object" || Array.isArray(options)) return options;
128
+ const { signal: _s, ...o } = options;
129
+ if (o.css === null) throw new TypeError(CSS_NULL);
130
+ return o;
131
+ }
132
+
133
+ // React's unitless style properties (a number stays a number; any other takes px)
134
+ const UNITLESS = new Set(("animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup " +
135
+ "boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd " +
136
+ "gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order " +
137
+ "orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit " +
138
+ "strokeOpacity strokeWidth").split(" "));
139
+ // SVG presentation attributes written camelCase in JSX (takumi helpers jsx.ts)
140
+ const SVG_KEBAB = new Set(("stopColor stopOpacity strokeWidth strokeDasharray strokeDashoffset strokeLinecap strokeLinejoin fillRule " +
141
+ "clipRule colorInterpolationFilters floodColor floodOpacity clipPath fillOpacity fontFamily fontSize fontStyle fontWeight " +
142
+ "strokeMiterlimit strokeOpacity textAnchor textDecoration transformOrigin dominantBaseline alignmentBaseline baselineShift " +
143
+ "letterSpacing wordSpacing markerEnd markerMid markerStart paintOrder vectorEffect").split(" "));
144
+ const VOID = new Set(["area", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "wbr"]);
145
+ const kebab = (k) => (k.startsWith("--") ? k : k.replace(/^ms(?=[A-Z])/, "-ms").replace(/[A-Z]/g, (c) => "-" + c.toLowerCase()));
146
+ const escText = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
147
+ const escAttr = (s) => escText(s).replace(/"/g, "&quot;");
148
+ const cssText = (style) =>
149
+ Object.entries(style)
150
+ .filter(([, v]) => v != null && v !== "" && typeof v !== "boolean")
151
+ .map(([k, v]) => `${kebab(k)}:${typeof v === "number" && v !== 0 && !UNITLESS.has(k) && !k.startsWith("--") ? v + "px" : String(v)}`)
152
+ .join(";");
153
+
154
+ /**
155
+ * takumi helpers `fromJsx`, as HTML markup bm-render's HTML reader lays out: function / class / forwardRef / memo
156
+ * components are called, fragments and context providers give their children, `<style>` stays a style sheet,
157
+ * `className` is `class`, a `style` object is CSS text (numbers in px, React's unitless properties excepted).
158
+ * Components run once without a React dispatcher: hooks other than plain reads are not supported.
159
+ */
160
+ export function jsxToHtml(v, svg = false) {
161
+ if (v == null || v === false) return "";
162
+ if (typeof v === "string" || typeof v === "number" || typeof v === "bigint" || v === true) return escText(String(v));
163
+ if (typeof v === "object" && typeof v.then === "function") throw new TypeError("bm-render: an async component needs to be awaited before render");
164
+ if (isJsxElement(v)) return jsxElement(v, svg);
165
+ if (typeof v === "object" && typeof v[Symbol.iterator] === "function") return Array.from(v, (x) => jsxToHtml(x, svg)).join("");
166
+ return escText(String(v));
167
+ }
168
+
169
+ function jsxElement(el, svg) {
170
+ const { type } = el;
171
+ const props = el.props || {};
172
+ if (typeof type === "function") {
173
+ if (type.prototype && type.prototype.isReactComponent) return jsxToHtml(new type(props).render(), svg);
174
+ return jsxToHtml(type(props), svg);
175
+ }
176
+ if (typeof type === "symbol") return jsxToHtml(props.children, svg);
177
+ if (typeof type === "object" && type !== null) {
178
+ const kind = String(type.$$typeof && type.$$typeof.description);
179
+ if (typeof type.render === "function") return jsxToHtml(type.render(props, null), svg); // forwardRef
180
+ if (type.type !== undefined) return jsxElement({ ...el, type: type.type }, svg); // memo
181
+ if (kind === "react.consumer" || (kind === "react.context" && typeof props.children === "function")) {
182
+ const ctx = type._context || type;
183
+ return jsxToHtml(typeof props.children === "function" ? props.children(ctx._currentValue) : props.children, svg);
184
+ }
185
+ return jsxToHtml(props.children, svg); // providers
186
+ }
187
+ if (typeof type !== "string") return "";
188
+ const tag = type;
189
+ const inSvg = svg || tag === "svg";
190
+ let attrs = "";
191
+ for (const [k, val] of Object.entries(props)) {
192
+ if (k === "children" || k === "key" || k === "ref" || k === "dangerouslySetInnerHTML" || val == null || val === false || typeof val === "function") continue;
193
+ const name = k === "className" ? "class" : k === "htmlFor" ? "for" : inSvg && SVG_KEBAB.has(k) ? kebab(k) : k;
194
+ const text = k === "style" && typeof val === "object" ? cssText(val) : val === true ? "" : String(val);
195
+ attrs += ` ${name}="${escAttr(text)}"`;
196
+ }
197
+ if (tag === "svg" && props.xmlns == null) attrs += ` xmlns="http://www.w3.org/2000/svg"`;
198
+ if (tag === "style") return `<style${attrs}>${styleText(props.children)}</style>`;
199
+ if (VOID.has(tag) && !inSvg) return `<${tag}${attrs}>`;
200
+ const inner = props.dangerouslySetInnerHTML && props.dangerouslySetInnerHTML.__html != null ? String(props.dangerouslySetInnerHTML.__html) : jsxToHtml(props.children, inSvg);
201
+ return `<${tag}${attrs}>${inner}</${tag}>`;
202
+ }
203
+
204
+ /** The text of a `<style>` element's children (takumi helpers: strings and numbers, joined). */
205
+ function styleText(c) {
206
+ if (c == null || typeof c === "boolean") return "";
207
+ if (typeof c === "string" || typeof c === "number") return String(c).replace(/<\/style/gi, "<\\/style");
208
+ if (typeof c === "object" && typeof c[Symbol.iterator] === "function") return Array.from(c, styleText).join("");
209
+ return isJsxElement(c) ? styleText(c.props && c.props.children) : "";
210
+ }
211
+
212
+ // ---- page counter primitives (takumi-pdf primitives.ts, as bm-render nodes instead of JSX elements)
213
+
214
+ const counter = (hook, { format, className, ...rest } = {}) => ({
215
+ type: "container",
216
+ tagName: "span",
217
+ ...rest,
218
+ className: [hook, format, className].filter(Boolean).join(" "),
219
+ });
220
+
221
+ /** The number of the page this element lands on. Meaningful inside a `header` / `footer` band. */
222
+ export const PageNumber = (props) => counter("pageNumber", props);
223
+ /** The document's total page count. Same placement rules as {@link PageNumber}. */
224
+ export const TotalPages = (props) => counter("totalPages", props);
225
+ /**
226
+ * The number of the page a link's target element lands on, for cross references like "see page 12".
227
+ * Without `href` it reads the nearest enclosing `<a>`; with one it renders its own link.
228
+ */
229
+ export const TargetPageNumber = ({ href, ...props } = {}) => {
230
+ const span = counter("targetPageNumber", props);
231
+ return href === undefined ? span : { type: "container", tagName: "a", attributes: { href }, children: [span] };
232
+ };