@paragraf/shaping-wasm 0.0.0-stage → 0.7.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 paragraf contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,88 @@
1
- # Temporary Holding Version
1
+ # @paragraf/shaping-wasm
2
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.
3
+ Rust/WASM shaping engine for paragraf. Provides OpenType text shaping and
4
+ font metrics via [rustybuzz](https://github.com/RazrFalcon/rustybuzz), compiled
5
+ to WebAssembly.
6
+
7
+ **Node.js only.** The wasm-bindgen glue uses `require('fs')` and `__dirname`
8
+ to locate the `.wasm` binary at runtime.
9
+
10
+ ## Install
11
+
12
+ ```bash
13
+ npm install @paragraf/shaping-wasm @paragraf/font-engine @paragraf/types
14
+ ```
15
+
16
+ ## Usage
17
+
18
+ This package is not typically used directly. `@paragraf/typography` loads the
19
+ WASM module automatically. If the module is unavailable it falls back to the
20
+ TypeScript fontkit engine with a warning, or throws when `shaping: 'wasm'` was
21
+ requested.
22
+
23
+ ### Manual loading
24
+
25
+ ```ts
26
+ import { loadShapingWasm, WasmFontEngine } from '@paragraf/shaping-wasm';
27
+
28
+ const wasm = loadShapingWasm(); // synchronous CJS require
29
+ const engine = new WasmFontEngine(wasm);
30
+
31
+ await engine.loadFont('regular', './fonts/SourceSerif4-Regular.ttf');
32
+
33
+ const glyphs = engine.glyphsForString('regular', 'Hello');
34
+ const metrics = engine.getFontMetrics('regular', 12);
35
+ ```
36
+
37
+ ### WASM binary: low-level access
38
+
39
+ The serialized binary protocol (used by `@paragraf/typography` internally):
40
+
41
+ ```ts
42
+ import { serializeNodesToBinary, tracebackWasmBinary } from '@paragraf/shaping-wasm';
43
+
44
+ const [f64s, u8s] = serializeNodesToBinary(nodes);
45
+
46
+ const result = tracebackWasmBinary(wasm, nodes, lineWidth, tolerance,
47
+ emergencyStretch, looseness, consecutiveHyphenLimit, lineWidths, runtPenalty, singleLinePenalty);
48
+ if ('error' in result) throw new Error(result.error);
49
+ const { breaks, usedEmergency } = result.ok;
50
+ ```
51
+
52
+ ## WASM build
53
+
54
+ The compiled WASM artifacts live in `wasm/pkg/` and are included in the
55
+ package. They are produced by:
56
+
57
+ ```bash
58
+ wasm-pack build --target nodejs wasm/
59
+ ```
60
+
61
+ If you modify the Rust source (`wasm/src/lib.rs`), rebuild before running tests.
62
+
63
+ ## Fallback behaviour
64
+
65
+ `@paragraf/typography` loads this module at startup. If the module is absent
66
+ or fails to initialise, composition falls back to the TypeScript
67
+ Knuth-Plass implementation and prints one warning. With `shaping: 'wasm'`
68
+ it throws instead; with `shaping: 'fontkit'` the TypeScript path is chosen
69
+ on purpose. Call `wasmStatus()` from
70
+ `@paragraf/typography` to inspect the current state.
71
+
72
+ ## Benchmark
73
+
74
+ Combined cache benchmark is owned by `@paragraf/typography`:
75
+
76
+ `3a-typography/scripts/benchmark-cache.ts`
77
+
78
+ Run via:
79
+
80
+ ```bash
81
+ cd 3a-typography && npm run benchmark:cache
82
+ ```
83
+
84
+ ## Browser support
85
+
86
+ Not yet supported. Requires switching to `wasm-pack --target bundler` and an
87
+ async `WebAssembly.instantiateStreaming` init path, which is a breaking API
88
+ change. Tracked as future work.
@@ -0,0 +1,84 @@
1
+ import { FontEngine, Glyph, GlyphPath } from '@paragraf/font-engine';
2
+ import { Font, FontMetrics, Node } from '@paragraf/types';
3
+
4
+ type FaceCacheStats = {
5
+ size: number;
6
+ hits: number;
7
+ misses: number;
8
+ evictions: number;
9
+ };
10
+ type FaceCacheOptions = {
11
+ maxEntries?: number;
12
+ };
13
+ type FallbackShapeInput = {
14
+ fontId: string;
15
+ text: string;
16
+ font: Font;
17
+ fontBytes: Uint8Array;
18
+ };
19
+ type WasmFontEngineOptions = {
20
+ faceCache?: FaceCacheOptions;
21
+ fallbackShaper?: (input: FallbackShapeInput) => Glyph[];
22
+ };
23
+ declare function getFaceCacheStats(): FaceCacheStats;
24
+ declare class WasmFontEngine implements FontEngine {
25
+ private readonly wasm;
26
+ private readonly fallbackShaper?;
27
+ private readonly maxFaceCacheEntries;
28
+ private readonly fontBytesById;
29
+ private readonly faceHandlesByFontId;
30
+ private stats;
31
+ private readonly hasFaceApi;
32
+ constructor(wasm: any, options?: WasmFontEngineOptions);
33
+ private syncGlobalStats;
34
+ getFaceCacheStats(): FaceCacheStats;
35
+ loadFont(id: string, path: string): Promise<void>;
36
+ /**
37
+ * Browser-compatible alternative to loadFont().
38
+ * Registers raw font bytes (e.g. from fetch().arrayBuffer()) without fs access.
39
+ */
40
+ loadFontBytes(id: string, bytes: Uint8Array): void;
41
+ private mapShapeResult;
42
+ private touchFaceHandle;
43
+ private evictIfNeeded;
44
+ private createFaceHandle;
45
+ private getOrCreateFaceHandle;
46
+ dispose(): void;
47
+ /**
48
+ * Shape `text` using rustybuzz, returning per-glyph info in font units.
49
+ * `font` provides the font id, variant, and letter spacing.
50
+ * When omitted, falls back to normal shaping (liga/rlig, no sups/subs).
51
+ */
52
+ glyphsForString(fontId: string, text: string, font?: Font): Glyph[];
53
+ applyLigatures(_fontId: string, glyphs: Glyph[]): Glyph[];
54
+ applySingleSubstitution(_fontId: string, glyphs: Glyph[], _featureTag: 'sups' | 'subs'): Glyph[];
55
+ getKerning(_fontId: string, _glyph1: Glyph, _glyph2: Glyph): number;
56
+ getGlyphPath(fontId: string, glyph: Glyph, x: number, y: number, fontSize: number): GlyphPath;
57
+ getFontMetrics(fontId: string, fontSize: number, variant?: 'normal' | 'superscript' | 'subscript'): FontMetrics;
58
+ }
59
+
60
+ /**
61
+ * Binary serialization for WASM boundary optimization.
62
+ * Converts Node[] to compact binary format (Float64Array + Uint8Array) to
63
+ * avoid JSON serialization/deserialization overhead.
64
+ */
65
+
66
+ declare function serializeNodesToBinary(nodes: Node[]): [Float64Array, Uint8Array];
67
+ /**
68
+ * Call WASM traceback with binary node serialization.
69
+ * Avoids JSON overhead compared to traceback_wasm(json).
70
+ *
71
+ * Returns { ok: { breaks: LineBreak[], usedEmergency: bool, usedFallback: bool } }
72
+ * or { error: string }. With onInfeasible 'overfull' (default) an infeasible
73
+ * paragraph returns fallback breaks; with 'throw' it returns { error }.
74
+ */
75
+ declare function tracebackWasmBinary(wasm: any, nodes: Node[], lineWidth: number, tolerance: number, emergencyStretch?: number, looseness?: number, consecutiveHyphenLimit?: number, lineWidths?: number[], runtPenalty?: number, singleLinePenalty?: number, adjDemerits?: number, onInfeasible?: 'throw' | 'overfull'): any;
76
+
77
+ /**
78
+ * Load the compiled Rust/WASM module synchronously.
79
+ * Throws if the WASM package is not present (e.g. wasm-pack not run).
80
+ * The returned object is the raw wasm-bindgen JS module.
81
+ */
82
+ declare function loadShapingWasm(): unknown;
83
+
84
+ export { type FaceCacheStats, WasmFontEngine, type WasmFontEngineOptions, getFaceCacheStats, loadShapingWasm, serializeNodesToBinary, tracebackWasmBinary };
package/dist/index.js ADDED
@@ -0,0 +1,304 @@
1
+ // src/engines/wasm-engine.ts
2
+ import { readFileSync } from "fs";
3
+ var DEFAULT_FACE_CACHE_MAX_ENTRIES = 20;
4
+ var globalFaceCacheStats = {
5
+ size: 0,
6
+ hits: 0,
7
+ misses: 0,
8
+ evictions: 0
9
+ };
10
+ function getFaceCacheStats() {
11
+ return { ...globalFaceCacheStats };
12
+ }
13
+ var WasmFontEngine = class {
14
+ wasm;
15
+ fallbackShaper;
16
+ maxFaceCacheEntries;
17
+ // Font bytes remain JS-owned; face handles are a separate cache layer.
18
+ fontBytesById = /* @__PURE__ */ new Map();
19
+ faceHandlesByFontId = /* @__PURE__ */ new Map();
20
+ stats = {
21
+ size: 0,
22
+ hits: 0,
23
+ misses: 0,
24
+ evictions: 0
25
+ };
26
+ hasFaceApi;
27
+ constructor(wasm, options) {
28
+ this.wasm = wasm;
29
+ this.fallbackShaper = options?.fallbackShaper;
30
+ this.maxFaceCacheEntries = options?.faceCache?.maxEntries ?? DEFAULT_FACE_CACHE_MAX_ENTRIES;
31
+ this.hasFaceApi = typeof wasm?.create_face === "function" && typeof wasm?.drop_face === "function" && typeof wasm?.shape_with_face === "function";
32
+ this.syncGlobalStats();
33
+ }
34
+ syncGlobalStats() {
35
+ globalFaceCacheStats = this.getFaceCacheStats();
36
+ }
37
+ getFaceCacheStats() {
38
+ return {
39
+ ...this.stats,
40
+ size: this.faceHandlesByFontId.size
41
+ };
42
+ }
43
+ async loadFont(id, path) {
44
+ try {
45
+ const data = new Uint8Array(readFileSync(path));
46
+ this.loadFontBytes(id, data);
47
+ } catch (err) {
48
+ throw new Error(
49
+ `WasmFontEngine: failed to load font "${id}" from "${path}": ${err instanceof Error ? err.message : String(err)}`
50
+ );
51
+ }
52
+ }
53
+ /**
54
+ * Browser-compatible alternative to loadFont().
55
+ * Registers raw font bytes (e.g. from fetch().arrayBuffer()) without fs access.
56
+ */
57
+ loadFontBytes(id, bytes) {
58
+ const previousHandle = this.faceHandlesByFontId.get(id);
59
+ if (previousHandle !== void 0) {
60
+ this.wasm.drop_face?.(previousHandle);
61
+ this.faceHandlesByFontId.delete(id);
62
+ this.stats.evictions += 1;
63
+ }
64
+ const ownedCopy = new Uint8Array(bytes);
65
+ this.fontBytesById.set(id, ownedCopy);
66
+ this.wasm.register_font(id, ownedCopy);
67
+ this.syncGlobalStats();
68
+ }
69
+ mapShapeResult(rawJson, source) {
70
+ const raw = JSON.parse(rawJson);
71
+ if ("error" in raw)
72
+ throw new Error(`WasmFontEngine ${source}: ${raw.error}`);
73
+ return raw.ok.glyphs.map((g) => ({
74
+ index: g.glyphId,
75
+ advanceWidth: g.advanceWidth,
76
+ xOffset: g.xOffset,
77
+ yOffset: g.yOffset
78
+ }));
79
+ }
80
+ touchFaceHandle(fontId, handle) {
81
+ this.faceHandlesByFontId.delete(fontId);
82
+ this.faceHandlesByFontId.set(fontId, handle);
83
+ }
84
+ evictIfNeeded() {
85
+ if (this.maxFaceCacheEntries <= 0) return;
86
+ if (this.faceHandlesByFontId.size < this.maxFaceCacheEntries) return;
87
+ const oldest = this.faceHandlesByFontId.entries().next().value;
88
+ if (!oldest) return;
89
+ const [oldestFontId, oldestHandle] = oldest;
90
+ this.wasm.drop_face(oldestHandle);
91
+ this.faceHandlesByFontId.delete(oldestFontId);
92
+ this.stats.evictions += 1;
93
+ }
94
+ createFaceHandle(fontId) {
95
+ const bytes = this.fontBytesById.get(fontId);
96
+ if (!bytes) {
97
+ throw new Error(
98
+ `WasmFontEngine: font bytes for '${fontId}' are not loaded`
99
+ );
100
+ }
101
+ const handle = this.wasm.create_face(bytes);
102
+ if (typeof handle !== "number") {
103
+ throw new Error(
104
+ "WasmFontEngine: create_face did not return a numeric handle"
105
+ );
106
+ }
107
+ if (handle === 0) {
108
+ throw new Error(
109
+ `WasmFontEngine: create_face failed for font '${fontId}'`
110
+ );
111
+ }
112
+ return handle >>> 0;
113
+ }
114
+ getOrCreateFaceHandle(fontId) {
115
+ const cached = this.faceHandlesByFontId.get(fontId);
116
+ if (cached !== void 0) {
117
+ this.stats.hits += 1;
118
+ this.touchFaceHandle(fontId, cached);
119
+ this.syncGlobalStats();
120
+ return cached;
121
+ }
122
+ this.stats.misses += 1;
123
+ this.evictIfNeeded();
124
+ const created = this.createFaceHandle(fontId);
125
+ if (this.maxFaceCacheEntries > 0) {
126
+ this.faceHandlesByFontId.set(fontId, created);
127
+ }
128
+ this.syncGlobalStats();
129
+ return created;
130
+ }
131
+ dispose() {
132
+ for (const [, handle] of this.faceHandlesByFontId) {
133
+ this.wasm.drop_face(handle);
134
+ }
135
+ this.faceHandlesByFontId.clear();
136
+ this.fontBytesById.clear();
137
+ this.syncGlobalStats();
138
+ }
139
+ /**
140
+ * Shape `text` using rustybuzz, returning per-glyph info in font units.
141
+ * `font` provides the font id, variant, and letter spacing.
142
+ * When omitted, falls back to normal shaping (liga/rlig, no sups/subs).
143
+ */
144
+ glyphsForString(fontId, text, font) {
145
+ const shapeFont = font ?? {
146
+ id: fontId,
147
+ size: 12,
148
+ weight: 400,
149
+ style: "normal",
150
+ stretch: "normal"
151
+ };
152
+ if (this.hasFaceApi) {
153
+ if (this.maxFaceCacheEntries <= 0) {
154
+ const oneShot = this.createFaceHandle(fontId);
155
+ try {
156
+ return this.mapShapeResult(
157
+ this.wasm.shape_with_face(oneShot, text, JSON.stringify(shapeFont)),
158
+ "shape_with_face"
159
+ );
160
+ } finally {
161
+ this.wasm.drop_face(oneShot);
162
+ }
163
+ }
164
+ const faceHandle = this.getOrCreateFaceHandle(fontId);
165
+ return this.mapShapeResult(
166
+ this.wasm.shape_with_face(faceHandle, text, JSON.stringify(shapeFont)),
167
+ "shape_with_face"
168
+ );
169
+ }
170
+ if (this.fallbackShaper) {
171
+ const bytes = this.fontBytesById.get(fontId);
172
+ if (!bytes) {
173
+ throw new Error(
174
+ `WasmFontEngine: font bytes for '${fontId}' are not loaded`
175
+ );
176
+ }
177
+ return this.fallbackShaper({
178
+ fontId,
179
+ text,
180
+ font: shapeFont,
181
+ fontBytes: bytes
182
+ });
183
+ }
184
+ return this.mapShapeResult(
185
+ this.wasm.shape_text_wasm(text, JSON.stringify(shapeFont)),
186
+ "shape_text_wasm"
187
+ );
188
+ }
189
+ // glyphForCodePoint intentionally omitted — WasmFontEngine shapes full strings via
190
+ // shape_text_wasm; per-codepoint lookup is not needed by the rendering pipeline.
191
+ // The FontEngine interface marks this method optional for this reason.
192
+ // GSUB ligatures are applied by rustybuzz during shape_text_wasm — identity here
193
+ applyLigatures(_fontId, glyphs) {
194
+ return glyphs;
195
+ }
196
+ // GSUB single substitution (sups/subs) is applied by rustybuzz via Font.variant — identity here
197
+ applySingleSubstitution(_fontId, glyphs, _featureTag) {
198
+ return glyphs;
199
+ }
200
+ // GPOS kern is included in x_advance from shape_text_wasm — no separate adjustment needed
201
+ getKerning(_fontId, _glyph1, _glyph2) {
202
+ return 0;
203
+ }
204
+ getGlyphPath(fontId, glyph, x, y, fontSize) {
205
+ const raw = JSON.parse(
206
+ this.wasm.get_glyph_path(fontId, glyph.index, x, y, fontSize)
207
+ );
208
+ if ("error" in raw)
209
+ throw new Error(`WasmFontEngine get_glyph_path: ${raw.error}`);
210
+ const commands = raw.ok.commands;
211
+ const d = raw.ok.d;
212
+ return {
213
+ commands,
214
+ toSVG: (_precision) => d.length > 0 ? `<path d="${d}"/>` : "",
215
+ boundingBox: void 0
216
+ };
217
+ }
218
+ getFontMetrics(fontId, fontSize, variant) {
219
+ const fontJson = JSON.stringify({
220
+ id: fontId,
221
+ size: fontSize,
222
+ weight: 400,
223
+ style: "normal",
224
+ stretch: "normal",
225
+ variant
226
+ });
227
+ const raw = JSON.parse(this.wasm.font_metrics_wasm(fontJson));
228
+ if ("error" in raw)
229
+ throw new Error(`WasmFontEngine font_metrics_wasm: ${raw.error}`);
230
+ return raw.ok;
231
+ }
232
+ };
233
+
234
+ // src/wasm-binary.ts
235
+ var sentinel = (v) => {
236
+ if (v === Infinity) return 1e30;
237
+ if (v === -Infinity) return -1e30;
238
+ return v;
239
+ };
240
+ function serializeNodesToBinary(nodes) {
241
+ const f64s = new Float64Array(nodes.length * 4);
242
+ const u8s = new Uint8Array(nodes.length);
243
+ for (let i = 0; i < nodes.length; i++) {
244
+ const node = nodes[i];
245
+ const f64Idx = i * 4;
246
+ if (node.type === "box") {
247
+ f64s[f64Idx] = node.width;
248
+ f64s[f64Idx + 1] = 0;
249
+ f64s[f64Idx + 2] = 0;
250
+ f64s[f64Idx + 3] = 0;
251
+ const contentFlag = node.content !== "" ? 1 : 0;
252
+ u8s[i] = 0 | contentFlag << 4;
253
+ } else if (node.type === "glue") {
254
+ f64s[f64Idx] = node.width;
255
+ f64s[f64Idx + 1] = sentinel(node.stretch);
256
+ f64s[f64Idx + 2] = sentinel(node.shrink);
257
+ f64s[f64Idx + 3] = 0;
258
+ const kindFlag = node.kind === "word" ? 0 : 1;
259
+ u8s[i] = 1 | kindFlag << 4;
260
+ } else if (node.type === "penalty") {
261
+ f64s[f64Idx] = node.width;
262
+ f64s[f64Idx + 1] = sentinel(node.penalty);
263
+ f64s[f64Idx + 2] = 0;
264
+ f64s[f64Idx + 3] = 0;
265
+ const flaggedFlag = node.flagged ? 1 : 0;
266
+ u8s[i] = 2 | flaggedFlag << 4;
267
+ }
268
+ }
269
+ return [f64s, u8s];
270
+ }
271
+ function tracebackWasmBinary(wasm, nodes, lineWidth, tolerance, emergencyStretch = 0, looseness = 0, consecutiveHyphenLimit = 0, lineWidths = [], runtPenalty = 0, singleLinePenalty = 0, adjDemerits = 0, onInfeasible = "overfull") {
272
+ const [f64s, u8s] = serializeNodesToBinary(nodes);
273
+ const result = JSON.parse(
274
+ wasm.traceback_wasm_binary(
275
+ f64s,
276
+ u8s,
277
+ new Float64Array(lineWidths),
278
+ lineWidth,
279
+ tolerance,
280
+ emergencyStretch,
281
+ looseness,
282
+ runtPenalty,
283
+ singleLinePenalty,
284
+ consecutiveHyphenLimit,
285
+ adjDemerits,
286
+ onInfeasible === "throw"
287
+ )
288
+ );
289
+ return result;
290
+ }
291
+
292
+ // src/index.ts
293
+ import { createRequire } from "module";
294
+ var _require = createRequire(import.meta.url);
295
+ function loadShapingWasm() {
296
+ return _require("../wasm/pkg/paragraf_shaping_wasm.js");
297
+ }
298
+ export {
299
+ WasmFontEngine,
300
+ getFaceCacheStats,
301
+ loadShapingWasm,
302
+ serializeNodesToBinary,
303
+ tracebackWasmBinary
304
+ };
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "@paragraf/shaping-wasm",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.7.0",
4
+ "description": "Rust/WASM shaping engine for the paragraf typesetter.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/kadetr/paragraf.git",
9
+ "directory": "2a-shaping-wasm"
10
+ },
11
+ "homepage": "https://github.com/kadetr/paragraf/tree/main/2a-shaping-wasm#readme",
12
+ "keywords": [
13
+ "typography",
14
+ "typesetting",
15
+ "wasm",
16
+ "shaping",
17
+ "paragraf"
18
+ ],
19
+ "type": "module",
20
+ "engines": {
21
+ "node": ">=22"
22
+ },
23
+ "files": [
24
+ "dist/",
25
+ "wasm/pkg/",
26
+ "README.md"
27
+ ],
28
+ "exports": {
29
+ ".": {
30
+ "types": "./dist/index.d.ts",
31
+ "default": "./dist/index.js"
32
+ }
33
+ },
34
+ "publishConfig": {
35
+ "access": "public",
36
+ "exports": {
37
+ ".": {
38
+ "types": "./dist/index.d.ts",
39
+ "default": "./dist/index.js"
40
+ }
41
+ }
42
+ },
43
+ "scripts": {
44
+ "build": "tsup",
45
+ "prepublishOnly": "npm run build",
46
+ "test": "vitest run --passWithNoTests",
47
+ "test:watch": "vitest",
48
+ "typecheck": "tsc --noEmit",
49
+ "prepack": "node ../scripts/publishconfig-swap.mjs apply",
50
+ "postpack": "node ../scripts/publishconfig-swap.mjs restore"
51
+ },
52
+ "dependencies": {
53
+ "@paragraf/types": "^0.7.0",
54
+ "@paragraf/font-engine": "^0.7.0"
55
+ },
56
+ "devDependencies": {
57
+ "@types/node": "^22.19.15",
58
+ "tsx": "^4.21.0",
59
+ "typescript": "^5.4.0",
60
+ "vitest": "^3.2.4"
61
+ }
62
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "name": "paragraf-shaping-wasm",
3
+ "version": "0.1.0",
4
+ "files": [
5
+ "paragraf_shaping_wasm_bg.wasm",
6
+ "paragraf_shaping_wasm.js",
7
+ "paragraf_shaping_wasm.d.ts"
8
+ ],
9
+ "main": "paragraf_shaping_wasm.js",
10
+ "types": "paragraf_shaping_wasm.d.ts"
11
+ }
@@ -0,0 +1,141 @@
1
+ /* tslint:disable */
2
+ /* eslint-disable */
3
+
4
+ /**
5
+ * Analyse `text` into Unicode BiDi runs (auto-detected paragraph level).
6
+ *
7
+ * Run boundaries are snapped to grapheme cluster boundaries. In practice the
8
+ * UBA already handles Non-Spacing Marks (Arabic harakat, Hebrew nikud) via
9
+ * rule W1, so the snap is a safety net for unusual edge cases.
10
+ *
11
+ * Returns `{ ok: [ { text, level, isRtl }, … ] }` or `{ error: "…" }`.
12
+ */
13
+ export function analyze_bidi(text: string): string;
14
+
15
+ /**
16
+ * Extended BiDi analysis: paragraph base level (P2/P3 first-strong), logical
17
+ * runs, and a visual reorder map derived from the UBA L2 algorithm.
18
+ *
19
+ * Returns:
20
+ * ```json
21
+ * { "ok": { "paragraphLevel": 0|1, "paragraphDirection": "ltr"|"rtl",
22
+ * "runs": [{"text","level","isRtl"}],
23
+ * "reorderMap": [<logical run index at visual position 0>, …] } }
24
+ * ```
25
+ * or `{ "error": "…" }`.
26
+ *
27
+ * `reorderMap[i]` is the logical run index that should be rendered at visual
28
+ * position `i`. For LTR text it is the identity permutation.
29
+ */
30
+ export function analyze_bidi_v2(text: string): string;
31
+
32
+ /**
33
+ * Run the full Knuth-Plass forward pass (with multi-pass tolerance ladder) on
34
+ * a serialized ParagraphInput and return JSON.
35
+ *
36
+ * **Infinity convention:** TypeScript's `FORCED_BREAK` (-Infinity) and
37
+ * `PROHIBITED` (+Infinity) are not valid JSON. The caller must replace them
38
+ * with the finite sentinels `-1e30` / `1e30` before serialising.
39
+ *
40
+ * Returns `{ ok: { active, usedEmergency, optimalIndex } }` on success or
41
+ * `{ error: "..." }` on failure.
42
+ */
43
+ export function compute_breakpoints_wasm(input_json: string): string;
44
+
45
+ /**
46
+ * Create and register a parsed face from raw bytes, returning an opaque u32 handle.
47
+ */
48
+ export function create_face(data: Uint8Array): number;
49
+
50
+ /**
51
+ * Drop a registered face by handle. Unknown IDs are ignored with a warning.
52
+ */
53
+ export function drop_face(id: number): void;
54
+
55
+ /**
56
+ * OS/2 font metrics scaled to pt. Mirrors TypeScript `realMetrics`.
57
+ * Uses sTypo* values with hhea fallback; baseline shift from ySuperscriptYOffset /
58
+ * ySubscriptYOffset when Font.variant is set.
59
+ *
60
+ * Returns `{ ok: { unitsPerEm, ascender, descender, xHeight, capHeight, lineGap, baselineShift } }`
61
+ * or `{ error: "..." }`.
62
+ */
63
+ export function font_metrics_wasm(font_json: string): string;
64
+
65
+ /**
66
+ * Extract the outline path for a single glyph at position (x, y) scaled to fontSize.
67
+ * Y-flip is applied: font-space Y (up) -> screen-space Y (down).
68
+ *
69
+ * Returns `{ ok: { commands: PathCommand[], d: string } }` or `{ error: "..." }`.
70
+ */
71
+ export function get_glyph_path(font_id: string, glyph_id: number, x: number, y: number, font_size: number): string;
72
+
73
+ export function hello(name: string): string;
74
+
75
+ /**
76
+ * Measure the advance width of `text` in pt, applying GSUB (liga, sups/subs) and GPOS kern.
77
+ * Mirrors TypeScript `realMeasure`: letterSpacing added between glyphs, not after the last one.
78
+ *
79
+ * Returns `{ ok: { width: number } }` or `{ error: "..." }`.
80
+ */
81
+ export function measure_text_wasm(text: string, font_json: string): string;
82
+
83
+ /**
84
+ * Register a font's raw bytes under `font_id` in the WASM-local cache.
85
+ * Call once at startup for each font file used by the paragraph composer.
86
+ */
87
+ export function register_font(font_id: string, data: Uint8Array): void;
88
+
89
+ /**
90
+ * Deserialize a single Node from JSON and re-serialize it.
91
+ * Used by tests to verify the TypeScript ↔ Rust JSON contract.
92
+ */
93
+ export function round_trip_node(node_json: string): string;
94
+
95
+ /**
96
+ * Deserialize a full ParagraphInput from JSON and re-serialize it.
97
+ * Used by tests to verify the TypeScript ↔ Rust JSON contract.
98
+ */
99
+ export function round_trip_paragraph(input_json: string): string;
100
+
101
+ /**
102
+ * Shape `text` and return per-glyph info in font units.
103
+ * Applies GSUB features (liga, rlig, sups/subs via Font.variant) and GPOS kern.
104
+ * Values are in font units so callers scale with `fontSize / unitsPerEm`.
105
+ *
106
+ * Returns `{ ok: { glyphs: ShapedGlyph[], unitsPerEm: number } }` or `{ error: "..." }`.
107
+ */
108
+ export function shape_text_wasm(text: string, font_json: string): string;
109
+
110
+ /**
111
+ * Shape text using a previously created face handle.
112
+ * Returns `{ ok: { glyphs, unitsPerEm } }` or `{ error: "..." }`.
113
+ */
114
+ export function shape_with_face(id: number, text: string, font_json: string): string;
115
+
116
+ /**
117
+ * Space glyph metrics in pt: natural width, stretch, shrink.
118
+ * Mirrors TypeScript `realSpace`: width = raw space advance (fallback em/3),
119
+ * stretch = em/6, shrink = em/9.
120
+ *
121
+ * Returns `{ ok: { width, stretch, shrink } }` or `{ error: "..." }`.
122
+ */
123
+ export function space_metrics_wasm(font_json: string): string;
124
+
125
+ /**
126
+ * Run the forward pass and traceback, returning an ordered `LineBreak[]`.
127
+ *
128
+ * Input JSON shape is identical to `compute_breakpoints_wasm`.
129
+ * Returns `{ ok: { breaks: [...] } }` or `{ error: "..." }`.
130
+ */
131
+ export function traceback_wasm(input_json: string): string;
132
+
133
+ /**
134
+ * Run the forward pass and traceback using binary node format.
135
+ * Returns `{ ok: { breaks: [...], usedEmergency: bool, usedFallback: bool } }`
136
+ * or `{ error: "..." }`.
137
+ *
138
+ * f64s: [width, p1, p2, p3, ...] (4 f64 per node)
139
+ * u8s: [type_and_flags, ...] (type in lower 4 bits, flags in upper 4 bits)
140
+ */
141
+ export function traceback_wasm_binary(f64s: Float64Array, u8s: Uint8Array, line_widths_f64: Float64Array, line_width: number, tolerance: number, emergency_stretch: number, looseness: number, runt_penalty: number, single_line_penalty: number, consecutive_hyphen_limit: number, adj_demerits: number, throw_on_infeasible: boolean): string;
@@ -0,0 +1,534 @@
1
+ /* @ts-self-types="./paragraf_shaping_wasm.d.ts" */
2
+
3
+ /**
4
+ * Analyse `text` into Unicode BiDi runs (auto-detected paragraph level).
5
+ *
6
+ * Run boundaries are snapped to grapheme cluster boundaries. In practice the
7
+ * UBA already handles Non-Spacing Marks (Arabic harakat, Hebrew nikud) via
8
+ * rule W1, so the snap is a safety net for unusual edge cases.
9
+ *
10
+ * Returns `{ ok: [ { text, level, isRtl }, … ] }` or `{ error: "…" }`.
11
+ * @param {string} text
12
+ * @returns {string}
13
+ */
14
+ function analyze_bidi(text) {
15
+ let deferred2_0;
16
+ let deferred2_1;
17
+ try {
18
+ const ptr0 = passStringToWasm0(text, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
19
+ const len0 = WASM_VECTOR_LEN;
20
+ const ret = wasm.analyze_bidi(ptr0, len0);
21
+ deferred2_0 = ret[0];
22
+ deferred2_1 = ret[1];
23
+ return getStringFromWasm0(ret[0], ret[1]);
24
+ } finally {
25
+ wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);
26
+ }
27
+ }
28
+ exports.analyze_bidi = analyze_bidi;
29
+
30
+ /**
31
+ * Extended BiDi analysis: paragraph base level (P2/P3 first-strong), logical
32
+ * runs, and a visual reorder map derived from the UBA L2 algorithm.
33
+ *
34
+ * Returns:
35
+ * ```json
36
+ * { "ok": { "paragraphLevel": 0|1, "paragraphDirection": "ltr"|"rtl",
37
+ * "runs": [{"text","level","isRtl"}],
38
+ * "reorderMap": [<logical run index at visual position 0>, …] } }
39
+ * ```
40
+ * or `{ "error": "…" }`.
41
+ *
42
+ * `reorderMap[i]` is the logical run index that should be rendered at visual
43
+ * position `i`. For LTR text it is the identity permutation.
44
+ * @param {string} text
45
+ * @returns {string}
46
+ */
47
+ function analyze_bidi_v2(text) {
48
+ let deferred2_0;
49
+ let deferred2_1;
50
+ try {
51
+ const ptr0 = passStringToWasm0(text, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
52
+ const len0 = WASM_VECTOR_LEN;
53
+ const ret = wasm.analyze_bidi_v2(ptr0, len0);
54
+ deferred2_0 = ret[0];
55
+ deferred2_1 = ret[1];
56
+ return getStringFromWasm0(ret[0], ret[1]);
57
+ } finally {
58
+ wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);
59
+ }
60
+ }
61
+ exports.analyze_bidi_v2 = analyze_bidi_v2;
62
+
63
+ /**
64
+ * Run the full Knuth-Plass forward pass (with multi-pass tolerance ladder) on
65
+ * a serialized ParagraphInput and return JSON.
66
+ *
67
+ * **Infinity convention:** TypeScript's `FORCED_BREAK` (-Infinity) and
68
+ * `PROHIBITED` (+Infinity) are not valid JSON. The caller must replace them
69
+ * with the finite sentinels `-1e30` / `1e30` before serialising.
70
+ *
71
+ * Returns `{ ok: { active, usedEmergency, optimalIndex } }` on success or
72
+ * `{ error: "..." }` on failure.
73
+ * @param {string} input_json
74
+ * @returns {string}
75
+ */
76
+ function compute_breakpoints_wasm(input_json) {
77
+ let deferred2_0;
78
+ let deferred2_1;
79
+ try {
80
+ const ptr0 = passStringToWasm0(input_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
81
+ const len0 = WASM_VECTOR_LEN;
82
+ const ret = wasm.compute_breakpoints_wasm(ptr0, len0);
83
+ deferred2_0 = ret[0];
84
+ deferred2_1 = ret[1];
85
+ return getStringFromWasm0(ret[0], ret[1]);
86
+ } finally {
87
+ wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);
88
+ }
89
+ }
90
+ exports.compute_breakpoints_wasm = compute_breakpoints_wasm;
91
+
92
+ /**
93
+ * Create and register a parsed face from raw bytes, returning an opaque u32 handle.
94
+ * @param {Uint8Array} data
95
+ * @returns {number}
96
+ */
97
+ function create_face(data) {
98
+ const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);
99
+ const len0 = WASM_VECTOR_LEN;
100
+ const ret = wasm.create_face(ptr0, len0);
101
+ return ret >>> 0;
102
+ }
103
+ exports.create_face = create_face;
104
+
105
+ /**
106
+ * Drop a registered face by handle. Unknown IDs are ignored with a warning.
107
+ * @param {number} id
108
+ */
109
+ function drop_face(id) {
110
+ wasm.drop_face(id);
111
+ }
112
+ exports.drop_face = drop_face;
113
+
114
+ /**
115
+ * OS/2 font metrics scaled to pt. Mirrors TypeScript `realMetrics`.
116
+ * Uses sTypo* values with hhea fallback; baseline shift from ySuperscriptYOffset /
117
+ * ySubscriptYOffset when Font.variant is set.
118
+ *
119
+ * Returns `{ ok: { unitsPerEm, ascender, descender, xHeight, capHeight, lineGap, baselineShift } }`
120
+ * or `{ error: "..." }`.
121
+ * @param {string} font_json
122
+ * @returns {string}
123
+ */
124
+ function font_metrics_wasm(font_json) {
125
+ let deferred2_0;
126
+ let deferred2_1;
127
+ try {
128
+ const ptr0 = passStringToWasm0(font_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
129
+ const len0 = WASM_VECTOR_LEN;
130
+ const ret = wasm.font_metrics_wasm(ptr0, len0);
131
+ deferred2_0 = ret[0];
132
+ deferred2_1 = ret[1];
133
+ return getStringFromWasm0(ret[0], ret[1]);
134
+ } finally {
135
+ wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);
136
+ }
137
+ }
138
+ exports.font_metrics_wasm = font_metrics_wasm;
139
+
140
+ /**
141
+ * Extract the outline path for a single glyph at position (x, y) scaled to fontSize.
142
+ * Y-flip is applied: font-space Y (up) -> screen-space Y (down).
143
+ *
144
+ * Returns `{ ok: { commands: PathCommand[], d: string } }` or `{ error: "..." }`.
145
+ * @param {string} font_id
146
+ * @param {number} glyph_id
147
+ * @param {number} x
148
+ * @param {number} y
149
+ * @param {number} font_size
150
+ * @returns {string}
151
+ */
152
+ function get_glyph_path(font_id, glyph_id, x, y, font_size) {
153
+ let deferred2_0;
154
+ let deferred2_1;
155
+ try {
156
+ const ptr0 = passStringToWasm0(font_id, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
157
+ const len0 = WASM_VECTOR_LEN;
158
+ const ret = wasm.get_glyph_path(ptr0, len0, glyph_id, x, y, font_size);
159
+ deferred2_0 = ret[0];
160
+ deferred2_1 = ret[1];
161
+ return getStringFromWasm0(ret[0], ret[1]);
162
+ } finally {
163
+ wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);
164
+ }
165
+ }
166
+ exports.get_glyph_path = get_glyph_path;
167
+
168
+ /**
169
+ * @param {string} name
170
+ * @returns {string}
171
+ */
172
+ function hello(name) {
173
+ let deferred2_0;
174
+ let deferred2_1;
175
+ try {
176
+ const ptr0 = passStringToWasm0(name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
177
+ const len0 = WASM_VECTOR_LEN;
178
+ const ret = wasm.hello(ptr0, len0);
179
+ deferred2_0 = ret[0];
180
+ deferred2_1 = ret[1];
181
+ return getStringFromWasm0(ret[0], ret[1]);
182
+ } finally {
183
+ wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);
184
+ }
185
+ }
186
+ exports.hello = hello;
187
+
188
+ /**
189
+ * Measure the advance width of `text` in pt, applying GSUB (liga, sups/subs) and GPOS kern.
190
+ * Mirrors TypeScript `realMeasure`: letterSpacing added between glyphs, not after the last one.
191
+ *
192
+ * Returns `{ ok: { width: number } }` or `{ error: "..." }`.
193
+ * @param {string} text
194
+ * @param {string} font_json
195
+ * @returns {string}
196
+ */
197
+ function measure_text_wasm(text, font_json) {
198
+ let deferred3_0;
199
+ let deferred3_1;
200
+ try {
201
+ const ptr0 = passStringToWasm0(text, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
202
+ const len0 = WASM_VECTOR_LEN;
203
+ const ptr1 = passStringToWasm0(font_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
204
+ const len1 = WASM_VECTOR_LEN;
205
+ const ret = wasm.measure_text_wasm(ptr0, len0, ptr1, len1);
206
+ deferred3_0 = ret[0];
207
+ deferred3_1 = ret[1];
208
+ return getStringFromWasm0(ret[0], ret[1]);
209
+ } finally {
210
+ wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);
211
+ }
212
+ }
213
+ exports.measure_text_wasm = measure_text_wasm;
214
+
215
+ /**
216
+ * Register a font's raw bytes under `font_id` in the WASM-local cache.
217
+ * Call once at startup for each font file used by the paragraph composer.
218
+ * @param {string} font_id
219
+ * @param {Uint8Array} data
220
+ */
221
+ function register_font(font_id, data) {
222
+ const ptr0 = passStringToWasm0(font_id, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
223
+ const len0 = WASM_VECTOR_LEN;
224
+ const ptr1 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);
225
+ const len1 = WASM_VECTOR_LEN;
226
+ wasm.register_font(ptr0, len0, ptr1, len1);
227
+ }
228
+ exports.register_font = register_font;
229
+
230
+ /**
231
+ * Deserialize a single Node from JSON and re-serialize it.
232
+ * Used by tests to verify the TypeScript ↔ Rust JSON contract.
233
+ * @param {string} node_json
234
+ * @returns {string}
235
+ */
236
+ function round_trip_node(node_json) {
237
+ let deferred2_0;
238
+ let deferred2_1;
239
+ try {
240
+ const ptr0 = passStringToWasm0(node_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
241
+ const len0 = WASM_VECTOR_LEN;
242
+ const ret = wasm.round_trip_node(ptr0, len0);
243
+ deferred2_0 = ret[0];
244
+ deferred2_1 = ret[1];
245
+ return getStringFromWasm0(ret[0], ret[1]);
246
+ } finally {
247
+ wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);
248
+ }
249
+ }
250
+ exports.round_trip_node = round_trip_node;
251
+
252
+ /**
253
+ * Deserialize a full ParagraphInput from JSON and re-serialize it.
254
+ * Used by tests to verify the TypeScript ↔ Rust JSON contract.
255
+ * @param {string} input_json
256
+ * @returns {string}
257
+ */
258
+ function round_trip_paragraph(input_json) {
259
+ let deferred2_0;
260
+ let deferred2_1;
261
+ try {
262
+ const ptr0 = passStringToWasm0(input_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
263
+ const len0 = WASM_VECTOR_LEN;
264
+ const ret = wasm.round_trip_paragraph(ptr0, len0);
265
+ deferred2_0 = ret[0];
266
+ deferred2_1 = ret[1];
267
+ return getStringFromWasm0(ret[0], ret[1]);
268
+ } finally {
269
+ wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);
270
+ }
271
+ }
272
+ exports.round_trip_paragraph = round_trip_paragraph;
273
+
274
+ /**
275
+ * Shape `text` and return per-glyph info in font units.
276
+ * Applies GSUB features (liga, rlig, sups/subs via Font.variant) and GPOS kern.
277
+ * Values are in font units so callers scale with `fontSize / unitsPerEm`.
278
+ *
279
+ * Returns `{ ok: { glyphs: ShapedGlyph[], unitsPerEm: number } }` or `{ error: "..." }`.
280
+ * @param {string} text
281
+ * @param {string} font_json
282
+ * @returns {string}
283
+ */
284
+ function shape_text_wasm(text, font_json) {
285
+ let deferred3_0;
286
+ let deferred3_1;
287
+ try {
288
+ const ptr0 = passStringToWasm0(text, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
289
+ const len0 = WASM_VECTOR_LEN;
290
+ const ptr1 = passStringToWasm0(font_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
291
+ const len1 = WASM_VECTOR_LEN;
292
+ const ret = wasm.shape_text_wasm(ptr0, len0, ptr1, len1);
293
+ deferred3_0 = ret[0];
294
+ deferred3_1 = ret[1];
295
+ return getStringFromWasm0(ret[0], ret[1]);
296
+ } finally {
297
+ wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);
298
+ }
299
+ }
300
+ exports.shape_text_wasm = shape_text_wasm;
301
+
302
+ /**
303
+ * Shape text using a previously created face handle.
304
+ * Returns `{ ok: { glyphs, unitsPerEm } }` or `{ error: "..." }`.
305
+ * @param {number} id
306
+ * @param {string} text
307
+ * @param {string} font_json
308
+ * @returns {string}
309
+ */
310
+ function shape_with_face(id, text, font_json) {
311
+ let deferred3_0;
312
+ let deferred3_1;
313
+ try {
314
+ const ptr0 = passStringToWasm0(text, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
315
+ const len0 = WASM_VECTOR_LEN;
316
+ const ptr1 = passStringToWasm0(font_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
317
+ const len1 = WASM_VECTOR_LEN;
318
+ const ret = wasm.shape_with_face(id, ptr0, len0, ptr1, len1);
319
+ deferred3_0 = ret[0];
320
+ deferred3_1 = ret[1];
321
+ return getStringFromWasm0(ret[0], ret[1]);
322
+ } finally {
323
+ wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);
324
+ }
325
+ }
326
+ exports.shape_with_face = shape_with_face;
327
+
328
+ /**
329
+ * Space glyph metrics in pt: natural width, stretch, shrink.
330
+ * Mirrors TypeScript `realSpace`: width = raw space advance (fallback em/3),
331
+ * stretch = em/6, shrink = em/9.
332
+ *
333
+ * Returns `{ ok: { width, stretch, shrink } }` or `{ error: "..." }`.
334
+ * @param {string} font_json
335
+ * @returns {string}
336
+ */
337
+ function space_metrics_wasm(font_json) {
338
+ let deferred2_0;
339
+ let deferred2_1;
340
+ try {
341
+ const ptr0 = passStringToWasm0(font_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
342
+ const len0 = WASM_VECTOR_LEN;
343
+ const ret = wasm.space_metrics_wasm(ptr0, len0);
344
+ deferred2_0 = ret[0];
345
+ deferred2_1 = ret[1];
346
+ return getStringFromWasm0(ret[0], ret[1]);
347
+ } finally {
348
+ wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);
349
+ }
350
+ }
351
+ exports.space_metrics_wasm = space_metrics_wasm;
352
+
353
+ /**
354
+ * Run the forward pass and traceback, returning an ordered `LineBreak[]`.
355
+ *
356
+ * Input JSON shape is identical to `compute_breakpoints_wasm`.
357
+ * Returns `{ ok: { breaks: [...] } }` or `{ error: "..." }`.
358
+ * @param {string} input_json
359
+ * @returns {string}
360
+ */
361
+ function traceback_wasm(input_json) {
362
+ let deferred2_0;
363
+ let deferred2_1;
364
+ try {
365
+ const ptr0 = passStringToWasm0(input_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
366
+ const len0 = WASM_VECTOR_LEN;
367
+ const ret = wasm.traceback_wasm(ptr0, len0);
368
+ deferred2_0 = ret[0];
369
+ deferred2_1 = ret[1];
370
+ return getStringFromWasm0(ret[0], ret[1]);
371
+ } finally {
372
+ wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);
373
+ }
374
+ }
375
+ exports.traceback_wasm = traceback_wasm;
376
+
377
+ /**
378
+ * Run the forward pass and traceback using binary node format.
379
+ * Returns `{ ok: { breaks: [...], usedEmergency: bool, usedFallback: bool } }`
380
+ * or `{ error: "..." }`.
381
+ *
382
+ * f64s: [width, p1, p2, p3, ...] (4 f64 per node)
383
+ * u8s: [type_and_flags, ...] (type in lower 4 bits, flags in upper 4 bits)
384
+ * @param {Float64Array} f64s
385
+ * @param {Uint8Array} u8s
386
+ * @param {Float64Array} line_widths_f64
387
+ * @param {number} line_width
388
+ * @param {number} tolerance
389
+ * @param {number} emergency_stretch
390
+ * @param {number} looseness
391
+ * @param {number} runt_penalty
392
+ * @param {number} single_line_penalty
393
+ * @param {number} consecutive_hyphen_limit
394
+ * @param {number} adj_demerits
395
+ * @param {boolean} throw_on_infeasible
396
+ * @returns {string}
397
+ */
398
+ function traceback_wasm_binary(f64s, u8s, line_widths_f64, line_width, tolerance, emergency_stretch, looseness, runt_penalty, single_line_penalty, consecutive_hyphen_limit, adj_demerits, throw_on_infeasible) {
399
+ let deferred4_0;
400
+ let deferred4_1;
401
+ try {
402
+ const ptr0 = passArrayF64ToWasm0(f64s, wasm.__wbindgen_malloc);
403
+ const len0 = WASM_VECTOR_LEN;
404
+ const ptr1 = passArray8ToWasm0(u8s, wasm.__wbindgen_malloc);
405
+ const len1 = WASM_VECTOR_LEN;
406
+ const ptr2 = passArrayF64ToWasm0(line_widths_f64, wasm.__wbindgen_malloc);
407
+ const len2 = WASM_VECTOR_LEN;
408
+ const ret = wasm.traceback_wasm_binary(ptr0, len0, ptr1, len1, ptr2, len2, line_width, tolerance, emergency_stretch, looseness, runt_penalty, single_line_penalty, consecutive_hyphen_limit, adj_demerits, throw_on_infeasible);
409
+ deferred4_0 = ret[0];
410
+ deferred4_1 = ret[1];
411
+ return getStringFromWasm0(ret[0], ret[1]);
412
+ } finally {
413
+ wasm.__wbindgen_free(deferred4_0, deferred4_1, 1);
414
+ }
415
+ }
416
+ exports.traceback_wasm_binary = traceback_wasm_binary;
417
+
418
+ function __wbg_get_imports() {
419
+ const import0 = {
420
+ __proto__: null,
421
+ __wbindgen_init_externref_table: function() {
422
+ const table = wasm.__wbindgen_externrefs;
423
+ const offset = table.grow(4);
424
+ table.set(0, undefined);
425
+ table.set(offset + 0, undefined);
426
+ table.set(offset + 1, null);
427
+ table.set(offset + 2, true);
428
+ table.set(offset + 3, false);
429
+ },
430
+ };
431
+ return {
432
+ __proto__: null,
433
+ "./paragraf_shaping_wasm_bg.js": import0,
434
+ };
435
+ }
436
+
437
+ let cachedFloat64ArrayMemory0 = null;
438
+ function getFloat64ArrayMemory0() {
439
+ if (cachedFloat64ArrayMemory0 === null || cachedFloat64ArrayMemory0.byteLength === 0) {
440
+ cachedFloat64ArrayMemory0 = new Float64Array(wasm.memory.buffer);
441
+ }
442
+ return cachedFloat64ArrayMemory0;
443
+ }
444
+
445
+ function getStringFromWasm0(ptr, len) {
446
+ ptr = ptr >>> 0;
447
+ return decodeText(ptr, len);
448
+ }
449
+
450
+ let cachedUint8ArrayMemory0 = null;
451
+ function getUint8ArrayMemory0() {
452
+ if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
453
+ cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
454
+ }
455
+ return cachedUint8ArrayMemory0;
456
+ }
457
+
458
+ function passArray8ToWasm0(arg, malloc) {
459
+ const ptr = malloc(arg.length * 1, 1) >>> 0;
460
+ getUint8ArrayMemory0().set(arg, ptr / 1);
461
+ WASM_VECTOR_LEN = arg.length;
462
+ return ptr;
463
+ }
464
+
465
+ function passArrayF64ToWasm0(arg, malloc) {
466
+ const ptr = malloc(arg.length * 8, 8) >>> 0;
467
+ getFloat64ArrayMemory0().set(arg, ptr / 8);
468
+ WASM_VECTOR_LEN = arg.length;
469
+ return ptr;
470
+ }
471
+
472
+ function passStringToWasm0(arg, malloc, realloc) {
473
+ if (realloc === undefined) {
474
+ const buf = cachedTextEncoder.encode(arg);
475
+ const ptr = malloc(buf.length, 1) >>> 0;
476
+ getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);
477
+ WASM_VECTOR_LEN = buf.length;
478
+ return ptr;
479
+ }
480
+
481
+ let len = arg.length;
482
+ let ptr = malloc(len, 1) >>> 0;
483
+
484
+ const mem = getUint8ArrayMemory0();
485
+
486
+ let offset = 0;
487
+
488
+ for (; offset < len; offset++) {
489
+ const code = arg.charCodeAt(offset);
490
+ if (code > 0x7F) break;
491
+ mem[ptr + offset] = code;
492
+ }
493
+ if (offset !== len) {
494
+ if (offset !== 0) {
495
+ arg = arg.slice(offset);
496
+ }
497
+ ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
498
+ const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
499
+ const ret = cachedTextEncoder.encodeInto(arg, view);
500
+
501
+ offset += ret.written;
502
+ ptr = realloc(ptr, len, offset, 1) >>> 0;
503
+ }
504
+
505
+ WASM_VECTOR_LEN = offset;
506
+ return ptr;
507
+ }
508
+
509
+ let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
510
+ cachedTextDecoder.decode();
511
+ function decodeText(ptr, len) {
512
+ return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
513
+ }
514
+
515
+ const cachedTextEncoder = new TextEncoder();
516
+
517
+ if (!('encodeInto' in cachedTextEncoder)) {
518
+ cachedTextEncoder.encodeInto = function (arg, view) {
519
+ const buf = cachedTextEncoder.encode(arg);
520
+ view.set(buf);
521
+ return {
522
+ read: arg.length,
523
+ written: buf.length
524
+ };
525
+ };
526
+ }
527
+
528
+ let WASM_VECTOR_LEN = 0;
529
+
530
+ const wasmPath = `${__dirname}/paragraf_shaping_wasm_bg.wasm`;
531
+ const wasmBytes = require('fs').readFileSync(wasmPath);
532
+ const wasmModule = new WebAssembly.Module(wasmBytes);
533
+ let wasm = new WebAssembly.Instance(wasmModule, __wbg_get_imports()).exports;
534
+ wasm.__wbindgen_start();
@@ -0,0 +1,25 @@
1
+ /* tslint:disable */
2
+ /* eslint-disable */
3
+ export const memory: WebAssembly.Memory;
4
+ export const analyze_bidi: (a: number, b: number) => [number, number];
5
+ export const analyze_bidi_v2: (a: number, b: number) => [number, number];
6
+ export const compute_breakpoints_wasm: (a: number, b: number) => [number, number];
7
+ export const create_face: (a: number, b: number) => number;
8
+ export const drop_face: (a: number) => void;
9
+ export const font_metrics_wasm: (a: number, b: number) => [number, number];
10
+ export const get_glyph_path: (a: number, b: number, c: number, d: number, e: number, f: number) => [number, number];
11
+ export const hello: (a: number, b: number) => [number, number];
12
+ export const measure_text_wasm: (a: number, b: number, c: number, d: number) => [number, number];
13
+ export const register_font: (a: number, b: number, c: number, d: number) => void;
14
+ export const round_trip_node: (a: number, b: number) => [number, number];
15
+ export const round_trip_paragraph: (a: number, b: number) => [number, number];
16
+ export const shape_text_wasm: (a: number, b: number, c: number, d: number) => [number, number];
17
+ export const shape_with_face: (a: number, b: number, c: number, d: number, e: number) => [number, number];
18
+ export const space_metrics_wasm: (a: number, b: number) => [number, number];
19
+ export const traceback_wasm: (a: number, b: number) => [number, number];
20
+ export const traceback_wasm_binary: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number, i: number, j: number, k: number, l: number, m: number, n: number, o: number) => [number, number];
21
+ export const __wbindgen_externrefs: WebAssembly.Table;
22
+ export const __wbindgen_malloc: (a: number, b: number) => number;
23
+ export const __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number;
24
+ export const __wbindgen_free: (a: number, b: number, c: number) => void;
25
+ export const __wbindgen_start: () => void;