Skip to content

feat: lex type-only TypeScript imports and exports - #220

Merged
guybedford merged 11 commits into
guybedford:v3from
BridgeAR:BridgeAR/2026-06-29-ts-on-lexer-min
Sep 7, 2026
Merged

guybedford merged 11 commits into
guybedford:v3from
BridgeAR:BridgeAR/2026-06-29-ts-on-lexer-min

Conversation

@BridgeAR

@BridgeAR BridgeAR commented Jul 2, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Teaches the full Wasm and asm.js builds to lex the type-only TypeScript subset that Node's stripTypeScriptTypes erases: type-only import/export clauses and type / interface declarations. Type-only module edges are reported with tp: true, and declaration bodies are skipped opaquely so nested import() types do not leak into the runtime graph.

Why

A single lexer avoids a separate TypeScript transform and gives module-graph consumers both runtime and type-only edges. Plain JavaScript remains metadata-compatible. TypeScript declaration lookahead only runs after shallow inline keyword gates, and tp reuses existing import/export reader values instead of adding a Wasm boundary call per specifier. Minimal builds remain JavaScript-only and compile out the type-only fields and paths.

The supported boundary follows Node's type stripping for these forms. Value-position annotations and generics, as / satisfies, non-null !, and non-erasable syntax such as enum and runtime namespace remain out of scope.

Fixes: #72

@BridgeAR
BridgeAR force-pushed the BridgeAR/2026-06-29-ts-on-lexer-min branch from fdfdeca to c18c022 Compare July 2, 2026 15:50

@guybedford guybedford left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks Ruben — this is a strong first increment: the write-head sentinel guards are correct, the minimal build reader/typings are properly insulated, and the inline-modifier semantics get the subtle case right (import { type A } keeps a runtime edge in Node's stripping output, so statement-level tp: false there is exactly right). Requesting changes on the items below.

Bug: import type from 'x' must be tp: false

Verified against both Node stripTypeScriptTypes (v26) and tsc 5.9 verbatimModuleSyntax: this form is a value import of the default export bound to the local name type — both keep it verbatim. Only import type from from 'x' (default import named from) is type-only:

import type from 'm';       =>  kept verbatim (value import)
import type from from 'm';  =>  stripped (type-only)

The PR marks the first tp: true, and the test comment ("Node strips the whole import") is incorrect. Since import type from 'x' is also valid plain JavaScript, a consumer eliding tp: true imports would drop a real runtime import from a pure-JS file — this breaks the JS-superset guarantee the PR is built on. The type follower exclusions need a third case: from followed (after whitespace/comments) by a quote. Please add import type from from 'x' as the disambiguation test.

Gating must be complete — zero cost to the minimal build

src/lexer.c is fully behind #ifdef LEX_TS, but src/lexer.h is not:

  • bool type_only; on struct Import / struct Export
  • the type_only = false stores in addImport / addExport
  • the itp() / etp() accessors

The minimal build currently pays two live stores per record and +4 bytes heap per export (the bool lands between pointer fields in the min Export layout), and only DCE keeps itp/etp out of the min wasm. All of these need #ifdef LEX_TS. This composes with the asm requirement below: the asm build defines LEX_TS and gets the field for real; the minimal build carries zero trace.

asm.js build must be included

The hand-maintained-dictionary blocker no longer exists: the build now auto-extracts the keyword dictionary from the fastcomp memory image (the lib/lexer.asm.in.js task scans lexer.layout.js.mem and substitutes {{WORDS}}/{{OFFSET}}), so adding YPE propagates automatically. Concretely:

  • -D LEX_TS and _itp/_etp in EXPORTED_FUNCTIONS on both fastcomp tasks (lib/lexer.emcc.asm.js and the layout sidecar must keep identical layout-affecting flags)
  • src/lexer.asm.js non-minimal branch: tp: !!asm.itp() instead of hardcoded false
  • run the test/typescript/ suites under ASM=1 — _harness.cjs hard-imports dist/lexer.js; give it the same WASM/ASM env switch the legacy suites use
  • fix the now-stale "MANUAL ASM DICTIONARY CONSTRUCTION" note at the top of lexer.c, and the README/lexer.ts JSDoc claims that the asm build is JS-only

Type declarations must be tracked

export type Foo = ... and export interface Foo {} need to record tp: true exports — top-level type / interface dispatch from the statement-start check exactly like import/export. Implementation notes:

  • For type Foo, read the name, then stop at the = and skip the RHS. Note default type parameters put a = before the real one (type Foo<T = string> = ...), so after the name skip a balanced <...> region first (>> closes two, => in function types doesn't close, {}/[]/() nest inside). The same angle skipper serves interface Foo<T> extends Bar<T> {.
  • Interface bodies should be skipped opaquely (brace-matching, not the main token loop): a member like import(): void otherwise matches the dynamic-import dispatch and records a bogus import edge — a hazard that exists latently today for bare interface blocks.
  • Guards for the JS superset: require an identifier-start char after the keyword (type = 5, type(x) are plain JS) and no line break between type and the name (type\nX = 5 is two JS statements via ASI).
  • Dotted names can't be declared (export type Foo.Bar is invalid TS); qualified names only appear as RHS references (export type Bar = Foo.Bar;), which the RHS skip covers for free. import Bar = Foo.Bar / export import are non-erasable and stay out of scope.
  • Scope boundary: bare interface Foo {} + later export { Foo } should not be resolved — Node stripping does no cross-binding analysis (erasable TS requires export { type Foo }), so only directly-exported declaration forms are marked.

Smaller items

  • isTsTypeKeyword follower set misses import type/*c*/{ A } from 'm' (verified: Node strips it; the lexer reports tp: false) and import type* as ns from 'm'. Accepting / and * as followers is safe — the callers' savePos/restore logic already disambiguates.
  • The single-token as lookahead in the export brace loop mishandles export { type as/*c*/T } and export { type as as X } (type modifier on a specifier named as). Pathological, but worth a deliberate call — at minimum a comment.
  • README opening ("lexes the erasable TypeScript syntax that Node.js type stripping accepts") overstates this increment; scope it to the type-only subset until the annotation work lands.
  • Untested: export type * from 'x' (traced as correct — import edge tp: true — but pin it), and the tp: false additions in the JS builds once the harness is env-parameterized.
  • Nit: js-build-unchanged.cjs runs against the wasm build; js-superset.cjs would name what it actually asserts.

@BridgeAR
BridgeAR force-pushed the BridgeAR/2026-06-29-ts-on-lexer-min branch from c2fe15e to e32a1c8 Compare July 6, 2026 13:52
@BridgeAR

BridgeAR commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

This is still a WIP PR with some issues and not yet ready. It should move in the right direction though.

@BridgeAR
BridgeAR marked this pull request as ready for review July 6, 2026 15:48

@guybedford guybedford left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is really nicely done — pinning the accept/reject boundary to Node's stripTypeScriptTypes and backing it with a differential fuzzer is exactly the right approach for an opaque skipper, and it clearly earned its keep (several tests are annotated "fuzzer-found"). The minimal build staying zero-cost behind #ifdef LEX_TS and the JS-superset guarding are both thorough.

Two things I'd like addressed before merge:

1. import type from'x' (no space before the quote) is mis-marked type-only. In the import type detection:

if (!typeIsBinding && nextCh == 'f' && memcmp(pos + 1, &ROM[0], 3 * 2) == 0 && isBrOrWs(*(pos + 4))) {

The from-followed-by-quote check requires whitespace after from. import type from'x' is valid JS (type default binding, from keyword, 'x' with no separating space), but it fails isBrOrWs(*(pos + 4)), so typeIsBinding stays false and the import is reported tp: true — dropping a real runtime edge from a file that is also valid JavaScript, which breaks the "no JS consumer observes a change" invariant. The fuzzer misses it because the import-type-from form always emits a space before the specifier. Fix is to also accept a quote here, e.g. isBrOrWs(c) || isQuote(c), and add the no-space case to the fuzzer's form.

2. Type/interface declarations nested in a block still leak their import(...) types. Both bare triggers gate on openTokenDepth == 0:

if (*(pos + 1) == 'y' && openTokenDepth == 0 && keywordStart(pos))
  tryTsTypeDeclaration(true);

So function f() { type X = import('m').T; } — which Node strips cleanly — reports import('m') as a runtime edge. This is a remaining gap rather than a regression (everything leaked before), and the openTokenDepth == 0 guard is a reasonable defense against expression-context misfires, so I'm fine leaving the behaviour for a follow-up. But the README currently says type and interface declarations are skipped "whether exported or not" with no nesting caveat — please add a one-line scope note there so the limitation is documented, and ideally extend the fuzzer to emit nested declarations (it only generates top-level statements today, so it can't surface this class).

3. Prefer forcing the keyword dictionary contiguous over reconstructing it from a gappy span. The gen-asm-in.mjs change reconstructs the dictionary across the whole first-to-last span, filling gaps with NUL, because adding the new tables made the compiler place nterface at a non-adjacent offset. That works, but scanning first-to-last across the entire memory image is sensitive to any unrelated printable-char16 constant landing between the tables (it would widen the span and bloat words with a long NUL run).

The split happens only because each keyword is a separate static const char16_t[] object, which the compiler/linker may reorder or interleave. Merging them into one array and offsetting into it keeps the object contiguous on both toolchains (no linker script or section attributes needed — those don't actually guarantee intra-section ordering):

static const char16_t KEYWORDS[] = {
  'x','p','o','r','t',              // xport
  'm','p','o','r','t',              // mport
  /* ... */
  'y','p','e',                      // ype
  'n','t','e','r','f','a','c','e',  // nterface
};
#define XPORT (KEYWORDS + 0)
#define MPORT (KEYWORDS + 5)
/* ... */

The call sites already pass explicit lengths (memcmp(pos + 1, &MPORT[0], 5 * 2)) and never use sizeof, so only &NAME[0] becomes NAME. That lets the asm extraction go back to "grab the single contiguous run", drops the NUL-gap span logic and its end - start fragility, and the contiguous blob (no gap NULs) is likely smaller than today's span.

@BridgeAR
BridgeAR force-pushed the BridgeAR/2026-06-29-ts-on-lexer-min branch from 229afd6 to a03578e Compare July 12, 2026 12:08
@guybedford

Copy link
Copy Markdown
Owner

Review — type-only TypeScript import/export lexing

The architecture is sound and test coverage is reasonable, but the new speculative TS-skipping paths in src/lexer.c have a cluster of real bugs. The common thread: when the lexer opaquely skips an erased declaration, it leaves lastTokenPos, pos, and openTokenStack in states the rest of the tokenizer doesn't expect. Two of these are memory-safety / DoS class and were reproduced against a native build. I'd block on the five correctness findings below.

Correctness (all confirmed)

1. src/lexer.c:821 — wild pointer read after skipping a {}-terminated declaration (memory safety). Skipping interface A {} (or type X = {a:1}) leaves lastTokenPos on the } but never pushes onto openTokenStack, so openTokenDepth stays 0. A following / — e.g. interface A {}\n/import('m')/.test(x); — makes handleSlash read openTokenStack[0].pos (uninitialized stack garbage) and dereference it in isExpressionTerminator. SEGV under ASan; in Wasm it reads arbitrary linear memory and may leak a bogus import edge.

2. src/lexer.c:816 — enclosing block's } consumed as a type operator, corrupting brace depth. For valid TS function f() { type X = A }\nimport { v } from 'runtime';, the bare alias-RHS loop treats the function's closing } as an operator (operandPending = true; pos++), then swallows the following import. openTokenDepth is left at 1 and parse() throws PARSE_ERROR on input Node's stripTypeScriptTypes accepts. Also repros with switch/case bodies and object-method bodies.

3. src/lexer.c:161/:821 — regex after an erased bare type alias misread as division, leaking a phantom import. type X = A\n/import('m')/; erases to a regex statement with no imports, but the skip leaves lastTokenPos on A (an expression token), so handleSlash picks division and lexes the regex body as code — the built lexer reports a dynamic import of 'm' that doesn't exist after stripping.

4. src/lexer.c:692 — interface rejects an intervening comment before the name, unlike type. The guard !isBrOrWs(*(pos + 9)) fails on /, so export interface/*c*/Foo { m(): import('m').T } (valid TS, accepted by Node) isn't recognized: its body is tokenized, import('m') is recorded as a real dynamic import, and the Foo type-only export is dropped. isTsTypeKeyword (src/lexer.c:572) already accepts / as a follower for type — the interface check should match.

5. src/lexer.c:717 / skipTsBalanced — O(n²) on unbalanced < (DoS on untrusted source). In speculative mode, type a< triggers skipTsBalanced on the <, which scans to EOF when no > matches; the missing = then restores pos fully and the main loop re-lexes one token forward, re-triggering at the next type a<. Input "type a<\n" repeated N times is quadratic. ; and line breaks don't bound the angle scan.

These five share a root cause worth fixing at altitude: after an opaque declaration erasure, the skipper should restore tokenizer state to what an erased statement looks like — leave lastTokenPos on an expression-terminator sentinel (like ;) and never let an enclosing closer fall through the RHS operator path — rather than each site patching pos-- individually. Fixing that consistently likely closes 1, 2, and 3 together.

Efficiency (confirmed, lower severity)

6. src/lexer.c:147,161 — the "plain JavaScript pays nothing" claim isn't quite right. With LEX_TS on (all three shipped builds), every keyword-start token beginning in (in, instanceof, index…) or ty (typeof) makes a non-inlined call into tryTsTypeDeclaration. It's a handful of comparisons per occurrence, not a deep lookahead — minor — but the description should be corrected, and the gate could be widened inline (mirroring the existing case 'c' LASS pattern) to keep typeof/instanceof inside the switch arm.

7. src/lexer.ts:300,309 (and src/lexer.asm.js:75,84) — one extra wasm boundary call per specifier on every module. itp()/etp() exist solely to move the type_only bit across the boundary, including for plain JS where it's always false (~9% more calls per import, ~14% per export). Nearly free to fold in: it() returns enum 1–7 so bit 3+ is free (import_ty | (type_only << 3)); for exports, re()'s bool can carry it as value 2.

Minor

  • test/typescript/regex-division.cjs:4 — the // Increment 1 adds … comment narrates the PR's development staging rather than code semantics; goes stale once later increments land.
  • The triple-duplicated contextual-type disambiguation (src/lexer.c:361/997/1026) looked worth factoring, but on inspection the shared skeleton is only ~5 lines and the follower logic is genuinely site-specific — I'd leave it. (asm.js has no TS logic, so it's three copies, not six.)

@BridgeAR
BridgeAR force-pushed the BridgeAR/2026-06-29-ts-on-lexer-min branch from d0e2fa7 to 593ca50 Compare July 13, 2026 10:44

@guybedford guybedford left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, we must just make sure to land this on v3 not main.

@BridgeAR
BridgeAR force-pushed the BridgeAR/2026-06-29-ts-on-lexer-min branch from 593ca50 to e6bf1b0 Compare August 2, 2026 14:31
@BridgeAR
BridgeAR force-pushed the BridgeAR/2026-06-29-ts-on-lexer-min branch from e6bf1b0 to 356a94e Compare August 9, 2026 21:42
@BridgeAR
BridgeAR changed the base branch from main to v3 August 9, 2026 21:42
@BridgeAR
BridgeAR force-pushed the BridgeAR/2026-06-29-ts-on-lexer-min branch from 356a94e to 7fc28fb Compare August 9, 2026 21:44

@guybedford guybedford left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks Ruben — the rebase brings this down to a really clean scope, and the differential fuzzer against stripTypeScriptTypes is a great oracle. Minimal build checks out as unaffected (no -D LEX_TS in the min compiles, tp gated behind !MINIMAL, minimal suites passing).

One blocker, in code this diff doesn't touch but this feature now owns: the deferred export-resolution pass has no type handling. collectStaticImportBindingsFromRecord (src/lexer.c:1834) re-reads the statement at statement_start + 6 without the forward parser's LEX_TS keyword skip, and collectNamedImportBindings (src/lexer.c:1740) has no inline type modifier handling, while the resolver loop visits type-only records. Confirmed on this branch's build:

parse("import type Foo from 'm';\nconst type = 1;\nexport { type };")
// export of the local `type` reports { t: 2, im: 'default', f: 'm' } — a reexport of m's default
parse("import { type A } from 'm';\nconst type = 1;\nexport { type };")
// reports { t: 2, im: 'type', f: 'm' }
parse("import Bar from 'm';\nconst type = 1;\nexport { type };")
// control: correctly { t: 1, ln: 'type' }

The fix should mirror the typeOnly disambiguation the forward parse already does (src/lexer.c:540) in both deferred readers, and define what a detached export { A } of a type-only binding reports.

Remaining comments inline are non-blocking cleanups plus one scope question on the type-alias ASI heuristic.

Comment thread src/lexer.c Resolved
Comment thread src/lexer.c Resolved
Comment thread src/lexer.c Resolved
Comment thread src/lexer.c Resolved
Comment thread src/lexer.c Resolved
Comment thread test/typescript/_harness.cjs Resolved
@BridgeAR
BridgeAR force-pushed the BridgeAR/2026-06-29-ts-on-lexer-min branch 3 times, most recently from 2a0dcbb to 7ec47ee Compare August 9, 2026 22:58
@guybedford
guybedford force-pushed the BridgeAR/2026-06-29-ts-on-lexer-min branch 6 times, most recently from caba513 to 74e4551 Compare August 9, 2026 23:43
@guybedford
guybedford force-pushed the BridgeAR/2026-06-29-ts-on-lexer-min branch from 74e4551 to 557e476 Compare August 9, 2026 23:50

@guybedford guybedford left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was looking again at the dynamic import type-only cases, and I think the fact is we cannot conclusively define typeOnly as having real meaning here.

Instead I've reworked this to be an entirely heuristically classifier, based on the fact that import('m').T can heuristically known to be a type and await import('m') can heuristically be known not to be a type, because normally you'd do import('m').then(m => m.T) or (await import('m')).T before a member access for runtime usage.

Then honstly exposing this on DynamicImport as a new probablyTypeOnly field on it only.

I've worked this in in a new commit, PTAL.

@guybedford
guybedford force-pushed the BridgeAR/2026-06-29-ts-on-lexer-min branch from 2f64c90 to b97038d Compare August 10, 2026 00:13
@BridgeAR

Copy link
Copy Markdown
Collaborator Author

I looked at it and this seems to be a good heuristic to be valid. In reality, this will pretty much always hold.

@guybedford

Copy link
Copy Markdown
Owner

Pushed a round of review fixes on top of the rebase:

JS-superset fixes

  • export { type as as } terminated by , / } is again the value type renamed as — the type modifier now requires an identifier after the second as (type as as X)
  • U+00A0 is treated as ES whitespace in import/export names and around the as keyword, restoring the 2.x name splitting

TS lexing fixes

  • Multi-line conditional and union types stay erased: line-leading ?, :, ., => and extends now continue the erased alias RHS, so Prettier-formatted conditional types no longer leak a phantom runtime import() edge
  • TS import-equals is lexed: import A = require('m') records a runtime import edge (type-only under import type), and a namespace alias RHS (import A = N.M) is erased — previously these threw a parse error
  • export declare ... ambient declarations are erased with their names recorded as type-only exports; export abstract class C records C; export enum / export const enum / export namespace record their declared value names instead of garbage records
  • Bracketed promise member access (import('m')['then'](f)) stays a runtime import, and comments before a member access no longer defeat probablyTypeOnly classification
  • Reexport / ReexportAll from is typed string | undefined, and the asm.js build now agrees with the wasm build on undecodable specifiers (export * from 'a\u{}')

All of the new lexing is guarded by LEX_TS: the minimal wasm build is byte-identical after these changes (6,953B Brotli), and export * from stays t: 1 there — the StaticReexportStar record type is a full-build refinement only. Full suite green across all seven test targets on wasm and asm.

@guybedford
guybedford force-pushed the BridgeAR/2026-06-29-ts-on-lexer-min branch 2 times, most recently from c18c022 to f436815 Compare August 17, 2026 02:25
@guybedford guybedford mentioned this pull request Aug 17, 2026
BridgeAR and others added 3 commits August 23, 2026 22:03
Teach the full Wasm and asm.js builds to lex type-only imports, exports, type aliases, and interfaces accepted by Node.js type stripping. Type-only module edges carry `tp: true`, and erased declaration bodies do not leak nested `import()` types into the runtime graph.

Plain JavaScript keeps the same graph, and minimal builds compile the TypeScript paths out. Import metadata uses bit 16 above the public import-type range. Export metadata uses the spare bit above import-name types because fastcomp clears a neighboring `_Bool` while linking pending exports.

- chomp test
- TypeScript differential fuzzer against `stripTypeScriptTypes`

Fixes: guybedford#72
An import() type outside the skipped type declaration constructs (annotations,
generic arguments, as / satisfies) previously leaked a phantom runtime edge.
As a lexer without a full parser these positions cannot be comprehensively
classified, so dynamic imports now carry a best-effort probablyTypeOnly flag
classified by use: typeof import('m') and member or indexed access on the
result other than the promise members then / catch / finally mark the type
position, with await always vetoing as value-certain. Bare unqualified
annotation types remain over-reported as runtime edges.
JS-superset fixes:
* export { type as as } is again the value type renamed as; the type
  modifier now requires an identifier after the second as
* U+00A0 is treated as whitespace in import/export names and around the
  as keyword, matching ES whitespace semantics

TS lexing fixes:
* multi-line conditional / union types stay erased: line-leading ?, :,
  ., =>, extends continue the erased alias RHS
* import A = require('m') records a runtime import edge (type-only
  under import type); namespace alias RHS is erased
* export declare declarations are erased with their names recorded as
  type-only exports; export abstract class records the class name;
  export enum / const enum / namespace record their value names
* bracketed promise member access (import('m')['then']) stays runtime
  and comments no longer defeat dynamic import classification
* reexport from is typed string | undefined and the asm.js build now
  matches the wasm build on undecodable specifiers

All additions are guarded by LEX_TS: the minimal wasm build is
byte-identical, and export * from stays t: 1 there.
@guybedford
guybedford force-pushed the BridgeAR/2026-06-29-ts-on-lexer-min branch from f436815 to 305ae51 Compare August 24, 2026 05:04
@guybedford

Copy link
Copy Markdown
Owner

Rebased to the valid specifier PR. @BridgeAR anything else we still need to check here?

@BridgeAR

Copy link
Copy Markdown
Collaborator Author

I identified a few more issues and am working on them.

Direct strict eval avoids V8's sloppy lookup and strict insertion cache mismatch. It reduces IITM fixture parsing from 25.95 µs to 0.755 µs on Node.js 24.18.0. The asm.js decoder and re-export types retain the same parse-error contract.
A type annotation ended exported variable scanning at its colon, so later declarators were omitted from the export list.
Leading-character gates keep ordinary JavaScript imports and exports out of the TypeScript scanners. Two fresh Node 24.18.0 runs reduced a 147 KB parse from 312.2 to 302.7 µs and from 316.1 to 303.0 µs.
Dynamic imports expose their heuristic through `probablyTypeOnly`. Reading `typeOnly` classified each typed dynamic import as runtime and kept annotated binding lists outside the oracle.
Computed or escaped dynamic-import members can execute at runtime, while ambient declarations can span comments, binding lists, signatures, and bodies. Treating those forms as one-token cases either hid runtime edges or leaked erased imports and dropped exports.

The fuzzer marks expected runtime imports, erased imports, and type-only exports because differential stripping alone cannot detect matching errors on both paths.
@BridgeAR

Copy link
Copy Markdown
Collaborator Author

@guybedford I added more fixes and I also added a performance regression fix that could land as separate PR about use strict. PTAL

BridgeAR and others added 2 commits September 6, 2026 17:40
* perf: decode module strings without eval

The Wasm builds passed validated string literals through eval, so runtimes that disable string code generation rejected otherwise valid modules.

On Node.js 24.20.0, a one-import parse changed from 354.06-361.01 ns to 238.12-240.85 ns. A mixed parse with seven import records changed from 2.035-2.036 µs to 1.128-1.133 µs. The full ESM bundle grows by 176 Brotli bytes.

Refs: nodejs/cjs-module-lexer#118

* perf: bound module string scans

Unbounded backslash searches made 1,000-import modules take 267.0 ns per record instead of 60.7 ns on Node 24.20.0. The same export workload improves from 531.3 to 92.6 ns per record.

Benchmarks used V8 13.6, seven trials, and 500 parse iterations per shape after 50,000 warmup parses.

No-substitution templates now normalize raw CR and CRLF. The parser records CR during its existing scan, so normal strings need no additional pass.

* test: cover minimal CommonJS without eval

The combined minimal and CommonJS mode loaded the full CommonJS bundle, so CI did not exercise the published minimal require path.
* `export { type as }` / `import { type as }` are the type-only specifier
  `as`, matching the TypeScript parser table; previously the export was
  dropped entirely.
* Bare `declare` ambient declarations are erased at statement position like
  bare `type` / `interface`, so `declare const x: import('m').T` no longer
  records a dynamic import edge. `declare` as a plain identifier is untouched.
* `export default interface Foo {}` reports a type-only `default` export.
* Decode on the SafeString bit rather than exact flag equality.
* Drop the orphaned Acorn license header in the asm.js reader now that none
  of its code remains, and rename acornPos to errorPos.
* README: document `probablyTypeOnly` on DynamicImport and the above.
* Tests and fuzz forms for each case; the no-eval lane asserts eval is
  actually disabled.
@guybedford
guybedford merged commit 4f2884b into guybedford:v3 Sep 7, 2026
3 checks passed
This was referenced Sep 7, 2026
Merged
guybedford added a commit that referenced this pull request Sep 7, 2026
## Breaking

* **Full build records are tagged unions** discriminated by `type` (`static` | `reexport-star` | `dynamic` | `import-meta`; `direct` | `reexport` | `reexport-all`) with descriptive fields (`specifier`, `importStart`/`importEnd`, `attributes`, `phase`, `name`, `localName`, `from`, `importIndex`, `exportStart`) replacing the terse v2 names and numeric type tags. (#233)
* **`es-module-lexer/minimal`** is a new entry point holding the v2-shaped API: `parse` returns `[imports, exports]` only; `at` is dropped (read attributes via `source.slice(a, se - 1)`); `export { a as b } from 'c'` reports the imported name in `ln`/`ls`/`le`. (#211, #240)
* **`ImportType`** is a type-only union of named numeric literal aliases (`StaticImportType = 1`, `DynamicImportType = 2`, …); no runtime enum is exported. `initSync` is no longer exported — `parse` initializes on first use. (#240)
* **`es-module-lexer/js`** is the asm.js build; the unmaintained pure-JS port is removed. (#204)
* Invalid escape sequences in static specifiers throw a parse error instead of yielding `undefined`. (#238)
* Node.js 18+ is required. (#232)

## Features

* **TypeScript**: type-only imports, exports, aliases, interfaces and ambient declarations are lexed as accepted by Node.js type stripping; type-only edges carry `typeOnly`, dynamic imports carry a best-effort `probablyTypeOnly`, and erased declaration bodies never leak nested `import()` types. Full builds only. (#220, #241)
* **Export origin analysis**: reexports resolve to their originating import (`importName`, `from`, `importIndex`) regardless of statement order; `export * from` appears in `exports` as `reexport-all` and its import as `reexport-star`. (#229)
* **Template globs**: a dynamic import whose argument is a single template literal reports a glob specifier with each `${…}` collapsed to `*` (`./locales/*.js`), disambiguated by the parser so regex/division inside substitutions is handled. (#205)
* Dynamic import `attributes` is typed `null`; the options argument is located by `attributesStart`. (#240)
* `parse` initializes the Wasm synchronously on first call; `await init` is only required on browser main threads, and all four entry points export the same `parse` / `init` API. (#237, #240)

## Performance

* SIMD scanning for long line comments and templates in the full Wasm build (the minimal build stays Wasm MVP). (#231, #235)
* Identifier and number runs are skipped in bulk: ~15% faster sweeps across Wasm and asm.js. (#227)
* Module strings decode without `eval`: one-import parse 354 → 238 ns, and the Wasm builds now work under `--disallow-code-generation-from-strings`. (#239)
* Short sources (< 64 chars) copy via the typed-array loop rather than `Buffer`. (#242)
* Strict specifier decoding avoids V8's sloppy/strict cache mismatch. (#220)

## Fixes

* Bounds checks on the open-token and dynamic-import stacks; nesting past 1024 brackets or 512 dynamic imports is a parse error rather than memory corruption. (#243)
* Unannotated `declare let`/`var` and shorthand `declare module 'm'` no longer erase the following statement; `export default interface Foo {}` reports `Foo` as its local name. (#241)
* Typed export binding lists collect every declarator; `export { type as }` / `type as as` follow TypeScript's specifier table; U+00A0 is whitespace around import/export names. (#220)
* Minimal build enforces Wasm MVP (no post-MVP features) and is tested in Firefox 67. (#234)

## Docs & tooling

* README restructured: package exports table with Brotli footprint and cold/warm parse speed per MB, environment/CSP/usage up front, minimal-build "Upgrading from v2" section, WASI build steps replaced by the emsdk checkouts the build installs itself. (#240)
* `chomp bench` runs all four builds in one process and prints the README table; generated `types/` are tracked in the repo. (#240)
* TypeScript differential fuzzer against `stripTypeScriptTypes` in CI; no-eval lanes for minimal and CommonJS. (#220, #239)
guybedford added a commit that referenced this pull request Sep 7, 2026
* feat: lex type-only TypeScript imports and exports

Teach the full Wasm and asm.js builds to lex type-only imports, exports, type aliases, and interfaces accepted by Node.js type stripping. Type-only module edges carry `tp: true`, and erased declaration bodies do not leak nested `import()` types into the runtime graph.

Plain JavaScript keeps the same graph, and minimal builds compile the TypeScript paths out. Import metadata uses bit 16 above the public import-type range. Export metadata uses the spare bit above import-name types because fastcomp clears a neighboring `_Bool` while linking pending exports.

- chomp test
- TypeScript differential fuzzer against `stripTypeScriptTypes`

Fixes: #72

* feat: best-effort type-position classification for dynamic imports

An import() type outside the skipped type declaration constructs (annotations,
generic arguments, as / satisfies) previously leaked a phantom runtime edge.
As a lexer without a full parser these positions cannot be comprehensively
classified, so dynamic imports now carry a best-effort probablyTypeOnly flag
classified by use: typeof import('m') and member or indexed access on the
result other than the promise members then / catch / finally mark the type
position, with await always vetoing as value-certain. Bare unqualified
annotation types remain over-reported as runtime edges.

* fix: TS lexing review fixes

JS-superset fixes:
* export { type as as } is again the value type renamed as; the type
  modifier now requires an identifier after the second as
* U+00A0 is treated as whitespace in import/export names and around the
  as keyword, matching ES whitespace semantics

TS lexing fixes:
* multi-line conditional / union types stay erased: line-leading ?, :,
  ., =>, extends continue the erased alias RHS
* import A = require('m') records a runtime import edge (type-only
  under import type); namespace alias RHS is erased
* export declare declarations are erased with their names recorded as
  type-only exports; export abstract class records the class name;
  export enum / const enum / namespace record their value names
* bracketed promise member access (import('m')['then']) stays runtime
  and comments no longer defeat dynamic import classification
* reexport from is typed string | undefined and the asm.js build now
  matches the wasm build on undecodable specifiers

All additions are guarded by LEX_TS: the minimal wasm build is
byte-identical, and export * from stays t: 1 there.

* perf: preserve strict specifier decoding

Direct strict eval avoids V8's sloppy lookup and strict insertion cache mismatch. It reduces IITM fixture parsing from 25.95 µs to 0.755 µs on Node.js 24.18.0. The asm.js decoder and re-export types retain the same parse-error contract.

* fix: collect typed export binding lists

A type annotation ended exported variable scanning at its colon, so later declarators were omitted from the export list.

* perf: defer TypeScript checks behind character gates

Leading-character gates keep ordinary JavaScript imports and exports out of the TypeScript scanners. Two fresh Node 24.18.0 runs reduced a 147 KB parse from 312.2 to 302.7 µs and from 316.1 to 303.0 µs.

* test: fuzz typed export binding lists

Dynamic imports expose their heuristic through `probablyTypeOnly`. Reading `typeOnly` classified each typed dynamic import as runtime and kept annotated binding lists outside the oracle.

* refactor: reuse type-only specifier detection

* fix: correct TypeScript type-only classification

Computed or escaped dynamic-import members can execute at runtime, while ambient declarations can span comments, binding lists, signatures, and bodies. Treating those forms as one-token cases either hid runtime edges or leaked erased imports and dropped exports.

The fuzzer marks expected runtime imports, erased imports, and type-only exports because differential stripping alone cannot detect matching errors on both paths.

* perf: decode module strings without eval (#239)

* perf: decode module strings without eval

The Wasm builds passed validated string literals through eval, so runtimes that disable string code generation rejected otherwise valid modules.

On Node.js 24.20.0, a one-import parse changed from 354.06-361.01 ns to 238.12-240.85 ns. A mixed parse with seven import records changed from 2.035-2.036 µs to 1.128-1.133 µs. The full ESM bundle grows by 176 Brotli bytes.

Refs: nodejs/cjs-module-lexer#118

* perf: bound module string scans

Unbounded backslash searches made 1,000-import modules take 267.0 ns per record instead of 60.7 ns on Node 24.20.0. The same export workload improves from 531.3 to 92.6 ns per record.

Benchmarks used V8 13.6, seven trials, and 500 parse iterations per shape after 50,000 warmup parses.

No-substitution templates now normalize raw CR and CRLF. The parser records CR during its existing scan, so normal strings need no additional pass.

* test: cover minimal CommonJS without eval

The combined minimal and CommonJS mode loaded the full CommonJS bundle, so CI did not exercise the published minimal require path.

* fix: TS review follow-ups

* `export { type as }` / `import { type as }` are the type-only specifier
  `as`, matching the TypeScript parser table; previously the export was
  dropped entirely.
* Bare `declare` ambient declarations are erased at statement position like
  bare `type` / `interface`, so `declare const x: import('m').T` no longer
  records a dynamic import edge. `declare` as a plain identifier is untouched.
* `export default interface Foo {}` reports a type-only `default` export.
* Decode on the SafeString bit rather than exact flag equality.
* Drop the orphaned Acorn license header in the asm.js reader now that none
  of its code remains, and rename acornPos to errorPos.
* README: document `probablyTypeOnly` on DynamicImport and the above.
* Tests and fuzz forms for each case; the no-eval lane asserts eval is
  actually disabled.

---------

Co-authored-by: Guy Bedford <guybedford@gmail.com>
BridgeAR added a commit to nodejs/import-in-the-middle that referenced this pull request Sep 7, 2026
es-module-lexer v3 exposes TypeScript-only exports and bare star re-exports. This removes the ESM TypeScript strip pass and statement-text scan.

CommonJS TypeScript still needs Node's strip pass because cjs-module-lexer does not parse TypeScript syntax. The dependency stays pinned to the reviewed PR head until v3 is published.

Refs: guybedford/es-module-lexer#220
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Can not parse export type {} from 'xxx'

2 participants