@junejs/pdf-typst-wasm 0.1.0-dev.0 → 0.2.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.
@@ -0,0 +1,69 @@
1
+ import { PdfRenderer } from "@junejs/pdf";
2
+ //#region src/engine.d.ts
3
+ type FontScope = "persistent" | "document";
4
+ type TypstOutput = {
5
+ pdf: Uint8Array;
6
+ missingGlyphs: string[];
7
+ };
8
+ interface TypstEngine {
9
+ addFont(data: Uint8Array, scope: FontScope): number;
10
+ clearDocumentFonts(): void;
11
+ compile(source: string): TypstOutput;
12
+ memoryBytes(): number;
13
+ }
14
+ declare class TypstCompileError extends Error {
15
+ constructor(message: string);
16
+ }
17
+ type WasmSource = WebAssembly.Module | BufferSource;
18
+ declare function createEngine(wasm: WasmSource): Promise<TypstEngine>;
19
+ //#endregion
20
+ //#region src/fonts.d.ts
21
+ type FontEgress = {
22
+ host: string;
23
+ sends: "nothing" | "document-characters";
24
+ };
25
+ interface FontProvider {
26
+ readonly name: string;
27
+ readonly egress: readonly FontEgress[];
28
+ persistent?(): Promise<Uint8Array[]>;
29
+ forDocument?(text: string): Promise<DocumentFonts>;
30
+ }
31
+ type DocumentFonts = {
32
+ fonts: Uint8Array[];
33
+ failed?: string[];
34
+ };
35
+ type FontSource = Uint8Array | ArrayBuffer | string | (() => Promise<Uint8Array | ArrayBuffer>);
36
+ declare function localFonts(input: FontSource[], opts?: {
37
+ fetch?: typeof fetch;
38
+ }): FontProvider;
39
+ type GoogleFont = {
40
+ family: string;
41
+ weights?: number[];
42
+ };
43
+ declare function googleFontSubsets(opts: {
44
+ families: GoogleFont[];
45
+ fetch?: typeof fetch;
46
+ }): FontProvider;
47
+ //#endregion
48
+ //#region src/renderer.d.ts
49
+ type TypstWasmRendererOptions = {
50
+ wasm?: WasmSource | (() => Promise<WasmSource>);
51
+ fonts?: FontProvider[];
52
+ fontFamilies?: string[];
53
+ onMissingGlyphs?: "error" | "warn";
54
+ };
55
+ interface TypstWasmRenderer extends PdfRenderer {
56
+ readonly egress: readonly FontEgress[];
57
+ }
58
+ //#endregion
59
+ //#region src/assets.d.ts
60
+ type AssetRef = {
61
+ name: string;
62
+ sha256: string;
63
+ size: number;
64
+ urls: string[];
65
+ };
66
+ type AssetLoader = (ref: AssetRef) => Promise<Uint8Array | ArrayBuffer>;
67
+ declare function loadVerified(ref: AssetRef, load: AssetLoader): Promise<Uint8Array>;
68
+ //#endregion
69
+ export { WasmSource as _, TypstWasmRendererOptions as a, FontProvider as c, googleFontSubsets as d, localFonts as f, TypstOutput as g, TypstEngine as h, TypstWasmRenderer as i, FontSource as l, TypstCompileError as m, AssetRef as n, DocumentFonts as o, FontScope as p, loadVerified as r, FontEgress as s, AssetLoader as t, GoogleFont as u, createEngine as v };
@@ -0,0 +1,197 @@
1
+ import { PdfRenderError, typstSource } from "@junejs/pdf";
2
+ //#region src/engine.ts
3
+ var TypstCompileError = class extends Error {
4
+ constructor(message) {
5
+ super(message);
6
+ this.name = "TypstCompileError";
7
+ }
8
+ };
9
+ async function createEngine(wasm) {
10
+ const made = await WebAssembly.instantiate(wasm, {});
11
+ const x = (made instanceof WebAssembly.Instance ? made : made.instance).exports;
12
+ x.init();
13
+ const put = (bytes) => {
14
+ const ptr = x.alloc(bytes.length);
15
+ new Uint8Array(x.memory.buffer, ptr, bytes.length).set(bytes);
16
+ return ptr;
17
+ };
18
+ const output = () => new Uint8Array(x.memory.buffer, x.output_ptr(), x.output_len()).slice();
19
+ const utf8 = new TextEncoder();
20
+ const text = new TextDecoder();
21
+ return {
22
+ addFont(data, scope) {
23
+ return x.add_font(put(data), data.length, scope === "document" ? 1 : 0);
24
+ },
25
+ clearDocumentFonts() {
26
+ x.clear_document_fonts();
27
+ },
28
+ compile(source) {
29
+ const bytes = utf8.encode(source);
30
+ const status = x.compile(put(bytes), bytes.length);
31
+ const out = output();
32
+ if (status !== 0) throw new TypstCompileError(text.decode(out));
33
+ return {
34
+ pdf: out,
35
+ missingGlyphs: [...text.decode(new Uint8Array(x.memory.buffer, x.missing_glyphs_ptr(), x.missing_glyphs_len()))]
36
+ };
37
+ },
38
+ memoryBytes() {
39
+ return x.memory.buffer.byteLength;
40
+ }
41
+ };
42
+ }
43
+ //#endregion
44
+ //#region src/renderer.ts
45
+ const MISSING_SHOWN = 10;
46
+ function createTypstWasmRenderer(defaultWasm, opts = {}, engineEgress = []) {
47
+ const providers = [...opts.fonts ?? []];
48
+ let engine;
49
+ const ready = () => engine ??= (async () => {
50
+ const e = await createEngine(typeof opts.wasm === "function" ? await opts.wasm() : opts.wasm ?? await defaultWasm());
51
+ const persistent = await Promise.all(providers.map((p) => p.persistent?.() ?? []));
52
+ for (const font of persistent.flat()) e.addFont(font, "persistent");
53
+ return e;
54
+ })().catch((err) => {
55
+ engine = void 0;
56
+ throw err;
57
+ });
58
+ return {
59
+ name: "typst-wasm",
60
+ egress: uniqueEgress([...engineEgress, ...providers.flatMap((p) => p.egress)]),
61
+ async render(doc) {
62
+ const source = typstSource(doc, { fonts: opts.fontFamilies });
63
+ const [e, documentFonts] = await Promise.all([ready(), fontsFor(doc, providers)]);
64
+ e.clearDocumentFonts();
65
+ for (const font of documentFonts.fonts) e.addFont(font, "document");
66
+ let out;
67
+ try {
68
+ out = e.compile(source);
69
+ } catch (err) {
70
+ if (err instanceof TypstCompileError) throw new PdfRenderError(`the document could not be typeset: ${err.message}`, { cause: err });
71
+ throw err;
72
+ } finally {
73
+ e.clearDocumentFonts();
74
+ }
75
+ if (out.missingGlyphs.length === 0) return out.pdf;
76
+ const message = missingGlyphsMessage(out.missingGlyphs, documentFonts.failed);
77
+ if (opts.onMissingGlyphs === "warn") {
78
+ console.warn(`[june] pdf-typst-wasm: ${message}`);
79
+ return out.pdf;
80
+ }
81
+ throw new PdfRenderError(message);
82
+ }
83
+ };
84
+ }
85
+ function uniqueEgress(all) {
86
+ const seen = /* @__PURE__ */ new Map();
87
+ for (const e of all) if (!seen.get(e.host) || e.sends === "document-characters") seen.set(e.host, {
88
+ host: e.host,
89
+ sends: e.sends
90
+ });
91
+ return [...seen.values()];
92
+ }
93
+ function documentText(doc) {
94
+ return [...new Set(doc.markdown.replace(/[\x00-\x7f]/g, ""))].join("");
95
+ }
96
+ async function fontsFor(doc, providers) {
97
+ const text = documentText(doc);
98
+ const loaders = providers.filter((p) => p.forDocument);
99
+ if (!text || loaders.length === 0) return {
100
+ fonts: [],
101
+ failed: []
102
+ };
103
+ const settled = await Promise.allSettled(loaders.map((p) => p.forDocument(text)));
104
+ const failure = (i, why) => `${loaders[i].name} failed (${why})`;
105
+ return {
106
+ fonts: settled.flatMap((s) => s.status === "fulfilled" ? s.value.fonts : []),
107
+ failed: settled.flatMap((s, i) => s.status === "rejected" ? [failure(i, s.reason instanceof Error ? s.reason.message : String(s.reason))] : (s.value.failed ?? []).map((why) => failure(i, why)))
108
+ };
109
+ }
110
+ function missingGlyphsMessage(missing, failed) {
111
+ return `no font available to the PDF renderer covers ${missing.slice(0, MISSING_SHOWN).join(" ")}${missing.length > MISSING_SHOWN ? ` (and ${missing.length - MISSING_SHOWN} more)` : ""}, so they would be missing from the document. ` + (failed.length ? `${failed.join("; ")}. ` : "") + "Remove them from the Markdown if they are decorative (emoji, symbols); otherwise tell the user the PDF can't include them until the app adds a font that covers them to typstWasmRenderer's `fonts` (localFonts or googleFontSubsets).";
112
+ }
113
+ //#endregion
114
+ //#region src/fonts.ts
115
+ function localFonts(input, opts = {}) {
116
+ const sources = [...input];
117
+ const fetcher = opts.fetch ?? fetch;
118
+ return {
119
+ name: "local-fonts",
120
+ egress: [...new Set(sources.filter((s) => typeof s === "string").map((url) => new URL(url).host))].map((host) => ({
121
+ host,
122
+ sends: "nothing"
123
+ })),
124
+ persistent: () => Promise.all(sources.map((s) => loadFont(s, fetcher)))
125
+ };
126
+ }
127
+ async function loadFont(source, fetcher) {
128
+ if (source instanceof Uint8Array) return source;
129
+ if (source instanceof ArrayBuffer) return new Uint8Array(source);
130
+ if (typeof source === "function") {
131
+ const data = await source();
132
+ return data instanceof Uint8Array ? data : new Uint8Array(data);
133
+ }
134
+ const res = await fetcher(source);
135
+ if (!res.ok) throw new Error(`font ${source}: HTTP ${res.status}`);
136
+ return new Uint8Array(await res.arrayBuffer());
137
+ }
138
+ function googleFontSubsets(opts) {
139
+ const fetcher = opts.fetch ?? fetch;
140
+ const wanted = opts.families.flatMap((f) => (f.weights ?? [400]).map((w) => [f.family, w]));
141
+ const cache = /* @__PURE__ */ new Map();
142
+ return {
143
+ name: "google-font-subsets",
144
+ egress: [{
145
+ host: "fonts.googleapis.com",
146
+ sends: "document-characters"
147
+ }, {
148
+ host: "fonts.gstatic.com",
149
+ sends: "document-characters"
150
+ }],
151
+ async forDocument(text) {
152
+ const settled = await Promise.allSettled(wanted.map(([family, weight]) => googleSubset(cache, family, weight, text, fetcher)));
153
+ return {
154
+ fonts: settled.flatMap((s) => s.status === "fulfilled" ? [s.value] : []),
155
+ failed: settled.flatMap((s, i) => s.status === "rejected" ? [`${wanted[i][0]} ${wanted[i][1]}: ${message(s.reason)}`] : [])
156
+ };
157
+ }
158
+ };
159
+ }
160
+ const message = (err) => err instanceof Error ? err.message : String(err);
161
+ const OLD_SAFARI = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1";
162
+ const SUBSET_CACHE_MAX = 32;
163
+ function googleSubset(cache, family, weight, text, fetcher) {
164
+ const css = `https://fonts.googleapis.com/css2?family=${encodeURIComponent(family)}:wght@${weight}&text=${encodeURIComponent(text)}`;
165
+ const hit = cache.get(css);
166
+ if (hit) {
167
+ cache.delete(css);
168
+ cache.set(css, hit);
169
+ return hit;
170
+ }
171
+ const load = (async () => {
172
+ const res = await fetcher(css, { headers: { "user-agent": OLD_SAFARI } });
173
+ if (!res.ok) throw new Error(`Google Fonts CSS: HTTP ${res.status}`);
174
+ const url = (await res.text()).match(/src:\s*url\((.+?)\)/)?.[1];
175
+ if (!url) throw new Error("Google Fonts CSS named no font file");
176
+ const font = await fetcher(url);
177
+ if (!font.ok) throw new Error(`Google Fonts file: HTTP ${font.status}`);
178
+ return new Uint8Array(await font.arrayBuffer());
179
+ })();
180
+ load.catch(() => cache.delete(css));
181
+ cache.set(css, load);
182
+ if (cache.size > SUBSET_CACHE_MAX) cache.delete(cache.keys().next().value);
183
+ return load;
184
+ }
185
+ //#endregion
186
+ //#region src/assets.ts
187
+ async function loadVerified(ref, load) {
188
+ const got = await load(ref);
189
+ const bytes = got instanceof Uint8Array ? got.buffer instanceof SharedArrayBuffer ? got.slice() : got : new Uint8Array(got);
190
+ if (bytes.byteLength !== ref.size) throw new Error(`${ref.name}: the loader returned ${bytes.byteLength} bytes, expected ${ref.size} (sha256 ${ref.sha256})`);
191
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
192
+ const hex = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
193
+ if (hex !== ref.sha256) throw new Error(`${ref.name}: the loader returned bytes with sha256 ${hex}, expected ${ref.sha256}`);
194
+ return bytes;
195
+ }
196
+ //#endregion
197
+ export { TypstCompileError as a, createTypstWasmRenderer as i, googleFontSubsets as n, createEngine as o, localFonts as r, loadVerified as t };
package/dist/node.d.ts CHANGED
@@ -1,7 +1,6 @@
1
- import { a as FontScope, c as WasmSource, i as TypstWasmRendererOptions, l as createEngine, n as FontSource, o as TypstCompileError, r as GoogleFont, s as TypstEngine, t as DEFAULT_GOOGLE_FONTS } from "./renderer--txXuJuD.js";
2
- import { PdfRenderer } from "@junejs/pdf";
1
+ import { _ as WasmSource, a as TypstWasmRendererOptions, c as FontProvider, d as googleFontSubsets, f as localFonts, g as TypstOutput, h as TypstEngine, i as TypstWasmRenderer, l as FontSource, m as TypstCompileError, n as AssetRef, o as DocumentFonts, p as FontScope, r as loadVerified, s as FontEgress, t as AssetLoader, u as GoogleFont, v as createEngine } from "./assets-0jc0W7Pm.js";
3
2
  //#region src/node.d.ts
4
3
  export declare const WASM_URL: URL;
5
- export declare function typstWasmRenderer(opts?: TypstWasmRendererOptions): PdfRenderer;
4
+ export declare function typstWasmRenderer(opts?: TypstWasmRendererOptions): TypstWasmRenderer;
6
5
  //#endregion
7
- export { DEFAULT_GOOGLE_FONTS, type FontScope, type FontSource, type GoogleFont, TypstCompileError, type TypstEngine, type TypstWasmRendererOptions, type WasmSource, createEngine };
6
+ export { type AssetLoader, type AssetRef, type DocumentFonts, type FontEgress, type FontProvider, type FontScope, type FontSource, type GoogleFont, TypstCompileError, type TypstEngine, type TypstOutput, type TypstWasmRenderer, type TypstWasmRendererOptions, type WasmSource, createEngine, googleFontSubsets, loadVerified, localFonts };
package/dist/node.js CHANGED
@@ -1,4 +1,4 @@
1
- import { i as createEngine, n as createTypstWasmRenderer, r as TypstCompileError, t as DEFAULT_GOOGLE_FONTS } from "./renderer-CHKIXC79.js";
1
+ import { a as TypstCompileError, i as createTypstWasmRenderer, n as googleFontSubsets, o as createEngine, r as localFonts, t as loadVerified } from "./assets-rrgfvCKs.js";
2
2
  //#region src/node.ts
3
3
  const WASM_URL = new URL("../dist/typst.wasm", import.meta.url);
4
4
  let compiled;
@@ -9,7 +9,7 @@ async function loadWasm() {
9
9
  try {
10
10
  bytes = await readFile(fileURLToPath(WASM_URL));
11
11
  } catch (err) {
12
- throw new Error(`@junejs/pdf-typst-wasm: ${fileURLToPath(WASM_URL)} is missing — in the June repo, run \`bun run build\` in packages/pdf-typst-wasm`, { cause: err });
12
+ throw new Error(`@junejs/pdf-typst-wasm: ${fileURLToPath(WASM_URL)} is missing — in the June repo, run \`bun run build\` in packages/pdf-typst-wasm; in a bundled or single-file build, pass the module through the \`wasm\` option`, { cause: err });
13
13
  }
14
14
  return WebAssembly.compile(bytes);
15
15
  })().catch((err) => {
@@ -21,4 +21,4 @@ function typstWasmRenderer(opts = {}) {
21
21
  return createTypstWasmRenderer(loadWasm, opts);
22
22
  }
23
23
  //#endregion
24
- export { DEFAULT_GOOGLE_FONTS, TypstCompileError, WASM_URL, createEngine, typstWasmRenderer };
24
+ export { TypstCompileError, WASM_URL, createEngine, googleFontSubsets, loadVerified, localFonts, typstWasmRenderer };
package/dist/typst.wasm CHANGED
Binary file
@@ -0,0 +1,9 @@
1
+ {
2
+ "name": "typst.wasm",
3
+ "sha256": "65482a22d5c7fa257bce3f0bf9531548f1f553427d29b783ff84b346f678517f",
4
+ "size": 30456380,
5
+ "urls": [
6
+ "https://cdn.jsdelivr.net/npm/@junejs/pdf-typst-wasm@0.2.1/dist/typst.wasm",
7
+ "https://unpkg.com/@junejs/pdf-typst-wasm@0.2.1/dist/typst.wasm"
8
+ ]
9
+ }
@@ -0,0 +1,11 @@
1
+ import { _ as WasmSource, a as TypstWasmRendererOptions, c as FontProvider, d as googleFontSubsets, f as localFonts, g as TypstOutput, h as TypstEngine, i as TypstWasmRenderer, l as FontSource, m as TypstCompileError, n as AssetRef, o as DocumentFonts, p as FontScope, r as loadVerified, s as FontEgress, t as AssetLoader, u as GoogleFont, v as createEngine } from "./assets-0jc0W7Pm.js";
2
+ //#region src/unbundled.d.ts
3
+ export declare function engineUrls(version: string): string[];
4
+ export declare function typstWasmAsset(): Promise<AssetRef>;
5
+ export type UnbundledRendererOptions = Omit<TypstWasmRendererOptions, "wasm"> & {
6
+ load: AssetLoader;
7
+ engineEgress?: FontEgress[];
8
+ };
9
+ export declare function typstWasmRenderer(opts: UnbundledRendererOptions): TypstWasmRenderer;
10
+ //#endregion
11
+ export { type AssetLoader, type AssetRef, type DocumentFonts, type FontEgress, type FontProvider, type FontScope, type FontSource, type GoogleFont, TypstCompileError, type TypstEngine, type TypstOutput, type TypstWasmRenderer, type WasmSource, createEngine, googleFontSubsets, loadVerified, localFonts };
@@ -0,0 +1,22 @@
1
+ import { a as TypstCompileError, i as createTypstWasmRenderer, n as googleFontSubsets, o as createEngine, r as localFonts, t as loadVerified } from "./assets-rrgfvCKs.js";
2
+ //#region src/unbundled.ts
3
+ function engineUrls(version) {
4
+ return [`https://cdn.jsdelivr.net/npm/@junejs/pdf-typst-wasm@${version}/dist/typst.wasm`, `https://unpkg.com/@junejs/pdf-typst-wasm@${version}/dist/typst.wasm`];
5
+ }
6
+ const ENGINE_HOSTS = engineUrls("0").map((url) => ({
7
+ host: new URL(url).host,
8
+ sends: "nothing"
9
+ }));
10
+ async function typstWasmAsset() {
11
+ try {
12
+ return (await import("../dist/typst.wasm.ref.json", { with: { type: "json" } })).default;
13
+ } catch (err) {
14
+ throw new Error("@junejs/pdf-typst-wasm/unbundled: dist/typst.wasm.ref.json is missing — in the June repo, run `bun run build` in packages/pdf-typst-wasm", { cause: err });
15
+ }
16
+ }
17
+ function typstWasmRenderer(opts) {
18
+ const { load, engineEgress, ...rest } = opts;
19
+ return createTypstWasmRenderer(async () => loadVerified(await typstWasmAsset(), load), rest, engineEgress ?? ENGINE_HOSTS);
20
+ }
21
+ //#endregion
22
+ export { TypstCompileError, createEngine, engineUrls, googleFontSubsets, loadVerified, localFonts, typstWasmAsset, typstWasmRenderer };
package/dist/workerd.d.ts CHANGED
@@ -1,6 +1,5 @@
1
- import { a as FontScope, c as WasmSource, i as TypstWasmRendererOptions, l as createEngine, n as FontSource, o as TypstCompileError, r as GoogleFont, s as TypstEngine, t as DEFAULT_GOOGLE_FONTS } from "./renderer--txXuJuD.js";
2
- import { PdfRenderer } from "@junejs/pdf";
1
+ import { _ as WasmSource, a as TypstWasmRendererOptions, c as FontProvider, d as googleFontSubsets, f as localFonts, g as TypstOutput, h as TypstEngine, i as TypstWasmRenderer, l as FontSource, m as TypstCompileError, n as AssetRef, o as DocumentFonts, p as FontScope, r as loadVerified, s as FontEgress, t as AssetLoader, u as GoogleFont, v as createEngine } from "./assets-0jc0W7Pm.js";
3
2
  //#region src/workerd.d.ts
4
- export declare function typstWasmRenderer(opts?: TypstWasmRendererOptions): PdfRenderer;
3
+ export declare function typstWasmRenderer(opts?: TypstWasmRendererOptions): TypstWasmRenderer;
5
4
  //#endregion
6
- export { DEFAULT_GOOGLE_FONTS, type FontScope, type FontSource, type GoogleFont, TypstCompileError, type TypstEngine, type TypstWasmRendererOptions, type WasmSource, createEngine };
5
+ export { type AssetLoader, type AssetRef, type DocumentFonts, type FontEgress, type FontProvider, type FontScope, type FontSource, type GoogleFont, TypstCompileError, type TypstEngine, type TypstOutput, type TypstWasmRenderer, type TypstWasmRendererOptions, type WasmSource, createEngine, googleFontSubsets, loadVerified, localFonts };
package/dist/workerd.js CHANGED
@@ -1,8 +1,8 @@
1
- import { i as createEngine, n as createTypstWasmRenderer, r as TypstCompileError, t as DEFAULT_GOOGLE_FONTS } from "./renderer-CHKIXC79.js";
1
+ import { a as TypstCompileError, i as createTypstWasmRenderer, n as googleFontSubsets, o as createEngine, r as localFonts, t as loadVerified } from "./assets-rrgfvCKs.js";
2
2
  import wasm from "../dist/typst.wasm";
3
3
  //#region src/workerd.ts
4
4
  function typstWasmRenderer(opts = {}) {
5
5
  return createTypstWasmRenderer(async () => wasm, opts);
6
6
  }
7
7
  //#endregion
8
- export { DEFAULT_GOOGLE_FONTS, TypstCompileError, createEngine, typstWasmRenderer };
8
+ export { TypstCompileError, createEngine, googleFontSubsets, loadVerified, localFonts, typstWasmRenderer };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@junejs/pdf-typst-wasm",
3
- "version": "0.1.0-dev.0",
3
+ "version": "0.2.1",
4
4
  "description": "June — a PdfRenderer on a Typst to PDF engine compiled to WebAssembly: no browser, no native binary, and it runs on Cloudflare Workers.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -9,11 +9,12 @@
9
9
  ".": {
10
10
  "source": {
11
11
  "workerd": "./src/workerd.ts",
12
+ "bun": "./src/bun.ts",
12
13
  "default": "./src/node.ts"
13
14
  },
14
15
  "bun": {
15
16
  "workerd": "./src/workerd.ts",
16
- "default": "./src/node.ts"
17
+ "default": "./src/bun.ts"
17
18
  },
18
19
  "workerd": {
19
20
  "types": "./dist/workerd.d.ts",
@@ -24,6 +25,12 @@
24
25
  "default": "./dist/node.js"
25
26
  }
26
27
  },
28
+ "./unbundled": {
29
+ "source": "./src/unbundled.ts",
30
+ "bun": "./src/unbundled.ts",
31
+ "types": "./dist/unbundled.d.ts",
32
+ "default": "./dist/unbundled.js"
33
+ },
27
34
  "./typst.wasm": "./dist/typst.wasm"
28
35
  },
29
36
  "files": [
@@ -36,10 +43,11 @@
36
43
  "test": "bun test"
37
44
  },
38
45
  "dependencies": {
39
- "@junejs/pdf": ">=0.1.0-dev.1"
46
+ "@junejs/pdf": "^0.2.1"
40
47
  },
41
48
  "devDependencies": {
42
- "@junejs/core": ">=0.2.0-dev.66"
49
+ "@junejs/core": "^0.2.1",
50
+ "@junejs/server": "^0.2.1"
43
51
  },
44
52
  "keywords": [
45
53
  "june",
package/src/assets.ts ADDED
@@ -0,0 +1,38 @@
1
+ // Large files a package needs but doesn't embed (#383). The `unbundled` entries never reference
2
+ // their files, so `bun build --compile` leaves ~41 MB of engine and fonts out of a binary that
3
+ // may never render a PDF; the app supplies a loader instead (a cache on a volume, a download,
4
+ // a file it shipped next to the binary).
5
+ //
6
+ // The package, not the loader, is what's trusted: every ref pins a size and a sha256, and
7
+ // loadVerified checks the loader's bytes against them before they are used, so a naive loader
8
+ // (one fetch, no checks) is as safe as a careful one. The URLs are where the file can be
9
+ // fetched; any of them may be down, and none of them needs to be trusted.
10
+ //
11
+ // Nothing here depends on PDF types: another package with a large optional file can use it.
12
+
13
+ export type AssetRef = {
14
+ // The file's name, for errors and for a cache directory: "typst.wasm".
15
+ name: string;
16
+ // Hex SHA-256 of the file's bytes: the only thing trusted.
17
+ sha256: string;
18
+ // Bytes. A loader may use it to cut a download off.
19
+ size: number;
20
+ // Where the file can be fetched, in order of preference.
21
+ urls: string[];
22
+ };
23
+
24
+ // The app's way to get a file's bytes: from a cache, a download, a pre-seeded directory.
25
+ export type AssetLoader = (ref: AssetRef) => Promise<Uint8Array | ArrayBuffer>;
26
+
27
+ // The loader's bytes, after checking them against the ref. Throws an error naming the file and
28
+ // both digests when they don't match: a wrong engine or font is never used.
29
+ export async function loadVerified(ref: AssetRef, load: AssetLoader): Promise<Uint8Array> {
30
+ const got = await load(ref);
31
+ // WebCrypto refuses a view on a SharedArrayBuffer: copy one into a plain buffer first.
32
+ const bytes = got instanceof Uint8Array ? (got.buffer instanceof SharedArrayBuffer ? got.slice() : got) : new Uint8Array(got);
33
+ if (bytes.byteLength !== ref.size) throw new Error(`${ref.name}: the loader returned ${bytes.byteLength} bytes, expected ${ref.size} (sha256 ${ref.sha256})`);
34
+ const digest = await crypto.subtle.digest("SHA-256", bytes as Uint8Array<ArrayBuffer>);
35
+ const hex = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
36
+ if (hex !== ref.sha256) throw new Error(`${ref.name}: the loader returned bytes with sha256 ${hex}, expected ${ref.sha256}`);
37
+ return bytes;
38
+ }
package/src/bun.ts ADDED
@@ -0,0 +1,40 @@
1
+ // @junejs/pdf-typst-wasm on Bun (the `bun` export condition). Everything is node.ts's except
2
+ // how the engine module is found: here it is imported `with { type: "file" }`, which
3
+ // `bun build --compile` sees and embeds, and which yields the module's path inside the binary
4
+ // (/$bunfs/…). node.ts reads ../dist/typst.wasm by URL at first render, which the bundler can't
5
+ // see, so a compiled app failed its first render_pdf (#367).
6
+ //
7
+ // A dynamic import, on the first render: a process that never renders a PDF never reads the
8
+ // 29 MiB, and a repo checkout without the built module still loads this file (its tests skip).
9
+ // The bundler embeds the file when it exists and doesn't check when it doesn't (verified on Bun
10
+ // 1.4.2): a binary compiled from a checkout without it fails at first render, with the message
11
+ // below. A published package always ships it.
12
+
13
+ import { readFile } from "node:fs/promises";
14
+
15
+ import type { WasmSource } from "./engine";
16
+ import { createTypstWasmRenderer, type TypstWasmRenderer, type TypstWasmRendererOptions } from "./renderer";
17
+
18
+ // The same names as node.ts; the local typstWasmRenderer below takes precedence over its own.
19
+ export * from "./node";
20
+
21
+ let compiled: Promise<WebAssembly.Module> | undefined;
22
+ async function loadWasm(): Promise<WasmSource> {
23
+ return (compiled ??= (async () => {
24
+ let path: string;
25
+ try {
26
+ // wasm.d.ts types a .wasm import as a module (workerd); with type "file" it is a path.
27
+ path = ((await import("../dist/typst.wasm", { with: { type: "file" } })) as unknown as { default: string }).default;
28
+ } catch (err) {
29
+ throw new Error("@junejs/pdf-typst-wasm: dist/typst.wasm is missing — in the June repo, run `bun run build` in packages/pdf-typst-wasm", { cause: err });
30
+ }
31
+ return WebAssembly.compile((await readFile(path)) as Uint8Array<ArrayBuffer>);
32
+ })().catch((err: unknown) => {
33
+ compiled = undefined;
34
+ throw err;
35
+ }));
36
+ }
37
+
38
+ export function typstWasmRenderer(opts: TypstWasmRendererOptions = {}): TypstWasmRenderer {
39
+ return createTypstWasmRenderer(loadWasm, opts);
40
+ }
package/src/engine.ts CHANGED
@@ -5,13 +5,20 @@
5
5
 
6
6
  export type FontScope = "persistent" | "document";
7
7
 
8
+ export type TypstOutput = {
9
+ pdf: Uint8Array;
10
+ // Characters no loaded font covers, each once, in document order: they render blank or go
11
+ // missing from the PDF's text. Empty when every character has a glyph.
12
+ missingGlyphs: string[];
13
+ };
14
+
8
15
  export interface TypstEngine {
9
16
  // Register a font file; returns the number of faces it held (0: not a font).
10
17
  addFont(data: Uint8Array, scope: FontScope): number;
11
18
  // Drop the document-scoped fonts.
12
19
  clearDocumentFonts(): void;
13
20
  // Typst source → PDF bytes. Throws TypstCompileError with the document's diagnostics.
14
- compile(source: string): Uint8Array;
21
+ compile(source: string): TypstOutput;
15
22
  // The engine's linear memory, in bytes (it only grows).
16
23
  memoryBytes(): number;
17
24
  }
@@ -32,6 +39,8 @@ type Exports = {
32
39
  compile(ptr: number, len: number): number;
33
40
  output_ptr(): number;
34
41
  output_len(): number;
42
+ missing_glyphs_ptr(): number;
43
+ missing_glyphs_len(): number;
35
44
  };
36
45
 
37
46
  export type WasmSource = WebAssembly.Module | BufferSource;
@@ -52,6 +61,7 @@ export async function createEngine(wasm: WasmSource): Promise<TypstEngine> {
52
61
  };
53
62
  const output = (): Uint8Array => new Uint8Array(x.memory.buffer, x.output_ptr(), x.output_len()).slice();
54
63
  const utf8 = new TextEncoder();
64
+ const text = new TextDecoder();
55
65
 
56
66
  return {
57
67
  addFont(data, scope) {
@@ -64,8 +74,9 @@ export async function createEngine(wasm: WasmSource): Promise<TypstEngine> {
64
74
  const bytes = utf8.encode(source);
65
75
  const status = x.compile(put(bytes), bytes.length);
66
76
  const out = output();
67
- if (status !== 0) throw new TypstCompileError(new TextDecoder().decode(out));
68
- return out;
77
+ if (status !== 0) throw new TypstCompileError(text.decode(out));
78
+ const missing = text.decode(new Uint8Array(x.memory.buffer, x.missing_glyphs_ptr(), x.missing_glyphs_len()));
79
+ return { pdf: out, missingGlyphs: [...missing] };
69
80
  },
70
81
  memoryBytes() {
71
82
  return x.memory.buffer.byteLength;
package/src/fonts.ts ADDED
@@ -0,0 +1,122 @@
1
+ // Font providers (#371): where a PDF's fonts come from decides where the document goes. A
2
+ // provider fetching per-document subsets sends the document's characters to a third party;
3
+ // one reading bundled bytes sends nothing. That is the app's or the installer's call, so the
4
+ // renderer makes no network call unless the app lists a provider that does, and every
5
+ // provider declares its `egress` — what leaves the process, and to which host — so an app
6
+ // can show the trade-off (a doctor check, its docs) without reading this source.
7
+ //
8
+ // `egress` is a description, not enforcement: a provider an app writes can omit or misstate
9
+ // it. Network policy belongs to the `fetch` a provider is given, or to the host.
10
+ //
11
+ // Nothing here depends on PDF types, so @junejs/og's Google Fonts loading could move onto
12
+ // the same providers later.
13
+
14
+ export type FontEgress = {
15
+ host: string;
16
+ // "nothing": a fixed request (a font file by URL). "document-characters": the request
17
+ // carries the characters of the document being rendered.
18
+ sends: "nothing" | "document-characters";
19
+ };
20
+
21
+ export interface FontProvider {
22
+ // Shown in errors ("google-font-subsets: HTTP 503").
23
+ readonly name: string;
24
+ // Every host this provider contacts; empty when it never touches the network.
25
+ readonly egress: readonly FontEgress[];
26
+ // Font files registered once, for the renderer's lifetime. A failure fails the render and
27
+ // is retried by the next one.
28
+ persistent?(): Promise<Uint8Array[]>;
29
+ // Font files for one document, given its non-ASCII characters; dropped after it. A failure
30
+ // costs only the characters nothing else covers, and the missing glyphs error names it:
31
+ // report a partial one in `failed` and keep the fonts that loaded; a throw loses them all.
32
+ forDocument?(text: string): Promise<DocumentFonts>;
33
+ }
34
+
35
+ export type DocumentFonts = { fonts: Uint8Array[]; failed?: string[] };
36
+
37
+ // A font file: bytes, a URL fetched once, or a loader.
38
+ export type FontSource = Uint8Array | ArrayBuffer | string | (() => Promise<Uint8Array | ArrayBuffer>);
39
+
40
+ // The app's own font files, read once. Offline unless a source is a URL, which is fetched once
41
+ // at startup and sends nothing about any document.
42
+ // `sources` is copied, so `egress` always names what `persistent` fetches.
43
+ export function localFonts(input: FontSource[], opts: { fetch?: typeof fetch } = {}): FontProvider {
44
+ const sources = [...input];
45
+ const fetcher = opts.fetch ?? fetch;
46
+ const hosts = [...new Set(sources.filter((s): s is string => typeof s === "string").map((url) => new URL(url).host))];
47
+ return {
48
+ name: "local-fonts",
49
+ egress: hosts.map((host) => ({ host, sends: "nothing" as const })),
50
+ persistent: () => Promise.all(sources.map((s) => loadFont(s, fetcher))),
51
+ };
52
+ }
53
+
54
+ async function loadFont(source: FontSource, fetcher: typeof fetch): Promise<Uint8Array> {
55
+ if (source instanceof Uint8Array) return source;
56
+ if (source instanceof ArrayBuffer) return new Uint8Array(source);
57
+ if (typeof source === "function") {
58
+ const data = await source();
59
+ return data instanceof Uint8Array ? data : new Uint8Array(data);
60
+ }
61
+ const res = await fetcher(source);
62
+ if (!res.ok) throw new Error(`font ${source}: HTTP ${res.status}`);
63
+ return new Uint8Array(await res.arrayBuffer());
64
+ }
65
+
66
+ export type GoogleFont = { family: string; weights?: number[] };
67
+
68
+ // Per document, each family cut to the document's non-ASCII characters by Google Fonts, the
69
+ // way @junejs/og loads fonts: a subset is a few KB where a whole CJK family is tens of MB.
70
+ // The name says the trade-off: the characters go to fonts.googleapis.com in the request, and
71
+ // the font file's fonts.gstatic.com URL encodes them too.
72
+ export function googleFontSubsets(opts: { families: GoogleFont[]; fetch?: typeof fetch }): FontProvider {
73
+ const fetcher = opts.fetch ?? fetch;
74
+ const wanted = opts.families.flatMap((f) => (f.weights ?? [400]).map((w) => [f.family, w] as const));
75
+ // Per provider: a subset fetched through one provider's `fetch` must not answer another's.
76
+ const cache = new Map<string, Promise<Uint8Array>>();
77
+ return {
78
+ name: "google-font-subsets",
79
+ egress: [
80
+ { host: "fonts.googleapis.com", sends: "document-characters" },
81
+ { host: "fonts.gstatic.com", sends: "document-characters" },
82
+ ],
83
+ async forDocument(text) {
84
+ // Each weight on its own: a bold that fails costs only the bold, never the regular.
85
+ const settled = await Promise.allSettled(wanted.map(([family, weight]) => googleSubset(cache, family, weight, text, fetcher)));
86
+ return {
87
+ fonts: settled.flatMap((s) => (s.status === "fulfilled" ? [s.value] : [])),
88
+ failed: settled.flatMap((s, i) => (s.status === "rejected" ? [`${wanted[i]![0]} ${wanted[i]![1]}: ${message(s.reason)}`] : [])),
89
+ };
90
+ },
91
+ };
92
+ }
93
+
94
+ const message = (err: unknown) => (err instanceof Error ? err.message : String(err));
95
+
96
+ // Google Fonts answers an old Safari with TTF, which Typst reads (it does not read WOFF2).
97
+ // Cached, bounded, least recently used out: a re-render of the same document fetches nothing.
98
+ const OLD_SAFARI = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1";
99
+ const SUBSET_CACHE_MAX = 32;
100
+
101
+ function googleSubset(cache: Map<string, Promise<Uint8Array>>, family: string, weight: number, text: string, fetcher: typeof fetch): Promise<Uint8Array> {
102
+ const css = `https://fonts.googleapis.com/css2?family=${encodeURIComponent(family)}:wght@${weight}&text=${encodeURIComponent(text)}`;
103
+ const hit = cache.get(css);
104
+ if (hit) {
105
+ cache.delete(css);
106
+ cache.set(css, hit); // most recently used last
107
+ return hit;
108
+ }
109
+ const load = (async () => {
110
+ const res = await fetcher(css, { headers: { "user-agent": OLD_SAFARI } });
111
+ if (!res.ok) throw new Error(`Google Fonts CSS: HTTP ${res.status}`);
112
+ const url = (await res.text()).match(/src:\s*url\((.+?)\)/)?.[1];
113
+ if (!url) throw new Error("Google Fonts CSS named no font file");
114
+ const font = await fetcher(url);
115
+ if (!font.ok) throw new Error(`Google Fonts file: HTTP ${font.status}`);
116
+ return new Uint8Array(await font.arrayBuffer());
117
+ })();
118
+ load.catch(() => cache.delete(css)); // never cache a failure
119
+ cache.set(css, load);
120
+ if (cache.size > SUBSET_CACHE_MAX) cache.delete(cache.keys().next().value!);
121
+ return load;
122
+ }
package/src/node.ts CHANGED
@@ -4,15 +4,15 @@
4
4
  //
5
5
  // import { pdfTools } from "@junejs/pdf";
6
6
  // import { typstWasmRenderer } from "@junejs/pdf-typst-wasm";
7
- // export default pdfTools({ renderer: typstWasmRenderer() });
8
-
9
- import type { PdfRenderer } from "@junejs/pdf";
7
+ // export default pdfTools({ renderer: typstWasmRenderer() }); // offline: embedded fonts only
10
8
 
11
9
  import type { WasmSource } from "./engine";
12
- import { createTypstWasmRenderer, type TypstWasmRendererOptions } from "./renderer";
10
+ import { createTypstWasmRenderer, type TypstWasmRenderer, type TypstWasmRendererOptions } from "./renderer";
13
11
 
14
- export { DEFAULT_GOOGLE_FONTS, type FontSource, type GoogleFont, type TypstWasmRendererOptions } from "./renderer";
15
- export { createEngine, TypstCompileError, type FontScope, type TypstEngine, type WasmSource } from "./engine";
12
+ export { type TypstWasmRenderer, type TypstWasmRendererOptions } from "./renderer";
13
+ export { googleFontSubsets, localFonts, type DocumentFonts, type FontEgress, type FontProvider, type FontSource, type GoogleFont } from "./fonts";
14
+ export { loadVerified, type AssetLoader, type AssetRef } from "./assets";
15
+ export { createEngine, TypstCompileError, type FontScope, type TypstEngine, type TypstOutput, type WasmSource } from "./engine";
16
16
 
17
17
  export const WASM_URL = new URL("../dist/typst.wasm", import.meta.url);
18
18
 
@@ -24,7 +24,7 @@ async function loadWasm(): Promise<WasmSource> {
24
24
  try {
25
25
  bytes = await readFile(fileURLToPath(WASM_URL));
26
26
  } catch (err) {
27
- throw new Error(`@junejs/pdf-typst-wasm: ${fileURLToPath(WASM_URL)} is missing — in the June repo, run \`bun run build\` in packages/pdf-typst-wasm`, { cause: err });
27
+ throw new Error(`@junejs/pdf-typst-wasm: ${fileURLToPath(WASM_URL)} is missing — in the June repo, run \`bun run build\` in packages/pdf-typst-wasm; in a bundled or single-file build, pass the module through the \`wasm\` option`, { cause: err });
28
28
  }
29
29
  return WebAssembly.compile(bytes as Uint8Array<ArrayBuffer>);
30
30
  })().catch((err: unknown) => {
@@ -33,6 +33,6 @@ async function loadWasm(): Promise<WasmSource> {
33
33
  }));
34
34
  }
35
35
 
36
- export function typstWasmRenderer(opts: TypstWasmRendererOptions = {}): PdfRenderer {
36
+ export function typstWasmRenderer(opts: TypstWasmRendererOptions = {}): TypstWasmRenderer {
37
37
  return createTypstWasmRenderer(loadWasm, opts);
38
38
  }
package/src/renderer.ts CHANGED
@@ -1,58 +1,67 @@
1
- // typstWasmRenderer — a PdfRenderer on this package's engine (src/lib.rs): the same Markdown →
2
- // Typst source as @junejs/pdf's typstRenderer, compiled by a PDF-only Typst build with zero
3
- // imports, so it runs on Cloudflare Workers as well as Node, Bun and Deno.
1
+ // typstWasmRenderer — a PdfRenderer on this package's engine (src/lib.rs): @junejs/pdf's
2
+ // Markdown → Typst source, compiled by a PDF-only Typst build with zero imports, so it runs
3
+ // on Cloudflare Workers as well as Node, Bun and Deno.
4
4
  //
5
5
  // One engine per process or isolate, created on the first render and kept: an isolate's
6
6
  // requests share 128 MB on Workers, so a render must not cost a fresh instance. Fonts:
7
- // • embedded — Typst's defaults (Libertinus Serif, New Computer Modern, DejaVu Sans Mono);
8
- // • `fonts` — the app's own, registered once for the engine's lifetime;
9
- // • Google Fonts subsets — per document, the families in `googleFonts` (Noto Sans TC by
10
- // default) cut to the document's own non-ASCII characters, the way @junejs/og loads
11
- // fonts. A subset is a few KB where a whole CJK family is tens of MB, and it is dropped
12
- // after the document, so subsets never pile up in the engine.
7
+ // • embedded — Typst's defaults (Libertinus Serif, New Computer Modern, DejaVu Sans Mono),
8
+ // always there, so a Latin document needs nothing and the default makes no network call;
9
+ // • `fonts` — the app's providers (fonts.ts). Their order is not a preference: Typst picks
10
+ // by `fontFamilies`, then falls back to the most similar font that has the glyph. A provider's
11
+ // persistent fonts are registered once; its per-document fonts (a CJK subset cut to one
12
+ // document's characters) are dropped after the document, so they never pile up.
13
13
  // Each render fetches what it needs first, then clears the previous document's fonts, adds
14
14
  // its own and compiles with no await in between — concurrent renders can't see each other's
15
15
  // fonts.
16
+ //
17
+ // A character none of those fonts covers would come out blank: a wrong document that looks
18
+ // right, which an agent would hand to its user as if it were right (#368). So it is a
19
+ // PdfRenderError by default, naming the characters and any provider that failed; the model
20
+ // reads it and can drop a decorative emoji or tell the user. `onMissingGlyphs: "warn"` is for
21
+ // an app that accepts the gaps.
16
22
 
17
23
  import { PdfRenderError, typstSource, type PdfDocument, type PdfRenderer } from "@junejs/pdf";
18
24
 
19
25
  import { createEngine, TypstCompileError, type TypstEngine, type WasmSource } from "./engine";
20
-
21
- export type FontSource = Uint8Array | ArrayBuffer | string | (() => Promise<Uint8Array | ArrayBuffer>);
22
-
23
- export type GoogleFont = { family: string; weights?: number[] };
26
+ import type { FontEgress, FontProvider } from "./fonts";
24
27
 
25
28
  export type TypstWasmRendererOptions = {
26
29
  // The engine module. Default: the dist/typst.wasm this package ships, loaded the way the
27
30
  // host runtime needs (see node.ts / workerd.ts).
28
31
  wasm?: WasmSource | (() => Promise<WasmSource>);
29
- // Fonts registered once, for every document: bytes, a URL, or a loader.
30
- fonts?: FontSource[];
32
+ // Where fonts beyond the embedded ones come from (default: none, so no network call):
33
+ // localFonts([...]), googleFontSubsets({ families }), or a provider the app writes. Read
34
+ // once, here: `egress` must describe the providers that actually render.
35
+ fonts?: FontProvider[];
31
36
  // Font families in order of preference; Typst falls back to any loaded font with the glyph.
32
37
  fontFamilies?: string[];
33
- // Families fetched per document from Google Fonts, cut to the document's non-ASCII
34
- // characters (default: Noto Sans TC, regular and bold). false: no network call — supply
35
- // CJK fonts through `fonts`.
36
- googleFonts?: GoogleFont[] | false;
37
- // How fonts are fetched (default: global fetch).
38
- fetch?: typeof fetch;
38
+ // Characters no loaded font covers: "error" (default) throws a PdfRenderError naming them;
39
+ // "warn" logs them and returns the PDF with those characters blank.
40
+ onMissingGlyphs?: "error" | "warn";
39
41
  };
40
42
 
41
- export const DEFAULT_GOOGLE_FONTS: GoogleFont[] = [{ family: "Noto Sans TC", weights: [400, 700] }];
43
+ export interface TypstWasmRenderer extends PdfRenderer {
44
+ // Every host the renderer may contact, and what each is sent: the font providers', plus,
45
+ // with the unbundled entry, where loading the engine goes (`engineEgress`). Empty means it
46
+ // works offline. Declared, not observed (see fonts.ts).
47
+ readonly egress: readonly FontEgress[];
48
+ }
49
+
50
+ // How many missing characters a message names before it counts the rest.
51
+ const MISSING_SHOWN = 10;
42
52
 
43
- export function createTypstWasmRenderer(defaultWasm: () => Promise<WasmSource>, opts: TypstWasmRendererOptions = {}): PdfRenderer {
44
- const fetcher = opts.fetch ?? fetch;
45
- const google = opts.googleFonts === false ? [] : (opts.googleFonts ?? DEFAULT_GOOGLE_FONTS);
53
+ // `engineEgress`: what getting the engine itself contacts, for an entry whose engine is fetched
54
+ // (unbundled.ts); the bundled entries read it from the package and contact nothing.
55
+ export function createTypstWasmRenderer(defaultWasm: () => Promise<WasmSource>, opts: TypstWasmRendererOptions = {}, engineEgress: readonly FontEgress[] = []): TypstWasmRenderer {
56
+ const providers = [...(opts.fonts ?? [])];
46
57
  let engine: Promise<TypstEngine> | undefined;
47
- // Per renderer, not per module: a subset fetched through one renderer's `fetch` must not
48
- // answer another renderer that was given a different one.
49
- const subsets = subsetCache(fetcher);
50
58
 
51
59
  const ready = (): Promise<TypstEngine> =>
52
60
  (engine ??= (async () => {
53
61
  const wasm = typeof opts.wasm === "function" ? await opts.wasm() : (opts.wasm ?? (await defaultWasm()));
54
62
  const e = await createEngine(wasm);
55
- for (const font of await Promise.all((opts.fonts ?? []).map((f) => loadFont(f, fetcher)))) e.addFont(font, "persistent");
63
+ const persistent = await Promise.all(providers.map((p) => p.persistent?.() ?? []));
64
+ for (const font of persistent.flat()) e.addFont(font, "persistent");
56
65
  return e;
57
66
  })().catch((err: unknown) => {
58
67
  engine = undefined; // a failed start (an unreachable font URL) is retried by the next render
@@ -61,90 +70,74 @@ export function createTypstWasmRenderer(defaultWasm: () => Promise<WasmSource>,
61
70
 
62
71
  return {
63
72
  name: "typst-wasm",
73
+ egress: uniqueEgress([...engineEgress, ...providers.flatMap((p) => p.egress)]),
64
74
  async render(doc: PdfDocument): Promise<Uint8Array> {
65
75
  const source = typstSource(doc, { fonts: opts.fontFamilies });
66
- const [e, documentFonts] = await Promise.all([ready(), subsetsFor(doc, google, subsets)]);
76
+ const [e, documentFonts] = await Promise.all([ready(), fontsFor(doc, providers)]);
67
77
  // From here on, synchronous: no other render can interleave.
68
78
  e.clearDocumentFonts();
69
- for (const font of documentFonts) e.addFont(font, "document");
79
+ for (const font of documentFonts.fonts) e.addFont(font, "document");
80
+ let out;
70
81
  try {
71
- return e.compile(source);
82
+ out = e.compile(source);
72
83
  } catch (err) {
73
84
  if (err instanceof TypstCompileError) throw new PdfRenderError(`the document could not be typeset: ${err.message}`, { cause: err });
74
85
  throw err;
75
86
  } finally {
76
87
  e.clearDocumentFonts();
77
88
  }
89
+ if (out.missingGlyphs.length === 0) return out.pdf;
90
+ const message = missingGlyphsMessage(out.missingGlyphs, documentFonts.failed);
91
+ if (opts.onMissingGlyphs === "warn") {
92
+ console.warn(`[june] pdf-typst-wasm: ${message}`);
93
+ return out.pdf;
94
+ }
95
+ throw new PdfRenderError(message);
78
96
  },
79
97
  };
80
98
  }
81
99
 
82
- async function loadFont(source: FontSource, fetcher: typeof fetch): Promise<Uint8Array> {
83
- if (source instanceof Uint8Array) return source;
84
- if (source instanceof ArrayBuffer) return new Uint8Array(source);
85
- if (typeof source === "function") {
86
- const data = await source();
87
- return data instanceof Uint8Array ? data : new Uint8Array(data);
100
+ function uniqueEgress(all: readonly FontEgress[]): FontEgress[] {
101
+ const seen = new Map<string, FontEgress>();
102
+ for (const e of all) {
103
+ const prior = seen.get(e.host);
104
+ // A host sent the document's characters by any provider is sent them, full stop.
105
+ if (!prior || e.sends === "document-characters") seen.set(e.host, { host: e.host, sends: e.sends });
88
106
  }
89
- const res = await fetcher(source);
90
- if (!res.ok) throw new Error(`font ${source}: HTTP ${res.status}`);
91
- return new Uint8Array(await res.arrayBuffer());
107
+ return [...seen.values()];
92
108
  }
93
109
 
94
- // The document's characters outside ASCII, the text a subset must cover. The title rides in
95
- // the PDF metadata, not the body, so it needs no glyphs.
110
+ // The document's characters outside ASCII, the text a per-document font must cover. The
111
+ // title rides in the PDF metadata, not the body, so it needs no glyphs.
96
112
  function documentText(doc: PdfDocument): string {
97
113
  return [...new Set(doc.markdown.replace(/[\x00-\x7f]/g, ""))].join("");
98
114
  }
99
115
 
100
- type SubsetLoader = (family: string, weight: number, text: string) => Promise<Uint8Array>;
101
-
102
- async function subsetsFor(doc: PdfDocument, families: GoogleFont[], load: SubsetLoader): Promise<Uint8Array[]> {
116
+ // The per-document fonts that loaded, and a line for each provider that failed. A failure
117
+ // doesn't fail the render by itself: another font may cover the characters, and if none
118
+ // does, the missing glyphs error carries the line as the reason.
119
+ async function fontsFor(doc: PdfDocument, providers: FontProvider[]): Promise<{ fonts: Uint8Array[]; failed: string[] }> {
103
120
  const text = documentText(doc);
104
- if (!text || families.length === 0) return [];
105
- const wanted = families.flatMap((f) => (f.weights ?? [400]).map((w) => [f.family, w] as const));
106
- const fonts = await Promise.all(
107
- wanted.map(([family, weight]) =>
108
- load(family, weight, text).catch((err: unknown) => {
109
- // A font that can't be fetched costs glyphs, not the document: render without it.
110
- console.warn(`[june] pdf-typst-wasm: ${family} ${weight} for this document could not be fetched (${err instanceof Error ? err.message : String(err)}); its characters may render blank`);
111
- return undefined;
112
- }),
121
+ const loaders = providers.filter((p) => p.forDocument);
122
+ if (!text || loaders.length === 0) return { fonts: [], failed: [] };
123
+ const settled = await Promise.allSettled(loaders.map((p) => p.forDocument!(text)));
124
+ const failure = (i: number, why: string) => `${loaders[i]!.name} failed (${why})`;
125
+ return {
126
+ fonts: settled.flatMap((s) => (s.status === "fulfilled" ? s.value.fonts : [])),
127
+ failed: settled.flatMap((s, i) =>
128
+ s.status === "rejected" ? [failure(i, s.reason instanceof Error ? s.reason.message : String(s.reason))] : (s.value.failed ?? []).map((why) => failure(i, why)),
113
129
  ),
114
- );
115
- return fonts.filter((f): f is Uint8Array => f !== undefined);
116
- }
117
-
118
- // Google Fonts subsets a family to `text` and answers an old Safari with TTF, which Typst
119
- // reads (it does not read WOFF2). Cached, bounded, least recently used out: a re-render of
120
- // the same document fetches nothing.
121
- const OLD_SAFARI = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1";
122
- const SUBSET_CACHE_MAX = 32;
123
-
124
- function subsetCache(fetcher: typeof fetch): SubsetLoader {
125
- const cache = new Map<string, Promise<Uint8Array>>();
126
- return (family, weight, text) => googleSubset(cache, family, weight, text, fetcher);
130
+ };
127
131
  }
128
132
 
129
- function googleSubset(cache: Map<string, Promise<Uint8Array>>, family: string, weight: number, text: string, fetcher: typeof fetch): Promise<Uint8Array> {
130
- const css = `https://fonts.googleapis.com/css2?family=${encodeURIComponent(family)}:wght@${weight}&text=${encodeURIComponent(text)}`;
131
- const hit = cache.get(css);
132
- if (hit) {
133
- cache.delete(css);
134
- cache.set(css, hit); // most recently used last
135
- return hit;
136
- }
137
- const load = (async () => {
138
- const res = await fetcher(css, { headers: { "user-agent": OLD_SAFARI } });
139
- if (!res.ok) throw new Error(`Google Fonts CSS: HTTP ${res.status}`);
140
- const url = (await res.text()).match(/src:\s*url\((.+?)\)/)?.[1];
141
- if (!url) throw new Error("Google Fonts CSS named no font file");
142
- const font = await fetcher(url);
143
- if (!font.ok) throw new Error(`Google Fonts file: HTTP ${font.status}`);
144
- return new Uint8Array(await font.arrayBuffer());
145
- })();
146
- load.catch(() => cache.delete(css)); // never cache a failure
147
- cache.set(css, load);
148
- if (cache.size > SUBSET_CACHE_MAX) cache.delete(cache.keys().next().value!);
149
- return load;
133
+ // Written for the model, which reads it as render_pdf's error, and for the app's logs.
134
+ function missingGlyphsMessage(missing: string[], failed: string[]): string {
135
+ const shown = missing.slice(0, MISSING_SHOWN).join(" ");
136
+ const more = missing.length > MISSING_SHOWN ? ` (and ${missing.length - MISSING_SHOWN} more)` : "";
137
+ return (
138
+ `no font available to the PDF renderer covers ${shown}${more}, so they would be missing from the document. ` +
139
+ (failed.length ? `${failed.join("; ")}. ` : "") +
140
+ "Remove them from the Markdown if they are decorative (emoji, symbols); otherwise tell the user the PDF can't include them " +
141
+ "until the app adds a font that covers them to typstWasmRenderer's `fonts` (localFonts or googleFontSubsets)."
142
+ );
150
143
  }
@@ -0,0 +1,57 @@
1
+ // @junejs/pdf-typst-wasm/unbundled — the renderer without its engine file (#383). The default
2
+ // entries embed typst.wasm (bun.ts imports it as a file, workerd.ts as a module), so a
3
+ // `bun build --compile` binary carries its 29 MiB whether or not it ever renders. This entry
4
+ // never references the file: the app passes `load`, and the engine is fetched, read or taken
5
+ // from a cache only on the first render.
6
+ //
7
+ // import { typstWasmRenderer } from "@junejs/pdf-typst-wasm/unbundled";
8
+ // typstWasmRenderer({ load: (ref) => myCache.get(ref) });
9
+ //
10
+ // The engine's ref (size, sha256, URLs) is generated by scripts/build-wasm.ts from the file
11
+ // being published, since a local build's bytes differ from CI's. loadVerified checks the
12
+ // loader's bytes against it, so an engine that doesn't match the release is never run. In a
13
+ // checkout without a build there is no ref, and the first render says so.
14
+ //
15
+ // Runtime-neutral: no host imports, so the same file serves Node, Bun, Deno and workerd.
16
+
17
+ import { loadVerified, type AssetLoader, type AssetRef } from "./assets";
18
+ import type { FontEgress } from "./fonts";
19
+ import { createTypstWasmRenderer, type TypstWasmRenderer, type TypstWasmRendererOptions } from "./renderer";
20
+
21
+ export { loadVerified, type AssetLoader, type AssetRef } from "./assets";
22
+ export { googleFontSubsets, localFonts, type DocumentFonts, type FontEgress, type FontProvider, type FontSource, type GoogleFont } from "./fonts";
23
+ export { createEngine, TypstCompileError, type FontScope, type TypstEngine, type TypstOutput, type WasmSource } from "./engine";
24
+ export type { TypstWasmRenderer } from "./renderer";
25
+
26
+ // Where a release's engine can be fetched: the npm tarball's own file, through two CDNs that
27
+ // serve npm packages. The sha256 makes either as good as the other.
28
+ export function engineUrls(version: string): string[] {
29
+ return [`https://cdn.jsdelivr.net/npm/@junejs/pdf-typst-wasm@${version}/dist/typst.wasm`, `https://unpkg.com/@junejs/pdf-typst-wasm@${version}/dist/typst.wasm`];
30
+ }
31
+
32
+ const ENGINE_HOSTS: FontEgress[] = engineUrls("0").map((url) => ({ host: new URL(url).host, sends: "nothing" }));
33
+
34
+ // The ref of the engine this release ships. Rejects in a checkout that hasn't run
35
+ // `bun run build`.
36
+ export async function typstWasmAsset(): Promise<AssetRef> {
37
+ try {
38
+ // @ts-ignore — written by scripts/build-wasm.ts; absent until the engine is built.
39
+ return (await import("../dist/typst.wasm.ref.json", { with: { type: "json" } })).default as AssetRef;
40
+ } catch (err) {
41
+ throw new Error("@junejs/pdf-typst-wasm/unbundled: dist/typst.wasm.ref.json is missing — in the June repo, run `bun run build` in packages/pdf-typst-wasm", { cause: err });
42
+ }
43
+ }
44
+
45
+ export type UnbundledRendererOptions = Omit<TypstWasmRendererOptions, "wasm"> & {
46
+ // Gets the engine's bytes for its ref, on the first render. They are checked against the
47
+ // ref's size and sha256 before they run.
48
+ load: AssetLoader;
49
+ // What `load` contacts, for renderer.egress. Default: the ref's URL hosts, sending nothing
50
+ // (the engine may be downloaded). [] when the app pre-seeds it and never fetches.
51
+ engineEgress?: FontEgress[];
52
+ };
53
+
54
+ export function typstWasmRenderer(opts: UnbundledRendererOptions): TypstWasmRenderer {
55
+ const { load, engineEgress, ...rest } = opts;
56
+ return createTypstWasmRenderer(async () => loadVerified(await typstWasmAsset(), load), rest, engineEgress ?? ENGINE_HOSTS);
57
+ }
package/src/workerd.ts CHANGED
@@ -5,17 +5,17 @@
5
5
  //
6
6
  // import { pdfTools } from "@junejs/pdf";
7
7
  // import { typstWasmRenderer } from "@junejs/pdf-typst-wasm";
8
- // export default pdfTools({ renderer: typstWasmRenderer() });
9
-
10
- import type { PdfRenderer } from "@junejs/pdf";
8
+ // export default pdfTools({ renderer: typstWasmRenderer() }); // offline: embedded fonts only
11
9
 
12
10
  // The same path from src/ (the repo) and from dist/ (the published package).
13
11
  import wasm from "../dist/typst.wasm";
14
- import { createTypstWasmRenderer, type TypstWasmRendererOptions } from "./renderer";
12
+ import { createTypstWasmRenderer, type TypstWasmRenderer, type TypstWasmRendererOptions } from "./renderer";
15
13
 
16
- export { DEFAULT_GOOGLE_FONTS, type FontSource, type GoogleFont, type TypstWasmRendererOptions } from "./renderer";
17
- export { createEngine, TypstCompileError, type FontScope, type TypstEngine, type WasmSource } from "./engine";
14
+ export { type TypstWasmRenderer, type TypstWasmRendererOptions } from "./renderer";
15
+ export { googleFontSubsets, localFonts, type DocumentFonts, type FontEgress, type FontProvider, type FontSource, type GoogleFont } from "./fonts";
16
+ export { loadVerified, type AssetLoader, type AssetRef } from "./assets";
17
+ export { createEngine, TypstCompileError, type FontScope, type TypstEngine, type TypstOutput, type WasmSource } from "./engine";
18
18
 
19
- export function typstWasmRenderer(opts: TypstWasmRendererOptions = {}): PdfRenderer {
19
+ export function typstWasmRenderer(opts: TypstWasmRendererOptions = {}): TypstWasmRenderer {
20
20
  return createTypstWasmRenderer(async () => wasm, opts);
21
21
  }
@@ -1,31 +0,0 @@
1
- import { PdfRenderer } from "@junejs/pdf";
2
- //#region src/engine.d.ts
3
- type FontScope = "persistent" | "document";
4
- interface TypstEngine {
5
- addFont(data: Uint8Array, scope: FontScope): number;
6
- clearDocumentFonts(): void;
7
- compile(source: string): Uint8Array;
8
- memoryBytes(): number;
9
- }
10
- declare class TypstCompileError extends Error {
11
- constructor(message: string);
12
- }
13
- type WasmSource = WebAssembly.Module | BufferSource;
14
- declare function createEngine(wasm: WasmSource): Promise<TypstEngine>;
15
- //#endregion
16
- //#region src/renderer.d.ts
17
- type FontSource = Uint8Array | ArrayBuffer | string | (() => Promise<Uint8Array | ArrayBuffer>);
18
- type GoogleFont = {
19
- family: string;
20
- weights?: number[];
21
- };
22
- type TypstWasmRendererOptions = {
23
- wasm?: WasmSource | (() => Promise<WasmSource>);
24
- fonts?: FontSource[];
25
- fontFamilies?: string[];
26
- googleFonts?: GoogleFont[] | false;
27
- fetch?: typeof fetch;
28
- };
29
- declare const DEFAULT_GOOGLE_FONTS: GoogleFont[];
30
- //#endregion
31
- export { FontScope as a, WasmSource as c, TypstWasmRendererOptions as i, createEngine as l, FontSource as n, TypstCompileError as o, GoogleFont as r, TypstEngine as s, DEFAULT_GOOGLE_FONTS as t };
@@ -1,127 +0,0 @@
1
- import { PdfRenderError, typstSource } from "@junejs/pdf";
2
- //#region src/engine.ts
3
- var TypstCompileError = class extends Error {
4
- constructor(message) {
5
- super(message);
6
- this.name = "TypstCompileError";
7
- }
8
- };
9
- async function createEngine(wasm) {
10
- const made = await WebAssembly.instantiate(wasm, {});
11
- const x = (made instanceof WebAssembly.Instance ? made : made.instance).exports;
12
- x.init();
13
- const put = (bytes) => {
14
- const ptr = x.alloc(bytes.length);
15
- new Uint8Array(x.memory.buffer, ptr, bytes.length).set(bytes);
16
- return ptr;
17
- };
18
- const output = () => new Uint8Array(x.memory.buffer, x.output_ptr(), x.output_len()).slice();
19
- const utf8 = new TextEncoder();
20
- return {
21
- addFont(data, scope) {
22
- return x.add_font(put(data), data.length, scope === "document" ? 1 : 0);
23
- },
24
- clearDocumentFonts() {
25
- x.clear_document_fonts();
26
- },
27
- compile(source) {
28
- const bytes = utf8.encode(source);
29
- const status = x.compile(put(bytes), bytes.length);
30
- const out = output();
31
- if (status !== 0) throw new TypstCompileError(new TextDecoder().decode(out));
32
- return out;
33
- },
34
- memoryBytes() {
35
- return x.memory.buffer.byteLength;
36
- }
37
- };
38
- }
39
- //#endregion
40
- //#region src/renderer.ts
41
- const DEFAULT_GOOGLE_FONTS = [{
42
- family: "Noto Sans TC",
43
- weights: [400, 700]
44
- }];
45
- function createTypstWasmRenderer(defaultWasm, opts = {}) {
46
- const fetcher = opts.fetch ?? fetch;
47
- const google = opts.googleFonts === false ? [] : opts.googleFonts ?? DEFAULT_GOOGLE_FONTS;
48
- let engine;
49
- const subsets = subsetCache(fetcher);
50
- const ready = () => engine ??= (async () => {
51
- const e = await createEngine(typeof opts.wasm === "function" ? await opts.wasm() : opts.wasm ?? await defaultWasm());
52
- for (const font of await Promise.all((opts.fonts ?? []).map((f) => loadFont(f, fetcher)))) e.addFont(font, "persistent");
53
- return e;
54
- })().catch((err) => {
55
- engine = void 0;
56
- throw err;
57
- });
58
- return {
59
- name: "typst-wasm",
60
- async render(doc) {
61
- const source = typstSource(doc, { fonts: opts.fontFamilies });
62
- const [e, documentFonts] = await Promise.all([ready(), subsetsFor(doc, google, subsets)]);
63
- e.clearDocumentFonts();
64
- for (const font of documentFonts) e.addFont(font, "document");
65
- try {
66
- return e.compile(source);
67
- } catch (err) {
68
- if (err instanceof TypstCompileError) throw new PdfRenderError(`the document could not be typeset: ${err.message}`, { cause: err });
69
- throw err;
70
- } finally {
71
- e.clearDocumentFonts();
72
- }
73
- }
74
- };
75
- }
76
- async function loadFont(source, fetcher) {
77
- if (source instanceof Uint8Array) return source;
78
- if (source instanceof ArrayBuffer) return new Uint8Array(source);
79
- if (typeof source === "function") {
80
- const data = await source();
81
- return data instanceof Uint8Array ? data : new Uint8Array(data);
82
- }
83
- const res = await fetcher(source);
84
- if (!res.ok) throw new Error(`font ${source}: HTTP ${res.status}`);
85
- return new Uint8Array(await res.arrayBuffer());
86
- }
87
- function documentText(doc) {
88
- return [...new Set(doc.markdown.replace(/[\x00-\x7f]/g, ""))].join("");
89
- }
90
- async function subsetsFor(doc, families, load) {
91
- const text = documentText(doc);
92
- if (!text || families.length === 0) return [];
93
- const wanted = families.flatMap((f) => (f.weights ?? [400]).map((w) => [f.family, w]));
94
- return (await Promise.all(wanted.map(([family, weight]) => load(family, weight, text).catch((err) => {
95
- console.warn(`[june] pdf-typst-wasm: ${family} ${weight} for this document could not be fetched (${err instanceof Error ? err.message : String(err)}); its characters may render blank`);
96
- })))).filter((f) => f !== void 0);
97
- }
98
- const OLD_SAFARI = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1";
99
- const SUBSET_CACHE_MAX = 32;
100
- function subsetCache(fetcher) {
101
- const cache = /* @__PURE__ */ new Map();
102
- return (family, weight, text) => googleSubset(cache, family, weight, text, fetcher);
103
- }
104
- function googleSubset(cache, family, weight, text, fetcher) {
105
- const css = `https://fonts.googleapis.com/css2?family=${encodeURIComponent(family)}:wght@${weight}&text=${encodeURIComponent(text)}`;
106
- const hit = cache.get(css);
107
- if (hit) {
108
- cache.delete(css);
109
- cache.set(css, hit);
110
- return hit;
111
- }
112
- const load = (async () => {
113
- const res = await fetcher(css, { headers: { "user-agent": OLD_SAFARI } });
114
- if (!res.ok) throw new Error(`Google Fonts CSS: HTTP ${res.status}`);
115
- const url = (await res.text()).match(/src:\s*url\((.+?)\)/)?.[1];
116
- if (!url) throw new Error("Google Fonts CSS named no font file");
117
- const font = await fetcher(url);
118
- if (!font.ok) throw new Error(`Google Fonts file: HTTP ${font.status}`);
119
- return new Uint8Array(await font.arrayBuffer());
120
- })();
121
- load.catch(() => cache.delete(css));
122
- cache.set(css, load);
123
- if (cache.size > SUBSET_CACHE_MAX) cache.delete(cache.keys().next().value);
124
- return load;
125
- }
126
- //#endregion
127
- export { createEngine as i, createTypstWasmRenderer as n, TypstCompileError as r, DEFAULT_GOOGLE_FONTS as t };