From 277b5947f8b6beff6b6d87db4b2a486d78c134bf Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Fri, 28 Aug 2026 23:46:40 +0200 Subject: [PATCH] fix: initialize Wasm automatically before parsing The synchronous parse API cannot represent pending initialization, but it previously required callers to arrange initialization first. Browser callers should still await init() because main threads can restrict synchronous Wasm compilation. Refs: https://github.com/guybedford/es-module-lexer/commit/61ad2a5f90e480d40741985edcb5d94f7badc4cb --- README.md | 8 ++++++-- src/lexer.js | 2 +- test/_unit.js | 10 ++++++++++ 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index addf5ed..057c65e 100755 --- a/README.md +++ b/README.md @@ -59,12 +59,16 @@ When using the ESM version, Wasm is supported instead: ```js import { parse, init } from 'cjs-module-lexer'; -// init() needs to be called and waited upon, or use initSync() to compile -// Wasm blockingly and synchronously. +// In browsers, initialize the Wasm before parsing. await init(); const { exports, reexports } = parse(source); ``` +`parse` calls `initSync()` on first use if initialization has not completed. +Call `initSync()` directly to choose when the blocking initialization runs. +Browser main threads can restrict synchronous Wasm compilation, so await +`init()` before parsing in browsers. + The Wasm build is around 1.5x faster and without a cold start. ### Grammar diff --git a/src/lexer.js b/src/lexer.js index 30bca50..50e1961 100755 --- a/src/lexer.js +++ b/src/lexer.js @@ -4,7 +4,7 @@ const isLE = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1; export function parse (source, name = '@') { if (!wasm) - throw new Error('Not initialized'); + initSync(); const len = source.length + 1; diff --git a/test/_unit.js b/test/_unit.js index 0458f17..391d95e 100755 --- a/test/_unit.js +++ b/test/_unit.js @@ -20,6 +20,16 @@ async function loadParser () { suite('Lexer', () => { suiteSetup(async () => await loadParser()); + test('automatic Wasm initialization', async () => { + const lexer = await import('../dist/lexer.mjs?automatic-initialization'); + + assert.deepStrictEqual(lexer.parse('exports.value = 1'), { + exports: ['value'], + reexports: [] + }); + lexer.initSync(); + }); + test('export star failure', () => { parse(`__exportStar((0));`); });