@f-office/wasm 0.0.0-stage → 0.1.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.
package/dist/index.js ADDED
@@ -0,0 +1,315 @@
1
+ import wasmInit, { initSync, Renderer as RawRenderer, } from "./wasm/f_office_wasm.js";
2
+ const DEFAULT_TARGET = "word-win";
3
+ let initPromise = null;
4
+ let wasmMemory = null;
5
+ function isNodeRuntime() {
6
+ return (typeof process !== "undefined" &&
7
+ typeof process.versions === "object" &&
8
+ typeof process.versions.node === "string");
9
+ }
10
+ /**
11
+ * Returns the current byte length of the WebAssembly linear memory buffer, or `0` before
12
+ * `init()` completes. Useful for monitoring peak memory on mobile browsers.
13
+ */
14
+ export function wasmMemoryBytes() {
15
+ return wasmMemory ? wasmMemory.buffer.byteLength : 0;
16
+ }
17
+ /**
18
+ * Initializes the F-Office WebAssembly module. Safe to call multiple times;
19
+ * subsequent calls resolve immediately once initialized.
20
+ */
21
+ export function init(source) {
22
+ if (initPromise !== null && source === undefined) {
23
+ return initPromise;
24
+ }
25
+ const pending = (async () => {
26
+ if (source !== undefined) {
27
+ const output = await wasmInit({ module_or_path: source });
28
+ wasmMemory = output.memory;
29
+ return;
30
+ }
31
+ const wasmUrl = new URL("./wasm/f_office_wasm_bg.wasm", import.meta.url);
32
+ if (isNodeRuntime()) {
33
+ const { readFile } = await import("node:fs/promises");
34
+ const bytes = await readFile(wasmUrl);
35
+ const output = initSync({ module: bytes });
36
+ wasmMemory = output.memory;
37
+ return;
38
+ }
39
+ const output = await wasmInit({ module_or_path: wasmUrl });
40
+ wasmMemory = output.memory;
41
+ })();
42
+ if (source === undefined) {
43
+ initPromise = pending;
44
+ }
45
+ return pending;
46
+ }
47
+ function unwrapFontNeeds(raw) {
48
+ const out = [];
49
+ for (const item of raw) {
50
+ try {
51
+ out.push({
52
+ family: item.family ?? null,
53
+ tried: item.tried,
54
+ });
55
+ }
56
+ finally {
57
+ item.free();
58
+ }
59
+ }
60
+ return out;
61
+ }
62
+ function unwrapOutline(raw) {
63
+ const out = [];
64
+ for (const item of raw) {
65
+ try {
66
+ out.push({
67
+ level: item.level,
68
+ text: item.text,
69
+ page: item.page,
70
+ address: item.address,
71
+ });
72
+ }
73
+ finally {
74
+ item.free();
75
+ }
76
+ }
77
+ return out;
78
+ }
79
+ function unwrapTextRuns(raw) {
80
+ const out = [];
81
+ for (const item of raw) {
82
+ try {
83
+ out.push({
84
+ text: item.text,
85
+ size: item.size,
86
+ left: item.left,
87
+ top: item.top,
88
+ width: item.width,
89
+ height: item.height,
90
+ baseline: item.baseline,
91
+ glyphLefts: item.glyphLefts,
92
+ glyphWidths: item.glyphWidths,
93
+ glyphEnds: item.glyphEnds,
94
+ });
95
+ }
96
+ finally {
97
+ item.free();
98
+ }
99
+ }
100
+ return out;
101
+ }
102
+ /** A rendered page image (RGBA bytes, dimensions, and drawing warnings). */
103
+ export class PageImage {
104
+ #raw;
105
+ #cachedPixels = null;
106
+ constructor(raw) {
107
+ this.#raw = raw;
108
+ }
109
+ /** Width in pixels. */
110
+ get width() {
111
+ return this.#raw.width;
112
+ }
113
+ /** Height in pixels. */
114
+ get height() {
115
+ return this.#raw.height;
116
+ }
117
+ /** Distinct warnings produced while drawing this page. */
118
+ warnings() {
119
+ return this.#raw.warnings();
120
+ }
121
+ /**
122
+ * RGBA pixels copied out of WebAssembly memory, cached on first read so repeated
123
+ * accesses do not copy the buffer again.
124
+ */
125
+ get pixels() {
126
+ let cached = this.#cachedPixels;
127
+ if (cached === null) {
128
+ cached = this.#raw.pixels;
129
+ this.#cachedPixels = cached;
130
+ }
131
+ return cached;
132
+ }
133
+ /** Builds a browser `ImageData` backed by this page's RGBA pixels. */
134
+ toImageData() {
135
+ const data = new Uint8ClampedArray(this.pixels);
136
+ return new ImageData(data, this.width, this.height);
137
+ }
138
+ /** Releases WebAssembly memory held by this page image. */
139
+ free() {
140
+ this.#raw.free();
141
+ }
142
+ [Symbol.dispose]() {
143
+ this.free();
144
+ }
145
+ }
146
+ /** A laid-out DOCX document. Page indices are zero-based. */
147
+ export class Document {
148
+ #raw;
149
+ constructor(raw) {
150
+ this.#raw = raw;
151
+ }
152
+ /** Distinct layout warnings (such as substituted fonts or missing pictures). */
153
+ warnings() {
154
+ return this.#raw.warnings();
155
+ }
156
+ /**
157
+ * Fonts looked up during layout that were missing from the renderer, including
158
+ * glyph-fallback families discovered after primary fonts were loaded.
159
+ */
160
+ fontNeeds() {
161
+ return unwrapFontNeeds(this.#raw.fontNeeds());
162
+ }
163
+ /** Number of laid-out pages. */
164
+ pageCount() {
165
+ return this.#raw.pageCount();
166
+ }
167
+ /** Width in pixels of page `index` when rendered at `dpi`. */
168
+ pageWidth(index, dpi) {
169
+ return this.#raw.pageWidth(index, dpi);
170
+ }
171
+ /** Height in pixels of page `index` when rendered at `dpi`. */
172
+ pageHeight(index, dpi) {
173
+ return this.#raw.pageHeight(index, dpi);
174
+ }
175
+ /** Width and height in points of every page in order. */
176
+ pageSizes() {
177
+ const flat = this.#raw.pageSizes();
178
+ const out = [];
179
+ for (let i = 0; i + 1 < flat.length; i += 2) {
180
+ out.push({ width: flat[i], height: flat[i + 1] });
181
+ }
182
+ return out;
183
+ }
184
+ /** Upright text runs of page `index` in painting order. */
185
+ textRuns(index) {
186
+ return unwrapTextRuns(this.#raw.textRuns(index));
187
+ }
188
+ /** Document headings in reading order. */
189
+ outline() {
190
+ return unwrapOutline(this.#raw.outline());
191
+ }
192
+ /** Renders page `index` at `dpi` pixels per inch on a white background. */
193
+ renderPage(index, dpi) {
194
+ return new PageImage(this.#raw.renderPage(index, dpi));
195
+ }
196
+ /**
197
+ * Renders only the rectangular pixel tile `region` of page `index` at `dpi` pixels per inch.
198
+ * Ideal for mobile viewports and high-zoom viewing with constant memory.
199
+ */
200
+ renderRegion(index, region, dpi) {
201
+ return new PageImage(this.#raw.renderRegion(index, region.x, region.y, region.width, region.height, dpi));
202
+ }
203
+ /** Writes all pages to a PDF file with fonts subset and embedded. */
204
+ writePdf() {
205
+ return this.#raw.writePdf();
206
+ }
207
+ /** Releases WebAssembly memory held by this document. */
208
+ free() {
209
+ this.#raw.free();
210
+ }
211
+ [Symbol.dispose]() {
212
+ this.free();
213
+ }
214
+ }
215
+ /** Holds loaded fonts and opens DOCX documents into laid-out pages. */
216
+ export class Renderer {
217
+ #raw;
218
+ constructor() {
219
+ this.#raw = new RawRenderer();
220
+ }
221
+ /** Returns the supported Word target IDs. */
222
+ static targets() {
223
+ return RawRenderer.targets();
224
+ }
225
+ /**
226
+ * Lists fonts requested by a DOCX file before any font is added.
227
+ * Defaults to `"word-win"`.
228
+ */
229
+ static fontsNeeded(docx, target = DEFAULT_TARGET) {
230
+ return unwrapFontNeeds(RawRenderer.fontsNeeded(docx, target));
231
+ }
232
+ /** Adds all faces from an OpenType font or collection (`.ttf`, `.otf`, `.ttc`, `.otc`). */
233
+ addFont(data) {
234
+ return this.#raw.addFont(data);
235
+ }
236
+ /** Adds art page border pictures. */
237
+ addArtPictures(data) {
238
+ return this.#raw.addArtPictures(data);
239
+ }
240
+ /** Lays out a DOCX file with the fonts currently added to this renderer. */
241
+ openDocx(docx, options) {
242
+ const target = options?.target ?? DEFAULT_TARGET;
243
+ const now = options?.now;
244
+ const raw = options?.limits === "mobile"
245
+ ? this.#raw.openDocxMobile(docx, target, now)
246
+ : this.#raw.openDocx(docx, target, now);
247
+ return new Document(raw);
248
+ }
249
+ /** Releases WebAssembly memory held by this renderer. */
250
+ free() {
251
+ this.#raw.free();
252
+ }
253
+ [Symbol.dispose]() {
254
+ this.free();
255
+ }
256
+ }
257
+ /**
258
+ * Discovers the fonts requested by `docx` (including glyph-fallback families),
259
+ * fetches each missing family once via `fetchFont`, and registers them on `renderer`.
260
+ */
261
+ export async function loadFontsFor(renderer, docx, fetchFont, options) {
262
+ const target = options?.target ?? DEFAULT_TARGET;
263
+ const attempted = new Set();
264
+ const added = [];
265
+ const fetchNeeds = async (needs) => {
266
+ let addedHere = 0;
267
+ for (const need of needs) {
268
+ for (const family of need.tried) {
269
+ const key = family.toLowerCase();
270
+ if (attempted.has(key)) {
271
+ continue;
272
+ }
273
+ attempted.add(key);
274
+ const result = await fetchFont(family);
275
+ if (!result) {
276
+ continue;
277
+ }
278
+ const files = Array.isArray(result) ? result : [result];
279
+ let loaded = false;
280
+ for (const bytes of files) {
281
+ if (bytes.byteLength > 0) {
282
+ renderer.addFont(bytes);
283
+ loaded = true;
284
+ }
285
+ }
286
+ if (loaded) {
287
+ added.push(family);
288
+ addedHere += 1;
289
+ break;
290
+ }
291
+ }
292
+ }
293
+ return addedHere;
294
+ };
295
+ await fetchNeeds(Renderer.fontsNeeded(docx, target));
296
+ // Second pass catches fallback fonts requested for glyphs absent from the primary fonts.
297
+ for (let pass = 0; pass < 3; pass += 1) {
298
+ const doc = renderer.openDocx(docx, options);
299
+ let remaining;
300
+ try {
301
+ remaining = doc.fontNeeds();
302
+ }
303
+ finally {
304
+ doc.free();
305
+ }
306
+ if (remaining.length === 0) {
307
+ break;
308
+ }
309
+ const newlyAdded = await fetchNeeds(remaining);
310
+ if (newlyAdded === 0) {
311
+ break;
312
+ }
313
+ }
314
+ return added;
315
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Built-in Microsoft Word rendering targets.
3
+ *
4
+ * `"word-win"` (Microsoft Word for Windows) is the default and only stable target in v0.1.
5
+ * Preview targets (`"word-mac"`, `"word-web"`) require building `f-office-wasm` with
6
+ * `--features preview-targets`.
7
+ */
8
+ export type TargetId = "word-win" | (string & {});
9
+ /** Resource limit preset when opening a DOCX file. */
10
+ export type LimitProfile = "default" | "mobile";
11
+ /** Options when opening a DOCX file. */
12
+ export interface OpenOptions {
13
+ /** Word target whose layout to reproduce. Defaults to `"word-win"`. */
14
+ target?: TargetId;
15
+ /**
16
+ * Local clock timestamp (`YYYY-MM-DDTHH:MM:SSZ`) for `DATE` and `TIME` fields.
17
+ * When omitted, fields show the cached result stored in the DOCX file.
18
+ */
19
+ now?: string;
20
+ /**
21
+ * Resource limits preset (`"default"` or `"mobile"`). Use `"mobile"` on phones and
22
+ * memory-constrained browser tabs to fail gracefully before exhausting tab memory.
23
+ */
24
+ limits?: LimitProfile;
25
+ }
26
+ /** A rectangular pixel tile on a rasterized page, in whole pixels at the requested DPI. */
27
+ export interface PixelRegion {
28
+ x: number;
29
+ y: number;
30
+ width: number;
31
+ height: number;
32
+ }
33
+ /** A font family requested by a document and the ordered fallback families tried for it. */
34
+ export interface FontNeed {
35
+ /** Requested family name, or `null` when the text names no family. */
36
+ family: string | null;
37
+ /** Families tried by the target, in priority order. */
38
+ tried: string[];
39
+ }
40
+ /** A heading entry in the document outline. */
41
+ export interface OutlineEntry {
42
+ /** Heading depth from 0 (top level) to 8. */
43
+ level: number;
44
+ /** Single-line heading text. */
45
+ text: string;
46
+ /** Zero-based page index where the heading starts. */
47
+ page: number;
48
+ /** Stable body paragraph address (for example `"p12"`). */
49
+ address: string;
50
+ }
51
+ /** Dimensions of a page in typographic points (1/72 inch). */
52
+ export interface PageSizePoints {
53
+ width: number;
54
+ height: number;
55
+ }
56
+ /** An upright text run on a page, in points from the top-left corner. */
57
+ export interface TextRun {
58
+ text: string;
59
+ size: number;
60
+ left: number;
61
+ top: number;
62
+ width: number;
63
+ height: number;
64
+ baseline: number;
65
+ glyphLefts: Float64Array;
66
+ glyphWidths: Float64Array;
67
+ glyphEnds: Uint32Array;
68
+ }
69
+ /** Async callback that fetches font file bytes (`.ttf`, `.otf`, `.ttc`, `.otc`) for a family. */
70
+ export type FontFetcher = (family: string) => Promise<Uint8Array[] | Uint8Array | null | undefined>;
71
+ /** Optional source override passed to `init()`. */
72
+ export type WasmInitSource = URL | string | Request | Response | BufferSource | WebAssembly.Module;
73
+ /** Plain RGBA page image returned by the Web Worker client. */
74
+ export interface RenderedPageData {
75
+ width: number;
76
+ height: number;
77
+ pixels: Uint8ClampedArray;
78
+ warnings: string[];
79
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};