@meritt/microtypo-wasm 0.0.0-stage → 0.2.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,20 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Alexey Simonenko, alexey@simonenko.dev, https://simonenko.xyz
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ 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, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/glue.js ADDED
@@ -0,0 +1,456 @@
1
+ export class Engine {
2
+ __destroy_into_raw() {
3
+ const ptr = this.__wbg_ptr;
4
+ this.__wbg_ptr = 0;
5
+ EngineFinalization.unregister(this);
6
+ return ptr;
7
+ }
8
+ free() {
9
+ const ptr = this.__destroy_into_raw();
10
+ wasm.__wbg_engine_free(ptr, 0);
11
+ }
12
+ /**
13
+ * @param {string} method
14
+ * @param {string} args
15
+ */
16
+ call(method, args) {
17
+ let ptr0, len0, ptr1, len1;
18
+ try {
19
+ ptr0 = passStringToWasm0(method, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
20
+ len0 = WASM_VECTOR_LEN;
21
+ ptr1 = passStringToWasm0(args, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
22
+ len1 = WASM_VECTOR_LEN;
23
+ } catch (e) {
24
+ if (ptr1) { wasm.__wbindgen_free(ptr1, len1 * 1, 1); }
25
+ if (ptr0) { wasm.__wbindgen_free(ptr0, len0 * 1, 1); }
26
+ throw e;
27
+ }
28
+ const ret = wasm.engine_call(this.__wbg_ptr, ptr0, len0, ptr1, len1);
29
+ if (ret[1]) {
30
+ throw takeFromExternrefTable0(ret[0]);
31
+ }
32
+ }
33
+ /**
34
+ * @param {string | null} [config]
35
+ */
36
+ constructor(config) {
37
+ var ptr0 = isLikeNone(config) ? 0 : passStringToWasm0(config, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
38
+ var len0 = WASM_VECTOR_LEN;
39
+ const ret = wasm.engine_new(ptr0, len0);
40
+ if (ret[2]) {
41
+ throw takeFromExternrefTable0(ret[1]);
42
+ }
43
+ this.__wbg_ptr = ret[0];
44
+ EngineFinalization.register(this, this.__wbg_ptr, this);
45
+ return this;
46
+ }
47
+ /**
48
+ * @param {Uint16Array | number[]} text
49
+ * @param {boolean} changes
50
+ * @param {boolean} edits
51
+ * @param {boolean} trace
52
+ * @returns {Uint16Array}
53
+ */
54
+ process(text, changes, edits, trace) {
55
+ const val2 = +changes;
56
+ const val3 = +edits;
57
+ const val4 = +trace;
58
+ const ptr0 = passArray16ToWasm0(text, wasm.__wbindgen_malloc);
59
+ const len0 = WASM_VECTOR_LEN;
60
+ const ret = wasm.engine_process(this.__wbg_ptr, ptr0, len0, val2, val3, val4);
61
+ if (ret[3]) {
62
+ throw takeFromExternrefTable0(ret[2]);
63
+ }
64
+ var v5 = getArrayU16FromWasm0(ret[0], ret[1]).slice();
65
+ wasm.__wbindgen_free(ret[0], ret[1] * 2, 2);
66
+ return v5;
67
+ }
68
+ /**
69
+ * @param {Uint16Array | number[]} name
70
+ * @returns {string | undefined}
71
+ */
72
+ ruleGroup(name) {
73
+ const ptr0 = passArray16ToWasm0(name, wasm.__wbindgen_malloc);
74
+ const len0 = WASM_VECTOR_LEN;
75
+ const ret = wasm.engine_ruleGroup(this.__wbg_ptr, ptr0, len0);
76
+ let v2;
77
+ if (ret[0] !== 0) {
78
+ v2 = getStringFromWasm0(ret[0], ret[1]);
79
+ wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
80
+ }
81
+ return v2;
82
+ }
83
+ /**
84
+ * @returns {string}
85
+ */
86
+ ruleGroups() {
87
+ let deferred1_0;
88
+ let deferred1_1;
89
+ try {
90
+ const ret = wasm.engine_ruleGroups(this.__wbg_ptr);
91
+ deferred1_0 = ret[0];
92
+ deferred1_1 = ret[1];
93
+ return getStringFromWasm0(ret[0], ret[1]);
94
+ } finally {
95
+ wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);
96
+ }
97
+ }
98
+ /**
99
+ * @param {boolean} on
100
+ */
101
+ setCycleHook(on) {
102
+ wasm.engine_setCycleHook(this.__wbg_ptr, on);
103
+ }
104
+ /**
105
+ * @returns {Array<any>}
106
+ */
107
+ takeCycleLimits() {
108
+ const ret = wasm.engine_takeCycleLimits(this.__wbg_ptr);
109
+ return ret;
110
+ }
111
+ /**
112
+ * @returns {string | undefined}
113
+ */
114
+ takeDiagnostics() {
115
+ const ret = wasm.engine_takeDiagnostics(this.__wbg_ptr);
116
+ let v1;
117
+ if (ret[0] !== 0) {
118
+ v1 = getStringFromWasm0(ret[0], ret[1]);
119
+ wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
120
+ }
121
+ return v1;
122
+ }
123
+ }
124
+ if (Symbol.dispose) Engine.prototype[Symbol.dispose] = Engine.prototype.free;
125
+
126
+ /**
127
+ * @returns {number}
128
+ */
129
+ export function defaultMaxInputLength() {
130
+ const ret = wasm.defaultMaxInputLength();
131
+ return ret;
132
+ }
133
+
134
+ /**
135
+ * @returns {string}
136
+ */
137
+ export function version() {
138
+ let deferred1_0;
139
+ let deferred1_1;
140
+ try {
141
+ const ret = wasm.version();
142
+ deferred1_0 = ret[0];
143
+ deferred1_1 = ret[1];
144
+ return getStringFromWasm0(ret[0], ret[1]);
145
+ } finally {
146
+ wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);
147
+ }
148
+ }
149
+ function __wbg_get_imports() {
150
+ const import0 = {
151
+ __proto__: null,
152
+ __wbg___wbindgen_throw_4c88d8bf264fd984: function(arg0, arg1) {
153
+ throw new Error(getStringFromWasm0(arg0, arg1));
154
+ },
155
+ __wbg_concat_3d00c6c70212d5c4: function(arg0, arg1) {
156
+ const ret = arg0.concat(arg1);
157
+ return ret;
158
+ },
159
+ __wbg_fromCharCode_98bae18718397aff: function(arg0, arg1) {
160
+ const ret = String.fromCharCode(...(getArrayU16FromWasm0(arg0, arg1)));
161
+ return ret;
162
+ },
163
+ __wbg_getRandomValues_8b6f1f663e6f188d: function() { return handleError(function (arg0, arg1) {
164
+ globalThis.crypto.getRandomValues(getArrayU8FromWasm0(arg0, arg1));
165
+ }, arguments); },
166
+ __wbg_new_37eb45aaf5eeb820: function() {
167
+ const ret = new Array();
168
+ return ret;
169
+ },
170
+ __wbg_new_cd4348290afae586: function() {
171
+ const ret = new Object();
172
+ return ret;
173
+ },
174
+ __wbg_now_463ac581d2fc7ea3: function() {
175
+ const ret = Date.now();
176
+ return ret;
177
+ },
178
+ __wbg_of_e7ea0fcd535c1444: function(arg0, arg1) {
179
+ const ret = Array.of(arg0, arg1);
180
+ return ret;
181
+ },
182
+ __wbg_parse_c3f72b5a24f83c01: function() { return handleError(function (arg0, arg1) {
183
+ const ret = JSON.parse(getStringFromWasm0(arg0, arg1));
184
+ return ret;
185
+ }, arguments); },
186
+ __wbg_push_c9f4893fc209f768: function(arg0, arg1) {
187
+ const ret = arg0.push(arg1);
188
+ return ret;
189
+ },
190
+ __wbg_set_2793479888329cb6: function() { return handleError(function (arg0, arg1, arg2) {
191
+ const ret = Reflect.set(arg0, arg1, arg2);
192
+ return ret;
193
+ }, arguments); },
194
+ __wbindgen_generic_0000000000000001: function(arg0) {
195
+ // Cast intrinsic for `F64 -> Externref`.
196
+ const ret = arg0;
197
+ return ret;
198
+ },
199
+ __wbindgen_generic_0000000000000002: function(arg0, arg1) {
200
+ // Cast intrinsic for `Ref(String) -> Externref`.
201
+ const ret = getStringFromWasm0(arg0, arg1);
202
+ return ret;
203
+ },
204
+ __wbindgen_init_externref_table: function() {
205
+ const table = wasm.__wbindgen_externrefs;
206
+ table.set(0, undefined);
207
+ table.set(1024, undefined);
208
+ table.set(1025, null);
209
+ table.set(1026, true);
210
+ table.set(1027, false);
211
+ },
212
+ };
213
+ return {
214
+ __proto__: null,
215
+ "./microtypo_wasm_bg.js": import0,
216
+ };
217
+ }
218
+
219
+ const EngineFinalization = (typeof FinalizationRegistry === 'undefined')
220
+ ? { register: () => {}, unregister: () => {} }
221
+ : new FinalizationRegistry(ptr => wasm.__wbg_engine_free(ptr, 1));
222
+
223
+ function addToExternrefTable0(obj) {
224
+ const idx = wasm.__externref_table_alloc();
225
+ wasm.__wbindgen_externrefs.set(idx, obj);
226
+ return idx;
227
+ }
228
+
229
+ function getArrayU16FromWasm0(ptr, len) {
230
+ ptr = ptr >>> 0;
231
+ return getUint16ArrayMemory0().subarray(ptr / 2, ptr / 2 + len);
232
+ }
233
+
234
+ function getArrayU8FromWasm0(ptr, len) {
235
+ ptr = ptr >>> 0;
236
+ return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);
237
+ }
238
+
239
+ function getStringFromWasm0(ptr, len) {
240
+ ptr = ptr >>> 0;
241
+ return decodeText(getUint8ArrayMemory0().subarray(ptr, ptr + len));
242
+ }
243
+
244
+ let cachedUint16ArrayMemory0 = null;
245
+ function getUint16ArrayMemory0() {
246
+ if (cachedUint16ArrayMemory0 === null || cachedUint16ArrayMemory0.byteLength === 0) {
247
+ cachedUint16ArrayMemory0 = new Uint16Array(wasm.memory.buffer);
248
+ }
249
+ return cachedUint16ArrayMemory0;
250
+ }
251
+
252
+ let cachedUint8ArrayMemory0 = null;
253
+ function getUint8ArrayMemory0() {
254
+ if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
255
+ cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
256
+ }
257
+ return cachedUint8ArrayMemory0;
258
+ }
259
+
260
+ function handleError(f, args) {
261
+ try {
262
+ return f.apply(this, args);
263
+ } catch (e) {
264
+ const idx = addToExternrefTable0(e);
265
+ wasm.__wbindgen_exn_store(idx);
266
+ }
267
+ }
268
+
269
+ function isLikeNone(x) {
270
+ return x === undefined || x === null;
271
+ }
272
+
273
+ function passArray16ToWasm0(arg, malloc) {
274
+ const ptr = malloc(arg.length * 2, 2) >>> 0;
275
+ getUint16ArrayMemory0().set(arg, ptr / 2);
276
+ WASM_VECTOR_LEN = arg.length;
277
+ return ptr;
278
+ }
279
+
280
+ function passStringToWasm0(arg, malloc, realloc) {
281
+ if (realloc === undefined) {
282
+ const buf = cachedTextEncoder.encode(arg);
283
+ const ptr = malloc(buf.length, 1) >>> 0;
284
+ getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);
285
+ WASM_VECTOR_LEN = buf.length;
286
+ return ptr;
287
+ }
288
+
289
+ let len = arg.length;
290
+ let ptr = malloc(len, 1) >>> 0;
291
+
292
+ const mem = getUint8ArrayMemory0();
293
+
294
+ let offset = 0;
295
+
296
+ for (; offset < len; offset++) {
297
+ const code = arg.charCodeAt(offset);
298
+ if (code > 0x7F) break;
299
+ mem[ptr + offset] = code;
300
+ }
301
+ if (offset !== len) {
302
+ if (offset !== 0) {
303
+ arg = arg.slice(offset);
304
+ }
305
+ ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
306
+ const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
307
+ const ret = cachedTextEncoder.encodeInto(arg, view);
308
+
309
+ offset += ret.written;
310
+ ptr = realloc(ptr, len, offset, 1) >>> 0;
311
+ }
312
+
313
+ WASM_VECTOR_LEN = offset;
314
+ return ptr;
315
+ }
316
+
317
+ function takeFromExternrefTable0(idx) {
318
+ const value = wasm.__wbindgen_externrefs.get(idx);
319
+ wasm.__externref_table_dealloc(idx);
320
+ return value;
321
+ }
322
+
323
+ let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true });
324
+ cachedTextDecoder.decode();
325
+ const MAX_SAFARI_DECODE_BYTES = 2146435072;
326
+ let numBytesDecoded = 0;
327
+ function decodeText(bytes) {
328
+ numBytesDecoded += bytes.length;
329
+ if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {
330
+ cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true });
331
+ cachedTextDecoder.decode();
332
+ numBytesDecoded = bytes.length;
333
+ }
334
+ return cachedTextDecoder.decode(bytes);
335
+ }
336
+
337
+ const cachedTextEncoder = new TextEncoder();
338
+
339
+ if (!('encodeInto' in cachedTextEncoder)) {
340
+ cachedTextEncoder.encodeInto = function (arg, view) {
341
+ const buf = cachedTextEncoder.encode(arg);
342
+ view.set(buf);
343
+ return {
344
+ read: arg.length,
345
+ written: buf.length
346
+ };
347
+ };
348
+ }
349
+
350
+ let WASM_VECTOR_LEN = 0;
351
+
352
+ let wasmModule, wasmInstance, wasm;
353
+ function __wbg_finalize_init(instance, module) {
354
+ wasmInstance = instance;
355
+ wasm = instance.exports;
356
+ wasmModule = module;
357
+ cachedUint16ArrayMemory0 = null;
358
+ cachedUint8ArrayMemory0 = null;
359
+ wasm.__wbindgen_start();
360
+ return wasm;
361
+ }
362
+
363
+ async function __wbg_load(module, imports) {
364
+ if (typeof Response === 'function' && module instanceof Response) {
365
+ if (!module.ok) {
366
+ throw new Error(`failed to fetch Wasm: ${module.status} ${module.statusText} fetching '${module.url}'`);
367
+ }
368
+
369
+ if (typeof WebAssembly.instantiateStreaming === 'function') {
370
+ try {
371
+ return await WebAssembly.instantiateStreaming(module, imports);
372
+ } catch (e) {
373
+ const validResponse = expectedResponseType(module.type);
374
+
375
+ if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') {
376
+ console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);
377
+
378
+ } else { throw e; }
379
+ }
380
+ }
381
+
382
+ const bytes = await module.arrayBuffer();
383
+ return await WebAssembly.instantiate(bytes, imports);
384
+ } else {
385
+ const instance = await WebAssembly.instantiate(module, imports);
386
+
387
+ if (instance instanceof WebAssembly.Instance) {
388
+ return { instance, module };
389
+ } else {
390
+ return instance;
391
+ }
392
+ }
393
+
394
+ function expectedResponseType(type) {
395
+ switch (type) {
396
+ case 'basic': case 'cors': case 'default': return true;
397
+ }
398
+ return false;
399
+ }
400
+ }
401
+
402
+ function initSync(module) {
403
+ if (wasm !== undefined) return wasm;
404
+
405
+
406
+ if (module !== undefined) {
407
+ if (Object.getPrototypeOf(module) === Object.prototype) {
408
+ ({module} = module)
409
+ } else {
410
+ console.warn('using deprecated parameters for `initSync()`; pass a single object instead')
411
+ }
412
+ }
413
+
414
+ const imports = __wbg_get_imports();
415
+ if (!(module instanceof WebAssembly.Module)) {
416
+ module = new WebAssembly.Module(module);
417
+ }
418
+ const instance = new WebAssembly.Instance(module, imports);
419
+ return __wbg_finalize_init(instance, module);
420
+ }
421
+
422
+ let __wbg_init_promise;
423
+ async function __wbg_init(module_or_path) {
424
+ if (wasm !== undefined) return wasm;
425
+ if (__wbg_init_promise === undefined) {
426
+ __wbg_init_promise = __wbg_init_once(module_or_path);
427
+ __wbg_init_promise.catch(() => { __wbg_init_promise = undefined; });
428
+ }
429
+ return __wbg_init_promise;
430
+ }
431
+
432
+ async function __wbg_init_once(module_or_path) {
433
+
434
+ if (module_or_path !== undefined) {
435
+ if (Object.getPrototypeOf(module_or_path) === Object.prototype) {
436
+ ({module_or_path} = module_or_path)
437
+ } else {
438
+ console.warn('using deprecated parameters for the initialization function; pass a single object instead')
439
+ }
440
+ }
441
+
442
+ if (module_or_path === undefined) {
443
+ module_or_path = new URL('microtypo.wasm', import.meta.url);
444
+ }
445
+ const imports = __wbg_get_imports();
446
+
447
+ if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {
448
+ module_or_path = fetch(module_or_path);
449
+ }
450
+
451
+ const { instance, module } = await __wbg_load(await module_or_path, imports);
452
+
453
+ return __wbg_finalize_init(instance, module);
454
+ }
455
+
456
+ export { initSync, __wbg_init as default };
package/microtypo.js ADDED
@@ -0,0 +1,379 @@
1
+ import { Engine, defaultMaxInputLength, initSync, version } from './glue.js';
2
+
3
+ const VERSION = '0.2.0';
4
+ const MAX_ENTRIES = 100_000;
5
+
6
+ class MicroTypoError extends Error {
7
+ static code = 'ERR_MICROTYPO';
8
+
9
+ constructor(message, options = {}) {
10
+ super(message, options.cause ? { cause: options.cause } : undefined);
11
+
12
+ this.name = new.target.name;
13
+ this.code = new.target.code;
14
+
15
+ if (options.details !== undefined) {
16
+ this.details = options.details;
17
+ }
18
+ }
19
+ }
20
+
21
+ class MicroTypoConfigError extends MicroTypoError {
22
+ static code = 'ERR_MICROTYPO_CONFIG';
23
+ }
24
+
25
+ class MicroTypoInputError extends MicroTypoError {
26
+ static code = 'ERR_MICROTYPO_INPUT';
27
+ }
28
+
29
+ class MicroTypoBudgetError extends MicroTypoError {
30
+ static code = 'ERR_MICROTYPO_BUDGET';
31
+ }
32
+
33
+ class MicroTypoVersionError extends MicroTypoError {
34
+ static code = 'ERR_MICROTYPO_VERSION';
35
+ }
36
+
37
+ function capacityError(message, details) {
38
+ return new MicroTypoInputError(message, { details: { reason: 'capacity', ...details } });
39
+ }
40
+
41
+ const ERRORS = { MicroTypoError, MicroTypoConfigError, MicroTypoInputError, MicroTypoBudgetError };
42
+ const UNSAFE_PREFIX_RE = /["<>&\s]/;
43
+
44
+ function lift(error) {
45
+ if (error === null || typeof error !== 'object' || error.engine !== true) {
46
+ return error;
47
+ }
48
+
49
+ const Class = ERRORS[error.name];
50
+
51
+ if (Class) {
52
+ return new Class(error.message, 'details' in error ? { details: error.details } : {});
53
+ }
54
+
55
+ return error.name === 'TypeError' ? new TypeError(error.message) : new Error(error.message);
56
+ }
57
+
58
+ function toUnits(text) {
59
+ const units = new Uint16Array(text.length);
60
+
61
+ for (let i = 0; i < text.length; i++) {
62
+ units[i] = text.charCodeAt(i);
63
+ }
64
+
65
+ return units;
66
+ }
67
+
68
+ function fromUnits(units) {
69
+ let text = '';
70
+
71
+ for (let i = 0; i < units.length; i += 0x2000) {
72
+ text += String.fromCharCode.apply(null, units.subarray(i, i + 0x2000));
73
+ }
74
+
75
+ return text;
76
+ }
77
+
78
+ const notJson = (value) =>
79
+ typeof value === 'function' || typeof value === 'symbol' || typeof value === 'bigint';
80
+
81
+ function toJson(value) {
82
+ return JSON.stringify(value, (_, v) => notJson(v) ? null : v);
83
+ }
84
+
85
+ function checkConfig(config) {
86
+ if (
87
+ config !== undefined &&
88
+ config !== null &&
89
+ (typeof config !== 'object' || Array.isArray(config))
90
+ ) {
91
+ throw new MicroTypoConfigError(
92
+ `invalid config: expected an object, got ${Array.isArray(config) ? 'an array' : typeof config}`,
93
+ { details: { issues: ['config: expected an object'] } }
94
+ );
95
+ }
96
+ }
97
+
98
+ function readProcessOptions(options) {
99
+ const result = {};
100
+ for (const option of ['changes', 'edits', 'trace']) {
101
+ const value = options !== null && typeof options === 'object' && Object.hasOwn(options, option)
102
+ ? options[option] : undefined;
103
+ if (value !== undefined && typeof value !== 'boolean') {
104
+ throw new MicroTypoConfigError(`process() option "${option}" must be a boolean`, {
105
+ details: { option, receivedType: typeof value }
106
+ });
107
+ }
108
+ result[option] = value === true;
109
+ }
110
+ return result;
111
+ }
112
+
113
+ function freezeGroup(group) {
114
+ return Object.freeze({ ...group, rules: Object.freeze(group.rules.map(Object.freeze)) });
115
+ }
116
+
117
+ class MicroTypo {
118
+ #engine;
119
+ #processing = false;
120
+
121
+ onCycleLimit = null;
122
+
123
+ constructor(config) {
124
+ checkConfig(config);
125
+
126
+ try {
127
+ this.#engine = new Engine(config == null ? undefined : toJson(config));
128
+ } catch (error) {
129
+ throw lift(error);
130
+ }
131
+ }
132
+
133
+ #call(method, args) {
134
+ try {
135
+ this.#engine.call(method, toJson(args));
136
+ } catch (error) {
137
+ throw lift(error);
138
+ }
139
+
140
+ return this;
141
+ }
142
+
143
+ registerRuleGroup(group, options) {
144
+ if (typeof group?.preParse === 'function' || (Array.isArray(group?.rules) && group.rules.some((rule) =>
145
+ typeof rule?.handler === 'function' ||
146
+ typeof rule?.replacement === 'function' ||
147
+ (Array.isArray(rule?.replacement) && rule.replacement.some((value) => typeof value === 'function')) ||
148
+ (Array.isArray(rule?.pattern) ? rule.pattern : [rule?.pattern]).some((pattern) => pattern instanceof RegExp)
149
+ ))) {
150
+ throw new TypeError(
151
+ 'registerRuleGroup: a rule group is JavaScript code, which the wasm engine cannot run'
152
+ );
153
+ }
154
+ return this.#call('registerRuleGroup', options === undefined ? [group] : [group, options]);
155
+ }
156
+
157
+ getRuleGroup(name) {
158
+ const json = name ? this.#engine.ruleGroup(toUnits(String(name))) : undefined;
159
+
160
+ return json === undefined ? undefined : freezeGroup(JSON.parse(json));
161
+ }
162
+
163
+ listRuleGroups() {
164
+ return Object.freeze(JSON.parse(this.#engine.ruleGroups()).map(freezeGroup));
165
+ }
166
+
167
+ addSafeTag(tag) {
168
+ if (typeof tag === 'bigint') {
169
+ JSON.stringify(tag);
170
+ }
171
+
172
+ const absent = tag === undefined || typeof tag === 'function' || typeof tag === 'symbol';
173
+
174
+ return this.#call('addSafeTag', absent ? [] : [tag]);
175
+ }
176
+
177
+ addSafeBlock(spec) {
178
+ let args = spec === undefined ? [] : [notJson(spec) ? 0 : spec];
179
+ let spellError;
180
+
181
+ if (spec !== null && typeof spec === 'object') {
182
+ const { id, open, close, unsafeRegex } = spec;
183
+ const plain =
184
+ id == null ||
185
+ typeof id === 'string' ||
186
+ typeof id === 'boolean' ||
187
+ (typeof id === 'number' && Number.isFinite(id));
188
+ let spelled = id;
189
+
190
+ if (!plain) {
191
+ try {
192
+ spelled = `${id}`;
193
+ } catch (error) {
194
+ spelled = undefined;
195
+ spellError = { error };
196
+ }
197
+ }
198
+
199
+ args = [{ id: spelled, open, close, unsafeRegex }];
200
+ }
201
+
202
+ try {
203
+ return this.#call('addSafeBlock', args);
204
+ } catch (error) {
205
+ if (
206
+ error instanceof MicroTypoConfigError &&
207
+ error.message.startsWith("safe block '") &&
208
+ error.details &&
209
+ spec != null
210
+ ) {
211
+ if (spellError) {
212
+ throw spellError.error;
213
+ }
214
+
215
+ const { id, open, close } = spec;
216
+
217
+ Object.assign(error.details, 'open' in error.details ? { id, open, close } : { id });
218
+ }
219
+
220
+ throw error;
221
+ }
222
+ }
223
+
224
+ setLayout(layout) {
225
+ if (layout !== 'style' && layout !== 'class' && layout !== 'both') {
226
+ throw new MicroTypoConfigError(
227
+ `layout must be "style", "class", or "both": ${JSON.stringify(layout)}`,
228
+ { details: { layout } }
229
+ );
230
+ }
231
+
232
+ return this.#call('setLayout', [layout]);
233
+ }
234
+
235
+ setPrefix(p) {
236
+ const prefix = p === true ? 'mt_' : p || '';
237
+ const spelled = `${prefix}`;
238
+
239
+ if (UNSAFE_PREFIX_RE.test(spelled)) {
240
+ throw new MicroTypoConfigError(
241
+ `prefix must not contain a quote, angle bracket, "&", or whitespace: ${JSON.stringify(prefix)}`,
242
+ { details: { prefix } }
243
+ );
244
+ }
245
+
246
+ return this.#call('setPrefix', [spelled]);
247
+ }
248
+
249
+ applyOptions(options) {
250
+ checkConfig(options);
251
+
252
+ return this.#call('applyOptions', options === undefined ? [] : [options]);
253
+ }
254
+
255
+ process(text, options) {
256
+ if (typeof text !== 'string') {
257
+ throw new MicroTypoInputError(`process() expects string, got ${typeof text}`, {
258
+ details: { receivedType: typeof text }
259
+ });
260
+ }
261
+
262
+ const diagnostics = readProcessOptions(options);
263
+
264
+ if (this.#processing) {
265
+ throw new MicroTypoInputError(
266
+ 'process() called reentrantly on the same MicroTypo instance; recursive process() calls are not supported',
267
+ { details: {} }
268
+ );
269
+ }
270
+
271
+ const hook = typeof this.onCycleLimit === 'function' ? this.onCycleLimit : undefined;
272
+ let units;
273
+ let failure;
274
+
275
+ this.#processing = true;
276
+
277
+ try {
278
+ try {
279
+ this.#engine.setCycleHook(hook !== undefined);
280
+ units = this.#engine.process(toUnits(text), diagnostics.changes, diagnostics.edits, diagnostics.trace);
281
+ } catch (error) {
282
+ failure = { error: lift(error) };
283
+ }
284
+
285
+ if (hook) {
286
+ for (const [id, n] of this.#engine.takeCycleLimits()) {
287
+ hook.call(undefined, id, n);
288
+ }
289
+ }
290
+ } finally {
291
+ this.#processing = false;
292
+ }
293
+
294
+ if (failure) {
295
+ throw failure.error;
296
+ }
297
+
298
+ if (diagnostics.changes || diagnostics.edits || diagnostics.trace) {
299
+ return JSON.parse(this.#engine.takeDiagnostics());
300
+ }
301
+ return fromUnits(units);
302
+ }
303
+
304
+ free() {
305
+ this.#engine.free();
306
+ }
307
+ }
308
+
309
+ function microtypo(text, options) {
310
+ return new MicroTypo(options).process(text);
311
+ }
312
+
313
+ async function compile(source) {
314
+ if (source instanceof WebAssembly.Module) return source;
315
+ if (typeof source === 'string') source = new URL(source, import.meta.url);
316
+ if (source instanceof URL) {
317
+ if (source.protocol === 'file:') {
318
+ const { readFile } = await import('node:fs/promises');
319
+ return WebAssembly.compile(await readFile(source));
320
+ }
321
+ source = fetch(source);
322
+ }
323
+ if (source instanceof Promise || source instanceof Response) {
324
+ return WebAssembly.compileStreaming(source);
325
+ }
326
+ return WebAssembly.compile(source);
327
+ }
328
+
329
+ function mismatch(found) {
330
+ return new MicroTypoVersionError(
331
+ `microtypo.wasm is ${found === undefined ? 'from another build' : `version ${found}`}, microtypo.js is version ${VERSION}`,
332
+ { details: { expected: VERSION, found } }
333
+ );
334
+ }
335
+
336
+ async function instantiate(source) {
337
+ const module = await compile(source);
338
+
339
+ if (!WebAssembly.Module.exports(module).some(({ name }) => name === 'version')) {
340
+ throw mismatch(undefined);
341
+ }
342
+
343
+ try {
344
+ initSync({ module });
345
+ } catch (error) {
346
+ throw error instanceof WebAssembly.LinkError ? mismatch(undefined) : error;
347
+ }
348
+
349
+ const found = version();
350
+
351
+ if (found !== VERSION) {
352
+ throw mismatch(found);
353
+ }
354
+
355
+ return Object.freeze({
356
+ MicroTypo,
357
+ microtypo,
358
+ VERSION,
359
+ DEFAULT_MAX_INPUT_LENGTH: defaultMaxInputLength(),
360
+ MAX_ENTRIES,
361
+ capacityError,
362
+ MicroTypoError,
363
+ MicroTypoConfigError,
364
+ MicroTypoInputError,
365
+ MicroTypoBudgetError,
366
+ MicroTypoVersionError
367
+ });
368
+ }
369
+
370
+ let loading;
371
+
372
+ export function load(source = new URL('./microtypo.wasm', import.meta.url)) {
373
+ loading ??= instantiate(source).catch((error) => {
374
+ loading = undefined;
375
+ throw error;
376
+ });
377
+
378
+ return loading;
379
+ }
package/microtypo.wasm ADDED
Binary file
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@meritt/microtypo-wasm",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.0",
4
+ "description": "Russian typography that never mangles your code, URLs, or markup: the Rust port of microtypo in WebAssembly, with the JavaScript API of microtypo",
5
+ "keywords": [
6
+ "cyrillic",
7
+ "nbsp",
8
+ "quotes",
9
+ "russian",
10
+ "russian-typography",
11
+ "typographer",
12
+ "typography",
13
+ "wasm",
14
+ "webassembly"
15
+ ],
16
+ "license": "MIT",
17
+ "author": {
18
+ "name": "Alexey Simonenko",
19
+ "email": "alexey@simonenko.dev",
20
+ "url": "https://simonenko.xyz"
21
+ },
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/meritt/microtypo.rs.git",
25
+ "directory": "packages/npm"
26
+ },
27
+ "type": "module",
28
+ "engines": {
29
+ "node": ">=26.13.0"
30
+ },
31
+ "sideEffects": false,
32
+ "exports": {
33
+ ".": "./microtypo.js",
34
+ "./microtypo.wasm": "./microtypo.wasm"
35
+ },
36
+ "files": [
37
+ "glue.js",
38
+ "microtypo.js",
39
+ "microtypo.wasm"
40
+ ],
41
+ "publishConfig": {
42
+ "access": "public"
43
+ },
44
+ "devEngines": {
45
+ "packageManager": {
46
+ "name": "pnpm",
47
+ "version": "^12.21.0",
48
+ "onFail": "download"
49
+ },
50
+ "runtime": {
51
+ "name": "node",
52
+ "version": "^26.13.1",
53
+ "onFail": "error"
54
+ }
55
+ }
6
56
  }
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.