@junejs/pdf 0.0.0-stage → 0.1.0-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ import { PdfDocument, PdfPaper, PdfRenderError, PdfRenderer } from "./renderer.js";
2
+ import { PdfToolsOptions, RenderPdfInput, RenderPdfResult, pdfFilename, pdfTools } from "./tools.js";
3
+ export { type PdfDocument, type PdfPaper, PdfRenderError, type PdfRenderer, type PdfToolsOptions, type RenderPdfInput, type RenderPdfResult, pdfFilename, pdfTools };
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ import { pdfFilename, pdfTools } from "./tools.js";
2
+ import { PdfRenderError } from "./renderer.js";
3
+ export { PdfRenderError, pdfFilename, pdfTools };
@@ -0,0 +1,8 @@
1
+ import { PdfDocument } from "./renderer.js";
2
+ //#region src/markdown-typst.d.ts
3
+ export type TypstSourceOptions = {
4
+ fonts?: string[];
5
+ };
6
+ export declare function markdownToTypst(markdown: string): string;
7
+ export declare function typstSource(doc: PdfDocument, opts?: TypstSourceOptions): string;
8
+ //#endregion
@@ -0,0 +1,168 @@
1
+ import { Lexer } from "marked";
2
+ //#region src/markdown-typst.ts
3
+ function markdownToTypst(markdown) {
4
+ return blocks(new Lexer({ gfm: true }).lex(markdown)).trim() + "\n";
5
+ }
6
+ function typstSource(doc, opts = {}) {
7
+ const lines = [];
8
+ const meta = [doc.title ? `title: ${str(doc.title)}` : "", doc.author ? `author: ${str(doc.author)}` : ""].filter(Boolean);
9
+ if (meta.length) lines.push(`#set document(${meta.join(", ")})`);
10
+ lines.push(`#set page(paper: ${str(doc.paper === "us-letter" ? "us-letter" : "a4")}, margin: (x: 2.2cm, y: 2.4cm), numbering: "1")`);
11
+ const text = ["size: 10.5pt", ...langArgs(doc.lang)];
12
+ if (opts.fonts?.length) text.push(`font: (${opts.fonts.map(str).join(", ")},)`);
13
+ lines.push(`#set text(${text.join(", ")})`);
14
+ lines.push("#set par(justify: true, leading: 0.75em)", "#show heading: set block(above: 1.4em, below: 0.9em)", "#show link: set text(fill: rgb(\"#1f4e9e\"))", "#set table(stroke: 0.5pt + luma(170), inset: 6pt)", "#show raw.where(block: true): block.with(fill: luma(245), inset: 8pt, radius: 3pt, width: 100%)", "");
15
+ return lines.join("\n") + markdownToTypst(doc.markdown);
16
+ }
17
+ function langArgs(tag) {
18
+ if (!tag) return [];
19
+ const [lang, ...rest] = tag.toLowerCase().split(/[-_]/);
20
+ if (!lang || !/^[a-z]{2,3}$/.test(lang)) return [];
21
+ const region = rest.find((p) => /^[a-z]{2}$/.test(p));
22
+ return [`lang: ${str(lang)}`, ...region ? [`region: ${str(region)}`] : []];
23
+ }
24
+ function blocks(tokens, sep = "\n\n") {
25
+ return tokens.map(block).filter((s) => s !== "").join(sep);
26
+ }
27
+ function block(t) {
28
+ switch (t.type) {
29
+ case "heading": {
30
+ const h = t;
31
+ return `#heading(level: ${Math.min(Math.max(h.depth, 1), 6)})[${inlines(h.tokens)}]`;
32
+ }
33
+ case "paragraph": return inlines(t.tokens);
34
+ case "text": {
35
+ const x = t;
36
+ return x.tokens ? inlines(x.tokens) : text(x.text);
37
+ }
38
+ case "code": {
39
+ const c = t;
40
+ const lang = c.lang?.trim().split(/\s+/)[0];
41
+ return `#raw(block: true, ${lang ? `lang: ${str(lang)}, ` : ""}${str(c.text)})`;
42
+ }
43
+ case "blockquote": return `#quote(block: true)[${blocks(t.tokens)}]`;
44
+ case "list": return list(t);
45
+ case "table": return table(t);
46
+ case "hr": return "#line(length: 100%, stroke: 0.5pt + luma(170))";
47
+ case "html": return text(htmlText(t.text).trim());
48
+ case "space":
49
+ case "def": return "";
50
+ default: {
51
+ const x = t;
52
+ return x.tokens ? inlines(x.tokens) : x.text ? text(x.text) : "";
53
+ }
54
+ }
55
+ }
56
+ function list(l) {
57
+ const items = l.items.map((item) => {
58
+ const body = item.tokens.filter((x) => x.type !== "checkbox");
59
+ return `[${item.task ? `#${str(item.checked ? "☑ " : "☐ ")};` : ""}${blocks(body, l.loose ? "\n\n" : "\n")}]`;
60
+ });
61
+ const args = [`tight: ${!l.loose}`];
62
+ if (l.ordered) {
63
+ const start = typeof l.start === "number" ? l.start : 1;
64
+ if (start !== 1) args.push(`start: ${start}`);
65
+ }
66
+ return `#${l.ordered ? "enum" : "list"}(${args.join(", ")}, ${items.join(", ")})`;
67
+ }
68
+ function table(t) {
69
+ const align = t.align.map((a) => a ?? "auto");
70
+ const header = t.header.map((c) => `[#strong[${inlines(c.tokens)}]]`);
71
+ const rows = t.rows.flatMap((row) => t.header.map((_, i) => `[${row[i] ? inlines(row[i].tokens) : ""}]`));
72
+ return [
73
+ "#table(",
74
+ ` columns: ${t.header.length},`,
75
+ ` align: (${align.join(", ")},),`,
76
+ ` table.header(${header.join(", ")}),`,
77
+ ...rows.length ? [` ${rows.join(", ")},`] : [],
78
+ ")"
79
+ ].join("\n");
80
+ }
81
+ function inlines(tokens) {
82
+ let out = "";
83
+ let run = "";
84
+ const flush = () => {
85
+ out += text(run);
86
+ run = "";
87
+ };
88
+ for (const t of tokens) {
89
+ const plain = plainText(t);
90
+ if (plain !== void 0) {
91
+ run += plain;
92
+ continue;
93
+ }
94
+ flush();
95
+ out += inline(t);
96
+ }
97
+ flush();
98
+ return out;
99
+ }
100
+ function plainText(t) {
101
+ if (t.type === "escape") return t.text;
102
+ if (t.type === "text" && !t.tokens) return t.text;
103
+ if (t.type === "html" && !isBreak(t.text)) return htmlText(t.text);
104
+ }
105
+ function inline(t) {
106
+ switch (t.type) {
107
+ case "text": {
108
+ const x = t;
109
+ return x.tokens ? inlines(x.tokens) : text(x.text);
110
+ }
111
+ case "escape": return text(t.text);
112
+ case "strong": return `#strong[${inlines(t.tokens)}]`;
113
+ case "em": return `#emph[${inlines(t.tokens)}]`;
114
+ case "del": return `#strike[${inlines(t.tokens)}]`;
115
+ case "codespan": return `#raw(${str(decodeEntities(t.text))});`;
116
+ case "br": return "#linebreak();";
117
+ case "link": {
118
+ const l = t;
119
+ const body = inlines(l.tokens);
120
+ return l.href ? `#link(${str(l.href)})[${body}]` : body;
121
+ }
122
+ case "image": {
123
+ const i = t;
124
+ return `#emph[${text(i.text ? `[${i.text}]` : "[image]")}]`;
125
+ }
126
+ case "html": return isBreak(t.text) ? "#linebreak();" : text(htmlText(t.text));
127
+ default: {
128
+ const x = t;
129
+ return x.tokens ? inlines(x.tokens) : x.text ? text(x.text) : "";
130
+ }
131
+ }
132
+ }
133
+ const CJK = "\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}\\p{Script=Hangul}\\u3000-\\u303f\\uff00-\\uffef";
134
+ const CJK_BREAK = new RegExp(`([${CJK}])[ \\t]*\\n[ \\t]*(?=[${CJK}])`, "gu");
135
+ function text(s) {
136
+ const flowed = decodeEntities(s).replace(CJK_BREAK, "$1").replace(/[ \t]*\n[ \t]*/g, " ");
137
+ return flowed ? `#${str(flowed)};` : "";
138
+ }
139
+ function str(s) {
140
+ return `"${s.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\r?\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t")}"`;
141
+ }
142
+ const HTML_TAGS = new Set("a abbr b big blockquote br center code del details div em font h1 h2 h3 h4 h5 h6 hr i img ins kbd li mark ol p pre q s samp small span strike strong sub summary sup table tbody td th thead tr tt u ul var".split(" "));
143
+ function htmlText(s) {
144
+ return s.replace(/<!--[\s\S]*?-->/g, "").replace(/<\/?([a-zA-Z][a-zA-Z0-9]*)\b[^>]*>/g, (tag, name) => HTML_TAGS.has(name.toLowerCase()) ? "" : tag);
145
+ }
146
+ function isBreak(html) {
147
+ return /^<br\b[^>]*>$/i.test(html.trim());
148
+ }
149
+ const NAMED = {
150
+ amp: "&",
151
+ lt: "<",
152
+ gt: ">",
153
+ quot: "\"",
154
+ apos: "'",
155
+ nbsp: "\xA0",
156
+ "#39": "'"
157
+ };
158
+ function decodeEntities(s) {
159
+ return s.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (m, e) => {
160
+ if (e[0] === "#") {
161
+ const code = e[1] === "x" || e[1] === "X" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
162
+ return Number.isFinite(code) && code > 0 && code <= 1114111 ? String.fromCodePoint(code) : m;
163
+ }
164
+ return NAMED[e.toLowerCase()] ?? m;
165
+ });
166
+ }
167
+ //#endregion
168
+ export { markdownToTypst, typstSource };
@@ -0,0 +1,19 @@
1
+ //#region src/renderer.d.ts
2
+ export type PdfDocument = {
3
+ markdown: string;
4
+ title?: string;
5
+ author?: string;
6
+ lang?: string;
7
+ paper?: PdfPaper;
8
+ };
9
+ export type PdfPaper = "a4" | "us-letter";
10
+ export interface PdfRenderer {
11
+ readonly name: string;
12
+ render(doc: PdfDocument): Promise<Uint8Array>;
13
+ }
14
+ export declare class PdfRenderError extends Error {
15
+ constructor(message: string, options?: {
16
+ cause?: unknown;
17
+ });
18
+ }
19
+ //#endregion
@@ -0,0 +1,9 @@
1
+ //#region src/renderer.ts
2
+ var PdfRenderError = class extends Error {
3
+ constructor(message, options) {
4
+ super(message, options);
5
+ this.name = "PdfRenderError";
6
+ }
7
+ };
8
+ //#endregion
9
+ export { PdfRenderError };
@@ -0,0 +1,25 @@
1
+ import { PdfDocument, PdfPaper, PdfRenderer } from "./renderer.js";
2
+ import { FileRef } from "@junejs/core/agent-files";
3
+ import { Tool } from "@junejs/core/agent-runtime";
4
+ //#region src/tools.d.ts
5
+ export type PdfToolsOptions = {
6
+ renderer: PdfRenderer;
7
+ name?: string;
8
+ defaults?: Pick<PdfDocument, "author" | "lang" | "paper">;
9
+ requiresPrincipal?: boolean;
10
+ maxMarkdownLength?: number;
11
+ };
12
+ export type RenderPdfInput = {
13
+ markdown: string;
14
+ filename?: string;
15
+ title?: string;
16
+ lang?: string;
17
+ paper?: PdfPaper;
18
+ };
19
+ export type RenderPdfResult = {
20
+ file: FileRef;
21
+ note: string;
22
+ };
23
+ export declare function pdfTools(opts: PdfToolsOptions): Tool[];
24
+ export declare function pdfFilename(raw: string): string;
25
+ //#endregion
package/dist/tools.js ADDED
@@ -0,0 +1,119 @@
1
+ //#region src/tools.ts
2
+ const PDF_MEDIA_TYPE = "application/pdf";
3
+ const MAX_MARKDOWN = 2e5;
4
+ function pdfTools(opts) {
5
+ const name = opts.name ?? "render_pdf";
6
+ const max = opts.maxMarkdownLength ?? MAX_MARKDOWN;
7
+ const tool = {
8
+ spec: {
9
+ name,
10
+ description: "Typeset Markdown into a PDF and attach it to the conversation. Use it when the user asks for a PDF, a report to download or print, or a document to share. Write the complete document as Markdown (headings, paragraphs, lists, tables, code blocks, links). The user receives the PDF as an attachment; reply with a short note about what it contains instead of repeating it.",
11
+ input: {
12
+ type: "object",
13
+ properties: {
14
+ markdown: {
15
+ type: "string",
16
+ description: "The whole document, in Markdown. Start with a # heading for the title."
17
+ },
18
+ filename: {
19
+ type: "string",
20
+ description: "The attachment's filename, e.g. \"revenue-2026-w41.pdf\". Defaults to the title."
21
+ },
22
+ title: {
23
+ type: "string",
24
+ description: "The document title (PDF metadata). Defaults to the first heading."
25
+ },
26
+ lang: {
27
+ type: "string",
28
+ description: "The document language as a BCP 47 tag, e.g. \"en\", \"zh-TW\", \"ja\"."
29
+ },
30
+ paper: {
31
+ type: "string",
32
+ enum: ["a4", "us-letter"],
33
+ description: "Paper size (default a4)."
34
+ }
35
+ },
36
+ required: ["markdown"]
37
+ }
38
+ },
39
+ mode: "remote",
40
+ run: async (raw, ctx) => {
41
+ const input = validateInput(name, raw, max);
42
+ const title = input.title?.trim() || firstHeading(input.markdown);
43
+ const doc = {
44
+ markdown: input.markdown,
45
+ ...title ? { title } : {},
46
+ ...dropUndefined({
47
+ author: opts.defaults?.author,
48
+ lang: input.lang ?? opts.defaults?.lang,
49
+ paper: input.paper ?? opts.defaults?.paper
50
+ })
51
+ };
52
+ const bytes = await opts.renderer.render(doc);
53
+ const filename = pdfFilename(input.filename || title || "document");
54
+ const file = await ctx.files.put(bytes, {
55
+ name: filename,
56
+ mediaType: PDF_MEDIA_TYPE
57
+ });
58
+ return {
59
+ file,
60
+ note: `${filename} (${formatSize(file.size)}) is attached to the conversation.`
61
+ };
62
+ }
63
+ };
64
+ if (opts.requiresPrincipal) tool.requiresPrincipal = true;
65
+ return [tool];
66
+ }
67
+ const PAPERS = ["a4", "us-letter"];
68
+ const LANG = /^[A-Za-z]{2,3}(?:[-_][A-Za-z0-9]{1,8})*$/;
69
+ function validateInput(tool, raw, max) {
70
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error(`${tool}: the input must be an object with a \`markdown\` string`);
71
+ const i = raw;
72
+ const problems = [];
73
+ const optionalString = (key) => {
74
+ const v = i[key];
75
+ if (v === void 0 || v === null) return void 0;
76
+ if (typeof v !== "string") {
77
+ problems.push(`\`${key}\` must be a string`);
78
+ return;
79
+ }
80
+ return v;
81
+ };
82
+ const markdown = i.markdown;
83
+ if (typeof markdown !== "string" || !markdown.trim()) problems.push("`markdown` must be a non-empty string");
84
+ else if (markdown.length > max) problems.push(`the Markdown is ${markdown.length} characters; the limit is ${max} — shorten the document`);
85
+ const filename = optionalString("filename");
86
+ const title = optionalString("title");
87
+ const lang = optionalString("lang");
88
+ if (lang !== void 0 && !LANG.test(lang)) problems.push(`\`lang\` must be a BCP 47 language tag such as "en" or "zh-TW", not ${JSON.stringify(lang)}`);
89
+ const paper = optionalString("paper");
90
+ if (paper !== void 0 && !PAPERS.includes(paper)) problems.push(`\`paper\` must be one of ${PAPERS.map((p) => `"${p}"`).join(", ")}, not ${JSON.stringify(paper)}`);
91
+ if (problems.length) throw new Error(`${tool}: ${problems.join("; ")}`);
92
+ return {
93
+ markdown,
94
+ ...dropUndefined({
95
+ filename,
96
+ title,
97
+ lang,
98
+ paper
99
+ })
100
+ };
101
+ }
102
+ function dropUndefined(o) {
103
+ return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== void 0));
104
+ }
105
+ function firstHeading(markdown) {
106
+ return /^#{1,6}[ \t]+(.+?)[ \t#]*$/m.exec(markdown)?.[1]?.replace(/[*_`]/g, "").trim() || void 0;
107
+ }
108
+ function pdfFilename(raw) {
109
+ let base = raw.normalize("NFC").replace(/\.pdf$/i, "").replace(/[\u0000-\u001f\u007f/\\:*?"<>|]+/g, "-").replace(/\s+/g, " ").trim().replace(/^[.\-\s]+|[.\-\s]+$/g, "");
110
+ if ([...base].length > 100) base = [...base].slice(0, 100).join("").trim();
111
+ return `${base || "document"}.pdf`;
112
+ }
113
+ function formatSize(bytes) {
114
+ if (bytes < 1024) return `${bytes} B`;
115
+ if (bytes < 1048576) return `${(bytes / 1024).toFixed(0)} KB`;
116
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
117
+ }
118
+ //#endregion
119
+ export { pdfFilename, pdfTools };
@@ -0,0 +1,13 @@
1
+ import { PdfRenderer } from "./renderer.js";
2
+ //#region src/typst.d.ts
3
+ export type TypstFontAsset = "text" | "cjk" | "emoji";
4
+ export type TypstRendererOptions = {
5
+ fonts?: (Uint8Array | string)[];
6
+ fontAssets?: TypstFontAsset[] | false;
7
+ fontAssetUrl?: string;
8
+ fontFamilies?: string[];
9
+ wasm?: Uint8Array | ArrayBuffer | WebAssembly.Module | (() => Promise<Uint8Array | ArrayBuffer | WebAssembly.Module>);
10
+ fetcher?: typeof fetch;
11
+ };
12
+ export declare function typstRenderer(opts?: TypstRendererOptions): PdfRenderer;
13
+ //#endregion
package/dist/typst.js ADDED
@@ -0,0 +1,58 @@
1
+ import { PdfRenderError } from "./renderer.js";
2
+ import { typstSource } from "./markdown-typst.js";
3
+ //#region src/typst.ts
4
+ const MAIN = "/main.typ";
5
+ const PDF_FORMAT = 1;
6
+ function typstRenderer(opts = {}) {
7
+ let compiler;
8
+ let queue = Promise.resolve();
9
+ const ready = () => compiler ??= init(opts).catch((err) => {
10
+ compiler = void 0;
11
+ throw err;
12
+ });
13
+ async function compile(doc) {
14
+ const c = await ready();
15
+ c.addSource(MAIN, typstSource(doc, { fonts: opts.fontFamilies }));
16
+ const out = await c.compile({
17
+ mainFilePath: MAIN,
18
+ format: PDF_FORMAT,
19
+ diagnostics: "full"
20
+ });
21
+ if (!out.result?.byteLength) {
22
+ const detail = (out.diagnostics ?? []).filter((d) => d.severity !== "warning").map((d) => `${d.range ? `${d.range}: ` : ""}${d.message ?? "unknown error"}`).join("; ");
23
+ throw new PdfRenderError(`the document could not be typeset${detail ? `: ${detail}` : ""}`);
24
+ }
25
+ return out.result;
26
+ }
27
+ return {
28
+ name: "typst",
29
+ render(doc) {
30
+ const run = queue.then(() => compile(doc));
31
+ queue = run.catch(() => {});
32
+ return run;
33
+ }
34
+ };
35
+ }
36
+ async function init(opts) {
37
+ const { createTypstCompiler, initOptions } = await import("@myriaddreamin/typst.ts");
38
+ const compiler = createTypstCompiler();
39
+ const fonts = initOptions.loadFonts(opts.fonts ?? [], {
40
+ assets: opts.fontAssets === false ? false : opts.fontAssets ?? ["text", "cjk"],
41
+ ...opts.fontAssetUrl ? { assetUrlPrefix: opts.fontAssetUrl } : {},
42
+ ...opts.fetcher ? { fetcher: opts.fetcher } : {}
43
+ });
44
+ await compiler.init({
45
+ getModule: () => loadWasm(opts.wasm),
46
+ beforeBuild: [fonts]
47
+ });
48
+ return compiler;
49
+ }
50
+ async function loadWasm(wasm) {
51
+ if (typeof wasm === "function") return wasm();
52
+ if (wasm) return wasm;
53
+ const url = import.meta.resolve("@myriaddreamin/typst-ts-web-compiler/wasm");
54
+ const [{ readFile }, { fileURLToPath }] = await Promise.all([import("node:fs/promises"), import("node:url")]);
55
+ return new Uint8Array(await readFile(fileURLToPath(url)));
56
+ }
57
+ //#endregion
58
+ export { typstRenderer };
package/package.json CHANGED
@@ -1,6 +1,68 @@
1
1
  {
2
2
  "name": "@junejs/pdf",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-dev.0",
4
+ "description": "June — PDF output as an agent capability: a render_pdf tool over a replaceable PdfRenderer (Typst on WebAssembly by default).",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "homepage": "https://june.build",
8
+ "exports": {
9
+ ".": {
10
+ "source": "./src/index.ts",
11
+ "bun": "./src/index.ts",
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "./typst": {
16
+ "source": "./src/typst.ts",
17
+ "bun": "./src/typst.ts",
18
+ "types": "./dist/typst.d.ts",
19
+ "default": "./dist/typst.js"
20
+ }
21
+ },
22
+ "files": [
23
+ "dist",
24
+ "src",
25
+ "skills"
26
+ ],
27
+ "scripts": {
28
+ "test": "bun test",
29
+ "typecheck": "tsc --noEmit",
30
+ "build": "tsdown"
31
+ },
32
+ "dependencies": {
33
+ "@junejs/core": ">=0.2.0-dev.66",
34
+ "marked": "^18.0.14"
35
+ },
36
+ "peerDependencies": {
37
+ "@myriaddreamin/typst.ts": "^0.7.0",
38
+ "@myriaddreamin/typst-ts-web-compiler": "^0.7.0"
39
+ },
40
+ "peerDependenciesMeta": {
41
+ "@myriaddreamin/typst.ts": {
42
+ "optional": true
43
+ },
44
+ "@myriaddreamin/typst-ts-web-compiler": {
45
+ "optional": true
46
+ }
47
+ },
48
+ "devDependencies": {
49
+ "@junejs/server": ">=1.0.0-dev.47",
50
+ "@myriaddreamin/typst.ts": "^0.7.0",
51
+ "@myriaddreamin/typst-ts-web-compiler": "^0.7.0"
52
+ },
53
+ "keywords": [
54
+ "june",
55
+ "agent",
56
+ "pdf",
57
+ "typst",
58
+ "wasm"
59
+ ],
60
+ "publishConfig": {
61
+ "access": "public"
62
+ },
63
+ "repository": {
64
+ "type": "git",
65
+ "url": "git+https://github.com/junebuild/june.git",
66
+ "directory": "packages/pdf"
67
+ }
68
+ }
@@ -0,0 +1,25 @@
1
+ ---
2
+ name: pdf-report
3
+ description: Write a document and deliver it as a PDF attachment with render_pdf.
4
+ when-to-use: the user asks for a PDF, a report or summary to download, print or forward, or a document to share.
5
+ ---
6
+ # Delivering a PDF
7
+
8
+ 1. Gather what the document needs first (query tools, earlier messages). Don't render a
9
+ draft and then render again — each render_pdf call attaches another file.
10
+ 2. Write the whole document as Markdown in one piece:
11
+ - Open with a `#` title, then a one-paragraph summary of the key result.
12
+ - Use `##` sections, short paragraphs, and bullet lists for findings.
13
+ - Put figures in tables (`| a | b |` with a `|---|---|` row); right-align numbers
14
+ with `|--:|`.
15
+ - Use code blocks only for code or queries.
16
+ - Images are not supported: describe a chart's message in words or a table.
17
+ - Write in the user's language, and pass it as `lang` (e.g. `zh-TW`, `en`, `ja`).
18
+ 3. Call `render_pdf` with `markdown`, a descriptive `filename` (e.g.
19
+ `revenue-2026-w41.pdf`), and `lang`.
20
+ 4. Reply in one or two sentences: what the PDF covers and the headline number or
21
+ conclusion. The user receives the file as an attachment — don't paste its content
22
+ into the chat.
23
+ 5. If render_pdf returns an error, read it, fix the Markdown, and try once more. If it
24
+ fails again, give the user the content as a normal message and say the PDF couldn't
25
+ be produced.
package/src/index.ts ADDED
@@ -0,0 +1,6 @@
1
+ // @junejs/pdf — PDF output as an agent capability (docs/rfc-agent-files.md §4): the
2
+ // render_pdf tool (pdfTools) over a replaceable PdfRenderer. The bundled renderer, Typst on
3
+ // WebAssembly, is its own entry: `import { typstRenderer } from "@junejs/pdf/typst"`.
4
+
5
+ export { pdfTools, pdfFilename, type PdfToolsOptions, type RenderPdfInput, type RenderPdfResult } from "./tools";
6
+ export { PdfRenderError, type PdfDocument, type PdfPaper, type PdfRenderer } from "./renderer";
@@ -0,0 +1,233 @@
1
+ // Markdown → Typst source, for typstRenderer. Pure (no WASM), so it is tested on its own.
2
+ //
3
+ // Every run of text is emitted as a Typst STRING LITERAL in code mode — `#"text";` — never as
4
+ // markup. Typst markup gives meaning to dozens of characters (`#`, `*`, `_`, `$`, `@`, `<`,
5
+ // `//`, `=` or `-` at a line start…), and a model's Markdown contains all of them: a price, an
6
+ // email address, a URL, a C comment. Escaping them one by one is a list that is always
7
+ // incomplete; a string literal needs only `\` and `"` escaped. The trailing `;` ends the
8
+ // embedded expression, so a following `.` or `[` can never be read as a field access or a
9
+ // content argument. Structure (headings, lists, tables, …) is emitted as Typst function calls
10
+ // whose content arguments are built the same way.
11
+ //
12
+ // Images are not fetched (the compiler has no network): an image renders as its alt text.
13
+
14
+ import { Lexer, type Token, type Tokens } from "marked";
15
+
16
+ import type { PdfDocument } from "./renderer";
17
+
18
+ export type TypstSourceOptions = {
19
+ // Font families in order of preference; Typst falls back to any loaded font that has the
20
+ // glyph, so CJK text still renders when the first family is Latin-only.
21
+ fonts?: string[];
22
+ };
23
+
24
+ export function markdownToTypst(markdown: string): string {
25
+ const tokens = new Lexer({ gfm: true }).lex(markdown);
26
+ return blocks(tokens).trim() + "\n";
27
+ }
28
+
29
+ // The whole document: page and text setup, then the body.
30
+ export function typstSource(doc: PdfDocument, opts: TypstSourceOptions = {}): string {
31
+ const lines: string[] = [];
32
+ const meta = [doc.title ? `title: ${str(doc.title)}` : "", doc.author ? `author: ${str(doc.author)}` : ""].filter(Boolean);
33
+ if (meta.length) lines.push(`#set document(${meta.join(", ")})`);
34
+ lines.push(`#set page(paper: ${str(doc.paper === "us-letter" ? "us-letter" : "a4")}, margin: (x: 2.2cm, y: 2.4cm), numbering: "1")`);
35
+ const text = ["size: 10.5pt", ...langArgs(doc.lang)];
36
+ if (opts.fonts?.length) text.push(`font: (${opts.fonts.map(str).join(", ")},)`);
37
+ lines.push(`#set text(${text.join(", ")})`);
38
+ lines.push(
39
+ "#set par(justify: true, leading: 0.75em)",
40
+ "#show heading: set block(above: 1.4em, below: 0.9em)",
41
+ '#show link: set text(fill: rgb("#1f4e9e"))',
42
+ "#set table(stroke: 0.5pt + luma(170), inset: 6pt)",
43
+ "#show raw.where(block: true): block.with(fill: luma(245), inset: 8pt, radius: 3pt, width: 100%)",
44
+ "",
45
+ );
46
+ return lines.join("\n") + markdownToTypst(doc.markdown);
47
+ }
48
+
49
+ // BCP 47 → Typst's `lang` (ISO 639) and `region` (ISO 3166-1 alpha-2). A tag Typst can't take
50
+ // (a script subtag alone, a malformed tag) contributes what it can, or nothing.
51
+ function langArgs(tag: string | undefined): string[] {
52
+ if (!tag) return [];
53
+ const [lang, ...rest] = tag.toLowerCase().split(/[-_]/);
54
+ if (!lang || !/^[a-z]{2,3}$/.test(lang)) return [];
55
+ const region = rest.find((p) => /^[a-z]{2}$/.test(p));
56
+ return [`lang: ${str(lang)}`, ...(region ? [`region: ${str(region)}`] : [])];
57
+ }
58
+
59
+ // ── blocks ──────────────────────────────────────────────────────────────────
60
+
61
+ // Blocks are separated by a paragraph break — except inside a tight list item, where a
62
+ // break would loosen the list; a single newline is a space in Typst markup, and the
63
+ // block-level calls that follow (a nested list) start their own line regardless.
64
+ function blocks(tokens: Token[], sep = "\n\n"): string {
65
+ return tokens.map(block).filter((s) => s !== "").join(sep);
66
+ }
67
+
68
+ function block(t: Token): string {
69
+ switch (t.type) {
70
+ case "heading": {
71
+ const h = t as Tokens.Heading;
72
+ return `#heading(level: ${Math.min(Math.max(h.depth, 1), 6)})[${inlines(h.tokens)}]`;
73
+ }
74
+ case "paragraph":
75
+ return inlines((t as Tokens.Paragraph).tokens);
76
+ case "text": {
77
+ // Block-level text: the content of a tight list item.
78
+ const x = t as Tokens.Text;
79
+ return x.tokens ? inlines(x.tokens) : text(x.text);
80
+ }
81
+ case "code": {
82
+ const c = t as Tokens.Code;
83
+ const lang = c.lang?.trim().split(/\s+/)[0];
84
+ return `#raw(block: true, ${lang ? `lang: ${str(lang)}, ` : ""}${str(c.text)})`;
85
+ }
86
+ case "blockquote":
87
+ return `#quote(block: true)[${blocks((t as Tokens.Blockquote).tokens)}]`;
88
+ case "list":
89
+ return list(t as Tokens.List);
90
+ case "table":
91
+ return table(t as Tokens.Table);
92
+ case "hr":
93
+ return "#line(length: 100%, stroke: 0.5pt + luma(170))";
94
+ case "html":
95
+ return text(htmlText((t as Tokens.HTML).text).trim());
96
+ case "space":
97
+ case "def":
98
+ return "";
99
+ default: {
100
+ // A token type this converter doesn't know (an extension): keep its text, never drop it.
101
+ const x = t as { tokens?: Token[]; text?: string };
102
+ return x.tokens ? inlines(x.tokens) : x.text ? text(x.text) : "";
103
+ }
104
+ }
105
+ }
106
+
107
+ function list(l: Tokens.List): string {
108
+ const items = l.items.map((item) => {
109
+ const body = item.tokens.filter((x) => x.type !== "checkbox");
110
+ const box = item.task ? `#${str(item.checked ? "☑ " : "☐ ")};` : "";
111
+ return `[${box}${blocks(body, l.loose ? "\n\n" : "\n")}]`;
112
+ });
113
+ const args = [`tight: ${!l.loose}`];
114
+ if (l.ordered) {
115
+ const start = typeof l.start === "number" ? l.start : 1;
116
+ if (start !== 1) args.push(`start: ${start}`);
117
+ }
118
+ return `#${l.ordered ? "enum" : "list"}(${args.join(", ")}, ${items.join(", ")})`;
119
+ }
120
+
121
+ function table(t: Tokens.Table): string {
122
+ const align = t.align.map((a) => a ?? "auto");
123
+ const header = t.header.map((c) => `[#strong[${inlines(c.tokens)}]]`);
124
+ const rows = t.rows.flatMap((row) => t.header.map((_, i) => `[${row[i] ? inlines(row[i]!.tokens) : ""}]`));
125
+ return [
126
+ "#table(",
127
+ ` columns: ${t.header.length},`,
128
+ ` align: (${align.join(", ")},),`,
129
+ ` table.header(${header.join(", ")}),`,
130
+ ...(rows.length ? [` ${rows.join(", ")},`] : []),
131
+ ")",
132
+ ].join("\n");
133
+ }
134
+
135
+ // ── inlines ─────────────────────────────────────────────────────────────────
136
+
137
+ // Adjacent plain runs (text split around an escape or a dropped tag) merge into one literal.
138
+ function inlines(tokens: Token[]): string {
139
+ let out = "";
140
+ let run = "";
141
+ const flush = () => { out += text(run); run = ""; };
142
+ for (const t of tokens) {
143
+ const plain = plainText(t);
144
+ if (plain !== undefined) { run += plain; continue; }
145
+ flush();
146
+ out += inline(t);
147
+ }
148
+ flush();
149
+ return out;
150
+ }
151
+
152
+ // The raw text of a token that renders as plain text, undefined for anything else.
153
+ function plainText(t: Token): string | undefined {
154
+ if (t.type === "escape") return (t as Tokens.Escape).text;
155
+ if (t.type === "text" && !(t as Tokens.Text).tokens) return (t as Tokens.Text).text;
156
+ if (t.type === "html" && !isBreak((t as Tokens.Tag).text)) return htmlText((t as Tokens.Tag).text);
157
+ return undefined;
158
+ }
159
+
160
+ function inline(t: Token): string {
161
+ switch (t.type) {
162
+ case "text": {
163
+ const x = t as Tokens.Text;
164
+ return x.tokens ? inlines(x.tokens) : text(x.text);
165
+ }
166
+ case "escape":
167
+ return text((t as Tokens.Escape).text);
168
+ case "strong":
169
+ return `#strong[${inlines((t as Tokens.Strong).tokens)}]`;
170
+ case "em":
171
+ return `#emph[${inlines((t as Tokens.Em).tokens)}]`;
172
+ case "del":
173
+ return `#strike[${inlines((t as Tokens.Del).tokens)}]`;
174
+ case "codespan":
175
+ return `#raw(${str(decodeEntities((t as Tokens.Codespan).text))});`;
176
+ case "br":
177
+ return "#linebreak();";
178
+ case "link": {
179
+ const l = t as Tokens.Link;
180
+ const body = inlines(l.tokens);
181
+ return l.href ? `#link(${str(l.href)})[${body}]` : body;
182
+ }
183
+ case "image": {
184
+ const i = t as Tokens.Image;
185
+ return `#emph[${text(i.text ? `[${i.text}]` : "[image]")}]`;
186
+ }
187
+ case "html":
188
+ return isBreak((t as Tokens.Tag).text) ? "#linebreak();" : text(htmlText((t as Tokens.Tag).text));
189
+ default: {
190
+ const x = t as { tokens?: Token[]; text?: string };
191
+ return x.tokens ? inlines(x.tokens) : x.text ? text(x.text) : "";
192
+ }
193
+ }
194
+ }
195
+
196
+ // A run of text as a string literal. A soft line break is a space between words, but
197
+ // nothing between two CJK characters — those scripts don't put spaces between words.
198
+ const CJK = "\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}\\p{Script=Hangul}\\u3000-\\u303f\\uff00-\\uffef";
199
+ const CJK_BREAK = new RegExp(`([${CJK}])[ \\t]*\\n[ \\t]*(?=[${CJK}])`, "gu");
200
+ function text(s: string): string {
201
+ const flowed = decodeEntities(s).replace(CJK_BREAK, "$1").replace(/[ \t]*\n[ \t]*/g, " ");
202
+ return flowed ? `#${str(flowed)};` : "";
203
+ }
204
+
205
+ // A Typst string literal.
206
+ function str(s: string): string {
207
+ return `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\r?\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t")}"`;
208
+ }
209
+
210
+ // HTML in Markdown: the tags of ordinary HTML elements are dropped (their text stays), and
211
+ // anything else that merely looks like a tag stays as written — prose such as `Vec<String>`
212
+ // or `<placeholder>` is text, not markup, and must not vanish from the PDF.
213
+ const HTML_TAGS = new Set(
214
+ "a abbr b big blockquote br center code del details div em font h1 h2 h3 h4 h5 h6 hr i img ins kbd li mark ol p pre q s samp small span strike strong sub summary sup table tbody td th thead tr tt u ul var".split(" "),
215
+ );
216
+ function htmlText(s: string): string {
217
+ return s.replace(/<!--[\s\S]*?-->/g, "").replace(/<\/?([a-zA-Z][a-zA-Z0-9]*)\b[^>]*>/g, (tag, name: string) => (HTML_TAGS.has(name.toLowerCase()) ? "" : tag));
218
+ }
219
+
220
+ function isBreak(html: string): boolean {
221
+ return /^<br\b[^>]*>$/i.test(html.trim()); // <br>, <br/>, <br class="…">
222
+ }
223
+
224
+ const NAMED: Record<string, string> = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " ", "#39": "'" };
225
+ function decodeEntities(s: string): string {
226
+ return s.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (m, e: string) => {
227
+ if (e[0] === "#") {
228
+ const code = e[1] === "x" || e[1] === "X" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
229
+ return Number.isFinite(code) && code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : m;
230
+ }
231
+ return NAMED[e.toLowerCase()] ?? m;
232
+ });
233
+ }
@@ -0,0 +1,35 @@
1
+ // The PdfRenderer seam (docs/rfc-agent-files.md §4). PDF output is a capability an app
2
+ // opts into, and HOW the PDF is produced is the app's choice: Typst on WebAssembly runs in
3
+ // process but costs a 28 MB module and tens of MB of memory per document; a headless
4
+ // browser renders HTML/CSS faithfully but needs one; a remote service needs none of it
5
+ // locally. So the tool depends on this interface only, and every
6
+ // engine — the bundled typstRenderer, or one an app writes — implements it.
7
+
8
+ // What a renderer is asked to produce. Markdown is the input because it is what a model
9
+ // writes best and what a skill can teach in a page; layout stays the renderer's job.
10
+ export type PdfDocument = {
11
+ markdown: string;
12
+ title?: string; // the PDF's document title (metadata); not inserted into the body
13
+ author?: string;
14
+ lang?: string; // BCP 47, e.g. "zh-TW" — drives hyphenation, quotes and CJK line breaking
15
+ paper?: PdfPaper;
16
+ };
17
+
18
+ export type PdfPaper = "a4" | "us-letter";
19
+
20
+ export interface PdfRenderer {
21
+ // Shown in errors and logs ("typst", "browser-rendering", …).
22
+ readonly name: string;
23
+ // The PDF's bytes. Throw a PdfRenderError for a problem with the document itself (the
24
+ // model can fix its Markdown and retry); anything else is the renderer's own failure.
25
+ render(doc: PdfDocument): Promise<Uint8Array>;
26
+ }
27
+
28
+ // A document the renderer could not typeset: the message is written for the model, which
29
+ // reads it as the tool's error and can rewrite the Markdown.
30
+ export class PdfRenderError extends Error {
31
+ constructor(message: string, options?: { cause?: unknown }) {
32
+ super(message, options);
33
+ this.name = "PdfRenderError";
34
+ }
35
+ }
package/src/tools.ts ADDED
@@ -0,0 +1,147 @@
1
+ // pdfTools — PDF output as an agent capability (docs/rfc-agent-files.md §4):
2
+ //
3
+ // // agent/tools/pdf.ts
4
+ // import { pdfTools } from "@junejs/pdf";
5
+ // import { typstRenderer } from "@junejs/pdf/typst";
6
+ // export default pdfTools({ renderer: typstRenderer() });
7
+ //
8
+ // One tool, render_pdf: Markdown in, a FileRef out. The bytes go to ctx.files (the host's
9
+ // FileStore), the ref goes back to the model and into the durable log, and the engine's
10
+ // file.attached event lets the channel deliver the PDF (a Slack upload into the thread).
11
+ //
12
+ // A plain Tool, not a defineAction: an action's run receives the action context (the
13
+ // principal), not the ToolContext, and ctx.files lives on the ToolContext.
14
+
15
+ import type { FileRef } from "@junejs/core/agent-files";
16
+ import type { Tool, ToolContext } from "@junejs/core/agent-runtime";
17
+
18
+ import type { PdfDocument, PdfPaper, PdfRenderer } from "./renderer";
19
+
20
+ export type PdfToolsOptions = {
21
+ renderer: PdfRenderer;
22
+ // The tool's name, for an agent that wires two renderers (default "render_pdf").
23
+ name?: string;
24
+ // Applied to every document; the model's own arguments win where it gives them.
25
+ defaults?: Pick<PdfDocument, "author" | "lang" | "paper">;
26
+ // Expose the tool only on turns with a resolved identity (see Tool.requiresPrincipal) —
27
+ // for an agent whose PDFs carry tenant data.
28
+ requiresPrincipal?: boolean;
29
+ // Refuse Markdown longer than this many characters (default 200 000) — a runaway model
30
+ // must not hand the renderer a megabyte of text.
31
+ maxMarkdownLength?: number;
32
+ };
33
+
34
+ export type RenderPdfInput = {
35
+ markdown: string;
36
+ filename?: string;
37
+ title?: string;
38
+ lang?: string;
39
+ paper?: PdfPaper;
40
+ };
41
+
42
+ export type RenderPdfResult = { file: FileRef; note: string };
43
+
44
+ const PDF_MEDIA_TYPE = "application/pdf";
45
+ const MAX_MARKDOWN = 200_000;
46
+
47
+ export function pdfTools(opts: PdfToolsOptions): Tool[] {
48
+ const name = opts.name ?? "render_pdf";
49
+ const max = opts.maxMarkdownLength ?? MAX_MARKDOWN;
50
+ const tool: Tool = {
51
+ spec: {
52
+ name,
53
+ description:
54
+ "Typeset Markdown into a PDF and attach it to the conversation. Use it when the user asks for a PDF, a report to download or print, or a document to share. " +
55
+ "Write the complete document as Markdown (headings, paragraphs, lists, tables, code blocks, links). The user receives the PDF as an attachment; " +
56
+ "reply with a short note about what it contains instead of repeating it.",
57
+ input: {
58
+ type: "object",
59
+ properties: {
60
+ markdown: { type: "string", description: "The whole document, in Markdown. Start with a # heading for the title." },
61
+ filename: { type: "string", description: 'The attachment\'s filename, e.g. "revenue-2026-w41.pdf". Defaults to the title.' },
62
+ title: { type: "string", description: "The document title (PDF metadata). Defaults to the first heading." },
63
+ lang: { type: "string", description: 'The document language as a BCP 47 tag, e.g. "en", "zh-TW", "ja".' },
64
+ paper: { type: "string", enum: ["a4", "us-letter"], description: "Paper size (default a4)." },
65
+ },
66
+ required: ["markdown"],
67
+ },
68
+ },
69
+ mode: "remote",
70
+ run: async (raw: unknown, ctx: ToolContext): Promise<RenderPdfResult> => {
71
+ const input = validateInput(name, raw, max);
72
+ const title = input.title?.trim() || firstHeading(input.markdown);
73
+ const doc: PdfDocument = {
74
+ markdown: input.markdown,
75
+ ...(title ? { title } : {}),
76
+ ...dropUndefined({ author: opts.defaults?.author, lang: input.lang ?? opts.defaults?.lang, paper: input.paper ?? opts.defaults?.paper }),
77
+ };
78
+ const bytes = await opts.renderer.render(doc);
79
+ const filename = pdfFilename(input.filename || title || "document");
80
+ const file = await ctx.files.put(bytes, { name: filename, mediaType: PDF_MEDIA_TYPE });
81
+ return { file, note: `${filename} (${formatSize(file.size)}) is attached to the conversation.` };
82
+ },
83
+ };
84
+ if (opts.requiresPrincipal) tool.requiresPrincipal = true;
85
+ return [tool];
86
+ }
87
+
88
+ // The engine does not check a call against `spec.input`, and models send malformed optional
89
+ // fields (a number for `title`, "A4" or "letter" for `paper`, a sentence for `lang`). Check
90
+ // every field and report every problem in one message the model can act on; null counts as
91
+ // absent, since models often send it for a field they mean to omit.
92
+ const PAPERS: readonly PdfPaper[] = ["a4", "us-letter"];
93
+ const LANG = /^[A-Za-z]{2,3}(?:[-_][A-Za-z0-9]{1,8})*$/;
94
+ function validateInput(tool: string, raw: unknown, max: number): RenderPdfInput {
95
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error(`${tool}: the input must be an object with a \`markdown\` string`);
96
+ const i = raw as Record<string, unknown>;
97
+ const problems: string[] = [];
98
+ const optionalString = (key: string): string | undefined => {
99
+ const v = i[key];
100
+ if (v === undefined || v === null) return undefined;
101
+ if (typeof v !== "string") { problems.push(`\`${key}\` must be a string`); return undefined; }
102
+ return v;
103
+ };
104
+ const markdown = i.markdown;
105
+ if (typeof markdown !== "string" || !markdown.trim()) problems.push("`markdown` must be a non-empty string");
106
+ else if (markdown.length > max) problems.push(`the Markdown is ${markdown.length} characters; the limit is ${max} — shorten the document`);
107
+ const filename = optionalString("filename");
108
+ const title = optionalString("title");
109
+ const lang = optionalString("lang");
110
+ if (lang !== undefined && !LANG.test(lang)) problems.push(`\`lang\` must be a BCP 47 language tag such as "en" or "zh-TW", not ${JSON.stringify(lang)}`);
111
+ const paper = optionalString("paper");
112
+ if (paper !== undefined && !PAPERS.includes(paper as PdfPaper)) problems.push(`\`paper\` must be one of ${PAPERS.map((p) => `"${p}"`).join(", ")}, not ${JSON.stringify(paper)}`);
113
+ if (problems.length) throw new Error(`${tool}: ${problems.join("; ")}`);
114
+ return { markdown: markdown as string, ...dropUndefined({ filename, title, lang, paper: paper as PdfPaper | undefined }) };
115
+ }
116
+
117
+ function dropUndefined<T extends Record<string, unknown>>(o: T): Partial<T> {
118
+ return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined)) as Partial<T>;
119
+ }
120
+
121
+ // The first ATX heading's text, as a fallback title. Setext headings and headings inside
122
+ // code fences are rare in model output; missing them only costs the fallback.
123
+ function firstHeading(markdown: string): string | undefined {
124
+ const m = /^#{1,6}[ \t]+(.+?)[ \t#]*$/m.exec(markdown);
125
+ return m?.[1]?.replace(/[*_`]/g, "").trim() || undefined;
126
+ }
127
+
128
+ // A filename every channel accepts: no path separators or control characters, a bounded
129
+ // length, and the .pdf extension. Letters of any script survive — a Chinese title stays a
130
+ // Chinese filename.
131
+ export function pdfFilename(raw: string): string {
132
+ let base = raw
133
+ .normalize("NFC")
134
+ .replace(/\.pdf$/i, "")
135
+ .replace(/[\u0000-\u001f\u007f/\\:*?"<>|]+/g, "-")
136
+ .replace(/\s+/g, " ")
137
+ .trim()
138
+ .replace(/^[.\-\s]+|[.\-\s]+$/g, "");
139
+ if ([...base].length > 100) base = [...base].slice(0, 100).join("").trim();
140
+ return `${base || "document"}.pdf`;
141
+ }
142
+
143
+ function formatSize(bytes: number): string {
144
+ if (bytes < 1024) return `${bytes} B`;
145
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;
146
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
147
+ }
package/src/typst.ts ADDED
@@ -0,0 +1,104 @@
1
+ // typstRenderer — a PdfRenderer on the Typst compiler built for WebAssembly
2
+ // (@myriaddreamin/typst.ts). Markdown → Typst source (markdown-typst.ts) → PDF, in process,
3
+ // with no browser and no native binary. Verified on Bun and Node. Cloudflare Workers allow
4
+ // 64 MiB uncompressed per Worker, so the 28 MB module fits, but this renderer is not yet
5
+ // verified on workerd: there, pass the compiled module as `wasm` (the default loader reads
6
+ // it with node:fs), mind the 128 MB of memory an isolate's requests share, and expect the
7
+ // Free plan's 10 ms of CPU to be too little. Measured 2026-10-12 on Bun 1.3.14: ~550 ms to
8
+ // initialize once per process (fonts included), then ~30 ms per one-page document.
9
+ //
10
+ // A separate entry (@junejs/pdf/typst) so an app that renders with something else never
11
+ // references the compiler, and the compiler itself is imported on the first render, so an
12
+ // agent that never produces a PDF never loads it.
13
+ //
14
+ // Fonts are the renderer's job. typst.ts's hosted assets (Libertinus Serif, New Computer
15
+ // Modern, DejaVu Sans Mono; "cjk" adds a Simplified Chinese Noto Serif subset) are fetched
16
+ // from jsdelivr at init unless disabled. Traditional Chinese, Japanese and Korean text needs
17
+ // a font that covers it — pass its bytes or URL in `fonts`, or the missing glyphs render
18
+ // blank.
19
+
20
+ import type { TypstCompiler } from "@myriaddreamin/typst.ts/compiler";
21
+
22
+ import { typstSource } from "./markdown-typst";
23
+ import { PdfRenderError, type PdfDocument, type PdfRenderer } from "./renderer";
24
+
25
+ export type TypstFontAsset = "text" | "cjk" | "emoji";
26
+
27
+ export type TypstRendererOptions = {
28
+ // Extra font files: bytes, or URLs fetched at init.
29
+ fonts?: (Uint8Array | string)[];
30
+ // typst.ts's hosted font sets to load at init (default ["text", "cjk"]); false loads none,
31
+ // for a deployment that supplies every font through `fonts` and makes no network call.
32
+ fontAssets?: TypstFontAsset[] | false;
33
+ // Where the hosted font sets are fetched from (default: jsdelivr) — a mirror you control.
34
+ fontAssetUrl?: string;
35
+ // Font families in order of preference, e.g. ["Noto Sans TC"]. Typst still falls back to
36
+ // any loaded font that has a glyph.
37
+ fontFamilies?: string[];
38
+ // The compiler's WASM module: its bytes, a compiled module, or a loader. Default: the file
39
+ // @myriaddreamin/typst-ts-web-compiler ships, read from disk. typst.ts instantiates the
40
+ // module once per process, so the first renderer to initialize decides it.
41
+ wasm?: Uint8Array | ArrayBuffer | WebAssembly.Module | (() => Promise<Uint8Array | ArrayBuffer | WebAssembly.Module>);
42
+ // How URLs in `fonts` and the hosted font sets are fetched (default: global fetch).
43
+ fetcher?: typeof fetch;
44
+ };
45
+
46
+ const MAIN = "/main.typ";
47
+ const PDF_FORMAT = 1; // CompileFormatEnum.pdf — a const enum value, inlined so no runtime import is needed
48
+
49
+ type Diagnostic = { path?: string; range?: string; severity?: string; message?: string };
50
+
51
+ export function typstRenderer(opts: TypstRendererOptions = {}): PdfRenderer {
52
+ let compiler: Promise<TypstCompiler> | undefined;
53
+ // One compiler holds one main file: renders run one at a time, in call order.
54
+ let queue: Promise<unknown> = Promise.resolve();
55
+
56
+ const ready = (): Promise<TypstCompiler> =>
57
+ (compiler ??= init(opts).catch((err: unknown) => {
58
+ compiler = undefined; // a failed init (offline font fetch, missing WASM) is retried next render
59
+ throw err;
60
+ }));
61
+
62
+ async function compile(doc: PdfDocument): Promise<Uint8Array> {
63
+ const c = await ready();
64
+ c.addSource(MAIN, typstSource(doc, { fonts: opts.fontFamilies }));
65
+ const out = (await c.compile({ mainFilePath: MAIN, format: PDF_FORMAT, diagnostics: "full" })) as { result?: Uint8Array; diagnostics?: Diagnostic[] };
66
+ if (!out.result?.byteLength) {
67
+ const errors = (out.diagnostics ?? []).filter((d) => d.severity !== "warning");
68
+ const detail = errors.map((d) => `${d.range ? `${d.range}: ` : ""}${d.message ?? "unknown error"}`).join("; ");
69
+ throw new PdfRenderError(`the document could not be typeset${detail ? `: ${detail}` : ""}`);
70
+ }
71
+ return out.result;
72
+ }
73
+
74
+ return {
75
+ name: "typst",
76
+ render(doc) {
77
+ const run = queue.then(() => compile(doc));
78
+ queue = run.catch(() => {});
79
+ return run;
80
+ },
81
+ };
82
+ }
83
+
84
+ async function init(opts: TypstRendererOptions): Promise<TypstCompiler> {
85
+ const { createTypstCompiler, initOptions } = await import("@myriaddreamin/typst.ts");
86
+ const compiler = createTypstCompiler();
87
+ const fonts = initOptions.loadFonts(opts.fonts ?? [], {
88
+ assets: opts.fontAssets === false ? false : (opts.fontAssets ?? ["text", "cjk"]),
89
+ ...(opts.fontAssetUrl ? { assetUrlPrefix: opts.fontAssetUrl } : {}),
90
+ ...(opts.fetcher ? { fetcher: opts.fetcher } : {}),
91
+ });
92
+ await compiler.init({ getModule: () => loadWasm(opts.wasm), beforeBuild: [fonts] });
93
+ return compiler;
94
+ }
95
+
96
+ async function loadWasm(wasm: TypstRendererOptions["wasm"]): Promise<Uint8Array | ArrayBuffer | WebAssembly.Module> {
97
+ if (typeof wasm === "function") return wasm();
98
+ if (wasm) return wasm;
99
+ // The package's own file, from disk: the hosts this renderer targets all have node:fs, and
100
+ // fetch() of a file: URL works on Bun but not on Node.
101
+ const url = import.meta.resolve("@myriaddreamin/typst-ts-web-compiler/wasm");
102
+ const [{ readFile }, { fileURLToPath }] = await Promise.all([import("node:fs/promises"), import("node:url")]);
103
+ return new Uint8Array(await readFile(fileURLToPath(url)));
104
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.