@stll/regex-set-wasm 1.0.5 → 1.0.8

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/wasm.mjs CHANGED
@@ -1,40 +1,930 @@
1
- import { WASI, getDefaultContext, instantiateNapiModuleSync } from "@napi-rs/wasm-runtime";
1
+ import { WASI, emnapiAsyncWorkPlugin, emnapiTSFNPlugin, instantiateNapiModule } from "@napi-rs/wasm-runtime";
2
+ import { createContext } from "@emnapi/runtime";
2
3
  //#region regex-set.wasi-browser.js
4
+ const __napiBindingTarget = "wasm32-wasi";
5
+ function __napiStampBindingTarget(exportsObject, target) {
6
+ if (Object.prototype.hasOwnProperty.call(exportsObject, "__napiBindingTarget")) {
7
+ if (exportsObject.__napiBindingTarget === target) return target;
8
+ const error = /* @__PURE__ */ new Error("`__napiBindingTarget` is reserved by the generated binding loader, but the loaded binding already exports it. Rename the export, e.g. #[napi(js_name = \"...\")].");
9
+ error.code = "ERR_NAPI_BINDING_TARGET_CONFLICT";
10
+ throw error;
11
+ }
12
+ if (!Object.isExtensible(exportsObject)) return target;
13
+ try {
14
+ Object.defineProperty(exportsObject, "__napiBindingTarget", {
15
+ configurable: true,
16
+ enumerable: true,
17
+ value: target,
18
+ writable: true
19
+ });
20
+ } catch {}
21
+ return target;
22
+ }
3
23
  const __wasi = new WASI({ version: "preview1" });
4
24
  const __wasmUrl = new URL("./regex-set.wasm32-wasi.wasm", import.meta.url).href;
5
- const __emnapiContext = getDefaultContext();
25
+ const __wasmResponse = await globalThis.fetch(__wasmUrl);
26
+ if (!__wasmResponse.ok) throw new Error("Failed to fetch WASI module " + __wasmUrl + ": " + __wasmResponse.status + " " + (__wasmResponse.statusText || "Unknown Status"));
27
+ const __wasmFile = await __wasmResponse.arrayBuffer();
28
+ const __wasmView = new Uint8Array(__wasmFile);
29
+ if (__wasmView.length < 4 || __wasmView[0] !== 0 || __wasmView[1] !== 97 || __wasmView[2] !== 115 || __wasmView[3] !== 109) throw new Error("@stll/regex-set-wasm failed to load its .wasm binary. The response did not contain WebAssembly bytes, which commonly happens when a bundler (Vite, webpack dev server, etc.) rewrites import.meta.url during pre-bundling.\n\nIf you are using Vite, import the bundled plugin:\n import stllWasm from \"@stll/regex-set-wasm/vite\"\n // ...\n plugins: [stllWasm()]");
6
30
  const __sharedMemory = new WebAssembly.Memory({
7
31
  initial: 4e3,
8
32
  maximum: 65536,
9
33
  shared: true
10
34
  });
11
- const { instance: __napiInstance, module: __wasiModule, napiModule: __napiModule } = instantiateNapiModuleSync(await fetch(__wasmUrl).then(async (res) => {
12
- const bytes = await res.arrayBuffer();
13
- const view = new Uint8Array(bytes);
14
- if (view.length < 4 || view[0] !== 0 || view[1] !== 97 || view[2] !== 115 || view[3] !== 109) throw new Error("@stll/regex-set-wasm failed to load its .wasm binary. The response did not contain WebAssembly bytes, which commonly happens when a bundler (Vite, webpack dev server, etc.) rewrites import.meta.url during pre-bundling.\n\nIf you are using Vite, import the bundled plugin:\n import stllWasm from \"@stll/regex-set-wasm/vite\"\n // ...\n plugins: [stllWasm()]");
15
- return bytes;
16
- }), {
17
- context: __emnapiContext,
18
- asyncWorkPoolSize: 4,
19
- wasi: __wasi,
20
- onCreateWorker() {
21
- return new Worker(new URL("./wasi-worker-browser.mjs", import.meta.url), { type: "module" });
22
- },
23
- overwriteImports(importObject) {
24
- importObject.env = {
25
- ...importObject.env,
26
- ...importObject.napi,
27
- ...importObject.emnapi,
28
- memory: __sharedMemory
35
+ const __asyncWorkPoolSize = 4;
36
+ const __workerPoolSize = Math.max(2, globalThis.navigator?.hardwareConcurrency ?? 4);
37
+ let __emnapiContext;
38
+ const __wasiDisposeSymbol = Symbol.for("napi.rs.wasi.dispose");
39
+ const __wasiWorkers = /* @__PURE__ */ new Set();
40
+ let __wasiThreadManager;
41
+ function __captureWasiThreadManager(context) {
42
+ if (context && context.PThread) __wasiThreadManager = context.PThread;
43
+ return {};
44
+ }
45
+ function __getWasiThreadManager() {
46
+ const manager = __wasiThreadManager !== void 0 ? __wasiThreadManager : __napiModule ? __napiModule.PThread : void 0;
47
+ if (manager && typeof manager.terminateWorker === "function") return manager;
48
+ }
49
+ let __napiInstance;
50
+ let __emnapiContextDestroyed = false;
51
+ let __emnapiContextDestroyPromise;
52
+ let __emnapiWasmEnvCleanupPrepared = false;
53
+ let __emnapiWasmEnvCleanupPreparing = false;
54
+ let __finishParkedWasmEnvCleanup;
55
+ let __emnapiWasmEnvCleanupYielding = false;
56
+ let __emnapiWasmEnvSettlementLossReported = false;
57
+ let __emnapiWasmEnvCleanupRan = false;
58
+ let __emnapiWasmEnvCleanupDrained = false;
59
+ let __emnapiWasmEnvCleanupDrainPromise;
60
+ let __wasiDisposed = false;
61
+ let __wasiAsyncWorkDrainPromise;
62
+ let __wasiDisposePromise;
63
+ let __completeWasiDisposal = function() {};
64
+ function __isThenable(value) {
65
+ return value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
66
+ }
67
+ function __createCleanupError(errors, message) {
68
+ if (errors.length === 1) return errors[0];
69
+ const __AggregateError = globalThis.AggregateError;
70
+ if (typeof __AggregateError === "function") return new __AggregateError(errors, message);
71
+ const error = new Error(message);
72
+ error.errors = errors;
73
+ return error;
74
+ }
75
+ function __attachCleanupErrors(error, cleanupErrors) {
76
+ if (cleanupErrors.length === 0) return error;
77
+ const cleanupError = __createCleanupError(cleanupErrors, "WASI binding cleanup failed");
78
+ try {
79
+ if (error && (typeof error === "object" || typeof error === "function")) {
80
+ if (error.cause === void 0) {
81
+ error.cause = cleanupError;
82
+ if (error.cause === cleanupError) return error;
83
+ }
84
+ if (Array.isArray(error.cleanupErrors)) {
85
+ error.cleanupErrors.push(cleanupError);
86
+ return error;
87
+ } else {
88
+ const attachedCleanupErrors = [cleanupError];
89
+ error.cleanupErrors = attachedCleanupErrors;
90
+ if (error.cleanupErrors === attachedCleanupErrors) return error;
91
+ }
92
+ }
93
+ } catch {}
94
+ const aggregate = __createCleanupError([error, cleanupError], "WASI binding initialization and cleanup failed");
95
+ try {
96
+ aggregate.cause = error;
97
+ } catch {}
98
+ return aggregate;
99
+ }
100
+ function __wrapEmnapiContextDestroyForSettlement(context, prepareEnvCleanup, isPreparingEnvCleanup) {
101
+ let destroy;
102
+ try {
103
+ destroy = context.destroy;
104
+ } catch {
105
+ return context;
106
+ }
107
+ if (typeof destroy !== "function") return context;
108
+ try {
109
+ Object.defineProperty(context, "destroy", {
110
+ configurable: true,
111
+ enumerable: false,
112
+ writable: true,
113
+ value: function() {
114
+ if (isPreparingEnvCleanup?.()) return;
115
+ prepareEnvCleanup?.();
116
+ return Reflect.apply(destroy, this, arguments);
117
+ }
118
+ });
119
+ } catch {}
120
+ return context;
121
+ }
122
+ function __isPreparingWasmEnvCleanup() {
123
+ return __emnapiWasmEnvCleanupPreparing;
124
+ }
125
+ function __prepareWasmEnvCleanup() {
126
+ if (__emnapiWasmEnvCleanupPrepared) return;
127
+ const finishParked = __finishParkedWasmEnvCleanup;
128
+ if (finishParked !== void 0) {
129
+ finishParked();
130
+ __reportUnreachedWasmEnvSettlements();
131
+ return;
132
+ }
133
+ if (__emnapiWasmEnvCleanupPreparing) return;
134
+ const prepare = __napiInstance?.exports?.napi_prepare_wasm_env_cleanup;
135
+ if (typeof prepare === "function") {
136
+ __emnapiWasmEnvCleanupPreparing = true;
137
+ try {
138
+ prepare();
139
+ } finally {
140
+ __emnapiWasmEnvCleanupPreparing = false;
141
+ }
142
+ __emnapiWasmEnvCleanupRan = true;
143
+ __reportUnreachedWasmEnvSettlements();
144
+ }
145
+ __emnapiWasmEnvCleanupPrepared = true;
146
+ }
147
+ /**
148
+ * Say so when the barrier leaves settlements queued and nothing is left that
149
+ * could deliver them.
150
+ *
151
+ * Only the disposal chain yields the event-loop turns @emnapi/core needs to
152
+ * dispatch its queue. Every other caller of the barrier destroys in the same
153
+ * turn — a raw `Context.destroy()`, the 'exit' teardown — and
154
+ * `Context.destroy()` runs the threadsafe function's cleanup hook, which drains
155
+ * that queue with a null env and discards it. The promises those settlements
156
+ * were for then hang forever, silently.
157
+ *
158
+ * Loud, once, and never throwing: this runs from inside `Context.destroy()`,
159
+ * emnapi's own beforeExit destroy included, where throwing would take the whole
160
+ * teardown down with it. Destroying anyway is still the right trade — the queue
161
+ * is already unreachable by then.
162
+ */
163
+ function __reportUnreachedWasmEnvSettlements() {
164
+ if (__emnapiWasmEnvCleanupYielding || __emnapiWasmEnvSettlementLossReported) return;
165
+ const pending = __napiInstance?.exports?.napi_wasm_env_cleanup_pending;
166
+ if (typeof pending !== "function") return;
167
+ let queued;
168
+ try {
169
+ queued = pending();
170
+ } catch {
171
+ return;
172
+ }
173
+ if (!queued) return;
174
+ __emnapiWasmEnvSettlementLossReported = true;
175
+ try {
176
+ const consoleHost = globalThis.console;
177
+ if (consoleHost && typeof consoleHost.error === "function") consoleHost.error("napi-rs: the wasm environment is being destroyed with " + queued + " queued promise settlement(s). Context.destroy() discards them, so those promises never settle. Dispose with binding[Symbol.for('napi.rs.wasi.dispose')]() instead: only it yields the event-loop turns the settlements need.");
178
+ } catch {}
179
+ }
180
+ const __scheduleMacrotask = (function() {
181
+ if (typeof setImmediate === "function") return function(callback) {
182
+ setImmediate(callback);
183
+ };
184
+ const __MessageChannel = globalThis.MessageChannel;
185
+ if (typeof __MessageChannel === "function") return function(callback) {
186
+ const channel = new __MessageChannel();
187
+ channel.port1.onmessage = function() {
188
+ channel.port1.onmessage = null;
189
+ try {
190
+ channel.port1.close();
191
+ } catch {}
192
+ try {
193
+ channel.port2.close();
194
+ } catch {}
195
+ callback();
29
196
  };
30
- return importObject;
31
- },
32
- beforeInit({ instance }) {
33
- for (const name of Object.keys(instance.exports)) if (name.startsWith("__napi_register__")) instance.exports[name]();
197
+ channel.port2.postMessage(null);
198
+ };
199
+ return function(callback) {
200
+ setTimeout(callback, 0);
201
+ };
202
+ })();
203
+ function __scheduleTimer(callback, delay) {
204
+ const setTimer = globalThis.setTimeout;
205
+ if (typeof setTimer !== "function") {
206
+ __scheduleMacrotask(callback);
207
+ return;
34
208
  }
35
- });
209
+ try {
210
+ setTimer(callback, delay);
211
+ } catch {
212
+ __scheduleMacrotask(callback);
213
+ }
214
+ }
215
+ const __WASM_RUNTIME_WORK_POLL_INTERVAL_MS = 1;
216
+ const __WASM_RUNTIME_WORK_POLL_TRUSTED_ARRIVALS = 2;
217
+ const __WASM_RUNTIME_WORK_POLL_STALL_MS = 50;
218
+ const __WASM_RUNTIME_WORK_POLL_BACKUP_MS = 200;
219
+ /**
220
+ * Pacing state for one runtime-work poll.
221
+ *
222
+ * Per poll, never per module: whether the host's timers arrive is not a
223
+ * property of the module. A host can lose its timers between two disposals,
224
+ * and in the deferred shape every instance shares this module — one healthy
225
+ * instance must not disarm the fallback for the next one.
226
+ */
227
+ function __createWasmRuntimePollPace() {
228
+ return {
229
+ arrivals: 0,
230
+ settleTurn: void 0,
231
+ turnTimerDueAt: 0
232
+ };
233
+ }
234
+ /**
235
+ * The backup that ends a turn whose timer is never going to arrive.
236
+ *
237
+ * Once the poll paces on the timer alone it has nothing left to fall back on
238
+ * if the host's timers stop mid-poll: the turn that armed the dead timer is
239
+ * the turn that parks, and a parked poll schedules nothing that could notice.
240
+ * So every turn arms one of these before it yields, and each one compares due
241
+ * times instead of measuring how long the parked turn has been waiting.
242
+ *
243
+ * Invariant: a parked turn is ended by the newest backup that was armed while
244
+ * the host's timers still worked, and a backup ends a turn only when that
245
+ * turn's own timer was already due a whole window before the backup itself.
246
+ * Neither half turns on how far apart the arms happen to fall — what bounds
247
+ * the rescue is how far back that newest live backup is:
248
+ *
249
+ * - *Ends it.* Hosts run timers in due order, so a backup that runs while a
250
+ * turn due a whole window earlier is still parked proves that turn's timer
251
+ * was dropped rather than merely late. That same comparison is what leaves a
252
+ * healthy host alone: there the turn's timer has already run and cleared
253
+ * `settleTurn` before any backup due after it can look.
254
+ * - *Two turns back, not one.* A turn that ended does not prove its own timer
255
+ * arrived: until `…_TRUSTED_ARRIVALS` is reached every turn arms both
256
+ * primitives and the macrotask wins, so such a turn can end with its own
257
+ * timer — and the backup armed one line before it — already dead. The
258
+ * arrival that then flips the poll onto the timer alone can itself be a
259
+ * timer armed before the host's timers died. So the turn that parks can sit
260
+ * two turns past the last live arm, and the newest live backup is due
261
+ * `…_BACKUP_MS` less *two* turn lengths after that turn's own timer.
262
+ * Arming on every turn is what holds it to two, rather than however far back
263
+ * a throttle last let one through.
264
+ * - *Ceiling.* Coverage therefore holds while two consecutive poll turns fit
265
+ * inside `…_BACKUP_MS` less the slack and one interval: 149 ms, so 74 ms
266
+ * per turn (measured: a 74 ms turn is still rescued, a 75 ms one parks).
267
+ * Past that the turn stays parked and the disposal promise never settles.
268
+ * The bound is deliberate: reaching it takes a host that drops timers
269
+ * mid-poll *and* keeps every poll turn busy for more than 74 ms, and neither
270
+ * Node nor WebContainer — the hosts that run the threaded artifact — does
271
+ * the second.
272
+ *
273
+ * The poll then goes back to arming both primitives until two fresh arrivals
274
+ * prove the timers again. A host that stops running the timers it has
275
+ * *already* accepted leaves nothing to fire, and the disposal promise stays
276
+ * pending rather than wedging the thread — the same outcome as a blocking
277
+ * closure that never returns. Unreferenced wherever the host allows it: the
278
+ * poll's own turn timers are what keep the loop alive, never these.
279
+ */
280
+ function __armWasmRuntimePollStallBackup(pace) {
281
+ const setTimer = globalThis.setTimeout;
282
+ if (typeof setTimer !== "function") return;
283
+ const dueAt = Date.now() + __WASM_RUNTIME_WORK_POLL_BACKUP_MS;
284
+ let handle;
285
+ try {
286
+ handle = setTimer(() => {
287
+ const settleTurn = pace.settleTurn;
288
+ if (!settleTurn || pace.turnTimerDueAt > dueAt - __WASM_RUNTIME_WORK_POLL_STALL_MS) return;
289
+ pace.arrivals = 0;
290
+ pace.settleTurn = void 0;
291
+ settleTurn();
292
+ }, __WASM_RUNTIME_WORK_POLL_BACKUP_MS);
293
+ } catch {
294
+ return;
295
+ }
296
+ if (handle && typeof handle.unref === "function") try {
297
+ handle.unref();
298
+ } catch {}
299
+ }
300
+ /**
301
+ * One turn of the runtime-work poll.
302
+ *
303
+ * `__scheduleTimer` falls back to the macrotask scheduler when `setTimeout` is
304
+ * missing or throws, but not when it is present, returns a handle and never
305
+ * fires — fake timers in a test suite that disposes from an `afterEach`, or a
306
+ * host whose timers belong to an IO context that is already gone. That host
307
+ * would park this poll forever, and the poll is unbounded, so nothing would
308
+ * ever call `…_finish`.
309
+ *
310
+ * Arm both primitives until timers armed by this poll have arrived twice, and
311
+ * let whichever lands first end the turn; the loser resolves nothing. A host
312
+ * with working timers therefore pays the double arming for the first turn or
313
+ * two — the macrotask wins the race, but the timers behind it still arrive and
314
+ * are counted — and paces on the timer alone from then on, instead of spinning
315
+ * the loop on a zero-delay queue. A host whose timers never arrive keeps both,
316
+ * and the macrotask is what keeps the poll moving. A host whose timers stop
317
+ * after proving themselves is caught by `__armWasmRuntimePollStallBackup`,
318
+ * which ends the parked turn and puts this poll back on both.
319
+ */
320
+ function __yieldWasmRuntimePollTurn(pace) {
321
+ __armWasmRuntimePollStallBackup(pace);
322
+ return new Promise((resolve) => {
323
+ let settled = false;
324
+ const settle = () => {
325
+ if (settled) return;
326
+ settled = true;
327
+ if (pace.settleTurn === settle) pace.settleTurn = void 0;
328
+ resolve();
329
+ };
330
+ __scheduleTimer(() => {
331
+ pace.arrivals++;
332
+ settle();
333
+ }, __WASM_RUNTIME_WORK_POLL_INTERVAL_MS);
334
+ const turnTimerDueAt = Date.now() + __WASM_RUNTIME_WORK_POLL_INTERVAL_MS;
335
+ if (pace.arrivals < __WASM_RUNTIME_WORK_POLL_TRUSTED_ARRIVALS) {
336
+ __scheduleMacrotask(settle);
337
+ return;
338
+ }
339
+ pace.settleTurn = settle;
340
+ pace.turnTimerDueAt = turnTimerDueAt;
341
+ });
342
+ }
343
+ /**
344
+ * The barrier for callers that can yield: `__prepareWasmEnvCleanup` with real
345
+ * event-loop turns in the middle.
346
+ *
347
+ * `napi_prepare_wasm_env_cleanup` waits — it returns only once the addon's
348
+ * async runtime has quiesced, and on `wasm32-wasip1-threads` the thread it
349
+ * waits on is this one, the only thread that can give a running blocking
350
+ * closure the JavaScript turn *it* is waiting for. A single call there can wait
351
+ * for work that can never finish. The addon's two-phase form splits that:
352
+ * `…_begin` stops the runtime without joining and reports whether anything is
353
+ * still live, `napi_wasm_runtime_work_pending` answers that question again
354
+ * without blocking, and `…_finish` joins. The turns yielded in between are the
355
+ * entire point.
356
+ *
357
+ * The poll has no deadline, for the same reason the async-work drain below has
358
+ * none: giving up means calling `…_finish`, which joins on this thread, and the
359
+ * work it would join is the work that is waiting for a turn from this thread —
360
+ * so a bound does not end the wait, it only moves it somewhere the JavaScript
361
+ * thread can no longer be reached. A blocking closure that never returns keeps
362
+ * the disposal promise pending instead, exactly as a task whose `execute` never
363
+ * returns already keeps an *undisposed* process alive. The host contract is in
364
+ * `crates/async-runtime/README.md`: a blocking closure must never wait on a
365
+ * JavaScript turn. The process-exit path still blocks in `…_finish`, because it
366
+ * has no turns left to give (see `__prepareWasmEnvCleanup`).
367
+ *
368
+ * Feature-detected like every other export in this teardown, so an addon built
369
+ * against a napi crate that predates the split keeps the single blocking call.
370
+ * Returns nothing whenever the handshake finished without yielding, which keeps
371
+ * an idle disposal synchronous.
372
+ */
373
+ function __prepareWasmEnvCleanupWithTurns() {
374
+ if (__emnapiWasmEnvCleanupPrepared || __emnapiWasmEnvCleanupPreparing) return;
375
+ const exports = __napiInstance?.exports;
376
+ const begin = exports?.napi_prepare_wasm_env_cleanup_begin;
377
+ const finish = exports?.napi_prepare_wasm_env_cleanup_finish;
378
+ if (typeof begin !== "function" || typeof finish !== "function") {
379
+ __emnapiWasmEnvCleanupYielding = true;
380
+ try {
381
+ __prepareWasmEnvCleanup();
382
+ } finally {
383
+ __emnapiWasmEnvCleanupYielding = false;
384
+ }
385
+ return;
386
+ }
387
+ const workPending = exports?.napi_wasm_runtime_work_pending;
388
+ __emnapiWasmEnvCleanupPreparing = true;
389
+ let live;
390
+ try {
391
+ live = begin();
392
+ } catch (error) {
393
+ __emnapiWasmEnvCleanupPreparing = false;
394
+ throw error;
395
+ }
396
+ __emnapiWasmEnvCleanupRan = true;
397
+ const finishCleanup = () => {
398
+ if (__emnapiWasmEnvCleanupPrepared) return;
399
+ __finishParkedWasmEnvCleanup = void 0;
400
+ try {
401
+ finish();
402
+ } finally {
403
+ __emnapiWasmEnvCleanupPreparing = false;
404
+ }
405
+ __emnapiWasmEnvCleanupPrepared = true;
406
+ };
407
+ if (!live || typeof workPending !== "function") {
408
+ finishCleanup();
409
+ return;
410
+ }
411
+ __finishParkedWasmEnvCleanup = finishCleanup;
412
+ return (async () => {
413
+ const pace = __createWasmRuntimePollPace();
414
+ for (;;) {
415
+ await __yieldWasmRuntimePollTurn(pace);
416
+ try {
417
+ if (!workPending()) return;
418
+ } catch {
419
+ return;
420
+ }
421
+ }
422
+ })().then(finishCleanup, finishCleanup);
423
+ }
424
+ const __WASM_ENV_CLEANUP_DRAIN_TURNS = 128;
425
+ const __WASM_ENV_CLEANUP_BLIND_DRAIN_TURNS = 4;
426
+ /**
427
+ * `napi_prepare_wasm_env_cleanup` only *queues* the promise settlements of the
428
+ * tasks it cancelled: `napi_call_threadsafe_function` appends to the
429
+ * threadsafe-function queue, and @emnapi/core dispatches that queue from a
430
+ * macrotask — two coalescing turns later, even for a call made on this very
431
+ * thread. `Context.destroy()` then runs the threadsafe function's cleanup hook,
432
+ * which drains the queue with a null env and *discards* whatever is still in it.
433
+ *
434
+ * So destroying without yielding first strands exactly the promises the barrier
435
+ * exists to settle. Yield real event-loop turns until the addon reports the
436
+ * queue empty; microtask checkpoints cannot help, no number of them lets a
437
+ * macrotask run.
438
+ *
439
+ * Returns nothing when there is nothing to wait for, which keeps disposal
440
+ * synchronous in the common case.
441
+ *
442
+ * The "already drained" flag is set only once a wait has actually finished.
443
+ * Scheduling a macrotask can fail — a host-provided or patched `setImmediate`
444
+ * that throws is enough — and a disposal that rejects stays retryable, so
445
+ * marking the drain complete up front would make the retry skip it and destroy
446
+ * the context with the barrier's settlements still queued.
447
+ *
448
+ * A wait that runs out of turns with the counter still nonzero rejects with
449
+ * `ERR_NAPI_WASI_CLEANUP_PENDING` for the same reason: at that point
450
+ * "finished" is indistinguishable from the stranding above, and destroying
451
+ * would discard the very settlement the wait was for. The rejection leaves the
452
+ * flag unset and disposal retryable.
453
+ */
454
+ function __drainWasmEnvCleanup() {
455
+ if (__emnapiWasmEnvCleanupDrained || !__emnapiWasmEnvCleanupRan) return;
456
+ if (__emnapiWasmEnvCleanupDrainPromise) return __emnapiWasmEnvCleanupDrainPromise;
457
+ const pending = __napiInstance?.exports?.napi_wasm_env_cleanup_pending;
458
+ const observable = typeof pending === "function";
459
+ if (observable) {
460
+ let queued;
461
+ try {
462
+ queued = pending();
463
+ } catch {
464
+ __emnapiWasmEnvCleanupDrained = true;
465
+ return;
466
+ }
467
+ if (!queued) {
468
+ __emnapiWasmEnvCleanupDrained = true;
469
+ return;
470
+ }
471
+ }
472
+ const limit = observable ? __WASM_ENV_CLEANUP_DRAIN_TURNS : __WASM_ENV_CLEANUP_BLIND_DRAIN_TURNS;
473
+ const drainPromise = (async () => {
474
+ let queued = 0;
475
+ for (let turn = 0; turn < limit; turn++) {
476
+ await new Promise((resolve) => {
477
+ __scheduleMacrotask(resolve);
478
+ });
479
+ if (!observable) continue;
480
+ try {
481
+ queued = pending();
482
+ } catch {
483
+ return;
484
+ }
485
+ if (!queued) return;
486
+ }
487
+ if (!observable) return;
488
+ const drainError = /* @__PURE__ */ new Error("the wasm environment still reports " + queued + " queued settlement(s) after " + limit + " event-loop turns; the context was not destroyed - retry dispose() to wait for the queue again");
489
+ drainError.code = "ERR_NAPI_WASI_CLEANUP_PENDING";
490
+ throw drainError;
491
+ })().then((value) => {
492
+ __emnapiWasmEnvCleanupDrained = true;
493
+ __emnapiWasmEnvCleanupDrainPromise = void 0;
494
+ return value;
495
+ }, (error) => {
496
+ __emnapiWasmEnvCleanupDrainPromise = void 0;
497
+ throw error;
498
+ });
499
+ __emnapiWasmEnvCleanupDrainPromise = drainPromise;
500
+ return drainPromise;
501
+ }
502
+ function __destroyEmnapiContext() {
503
+ if (__emnapiContextDestroyed || __emnapiContext === void 0) {
504
+ __emnapiContextDestroyed = true;
505
+ return;
506
+ }
507
+ if (__emnapiContextDestroyPromise) return __emnapiContextDestroyPromise;
508
+ __prepareWasmEnvCleanup();
509
+ if (__isPreparingWasmEnvCleanup()) return;
510
+ const result = __emnapiContext.destroy();
511
+ if (!__isThenable(result)) {
512
+ __emnapiContextDestroyed = true;
513
+ return;
514
+ }
515
+ const destroyPromise = Promise.resolve(result).then((value) => {
516
+ __emnapiContextDestroyed = true;
517
+ return value;
518
+ }, (error) => {
519
+ __emnapiContextDestroyPromise = void 0;
520
+ throw error;
521
+ });
522
+ __emnapiContextDestroyPromise = destroyPromise;
523
+ return destroyPromise;
524
+ }
525
+ /**
526
+ * Holds the event loop open until `work` settles.
527
+ *
528
+ * Nothing else can: the pool workers are deliberately unreferenced so an idle
529
+ * binding cannot keep a process alive, and referencing them again for the
530
+ * termination does not hold either — emnapi unreferences a worker the moment it
531
+ * reports `async-thread-ready`, which for a worker that was still starting
532
+ * lands *after* the termination began. Without a handle of its own, an
533
+ * `await dispose()` with nothing else pending exits the process with its
534
+ * promise unsettled, and everything after the `await` is skipped.
535
+ *
536
+ * The timer is cleared as soon as the work settles, so this never outlives the
537
+ * disposal that asked for it.
538
+ */
539
+ function __keepEventLoopAliveUntil(work) {
540
+ const setTimer = globalThis.setInterval;
541
+ const clearTimer = globalThis.clearInterval;
542
+ if (typeof setTimer !== "function" || typeof clearTimer !== "function") return work;
543
+ let timer;
544
+ try {
545
+ timer = setTimer(function() {}, 50);
546
+ } catch {
547
+ return work;
548
+ }
549
+ const release = function() {
550
+ try {
551
+ clearTimer(timer);
552
+ } catch {}
553
+ };
554
+ return work.then((value) => {
555
+ release();
556
+ return value;
557
+ }, (error) => {
558
+ release();
559
+ throw error;
560
+ });
561
+ }
562
+ const __WASI_ASYNC_WORK_POLL_INTERVAL_MS = 1;
563
+ /**
564
+ * Settles this addon's outstanding `napi_async_work` before the teardown that
565
+ * would strand it.
566
+ *
567
+ * `napi_prepare_wasm_env_cleanup` does not cover async work, and nothing about
568
+ * it is observable from JavaScript: the threadless archive resolves
569
+ * `napi_*_async_work` through the `@emnapi/core` plugins, but the threaded one
570
+ * links the C `async_work.c` on the uv threadpool, so there the wasm neither
571
+ * imports nor exports those symbols and the only brackets a loader could watch
572
+ * (`_emnapi_ctx_*_waiting_request_counter`) are shared with threadsafe
573
+ * functions. The addon is the one place both flavors go through, so it answers
574
+ * for both, through the same kind of handshake the settlement drain uses:
575
+ *
576
+ * - `napi_wasm_cancel_pending_async_work()` cancels what no thread has
577
+ * started. Those completion callbacks run with `napi_cancelled`, which
578
+ * napi-rs turns into a promise rejected with an `AbortError`.
579
+ * - `napi_wasm_async_work_pending()` counts what is still owed a completion
580
+ * callback. Work already executing refuses cancellation and stays counted
581
+ * until it finishes normally — which it can, because this runs before the
582
+ * barrier, before `Context.destroy()` and before anything is terminated.
583
+ *
584
+ * Both exports are optional: an addon built against a napi crate that predates
585
+ * them drains nothing and keeps the previous behavior, exactly as the
586
+ * `napi_wasm_env_cleanup_pending` handshake degrades.
587
+ *
588
+ * Returns nothing when there is nothing outstanding, which keeps disposal
589
+ * synchronous in the common case. The promise it returns otherwise never
590
+ * rejects.
591
+ *
592
+ * The wait has no deadline, and that is the point: giving up would destroy the
593
+ * environment with a completion callback still owed, which is the stranding
594
+ * this exists to prevent. A task whose `execute` never returns already keeps an
595
+ * *undisposed* process alive in exactly the same way, so disposal inherits that
596
+ * rather than inventing a bound it cannot honor.
597
+ *
598
+ * Safe to call from inside a completion callback, which is reachable: settling
599
+ * a task runs addon code that can re-enter JavaScript — a setter on the value
600
+ * being handed back, a threadsafe-function callback — and that JavaScript can
601
+ * call `dispose()`. Two things make it terminate rather than wait on itself:
602
+ *
603
+ * - The addon keeps a work registered until its completion callback
604
+ * *finishes*, so the count read here is at least one and this takes the
605
+ * polling path instead of declaring the environment drained and tearing it
606
+ * down from inside the frame that is still settling a promise.
607
+ * - The poll is a timer, so it cannot run until the callback has returned to
608
+ * the host — by which time that work has left the registry. The count the
609
+ * next poll reads is the one taken after the callback finished.
610
+ *
611
+ * `__disposeWasiBinding` hands every caller the same in-flight promise, so the
612
+ * nested call joins this disposal rather than starting a second one.
613
+ */
614
+ function __drainWasiAsyncWork() {
615
+ if (__wasiAsyncWorkDrainPromise !== void 0) return __wasiAsyncWorkDrainPromise;
616
+ const exports = __napiInstance?.exports;
617
+ const pending = exports?.napi_wasm_async_work_pending;
618
+ const cancelPending = exports?.napi_wasm_cancel_pending_async_work;
619
+ if (typeof pending !== "function" || typeof cancelPending !== "function") return;
620
+ const readPending = () => {
621
+ try {
622
+ return pending();
623
+ } catch (error) {
624
+ if (error instanceof globalThis.WebAssembly.RuntimeError) return 0;
625
+ throw error;
626
+ }
627
+ };
628
+ if (!readPending()) return;
629
+ try {
630
+ cancelPending();
631
+ } catch {}
632
+ if (!readPending()) return;
633
+ const drainPromise = __keepEventLoopAliveUntil((async () => {
634
+ while (readPending()) await new Promise((resolve) => {
635
+ __scheduleTimer(resolve, __WASI_ASYNC_WORK_POLL_INTERVAL_MS);
636
+ });
637
+ })()).then(() => {
638
+ __wasiAsyncWorkDrainPromise = void 0;
639
+ }, (error) => {
640
+ __wasiAsyncWorkDrainPromise = void 0;
641
+ throw error;
642
+ });
643
+ __wasiAsyncWorkDrainPromise = drainPromise;
644
+ return drainPromise;
645
+ }
646
+ /**
647
+ * `@emnapi/wasi-threads` counts a worker exit as expected only when its own
648
+ * thread manager performed the termination. A bare `worker.terminate()` reaches
649
+ * the manager's `exit` listener instead, which reports
650
+ * `worker (tid = N) sent an error! ... stopped with exit code 1` and rethrows
651
+ * inside the emit — aborting the `once('exit')` that backs the terminate
652
+ * promise, so disposal never settles and the process dies with an uncaught
653
+ * exception. Mark the termination through the manager first.
654
+ *
655
+ * The manager comes from `__getWasiThreadManager`, not from `__napiModule`:
656
+ * the initialization rollback runs on the one path where instantiation never
657
+ * returned, so `__napiModule` is still undefined there while the workers it
658
+ * spawned are already registered and loaded.
659
+ *
660
+ * Not `terminateAllThreads()`: that one recreates the pool it just shut down.
661
+ */
662
+ function __terminateWasiWorkers() {
663
+ const cleanupErrors = [];
664
+ const pending = [];
665
+ const threadManager = __getWasiThreadManager();
666
+ for (const worker of __wasiWorkers) {
667
+ let result;
668
+ try {
669
+ if (threadManager) {
670
+ threadManager.terminateWorker(worker);
671
+ worker.onmessage = void 0;
672
+ }
673
+ result = worker.terminate();
674
+ } catch (error) {
675
+ cleanupErrors.push(error);
676
+ continue;
677
+ }
678
+ if (__isThenable(result)) pending.push(Promise.resolve(result).then(() => {
679
+ __wasiWorkers.delete(worker);
680
+ }, (error) => {
681
+ cleanupErrors.push(error);
682
+ }));
683
+ else __wasiWorkers.delete(worker);
684
+ }
685
+ const finish = () => {
686
+ if (cleanupErrors.length > 0) throw __createCleanupError(cleanupErrors, "Failed to terminate WASI workers");
687
+ };
688
+ return pending.length > 0 ? __keepEventLoopAliveUntil(Promise.all(pending)).then(finish) : finish();
689
+ }
690
+ function __finishWasiDisposal() {
691
+ const workerResult = __terminateWasiWorkers();
692
+ if (__isThenable(workerResult)) return Promise.resolve(workerResult).then(__completeWasiDisposal);
693
+ }
694
+ function __continueWasiDisposal() {
695
+ const destroyResult = __destroyEmnapiContext();
696
+ if (__isThenable(destroyResult)) return Promise.resolve(destroyResult).then(__finishWasiDisposal);
697
+ return __finishWasiDisposal();
698
+ }
699
+ function __drainWasmEnvForWasiDisposal() {
700
+ const drainResult = __drainWasmEnvCleanup();
701
+ if (__isThenable(drainResult)) return Promise.resolve(drainResult).then(__continueWasiDisposal);
702
+ return __continueWasiDisposal();
703
+ }
704
+ function __cleanUpWasmEnvForWasiDisposal() {
705
+ const prepareResult = __prepareWasmEnvCleanupWithTurns();
706
+ if (__isThenable(prepareResult)) return Promise.resolve(prepareResult).then(__drainWasmEnvForWasiDisposal);
707
+ return __drainWasmEnvForWasiDisposal();
708
+ }
709
+ function __startWasiDisposal() {
710
+ const asyncWorkResult = __drainWasiAsyncWork();
711
+ if (__isThenable(asyncWorkResult)) return Promise.resolve(asyncWorkResult).then(__cleanUpWasmEnvForWasiDisposal);
712
+ return __cleanUpWasmEnvForWasiDisposal();
713
+ }
714
+ /**
715
+ * Disposes this generated WASI binding.
716
+ *
717
+ * Access this function with:
718
+ * binding[Symbol.for('napi.rs.wasi.dispose')]()
719
+ */
720
+ function __disposeWasiBinding() {
721
+ if (__wasiDisposePromise) return __wasiDisposePromise;
722
+ if (__wasiDisposed) return Promise.resolve();
723
+ let resolveDispose;
724
+ let rejectDispose;
725
+ const disposePromise = new Promise((resolve, reject) => {
726
+ resolveDispose = resolve;
727
+ rejectDispose = reject;
728
+ });
729
+ __wasiDisposePromise = disposePromise;
730
+ let result;
731
+ try {
732
+ result = __startWasiDisposal();
733
+ } catch (error) {
734
+ __wasiDisposePromise = void 0;
735
+ rejectDispose(error);
736
+ return disposePromise;
737
+ }
738
+ Promise.resolve(result).then((value) => {
739
+ __wasiDisposed = true;
740
+ resolveDispose(value);
741
+ }, (error) => {
742
+ __wasiDisposePromise = void 0;
743
+ rejectDispose(error);
744
+ });
745
+ return disposePromise;
746
+ }
747
+ function __publishWasiDispose(exports) {
748
+ Object.defineProperty(exports, __wasiDisposeSymbol, {
749
+ configurable: false,
750
+ enumerable: false,
751
+ value: __disposeWasiBinding,
752
+ writable: false
753
+ });
754
+ }
755
+ function __finishWasiInitializationRollback(cleanupErrors) {
756
+ let workerResult;
757
+ try {
758
+ workerResult = __terminateWasiWorkers();
759
+ } catch (cleanupError) {
760
+ cleanupErrors.push(cleanupError);
761
+ return cleanupErrors;
762
+ }
763
+ if (__isThenable(workerResult)) return Promise.resolve(workerResult).catch((cleanupError) => {
764
+ cleanupErrors.push(cleanupError);
765
+ }).then(() => cleanupErrors);
766
+ return cleanupErrors;
767
+ }
768
+ function __destroyContextForWasiRollback(cleanupErrors) {
769
+ let destroyResult;
770
+ try {
771
+ destroyResult = __destroyEmnapiContext();
772
+ } catch (cleanupError) {
773
+ cleanupErrors.push(cleanupError);
774
+ return __finishWasiInitializationRollback(cleanupErrors);
775
+ }
776
+ if (__isThenable(destroyResult)) return Promise.resolve(destroyResult).catch((cleanupError) => {
777
+ cleanupErrors.push(cleanupError);
778
+ }).then(() => __finishWasiInitializationRollback(cleanupErrors));
779
+ return __finishWasiInitializationRollback(cleanupErrors);
780
+ }
781
+ /**
782
+ * Leaves a rollback that could not reach the queued settlements undestroyed, and
783
+ * hands it to whatever this flavor has that can still reclaim it.
784
+ */
785
+ function __retainFailedWasiRollback(cleanupErrors) {
786
+ return cleanupErrors;
787
+ }
788
+ /**
789
+ * Initialization can fail *after* registration has already run, and registration
790
+ * runs with a live environment: a module-init hook can start async work and then
791
+ * return an error, and the promise it created may already have escaped into
792
+ * JavaScript. The barrier cancels that work and *queues* the settlement, so this
793
+ * path needs the same drain the ordinary disposal does — destroying without
794
+ * yielding discards the queue with a null env and strands the promise.
795
+ *
796
+ * Stays synchronous when nothing is queued, which covers every failure before
797
+ * `beforeInit`: there is no instance to run the barrier on, so nothing to drain.
798
+ *
799
+ * A barrier or drain that did *not* finish stops the rollback short of
800
+ * destroying, which is what `dispose()` already does — a rejected drain there
801
+ * never reaches `__continueWasiDisposal`. Destroying anyway is the worse of the
802
+ * two trades, and not because of what it saves:
803
+ *
804
+ * - It cannot deliver the settlements. `Context.destroy()` runs the
805
+ * threadsafe function's cleanup hook, which drains the queue with a null env
806
+ * and discards it, so a promise that already escaped into JavaScript hangs
807
+ * forever with nothing left that could ever settle it.
808
+ * - It saves less than it looks. `Context.destroy()` stops JavaScript calls
809
+ * and runs cleanup hooks; it does not free the wasm instance or its Memory,
810
+ * which this module's scope holds either way. What stopping short retains is
811
+ * the emnapi context's bookkeeping and its un-run cleanup hooks.
812
+ * - Retry is not theoretical. A rollback that records a cleanup error is
813
+ * already kept in the process-wide registry above, so re-`require()`ing this
814
+ * file replays it instead of re-instantiating — and the `6e15de6f` flag fix
815
+ * means the replay drains again rather than skipping it. Destroying first is
816
+ * what makes that retained record useless.
817
+ *
818
+ * The residual cost is honest: the CJS flavor hands the context to its
819
+ * `process.on('exit')` teardown, so a process that never retries still reclaims
820
+ * it on the way out. The ESM browser flavor has no equivalent — a module that
821
+ * throws while evaluating is permanently errored, so re-importing rethrows
822
+ * without re-running this file — and there the context stays until the realm
823
+ * goes away. That is the deliberate choice: a hung promise is a silent liveness
824
+ * bug with no upper bound, while the retained bookkeeping is bounded by the page.
825
+ */
826
+ function __rollbackWasiInitialization() {
827
+ function __rollbackWasmEnvForWasiInitialization() {
828
+ const cleanupErrors = [];
829
+ let prepareResult;
830
+ try {
831
+ prepareResult = __prepareWasmEnvCleanupWithTurns();
832
+ } catch (cleanupError) {
833
+ cleanupErrors.push(cleanupError);
834
+ return __retainFailedWasiRollback(cleanupErrors);
835
+ }
836
+ if (__isThenable(prepareResult)) return Promise.resolve(prepareResult).then(() => __drainWasmEnvForWasiRollback(cleanupErrors), (cleanupError) => {
837
+ cleanupErrors.push(cleanupError);
838
+ return __retainFailedWasiRollback(cleanupErrors);
839
+ });
840
+ return __drainWasmEnvForWasiRollback(cleanupErrors);
841
+ }
842
+ function __drainWasmEnvForWasiRollback(cleanupErrors) {
843
+ let drainResult;
844
+ try {
845
+ drainResult = __drainWasmEnvCleanup();
846
+ } catch (cleanupError) {
847
+ cleanupErrors.push(cleanupError);
848
+ return __retainFailedWasiRollback(cleanupErrors);
849
+ }
850
+ if (__isThenable(drainResult)) return Promise.resolve(drainResult).then(() => __destroyContextForWasiRollback(cleanupErrors), (cleanupError) => {
851
+ cleanupErrors.push(cleanupError);
852
+ return __retainFailedWasiRollback(cleanupErrors);
853
+ });
854
+ return __destroyContextForWasiRollback(cleanupErrors);
855
+ }
856
+ const __retainAfterAsyncWorkDrainFailure = (cleanupError) => __retainFailedWasiRollback([cleanupError]);
857
+ let asyncWorkResult;
858
+ try {
859
+ asyncWorkResult = __drainWasiAsyncWork();
860
+ } catch (cleanupError) {
861
+ return __retainAfterAsyncWorkDrainFailure(cleanupError);
862
+ }
863
+ if (__isThenable(asyncWorkResult)) return Promise.resolve(asyncWorkResult).then(__rollbackWasmEnvForWasiInitialization, __retainAfterAsyncWorkDrainFailure);
864
+ return __rollbackWasmEnvForWasiInitialization();
865
+ }
866
+ let __wasiAddonCrashFlag;
867
+ function __captureWasiAddonCrashFlag(instance) {
868
+ try {
869
+ const getAddress = instance.exports.napi_wasm_thread_crash_flag_address;
870
+ if (typeof getAddress !== "function") return;
871
+ const address = getAddress() >>> 0;
872
+ const buffer = __sharedMemory.buffer;
873
+ if (address === 0 || address % 4 !== 0 || address + 4 > buffer.byteLength) return;
874
+ __wasiAddonCrashFlag = new Int32Array(buffer, address, 1);
875
+ } catch {}
876
+ }
877
+ function __shareWasiAddonCrashFlag(worker) {
878
+ if (__wasiAddonCrashFlag === void 0) return;
879
+ try {
880
+ worker.postMessage({ __napiRsAddonCrashFlag: __wasiAddonCrashFlag });
881
+ } catch {}
882
+ }
883
+ let __wasiModule;
884
+ let __napiModule;
885
+ try {
886
+ __emnapiContext = __wrapEmnapiContextDestroyForSettlement(createContext({ autoDestroy: false }), __prepareWasmEnvCleanup, __isPreparingWasmEnvCleanup);
887
+ __emnapiContext.suppressDestroy();
888
+ ({instance: __napiInstance, module: __wasiModule, napiModule: __napiModule} = await instantiateNapiModule(__wasmFile, {
889
+ context: __emnapiContext,
890
+ asyncWorkPoolSize: __asyncWorkPoolSize,
891
+ reuseWorker: { size: __asyncWorkPoolSize + __workerPoolSize },
892
+ plugins: [
893
+ __captureWasiThreadManager,
894
+ emnapiAsyncWorkPlugin,
895
+ emnapiTSFNPlugin
896
+ ],
897
+ wasi: __wasi,
898
+ onCreateWorker() {
899
+ const worker = new Worker(new URL("./wasi-worker-browser.mjs", import.meta.url), { type: "module" });
900
+ __wasiWorkers.add(worker);
901
+ __shareWasiAddonCrashFlag(worker);
902
+ return worker;
903
+ },
904
+ overwriteImports(importObject) {
905
+ importObject.env = {
906
+ ...importObject.env,
907
+ ...importObject.napi,
908
+ ...importObject.emnapi,
909
+ memory: __sharedMemory
910
+ };
911
+ return importObject;
912
+ },
913
+ beforeInit({ instance }) {
914
+ __napiInstance = instance;
915
+ __captureWasiAddonCrashFlag(instance);
916
+ for (const worker of __wasiWorkers) __shareWasiAddonCrashFlag(worker);
917
+ for (const name of Object.keys(instance.exports)) if (name.startsWith("__napi_register__")) instance.exports[name]();
918
+ }
919
+ }));
920
+ __publishWasiDispose(__napiModule.exports);
921
+ __napiStampBindingTarget(__napiModule.exports, __napiBindingTarget);
922
+ } catch (error) {
923
+ throw __attachCleanupErrors(error, await __rollbackWasiInitialization());
924
+ }
36
925
  var regex_set_wasi_browser_default = __napiModule.exports;
37
926
  __napiModule.exports.RegexSet;
927
+ __napiModule.exports._prepareRegexSet;
38
928
  __napiModule.exports._uax29Boundaries;
39
929
  //#endregion
40
930
  //#region src/core.ts
@@ -81,13 +971,9 @@ function asciiBoundaries(src) {
81
971
  let i = 0;
82
972
  while (i < src.length) if (src.charAt(i) === "\\" && i + 1 < src.length) {
83
973
  const next = src.charAt(i + 1);
84
- if (!inClass && (next === "b" || next === "B")) {
85
- result += `(?-u:\\${next})`;
86
- i += 2;
87
- } else {
88
- result += src.charAt(i) + src.charAt(i + 1);
89
- i += 2;
90
- }
974
+ if (!inClass && (next === "b" || next === "B")) result += `(?-u:\\${next})`;
975
+ else result += src.charAt(i) + src.charAt(i + 1);
976
+ i += 2;
91
977
  } else {
92
978
  if (src.charAt(i) === "[") inClass = true;
93
979
  if (src.charAt(i) === "]") inClass = false;
@@ -241,9 +1127,10 @@ function scopeInnerFlags(src) {
241
1127
  }
242
1128
  }
243
1129
  if (enable.length > 0 && (src.charAt(j) === ")" || src.charAt(j) === ":")) {
244
- if (enable.includes("i")) if (disable.length > 0) result += `(?${enable}-${disable}${src.charAt(j)}`;
245
- else result += `(?${enable}${src.charAt(j)}`;
246
- else if (disable.length > 0) result += `(?${enable}-${disable}${src.charAt(j)}`;
1130
+ if (enable.includes("i")) {
1131
+ if (disable.length > 0) result += `(?${enable}-${disable}${src.charAt(j)}`;
1132
+ else result += `(?${enable}${src.charAt(j)}`;
1133
+ } else if (disable.length > 0) result += `(?${enable}-${disable}${src.charAt(j)}`;
247
1134
  else result += `(?${enable}${src.charAt(j)}`;
248
1135
  i = j + 1;
249
1136
  continue;
@@ -377,6 +1264,88 @@ function splitTopLevelAlternatives(body) {
377
1264
  branches.push(body.slice(start));
378
1265
  return branches;
379
1266
  }
1267
+ function buildNativeInput(patterns, options) {
1268
+ const entries = patterns.map(normalizeEntry);
1269
+ const names = entries.map((e) => e.name);
1270
+ const unicode = options?.unicodeBoundaries ?? true;
1271
+ const wholeWords = options?.wholeWords ?? false;
1272
+ const ci = options?.caseInsensitive ?? false;
1273
+ let processed = entries.map((e) => e.pattern);
1274
+ if (ci) processed = processed.map(caseInsensitivePattern);
1275
+ if (!unicode) processed = processed.map(asciiBoundaries);
1276
+ const nativeOpts = options ? {
1277
+ ...options.wholeWords !== void 0 ? { wholeWords: options.wholeWords } : {},
1278
+ ...options.unicodeBoundaries !== void 0 ? { unicodeBoundaries: options.unicodeBoundaries } : {}
1279
+ } : void 0;
1280
+ const nativePatterns = [];
1281
+ const nativeIndexMap = [];
1282
+ const jsFallbacks = [];
1283
+ for (let i = 0; i < processed.length; i++) {
1284
+ const pattern = processed[i];
1285
+ if (pattern === void 0) throw new Error(`Missing processed pattern ${i}`);
1286
+ const expanded = expandLargeAlternation(pattern);
1287
+ for (const expandedPattern of expanded) {
1288
+ const jsFallback = jsFallbackRegExp(expandedPattern, unicode);
1289
+ if (jsFallback) jsFallbacks.push({
1290
+ pattern: i,
1291
+ re: jsFallback
1292
+ });
1293
+ else {
1294
+ nativeIndexMap.push(i);
1295
+ nativePatterns.push(expandedPattern);
1296
+ }
1297
+ }
1298
+ }
1299
+ return {
1300
+ names,
1301
+ hasNames: entries.some((e) => e.name !== void 0),
1302
+ patternCount: entries.length,
1303
+ nativePatterns,
1304
+ nativeOpts,
1305
+ nativeIndexMap,
1306
+ jsFallbacks,
1307
+ boundaryOptions: {
1308
+ wholeWords,
1309
+ unicodeBoundaries: unicode
1310
+ }
1311
+ };
1312
+ }
1313
+ function caseInsensitivePattern(p) {
1314
+ if (/^(?:\\[bB]|\(\?[ims]+(?:-[imsu]+)?\))*\(\?[ims]*i[ims]*(?:-[imsu]+)?[:(]/.test(p)) return p;
1315
+ let src = p;
1316
+ let flagPrefix = "";
1317
+ const bareFlagMatch = src.match(/^\(\?[ims]+(?:-[imsu]+)?\)/);
1318
+ if (bareFlagMatch) {
1319
+ flagPrefix = bareFlagMatch[0];
1320
+ src = src.slice(flagPrefix.length);
1321
+ }
1322
+ let leading = "";
1323
+ let trailing = "";
1324
+ if (src.startsWith("\\b")) {
1325
+ leading = "\\b";
1326
+ src = src.slice(2);
1327
+ } else if (src.startsWith("\\B")) {
1328
+ leading = "\\B";
1329
+ src = src.slice(2);
1330
+ }
1331
+ if (src.length >= 2) {
1332
+ const last = src.at(-1);
1333
+ if (last === "b" || last === "B") {
1334
+ let bs = 0;
1335
+ let k = src.length - 2;
1336
+ while (k >= 0 && src[k] === "\\") {
1337
+ bs++;
1338
+ k--;
1339
+ }
1340
+ if (bs > 0 && bs % 2 === 1) {
1341
+ trailing = "\\" + last;
1342
+ src = src.slice(0, -2);
1343
+ }
1344
+ }
1345
+ }
1346
+ const uFlag = needsAsciiMode(src) && !hasNonAscii(src) ? "-u" : "";
1347
+ return `${flagPrefix}${leading}(?i${uFlag}:${src})${trailing}`;
1348
+ }
380
1349
  /**
381
1350
  * Multi-pattern regex matcher.
382
1351
  *
@@ -410,90 +1379,29 @@ var RegexSet = class {
410
1379
  _jsFallbacks;
411
1380
  _nativeSingles;
412
1381
  _boundaryOptions;
413
- constructor(patterns, options) {
414
- const entries = patterns.map(normalizeEntry);
415
- this._names = entries.map((e) => e.name);
416
- this._hasNames = entries.some((e) => e.name !== void 0);
417
- this._patternCount = entries.length;
418
- const unicode = options?.unicodeBoundaries ?? true;
419
- const wholeWords = options?.wholeWords ?? false;
420
- const ci = options?.caseInsensitive ?? false;
421
- this._boundaryOptions = {
422
- wholeWords,
423
- unicodeBoundaries: unicode
424
- };
425
- let processed = entries.map((e) => e.pattern);
426
- if (ci) processed = processed.map((p) => {
427
- if (/^(?:\\[bB]|\(\?[ims]+(?:-[imsu]+)?\))*\(\?[ims]*i[ims]*(?:-[imsu]+)?[:(]/.test(p)) return p;
428
- let src = p;
429
- let flagPrefix = "";
430
- const bareFlagMatch = src.match(/^\(\?[ims]+(?:-[imsu]+)?\)/);
431
- if (bareFlagMatch) {
432
- flagPrefix = bareFlagMatch[0];
433
- src = src.slice(flagPrefix.length);
434
- }
435
- let leading = "";
436
- let trailing = "";
437
- if (src.startsWith("\\b")) {
438
- leading = "\\b";
439
- src = src.slice(2);
440
- } else if (src.startsWith("\\B")) {
441
- leading = "\\B";
442
- src = src.slice(2);
443
- }
444
- if (src.length >= 2) {
445
- const last = src.at(-1);
446
- if (last === "b" || last === "B") {
447
- let bs = 0;
448
- let k = src.length - 2;
449
- while (k >= 0 && src[k] === "\\") {
450
- bs++;
451
- k--;
452
- }
453
- if (bs > 0 && bs % 2 === 1) {
454
- trailing = "\\" + last;
455
- src = src.slice(0, -2);
456
- }
457
- }
458
- }
459
- const uFlag = needsAsciiMode(src) && !hasNonAscii(src) ? "-u" : "";
460
- return `${flagPrefix}${leading}(?i${uFlag}:${src})${trailing}`;
461
- });
462
- if (!unicode) processed = processed.map(asciiBoundaries);
463
- const nativeOpts = options ? {
464
- ...options.wholeWords !== void 0 ? { wholeWords: options.wholeWords } : {},
465
- ...options.unicodeBoundaries !== void 0 ? { unicodeBoundaries: options.unicodeBoundaries } : {}
466
- } : void 0;
467
- const nativePatterns = [];
468
- this._nativeIndexMap = [];
469
- this._jsFallbacks = [];
1382
+ constructor(patterns, options, prepared) {
1383
+ const nativeInput = buildNativeInput(patterns, options);
1384
+ this._names = nativeInput.names;
1385
+ this._hasNames = nativeInput.hasNames;
1386
+ this._patternCount = nativeInput.patternCount;
1387
+ this._boundaryOptions = nativeInput.boundaryOptions;
1388
+ this._nativeIndexMap = nativeInput.nativeIndexMap;
1389
+ this._jsFallbacks = nativeInput.jsFallbacks;
470
1390
  this._nativeSingles = [];
471
- for (let i = 0; i < processed.length; i++) {
472
- const pattern = processed[i];
473
- if (pattern === void 0) throw new Error(`Missing processed pattern ${i}`);
474
- const expanded = expandLargeAlternation(pattern);
475
- for (const expandedPattern of expanded) {
476
- const jsFallback = jsFallbackRegExp(expandedPattern, unicode);
477
- if (jsFallback) this._jsFallbacks.push({
478
- pattern: i,
479
- re: jsFallback
480
- });
481
- else {
482
- this._nativeIndexMap.push(i);
483
- nativePatterns.push(expandedPattern);
484
- }
485
- }
486
- }
487
- this._inner = new binding.RegexSet(nativePatterns, nativeOpts);
488
- if (this._jsFallbacks.length > 0) this._nativeSingles = nativePatterns.map((pattern, i) => {
1391
+ this._inner = new binding.RegexSet(nativeInput.nativePatterns, nativeInput.nativeOpts, prepared);
1392
+ if (this._jsFallbacks.length > 0) this._nativeSingles = nativeInput.nativePatterns.map((pattern, i) => {
489
1393
  const original = this._nativeIndexMap[i];
490
1394
  if (original === void 0) throw new Error(`Missing native index map ${i}`);
491
1395
  return {
492
1396
  pattern: original,
493
- inner: new binding.RegexSet([pattern], nativeOpts)
1397
+ inner: new binding.RegexSet([pattern], nativeInput.nativeOpts)
494
1398
  };
495
1399
  });
496
1400
  }
1401
+ static prepare(patterns, options) {
1402
+ const nativeInput = buildNativeInput(patterns, options);
1403
+ return binding._prepareRegexSet(nativeInput.nativePatterns, nativeInput.nativeOpts);
1404
+ }
497
1405
  /** Number of patterns. */
498
1406
  get patternCount() {
499
1407
  return this._patternCount;