@formepdf/core 0.7.5 → 0.7.7

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,39 @@
1
+ /**
2
+ * Browser entry point for @formepdf/core.
3
+ *
4
+ * Import as `@formepdf/core/browser` — no Node APIs, works in any
5
+ * modern browser with WebAssembly support.
6
+ *
7
+ * WASM is loaded via fetch() from the same origin as the importing
8
+ * module (using import.meta.url resolution in the wasm-pack glue).
9
+ * Bundlers like Vite, esbuild, and webpack handle this automatically.
10
+ * For script-tag usage, call `initWasm()` with an explicit URL first.
11
+ */
12
+ import type { InitInput } from '../pkg/forme.js';
13
+ export type { Color, EdgeValues, CornerValues, ElementStyleInfo, ElementInfo, PageInfo, LayoutInfo, RenderWithLayoutResult, RenderDocumentOptions, } from './index.js';
14
+ import type { RenderWithLayoutResult, RenderDocumentOptions } from './index.js';
15
+ /**
16
+ * Initialize the WASM module. Called automatically on first render,
17
+ * but you can call it early to control timing or provide a custom
18
+ * WASM URL/bytes.
19
+ *
20
+ * @example
21
+ * // Auto-resolve (works with bundlers)
22
+ * await initWasm();
23
+ *
24
+ * // Explicit URL (CDN, custom path, etc.)
25
+ * await initWasm('/wasm/forme_bg.wasm');
26
+ * await initWasm(new URL('./forme_bg.wasm', import.meta.url));
27
+ */
28
+ export declare function init(module?: InitInput | Promise<InitInput>): Promise<void>;
29
+ export declare function renderPdf(json: string): Promise<Uint8Array>;
30
+ export declare function renderPdfWithLayout(json: string): Promise<RenderWithLayoutResult>;
31
+ export declare function renderDocument(element: import('react').ReactElement, options?: RenderDocumentOptions): Promise<Uint8Array>;
32
+ export declare function renderDocumentWithLayout(element: import('react').ReactElement, options?: RenderDocumentOptions): Promise<RenderWithLayoutResult>;
33
+ export declare function renderTemplate(templateJson: string, dataJson: string): Promise<Uint8Array>;
34
+ export declare function renderTemplateWithLayout(templateJson: string, dataJson: string): Promise<RenderWithLayoutResult>;
35
+ /**
36
+ * Extract embedded JSON data from a Forme-generated PDF.
37
+ * Uses the browser-native DecompressionStream API (no node:zlib).
38
+ */
39
+ export declare function extractData(pdfBytes: Uint8Array): Promise<unknown | null>;
@@ -0,0 +1,203 @@
1
+ /**
2
+ * Browser entry point for @formepdf/core.
3
+ *
4
+ * Import as `@formepdf/core/browser` — no Node APIs, works in any
5
+ * modern browser with WebAssembly support.
6
+ *
7
+ * WASM is loaded via fetch() from the same origin as the importing
8
+ * module (using import.meta.url resolution in the wasm-pack glue).
9
+ * Bundlers like Vite, esbuild, and webpack handle this automatically.
10
+ * For script-tag usage, call `initWasm()` with an explicit URL first.
11
+ */
12
+ import initWasm, { render_pdf as wasmRenderPdf, render_pdf_with_layout as wasmRenderPdfWithLayout, render_template_pdf as wasmRenderTemplatePdf, render_template_pdf_with_layout as wasmRenderTemplatePdfWithLayout, } from '../pkg/forme.js';
13
+ // ── WASM initialization ────────────────────────────────────────────
14
+ let initialized = false;
15
+ /**
16
+ * Initialize the WASM module. Called automatically on first render,
17
+ * but you can call it early to control timing or provide a custom
18
+ * WASM URL/bytes.
19
+ *
20
+ * @example
21
+ * // Auto-resolve (works with bundlers)
22
+ * await initWasm();
23
+ *
24
+ * // Explicit URL (CDN, custom path, etc.)
25
+ * await initWasm('/wasm/forme_bg.wasm');
26
+ * await initWasm(new URL('./forme_bg.wasm', import.meta.url));
27
+ */
28
+ export async function init(module) {
29
+ if (initialized)
30
+ return;
31
+ if (module !== undefined) {
32
+ await initWasm({ module_or_path: module });
33
+ }
34
+ else {
35
+ await initWasm();
36
+ }
37
+ initialized = true;
38
+ }
39
+ // ── Helpers ────────────────────────────────────────────────────────
40
+ function uint8ArrayToBase64(bytes) {
41
+ // Browser-native: binary string → btoa
42
+ let binary = '';
43
+ for (let i = 0; i < bytes.length; i++) {
44
+ binary += String.fromCharCode(bytes[i]);
45
+ }
46
+ return btoa(binary);
47
+ }
48
+ async function resolveFonts(doc) {
49
+ const fonts = doc.fonts;
50
+ if (!fonts?.length)
51
+ return;
52
+ for (const font of fonts) {
53
+ if (font.src instanceof Uint8Array) {
54
+ font.src = uint8ArrayToBase64(font.src);
55
+ }
56
+ else if (typeof font.src === 'string' && !font.src.startsWith('data:')) {
57
+ // In the browser, non-data-URI strings are treated as URLs
58
+ const res = await fetch(font.src);
59
+ if (!res.ok)
60
+ throw new Error(`Failed to fetch font: ${font.src} (${res.status})`);
61
+ const buf = new Uint8Array(await res.arrayBuffer());
62
+ font.src = uint8ArrayToBase64(buf);
63
+ }
64
+ // data URIs pass through as-is (engine extracts base64 portion)
65
+ }
66
+ }
67
+ async function resolveImages(doc) {
68
+ const children = doc.children;
69
+ if (!children?.length)
70
+ return;
71
+ for (const child of children) {
72
+ await resolveImagesInNode(child);
73
+ }
74
+ }
75
+ async function resolveImagesInNode(node) {
76
+ const kind = node.kind;
77
+ if (kind?.type === 'Image' && typeof kind.src === 'string') {
78
+ const src = kind.src;
79
+ if (src.startsWith('http://') || src.startsWith('https://')) {
80
+ const res = await fetch(src);
81
+ if (!res.ok)
82
+ throw new Error(`Failed to fetch image: ${src} (${res.status})`);
83
+ const contentType = res.headers.get('content-type') || 'image/png';
84
+ const buf = new Uint8Array(await res.arrayBuffer());
85
+ kind.src = `data:${contentType};base64,${uint8ArrayToBase64(buf)}`;
86
+ }
87
+ }
88
+ const children = node.children;
89
+ if (children?.length) {
90
+ for (const child of children) {
91
+ await resolveImagesInNode(child);
92
+ }
93
+ }
94
+ }
95
+ // ── Render functions ───────────────────────────────────────────────
96
+ async function ensureInit() {
97
+ if (!initialized)
98
+ await init();
99
+ }
100
+ export async function renderPdf(json) {
101
+ await ensureInit();
102
+ return wasmRenderPdf(json);
103
+ }
104
+ export async function renderPdfWithLayout(json) {
105
+ await ensureInit();
106
+ const result = wasmRenderPdfWithLayout(json);
107
+ return result;
108
+ }
109
+ export async function renderDocument(element, options) {
110
+ const { serialize } = await import('@formepdf/react');
111
+ const doc = serialize(element);
112
+ if (options?.embedData !== undefined) {
113
+ doc.embeddedData = JSON.stringify(options.embedData);
114
+ }
115
+ await Promise.all([resolveFonts(doc), resolveImages(doc)]);
116
+ return renderPdf(JSON.stringify(doc));
117
+ }
118
+ export async function renderDocumentWithLayout(element, options) {
119
+ const { serialize } = await import('@formepdf/react');
120
+ const doc = serialize(element);
121
+ if (options?.embedData !== undefined) {
122
+ doc.embeddedData = JSON.stringify(options.embedData);
123
+ }
124
+ await Promise.all([resolveFonts(doc), resolveImages(doc)]);
125
+ return renderPdfWithLayout(JSON.stringify(doc));
126
+ }
127
+ // ── Template rendering ──────────────────────────────────────────────
128
+ export async function renderTemplate(templateJson, dataJson) {
129
+ await ensureInit();
130
+ return wasmRenderTemplatePdf(templateJson, dataJson);
131
+ }
132
+ export async function renderTemplateWithLayout(templateJson, dataJson) {
133
+ await ensureInit();
134
+ const result = wasmRenderTemplatePdfWithLayout(templateJson, dataJson);
135
+ return result;
136
+ }
137
+ // ── Data extraction (browser-native decompression) ──────────────────
138
+ /**
139
+ * Extract embedded JSON data from a Forme-generated PDF.
140
+ * Uses the browser-native DecompressionStream API (no node:zlib).
141
+ */
142
+ export async function extractData(pdfBytes) {
143
+ const text = new TextDecoder('latin1').decode(pdfBytes);
144
+ // Find the FileSpec referencing forme-data.json
145
+ const fsMatch = text.match(/\/F\s*\(forme-data\.json\)/);
146
+ if (!fsMatch)
147
+ return null;
148
+ // Extract the EmbeddedFile stream object number from /EF << /F N 0 R >>
149
+ const fsStart = fsMatch.index;
150
+ const fsRegion = text.slice(Math.max(0, fsStart - 200), fsStart + 200);
151
+ const efMatch = fsRegion.match(/\/EF\s*<<\s*\/F\s+(\d+)\s+0\s+R\s*>>/);
152
+ if (!efMatch)
153
+ return null;
154
+ const streamObjId = efMatch[1];
155
+ // Find the stream object
156
+ const objPattern = new RegExp(streamObjId + '\\s+0\\s+obj\\b');
157
+ const objMatch = text.match(objPattern);
158
+ if (!objMatch)
159
+ return null;
160
+ const objStart = objMatch.index;
161
+ // Find stream start
162
+ const streamKeyword = text.indexOf('stream', objStart);
163
+ if (streamKeyword === -1)
164
+ return null;
165
+ let streamDataStart = streamKeyword + 6;
166
+ if (pdfBytes[streamDataStart] === 0x0d)
167
+ streamDataStart++;
168
+ if (pdfBytes[streamDataStart] === 0x0a)
169
+ streamDataStart++;
170
+ const endstreamPos = text.indexOf('\nendstream', streamDataStart);
171
+ if (endstreamPos === -1)
172
+ return null;
173
+ const compressedBytes = pdfBytes.slice(streamDataStart, endstreamPos);
174
+ const objRegion = text.slice(objStart, streamKeyword);
175
+ const isCompressed = objRegion.includes('/FlateDecode');
176
+ let jsonBytes;
177
+ if (isCompressed) {
178
+ const ds = new DecompressionStream('deflate');
179
+ const writer = ds.writable.getWriter();
180
+ writer.write(compressedBytes);
181
+ writer.close();
182
+ const reader = ds.readable.getReader();
183
+ const chunks = [];
184
+ while (true) {
185
+ const { done, value } = await reader.read();
186
+ if (done)
187
+ break;
188
+ chunks.push(value);
189
+ }
190
+ const totalLength = chunks.reduce((sum, c) => sum + c.length, 0);
191
+ jsonBytes = new Uint8Array(totalLength);
192
+ let offset = 0;
193
+ for (const chunk of chunks) {
194
+ jsonBytes.set(chunk, offset);
195
+ offset += chunk.length;
196
+ }
197
+ }
198
+ else {
199
+ jsonBytes = compressedBytes;
200
+ }
201
+ const jsonString = new TextDecoder('utf-8').decode(jsonBytes);
202
+ return JSON.parse(jsonString);
203
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Extract embedded JSON data from a Forme-generated PDF.
3
+ *
4
+ * Scans the PDF bytes for a `forme-data.json` EmbeddedFile attachment,
5
+ * decompresses the stream, and parses the JSON. Returns `null` if the
6
+ * PDF doesn't contain embedded data (e.g. non-Forme PDF).
7
+ */
8
+ export declare function extractData(pdfBytes: Uint8Array): unknown | null;
@@ -0,0 +1,56 @@
1
+ import { inflateSync } from 'node:zlib';
2
+ /**
3
+ * Extract embedded JSON data from a Forme-generated PDF.
4
+ *
5
+ * Scans the PDF bytes for a `forme-data.json` EmbeddedFile attachment,
6
+ * decompresses the stream, and parses the JSON. Returns `null` if the
7
+ * PDF doesn't contain embedded data (e.g. non-Forme PDF).
8
+ */
9
+ export function extractData(pdfBytes) {
10
+ const text = new TextDecoder('latin1').decode(pdfBytes);
11
+ // Find the FileSpec referencing forme-data.json
12
+ const fsMatch = text.match(/\/F\s*\(forme-data\.json\)/);
13
+ if (!fsMatch)
14
+ return null;
15
+ // Extract the EmbeddedFile stream object number from /EF << /F N 0 R >>
16
+ // Search around the FileSpec location for the /EF reference
17
+ const fsStart = fsMatch.index;
18
+ const fsRegion = text.slice(Math.max(0, fsStart - 200), fsStart + 200);
19
+ const efMatch = fsRegion.match(/\/EF\s*<<\s*\/F\s+(\d+)\s+0\s+R\s*>>/);
20
+ if (!efMatch)
21
+ return null;
22
+ const streamObjId = efMatch[1];
23
+ // Find the stream object: "N 0 obj ... stream\n...\nendstream"
24
+ const objPattern = new RegExp(streamObjId + '\\s+0\\s+obj\\b');
25
+ const objMatch = text.match(objPattern);
26
+ if (!objMatch)
27
+ return null;
28
+ const objStart = objMatch.index;
29
+ // Find stream start (after "stream\r\n" or "stream\n")
30
+ const streamKeyword = text.indexOf('stream', objStart);
31
+ if (streamKeyword === -1)
32
+ return null;
33
+ let streamDataStart = streamKeyword + 6; // "stream".length
34
+ // Skip \r\n or \n after "stream"
35
+ if (pdfBytes[streamDataStart] === 0x0d)
36
+ streamDataStart++; // \r
37
+ if (pdfBytes[streamDataStart] === 0x0a)
38
+ streamDataStart++; // \n
39
+ // Find endstream
40
+ const endstreamPos = text.indexOf('\nendstream', streamDataStart);
41
+ if (endstreamPos === -1)
42
+ return null;
43
+ const compressedBytes = pdfBytes.slice(streamDataStart, endstreamPos);
44
+ // Check if FlateDecode is used
45
+ const objRegion = text.slice(objStart, streamKeyword);
46
+ const isCompressed = objRegion.includes('/FlateDecode');
47
+ let jsonBytes;
48
+ if (isCompressed) {
49
+ jsonBytes = inflateSync(Buffer.from(compressedBytes));
50
+ }
51
+ else {
52
+ jsonBytes = compressedBytes;
53
+ }
54
+ const jsonString = new TextDecoder('utf-8').decode(jsonBytes);
55
+ return JSON.parse(jsonString);
56
+ }
package/dist/index.d.ts CHANGED
@@ -72,7 +72,12 @@ export interface RenderWithLayoutResult {
72
72
  }
73
73
  export declare function renderPdf(json: string): Promise<Uint8Array>;
74
74
  export declare function renderPdfWithLayout(json: string): Promise<RenderWithLayoutResult>;
75
- export declare function renderDocument(element: ReactElement): Promise<Uint8Array>;
76
- export declare function renderDocumentWithLayout(element: ReactElement): Promise<RenderWithLayoutResult>;
75
+ export interface RenderDocumentOptions {
76
+ /** Data to embed as a hidden JSON attachment in the PDF. */
77
+ embedData?: unknown;
78
+ }
79
+ export declare function renderDocument(element: ReactElement, options?: RenderDocumentOptions): Promise<Uint8Array>;
80
+ export declare function renderDocumentWithLayout(element: ReactElement, options?: RenderDocumentOptions): Promise<RenderWithLayoutResult>;
77
81
  export declare function renderTemplate(templateJson: string, dataJson: string): Promise<Uint8Array>;
78
82
  export declare function renderTemplateWithLayout(templateJson: string, dataJson: string): Promise<RenderWithLayoutResult>;
83
+ export { extractData } from './extract.js';
package/dist/index.js CHANGED
@@ -73,15 +73,21 @@ export async function renderPdfWithLayout(json) {
73
73
  const result = render_pdf_with_layout(json);
74
74
  return result;
75
75
  }
76
- export async function renderDocument(element) {
76
+ export async function renderDocument(element, options) {
77
77
  const { serialize } = await import('@formepdf/react');
78
78
  const doc = serialize(element);
79
+ if (options?.embedData !== undefined) {
80
+ doc.embeddedData = JSON.stringify(options.embedData);
81
+ }
79
82
  await Promise.all([resolveFonts(doc), resolveImages(doc)]);
80
83
  return renderPdf(JSON.stringify(doc));
81
84
  }
82
- export async function renderDocumentWithLayout(element) {
85
+ export async function renderDocumentWithLayout(element, options) {
83
86
  const { serialize } = await import('@formepdf/react');
84
87
  const doc = serialize(element);
88
+ if (options?.embedData !== undefined) {
89
+ doc.embeddedData = JSON.stringify(options.embedData);
90
+ }
85
91
  await Promise.all([resolveFonts(doc), resolveImages(doc)]);
86
92
  return renderPdfWithLayout(JSON.stringify(doc));
87
93
  }
@@ -97,3 +103,5 @@ export async function renderTemplateWithLayout(templateJson, dataJson) {
97
103
  const result = render_template_pdf_with_layout(templateJson, dataJson);
98
104
  return result;
99
105
  }
106
+ // ── Data extraction ──────────────────────────────────────────────────
107
+ export { extractData } from './extract.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@formepdf/core",
3
- "version": "0.7.5",
3
+ "version": "0.7.7",
4
4
  "description": "WASM-powered PDF rendering engine for Forme",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -10,6 +10,10 @@
10
10
  "types": "./dist/index.d.ts",
11
11
  "import": "./dist/index.js"
12
12
  },
13
+ "./browser": {
14
+ "types": "./dist/browser.d.ts",
15
+ "import": "./dist/browser.js"
16
+ },
13
17
  "./pkg/forme.js": {
14
18
  "types": "./pkg/forme.d.ts",
15
19
  "import": "./pkg/forme.js"
@@ -23,7 +27,7 @@
23
27
  "test": "vitest run"
24
28
  },
25
29
  "dependencies": {
26
- "@formepdf/react": "0.7.5"
30
+ "@formepdf/react": "0.7.7"
27
31
  },
28
32
  "peerDependencies": {
29
33
  "react": "^18 || ^19"
package/pkg/forme_bg.wasm CHANGED
Binary file
package/pkg/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "forme",
3
3
  "type": "module",
4
4
  "description": "A page-native PDF rendering engine. Layout INTO pages, not onto an infinite canvas.",
5
- "version": "0.7.5",
5
+ "version": "0.7.6",
6
6
  "files": [
7
7
  "forme_bg.wasm",
8
8
  "forme.js",