Skip to content

[lexical-compiler][lexical-eslint-plugin-internal] Feature: inject /* @__PURE__ */ annotations at build time - #9086

Merged
etrepum merged 17 commits into
meta:mainfrom
etrepum:claude/pure-annotations-build-time-co057o
Aug 24, 2026
Merged

etrepum merged 17 commits into
meta:mainfrom
etrepum:claude/pure-annotations-build-time-co057o

Conversation

@etrepum

@etrepum etrepum commented Aug 21, 2026 •

Copy link
Copy Markdown
Collaborator

Description

In order to enable tree-shaking we added /* @__PURE__ */ annotations to module-scoped calls in the source, enforced by lint. This injects them at build time with a vite/rollup plugin so they don't clutter the source and encourage cargo-culting them into places where they don't belong. This transform also gives us an opportunity to inline the trivial ones into the build product since they are function calls for type inference purposes and have no utility at runtime.

For example:

export const MarkExtension = defineExtension({name: '@lexical/mark', ...});
export const MARK_COMMAND = createCommand('MARK_COMMAND');
// becomes
export const MarkExtension = {name: '@lexical/mark', ...};
export const MARK_COMMAND = /* @__PURE__ */createCommand('MARK_COMMAND');

An annotated definition is only droppable when everything it is built from is droppable too, so one unannotated call in its arguments silently pins it. The build now fails on that instead (strict), naming the call — and the calls that used to need a hand-written annotation for this reason, sel.tag('span').attr('data-x', true) and friends, are annotated by the transform like any other.

More detailed description of the implementation

Module-scope calls to the side-effect-free factories (defineExtension, createCommand, createState, safeCast, …) need a /* @__PURE__ */ annotation for bundlers to tree-shake unused definitions. Until now those annotations lived in the sources, enforced by the @lexical/internal/require-pure-annotation ESLint rule: 442 of them across 131 files, and a lint-fix round trip for every new definition.

This injects them at build time instead, from a new published package @lexical/compiler — Lexical's build-time compiler, whose first pass this is, with codegen for importJSON/exportJSON to follow. Each pass is its own entry point (@lexical/compiler/PureAnnotations), and the root re-exports all of them:

  • pureAnnotations() — a Vite/Rollup plugin (enforce: 'post', so it runs after TypeScript/JSX is compiled away)
  • transformPureAnnotations() — the transform itself, for bundlers with no Rollup-style plugin API
  • PURE_FACTORY_FUNCTIONS / PURE_NAMESPACES / INLINE_FACTORY_FORMS, and pureCallNames() — the same resolution without rewriting the module, which is how the lint rule decides

It runs in scripts/build.mjs (the published bundles carry the annotations exactly as before) and in scripts/vite/lexicalMonorepoPlugin.ts (playground, examples, dev-examples). The annotations are gone from the sources, and require-pure-annotation is replaced by its inverse, @lexical/internal/no-pure-annotation, so a branch written before this migrates with pnpm run lint:fix instead of by hand. It only touches module-scope calls to the factories the build annotates — an annotation on a third-party factory or inside a function body was written deliberately and is left alone.

Publishing it is what keeps source-mode consumers whole: anyone resolving Lexical through the source export condition (a vendored copy, a link:ed checkout) adds the same plugin and gets the same annotations — for their own extension and command definitions too. The linked-checkout docs describe the setup, and the source-mode integration fixture uses it.

Which calls get annotated. The transform resolves the callee to its binding and only annotates when it is imported from lexical/@lexical/* (configurable), declared with @__NO_SIDE_EFFECTS__ in the module or one it imports relatively, or is a method of an object marked @lexical-pure-namespace. A same-named safeCast from your own ./utils is left alone — annotating a call that does have side effects would let a bundler drop it. A declaration is evidence on its own, so marking a factory of your own is enough; it does not also have to be named in the list. The specifier is what decides, which matters for a short name like sel: one imported from d3-selection or declared locally without the marker is not touched, import * as sel and default imports are not followed, and a block that rebinds the name is left alone inside itself.

strict is what makes the annotations a guarantee rather than a habit: it walks the arguments of every module-scope definition and fails on a call nothing has established is side-effect free (1145:25 gfmFootnoteFromMarkdown(...) inside defineExtension(...)). Calls that only run later — a nodes: () => [...] callback, a register body — pin nothing and are not counted, and neither are the built-ins every bundler treats as pure. Both this repo's builds turn it on. A dependency is annotated as usual but never checked — including a Lexical resolved out of node_modules through its source condition, which is the case this package exists for; a definition somebody else shipped is not the building project's to fix. It found four real pins in the examples, and objects whose methods build values and touch nothing else (sel in @lexical/html) are now marked @lexical-pure-namespace, so their calls are annotated by the build rather than by hand — only the outermost call of a chain, which rollup, terser and esbuild all accept as covering the whole chain.

inline: true goes further for the factories whose implementation is a trivial expression over their arguments — safeCast/defineExtension/defineImportRule (identity), configExtension/declarePeerDependency (their arguments as an array) — replacing the call with that literal and removing the import left behind:

export const MarkExtension = defineExtension({name: '@lexical/mark', ...});
// becomes
export const MarkExtension = {name: '@lexical/mark', ...};

A literal needs no annotation to be dropped and nothing is left to pin the definition. Calls that do not fit their form (spread arguments, a discarded result) are annotated as usual, and the call's parentheses are kept where they were doing work. createCommand is deliberately not inlined: {type: x} is more bytes than a call to a minified one-character name.

Each inlined factory is marked @lexical-inline <form> where it is defined. For a non-Lexical source that marker is what makes inlining possible at all — @__NO_SIDE_EFFECTS__ proves a call is safe to drop, only the marker says what it can be replaced with. Unit tests check that the markers in the tree and the transform's table agree, and that evaluating what the transform emits matches what the real function returns, so editing one of these bodies fails there rather than silently producing wrong code. inline is off by default in the published plugin (it assumes a matching Lexical version); Lexical's own build turns it on.

Test plan

pnpm run ci-check, the unit suite and the integration suite pass. What the new tests cover:

  • scripts/__tests__/integration/pure-annotations.test.mjs re-runs the transform over every built artifact and requires nothing left to annotate and nothing left to inline — the check that catches the plugin falling out of scripts/build.mjs.
  • Unit tests bundle a module with Rollup, factories in an external module so the bundler cannot infer purity itself, and assert an unused definition survives without the plugin and is dropped with it — including the nested-argument case that pins the enclosing definition, and the inlined case where no annotation is involved at all.
  • Unit tests check that the @lexical-inline markers in the tree and the transform's table agree, and that evaluating what the transform emits matches what the real function returns, so editing one of these bodies fails there rather than silently producing wrong code.
  • The strict check is exercised over the whole tree by the build itself, plus unit tests for the deferred-call, pure-built-in, annotated-by-hand and dependency cases.
  • A test holds PURE_FACTORY_FUNCTIONS and the declarations to each other, so a factory in the list that never says @__NO_SIDE_EFFECTS__ fails there (it found one: defineOverlayRules).
  • Tests cover which sources are trusted for a namespace, and that a shadowing block turns the annotation off for the calls inside it.
  • The source-mode integration fixture additionally asserts that every module-scope factory call in its bundle is annotated and that no calls to the trivial factories remain.

The published bundles are unchanged in substance — that is the point, the injected annotations reproduce what the hand-written ones did — and dev-examples/mdast-editor builds about 10% smaller with the annotations than without.

…nject /* @__PURE__ */ annotations at build time

## Description

Module-scope calls to the side-effect-free factories (`defineExtension`,
`createCommand`, `createState`, `safeCast`, ...) need a `/* @__PURE__ */`
annotation for bundlers to tree-shake unused definitions. Until now those
annotations were written into the sources and enforced by the
`@lexical/internal/require-pure-annotation` ESLint rule (with an autofixer),
which put 426 annotations across 125 source files and made every new
definition a lint-fix round trip.

This moves the injection to build time. The new published package
`@lexical/pure-annotations` exports:

- `pureAnnotations()` — a Vite/Rollup plugin (`enforce: 'post'`, so it runs
  after TypeScript/JSX is compiled away),
- `transformPureAnnotations()` — the transform itself, for bundlers with no
  Rollup-style plugin API,
- `PURE_FACTORY_FUNCTIONS` — the default factory list.

It parses with @babel/parser, walks only the nodes that are evaluated when the
module is initialized (function bodies, class fields, and static blocks are
skipped, matching the old rule), annotates every unannotated call — nested
argument-position calls included, since one unannotated nested call pins the
enclosing definition — and rewrites through magic-string so source maps stay
correct. It is idempotent, so it is a no-op on already-annotated code such as
the published `dist` bundles.

The plugin runs in `scripts/build.mjs` (after babel, so the published bundles
carry the annotations exactly as before) and in
`scripts/vite/lexicalMonorepoPlugin.ts` (so the playground, examples, and
dev-examples get them for everything they build from source). The annotations
are removed from the sources and the ESLint rule and its test are deleted.

Publishing the package is what keeps `source`-mode consumers whole: anyone
resolving Lexical through the `source` export condition (a vendored copy, a
`link:`ed checkout) now adds the same plugin to their build and gets the same
annotations, for their own extension and command definitions too. The
source-mode integration fixture does exactly that and asserts the annotations
land in its bundle, and the linked-checkout docs describe the setup.

## Test plan

### Before

`pnpm run build` at the parent commit, with the annotations in the sources:

```
$ grep -rn "@__PURE__" packages/lexical/src/LexicalCommands.ts | head -2
30:export const SELECTION_CHANGE_COMMAND: LexicalCommand<void> =
31:  /* @__PURE__ */ createCommand('SELECTION_CHANGE_COMMAND');
$ grep -ro "@__PURE__" packages/*/dist --include=*.mjs | wc -l
297
```

### After

The sources carry no annotations and the build injects them. Comparing the
`packages/*/dist` trees built before and after the change, the only difference
anywhere is the space the old sources did not have after the annotation
(`/* @__PURE__ */defineExtension` vs `/* @__PURE__ */ defineExtension`):

```
$ diff -rq baseline/ stripped/     # (excluding the new package)
$ python3 -c "...normalize annotation spacing, compare every dist file..."
files differing beyond annotation spacing/formatting: 0
$ grep -ro "@__PURE__" packages/*/dist --include=*.mjs | wc -l
298
$ grep -ro "@__PURE__" packages/*/dist --include=*.prod.mjs | wc -l
298
```

The Vite plugin, checked on a playground command that is defined without an
annotation in `src/plugins/CardExtension/index.tsx`:

```
$ pnpm -C packages/lexical-playground run build-dev
✓ built in 11.04s
$ grep -o ".\{20\}INSERT_CARD_COMMAND.\{0,12\}" build/assets/main-*.js | head -1
OMMAND = /* @__PURE__ */ createCommand("INSERT_CARD_COMMAND");
```

```
$ npx vitest --project unit --no-watch packages/lexical-pure-annotations
 Test Files  1 passed (1)
      Tests  24 passed (24)
$ pnpm run test-unit
 Test Files  259 passed (259)
      Tests  5185 passed | 1 skipped (5186)
$ pnpm run ci-check      # tsc, tsc-scripts, tsc-extension, tsc-website, flow, prettier, lint
(no output; all clean)
$ node scripts/build.mjs --prod
(exit 0)
```

The integration suite (`pnpm run test-integration`), which is what exercises
the source-mode fixture's new `pureAnnotations()` assertion end to end, was
not run locally: its global setup runs `pnpm run prepare-release`, which
rewrites `scripts/error-codes/codes.json`.

Co-Authored-By: Claude Opus 5 <[email protected]>
@vercel

vercel Bot commented Aug 21, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
lexical Ready Ready Preview Aug 24, 2026 7:52pm
lexical-playground Ready Ready Preview Aug 24, 2026 7:52pm

Request Review

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Aug 21, 2026
…to a side-effect-free factory, and test the tree-shaking

## Description

Two gaps in the build-time annotation transform.

**It matched bare names.** Like the ESLint rule it replaces, the transform
annotated any module-scope call to a function *named* `safeCast`,
`createCommand`, `createState`, ... That was tolerable inside this repo, but
the plugin is published and runs over application code, where an unrelated
same-named function may well have side effects — and annotating such a call
lets a bundler drop it.

The transform now resolves the callee to its binding and only annotates when
that binding is one of:

- an import from `lexical` or `@lexical/*` (the new `sources` option), where
  every factory is declared `@__NO_SIDE_EFFECTS__`; aliased imports resolve
  too, which the name matching could not do;
- a declaration in the same module marked `@__NO_SIDE_EFFECTS__` (how the
  factory modules themselves are written); or
- an import from a relative module that declares it `@__NO_SIDE_EFFECTS__` —
  the imported file is read and parsed to check (`relativeImports: false`
  turns that off).

Across the monorepo's 426 annotated call sites that is 360 imported from a
Lexical package, 58 declared in the same module, and 8 (`defineImportRule` in
`@lexical/html`) reached through a relative import — so the built output is
unchanged, while a consumer's own `safeCast` from `./utils` is now left alone.

**Nothing tested that the annotations tree-shake anything.** The tests only
checked that annotations were present. Added:

- unit tests that bundle a module with Rollup, with the factories in an
  external module so the bundler cannot infer purity for itself, and assert
  that an unused definition survives without the plugin and is dropped with
  it — including the nested-argument case (`safeCast` inside a
  `defineExtension` config) that pins the enclosing definition;
- an integration test that re-runs the transform over every built artifact
  and requires it to find nothing left to annotate, which is what catches the
  annotations silently not reaching the published bundles;
- the same property check in the source-mode fixture, replacing an assertion
  that also passed without the plugin (Rollup adds annotations of its own for
  calls it proves pure, so grepping for one proved nothing there).

`node:*` is added to the build's externals now that the transform reads
relatively imported modules from disk.

## Test plan

### Before

The published bundles depend on the plugin, but nothing failed when it was
removed from `scripts/build.mjs`:

```
$ node scripts/build.mjs   # with pureAnnotations() removed
$ pnpm run test-unit
 Test Files  259 passed (259)
      Tests  5185 passed | 1 skipped (5186)
```

...while the dist those tests passed against had lost every annotation:

```
$ grep -c "@__PURE__ \*/ createCommand" packages/lexical/dist/Lexical.dev.mjs
0
```

And a same-named function from anywhere else was annotated all the same:

```
> transformPureAnnotations("import {safeCast} from './my-utils';\n" +
    "export const config = safeCast({a: 1});")
{code: "...export const config = /* @__PURE__ */ safeCast({a: 1});", count: 1}
```

### After

The new integration guard fails on exactly that build (run here as a script,
since the integration project's global setup rewrites
`scripts/error-codes/codes.json`):

```
$ node verify.mjs dist-built-without-the-plugin
686 files, 31 with unannotated factory calls
    lexical/dist/Lexical.dev.js (50)
    lexical/dist/Lexical.dev.mjs (50)
    lexical-a11y/dist/LexicalA11y.dev.mjs (9)
$ node verify.mjs packages/lexical/dist packages/lexical-html/dist
packages/lexical/dist: 7 files, 0 with unannotated factory calls
packages/lexical-html/dist: 7 files, 0 with unannotated factory calls
```

Binding resolution leaves the build byte-for-byte unchanged — all 97 existing
`*.dev.mjs` bundles are identical to the ones the name-matching version
produced:

```
$ node scripts/build.mjs
$ python3 compare.py   # name-only vs binding-scoped dev bundles
name-only vs binding-scoped: compared 98 dev bundles, 1 differences
  ('DIFFERS', 'lexical-pure-annotations/dist/LexicalPureAnnotations.dev.mjs')
```

```
$ npx vitest --project unit --no-watch packages/lexical-pure-annotations
 Test Files  2 passed (2)
      Tests  34 passed (34)
$ pnpm run test-unit
 Test Files  260 passed (260)
      Tests  5195 passed | 1 skipped (5196)
$ npx tsc && npx tsc -p tsconfig.scripts.json && npx eslint ./ && npx prettier --list-different .
(no output; all clean)
```

The source-mode fixture, built and verified the way the integration suite
does:

```
$ pnpm install --ignore-workspace && pnpm run build && pnpm run test
ok - bundle includes class LexicalEditor (proves lexical source was compiled, not the prebuilt artifact)
ok - bundle exports makeEditor
ok - bundle includes registerRichText (proves @lexical/rich-text was bundled)
ok - bundle includes buildEditorFromExtensions (proves @lexical/extension was bundled)
ok - bundle does not reference any prebuilt artifact (no `Lexical*.{dev,prod,node}.{js,mjs}` paths)
ok - every module-scope factory call in the bundle is annotated
```

Co-Authored-By: Claude Opus 5 <[email protected]>
…trivial factory calls at build time

## Description

`safeCast`, `defineExtension`, `defineImportRule`, `configExtension`, and
`declarePeerDependency` are type-level helpers whose implementation is a
trivial expression over their own arguments. Annotating a call to one of them
tells the bundler it may drop the result; replacing the call with the
expression it would have returned is better in every way that matters: a
literal is inert for every bundler with no annotation to carry through
minification, there is no nested call left to pin the definition it appears
in, and the factory itself drops out of the bundle once nothing calls it.

`transformPureAnnotations` (and the plugin) take a new `inline` option that
does that:

```js
export const MarkExtension = defineExtension({name: '@lexical/mark', ...});
// becomes
export const MarkExtension = {name: '@lexical/mark', ...};
```

along with the import that is left over once nothing calls the factory — an
import specifier is removed only when every reference to the name anywhere in
the module (function bodies, re-exports, JSX included) was one of the calls
just replaced.

A call that does not fit its factory's form is annotated as before: a spread
argument, `declarePeerDependency` with one argument (which returns
`[name, undefined]`, not `[name]`), a comma expression that would lose its
parentheses, or a call whose result is discarded (where an object literal
would parse as a block). `createCommand` is deliberately not inlined:
`{type: x}` is more bytes than a call to a minified one-character name.

**Keeping the coupling honest.** The transform reproduces those function
bodies, so each one is marked `@lexicalInline <form>` where it is defined and
listed in the transform's `INLINE_FACTORIES`, and the package's unit tests
check both halves: that the markers in the tree and the table agree exactly,
and that evaluating what the transform emits gives the same result as calling
the real function. Editing one of these functions without updating the
transform fails there rather than silently producing wrong code in somebody's
bundle.

`inline` is **off by default** in the published plugin because it assumes the
Lexical being built matches this package's version. Lexical's own build turns
it on, as do the monorepo's vite builds and the source-mode integration
fixture, all of which build this checkout by construction.

## Test plan

### Before

The published bundles carried the calls, annotated:

```
$ grep -A 3 "^const MarkExtension" packages/lexical-mark/dist/LexicalMark.dev.mjs
const MarkExtension = /* @__PURE__ */ defineExtension({
  name: '@lexical/mark',
  nodes: () => [MarkNode]
});
```

### After

```
$ node scripts/build.mjs
$ grep -A 3 "^const MarkExtension" packages/lexical-mark/dist/LexicalMark.dev.mjs
const MarkExtension = {
  name: '@lexical/mark',
  nodes: () => [MarkNode]
};
```

Removing the calls leaves their imports unused, which Rollup warns about
(`"defineExtension" is imported from external module "lexical" but never used`)
— 60 such warnings before the import removal, none after:

```
$ node scripts/build.mjs 2>&1 | grep -c "never used in"
0
```

The built bundles still behave: a script that imports `dist` and builds an
editor out of the inlined definitions (extension config, a `configExtension`
dependency tuple, a command dispatch):

```
$ node dist-smoke.mjs
ok - built bundles: extension config, dependencies, commands, editor
```

A consumer bundle over the same source, built with and without `inline`
(the source-mode fixture, unminified):

```
inline: true  -> 617721 bytes, gzip 132558
inline: false -> 620123 bytes, gzip 133039
```

```
$ npx vitest --project unit --no-watch packages/lexical-pure-annotations
 Test Files  3 passed (3)
      Tests  57 passed (57)
$ pnpm run test-unit
 Test Files  261 passed (261)
      Tests  5218 passed | 1 skipped (5219)
$ pnpm run ci-check
(no output; all clean)
$ node scripts/build.mjs --prod && pnpm -C packages/lexical-playground run build-prod
(exit 0)
```

The source-mode fixture, built and verified the way the integration suite
does, with a new assertion that the trivial factories are gone from the
bundle entirely:

```
$ pnpm install --ignore-workspace && pnpm run build && pnpm run test
ok - bundle includes class LexicalEditor (proves lexical source was compiled, not the prebuilt artifact)
ok - bundle exports makeEditor
ok - bundle includes registerRichText (proves @lexical/rich-text was bundled)
ok - bundle includes buildEditorFromExtensions (proves @lexical/extension was bundled)
ok - bundle does not reference any prebuilt artifact (no `Lexical*.{dev,prod,node}.{js,mjs}` paths)
ok - every module-scope factory call in the bundle is annotated
ok - the trivial factories are inlined away (no calls left in the bundle)
```

The dist guard added in the previous commit now checks both halves (nothing
left to annotate, nothing left to inline). Run here as a script, since the
integration project's global setup rewrites `scripts/error-codes/codes.json`:

```
$ node guard.mjs
686 files checked, 0 incomplete
```

Co-Authored-By: Claude Opus 5 <[email protected]>
…ng code

## Description

Code review of the inlining pass found five cases where replacing a call with
a literal was not equivalent to the call. All five are reproducible with the
transform and now have regression tests.

**The call's parentheses were doing work.** Identity inlining dropped them
outright, so `safeCast(1 + 2) * 3` became `1 + 2 * 3` (9 → 7) and
`safeCast(a || b).c` became `a || b.c`. The parentheses are now kept unless
the argument is self-delimiting (an object or array literal, an identifier, a
literal, a template, JSX) — cases a minifier drops the parentheses from
anyway.

**An object literal cannot start an expression statement.** The guard only
covered a call that *was* the whole statement, so
`defineExtension({name: 'a'}).name;` became `{name: 'a'}.name;`, a
SyntaxError. Every node that begins an expression statement starts at the
same offset, so recording that one offset per statement identifies the whole
leftmost chain, wherever the call sits in it; those get parentheses too.

**`@__NO_SIDE_EFFECTS__` proves purity, not shape.** For a factory declared in
the module or reached through a relative import, that annotation was the only
evidence required, so a local `defineExtension` that returned something other
than its argument was replaced by that argument, dropping whatever else it
did. Inlining now needs the `@lexicalInline <form>` marker to agree with the
table (the marker was declared but never read — the one lint warning in the
new code). An import from a Lexical package is still taken on trust, which is
the version assumption `inline` already documents; everything else has to say
what shape it returns. A pure-but-unmarked look-alike is annotated instead.

**Import removal measured the wrong neighbour.** It took the span between
adjacent *specifiers*, so with a default import `import React, {safeCast}`
became `import React} from 'lexical'`. It now works within the braced clause,
and removes the clause and the comma before it when a default or namespace
import remains.

**Dropping the last import dropped the module.** Left as is: as noted in
review, a module that declares `@__NO_SIDE_EFFECTS__` (and `@lexicalInline`)
factories does not have module side effects to preserve, and the Lexical
packages are all `sideEffects: false`. The reasoning is now a comment where
the import is removed.

## Test plan

### Before

```
> transformPureAnnotations("import {safeCast} from 'lexical';\n" +
    "export const x = safeCast(1 + 2) * 3;", {inline: true}).code
"\nexport const x = 1 + 2 * 3;"

> transformPureAnnotations("import {defineExtension} from 'lexical';\n" +
    "defineExtension({name: 'a'}).name;", {inline: true}).code
"\n{name: 'a'}.name;"

> transformPureAnnotations("import React, {safeCast} from 'lexical';\n" +
    "export const c = safeCast({a: 1});\nexport const r = React;",
    {inline: true}).code
"import React} from 'lexical';\nexport const c = {a: 1};\nexport const r = React;"

> transformPureAnnotations("/**\n * @__NO_SIDE_EFFECTS__\n */\n" +
    "function defineExtension(c) { return {...c, extra: 1}; }\n" +
    "export const E = defineExtension({name: 'e'});", {inline: true}).code
"...export const E = {name: 'e'};"      // the `extra: 1` is gone
```

### After

```
export const x = (1 + 2) * 3;
({name: 'a'}).name;
import React from 'lexical';
export const E = /* @__PURE__ */ defineExtension({name: 'e'});
```

```
$ npx vitest --project unit --no-watch packages/lexical-pure-annotations
 Test Files  3 passed (3)
      Tests  61 passed (61)
$ pnpm run test-unit
 Test Files  261 passed (261)
      Tests  5222 passed | 1 skipped (5223)
$ pnpm run ci-check
(no output; all clean)
```

The build still inlines everything it did before — including the eight
`defineImportRule` calls in `@lexical/html`, which are reached through a
relative import and so now depend on that module's `@lexicalInline` marker:

```
$ node scripts/build.mjs 2>&1 | grep -c "never used in"
0
$ grep -n "defineImportRule(" packages/lexical-html/dist/LexicalHtml.dev.mjs
2896: * defineImportRule({          # a doc comment
2910:function defineImportRule(rule) {   # the definition; no calls left
$ node dist-smoke.mjs
ok - built bundles: extension config, dependencies, commands, editor
```

The source-mode fixture still passes all seven assertions, including that the
trivial factories are gone from the bundle.

Co-Authored-By: Claude Opus 5 <[email protected]>
…jected annotation

## Description

The transform inserted `/* @__PURE__ */ ` with a trailing space, copied from
the ESLint fixer it replaced. In source that space was worth having — the
annotation was prettier-formatted text a human reads, and it gives prettier a
break opportunity for wrapping — but the transform writes into build output
that prettier never sees, and a block comment is a token separator on its own,
so the space serves no grammatical purpose there. Terser strips it from the
prod bundles anyway.

Dropping it also makes the build's output line up with what babel used to
print for the hand-written annotations, so the dist is byte-identical to main
apart from deliberate source changes.

## Test plan

### Before

```
$ grep -o "PURE__ \*/[A-Za-z_$]\{1,14\}" packages/lexical/dist/Lexical.dev.mjs | head -1
PURE__ */ createCommand
```

...where main, whose annotations went through babel, printed no space:

```
$ grep -o "PURE__ \*/[A-Za-z_$]\{1,14\}" main/packages/lexical/dist/Lexical.dev.mjs | head -1
PURE__ */createCommand
```

### After

```
$ node scripts/build.mjs
$ grep -o "PURE__ \*/[A-Za-z_$]\{1,14\}" packages/lexical/dist/Lexical.dev.mjs | head -1
PURE__ */createCommand
```

Comparing every built artifact against a `main` build, with inlining off so
only the annotations differ: 918 of 929 files are byte-identical. The 11 that
differ are all accounted for — 7 by the `@lexicalInline` marker lines added to
the factory JSDoc (2 bundles, 2 more in @lexical/html, 3 `.d.ts`), and 4
because main's source had the annotation wrapped onto its own line by prettier
and babel reproduced that, where the transform writes it inline:

```
-  /* @__PURE__ */
-  configExtension(MdastImportExtension, {
+  /* @__PURE__ */configExtension(MdastImportExtension, {
```

```
$ pnpm run test-unit
 Test Files  261 passed (261)
      Tests  5222 passed | 1 skipped (5223)
$ pnpm run ci-check
(no output; all clean)
$ node scripts/build.mjs 2>&1 | grep -c "never used in"
0
```

The built bundles still behave (an editor built from the inlined definitions
in `dist` runs), and the source-mode fixture passes all seven assertions.

Co-Authored-By: Claude Opus 5 <[email protected]>
…rDependency call

## Description

`declarePeerDependency(name, config?)` returned `[name, config]`, so a call
with one argument produced `[name, undefined]` — two elements — while its
arguments were one. The build's `args` inline form replaces a call with its
argument list, so `declarePeerDependency` needed a separate `tuple` form with
an arity, and the common one-argument call could not be inlined at all: it
was annotated `/* @__PURE__ */` and left in the bundle along with the import
of the factory.

`NormalizedPeerDependency` now declares the config as an optional tuple
element rather than a required one that may be `undefined`, and the function
returns its rest arguments unchanged. `[name]` and `[name, config]` are both
assignable to the tuple, every consumer already destructures it, and the
serialized `EditorState` is not involved. That makes the runtime value
exactly the argument list for every arity, so the plugin's `args` form
applies and the `tuple` form and its `arity` are gone.

## Test plan

### Before

```
$ node demo.mjs   # transformPureAnnotations(..., {inline: true})
import {declarePeerDependency} from '@lexical/extension';
export const peers = [/* @__PURE__ */declarePeerDependency('@lexical/react')];
```

```
$ npx vitest --project unit --no-watch packages/lexical/src/__tests__/unit/LexicalExtensionCore.test.ts
 FAIL  packages/lexical/src/__tests__/unit/LexicalExtensionCore.test.ts > declarePeerDependency > validates the type argument
AssertionError: expected [ 'other' ] to deeply equal [ 'other', undefined ]
```

### After

```
$ node demo.mjs   # transformPureAnnotations(..., {inline: true})
export const peers = [['@lexical/react']];
```

```
$ npx vitest --project unit --project scripts-unit --no-watch
 Test Files  261 passed (261)
      Tests  5223 passed | 1 skipped (5224)

$ pnpm run ci-check
No errors!
```

Flow, TypeScript, Prettier and ESLint all pass; the browser and E2E suites
were not exercised for this change.

Co-Authored-By: Claude Opus 5 <[email protected]>
claude added 3 commits August 21, 2026 20:32
…nline marker to @lexical-inline

## Description

The marker that tells the build a factory's body is a trivial expression was
`@lexicalInline`, which is hard to read: `l` and `I` are near-identical in
most fonts, and the tag puts them adjacent. It is now `@lexical-inline`,
following the shape of a tool directive in a comment (`@ts-expect-error`,
`@ts-check`) rather than a documentation tag, which also keeps it out of the
`@__UPPER__` namespace that bundlers parse — nothing outside
`@lexical/pure-annotations` reads this marker.

Nothing consumes the old spelling: the marker was introduced on this branch
and has never been released.

## Test plan

### Before

```
$ grep -rn "@lexicalInline" packages/lexical/src/extension-core/safeCast.ts
15: * @lexicalInline identity
```

### After

```
$ grep -rn "@lexical-inline" packages/lexical/src/extension-core/safeCast.ts
15: * @lexical-inline identity

$ npx vitest --project unit --no-watch packages/lexical-pure-annotations
 Test Files  3 passed (3)
      Tests  62 passed (62)
```

The tests that check the markers in the tree against the transform's table
pass, which is what proves no marker was left behind in the old spelling.

Co-Authored-By: Claude Opus 5 <[email protected]>
…playground] Feature: lint away hand-written pure annotations

## Description

With the annotations injected at build time, a `/* @__PURE__ */` written in
the source is redundant — and there is no longer anything stopping one from
coming back. Merging `main` into this branch brought nine of them in with
new code, and they had to be removed by hand.

`@lexical/internal/no-pure-annotation` is the inverse of the
`require-pure-annotation` rule this branch deleted: it reports a
`/* @__PURE__ */` (or terser's `/* #__PURE__ */`) immediately before a
module-scope call to one of the factories the build annotates, and the fix
removes it. So a branch written before the transform existed migrates with
`pnpm run lint:fix` rather than by hand.

It is deliberately narrow. Annotations on anything else are left alone: a
third-party factory (`sel.tag(...)`, `gfmTable()`, `signal()`), or a call
inside a function body, class field, or static block — the build never
injects one there, so whoever wrote it meant it. The rule is scoped to the
sources, examples, and scripts, and skips `packages/lexical-pure-annotations`
itself, whose fixtures contain annotations as data.

Also removes the annotations that came in with the merge, in
`AutoLinkAnnounceExtension`, `WordListImportExtension`, and their tests.

## Test plan

### Before

The rule found one the manual sweep of the merge had missed:

```
$ pnpm run lint
/home/user/lexical/packages/lexical-playground/__tests__/unit/RubyNode.test.ts
  27:27  error  Remove this /* @__PURE__ */ annotation: the build injects it for every module-scope call to defineExtension (@lexical/pure-annotations), for the published bundles and for anything built from source  @lexical/internal/no-pure-annotation

✖ 1 problem (1 error, 0 warnings)
  1 error and 0 warnings potentially fixable with the `--fix` option.
```

### After

`eslint --fix` on `main`'s copy of a file that carried the annotations
reproduces this branch's copy of it byte for byte:

```
$ git show origin/main:packages/lexical-list/src/LexicalListExtension.ts > packages/lexical-list/src/LexicalListExtension.ts
$ npx eslint --fix packages/lexical-list/src/LexicalListExtension.ts
$ diff /tmp/keep.ts packages/lexical-list/src/LexicalListExtension.ts && echo IDENTICAL
IDENTICAL
```

```
$ pnpm run lint
(no output)

$ npx vitest --project unit --project scripts-unit --no-watch
 Test Files  265 passed (265)
      Tests  5240 passed | 1 skipped (5241)

$ pnpm run ci-check
(no output; all clean)
```

Co-Authored-By: Claude Opus 5 <[email protected]>
…ddress the code review findings

## Description

Six fixes from the review of this branch, all in the transform and the lint
rule that came with it.

**An inlined `args` array could be misparsed.** The replacement was written
bare on the theory that "an array literal reads the same in every position",
which is false at the start of an expression statement: `f()` on the previous
line and `[a, b].length` on this one is one member access, not two
statements. The array is now parenthesized, so it binds exactly where the
call it replaced did; terser drops the parentheses again
(`dependencies:[ot,[lt,{rules:Qt}]]` in the prod bundle).

**Inlining a call dropped the annotation on a nested one.**
`magicString.overwrite` clears the intro and outro of every chunk it spans,
and an annotation appended before a nested call lives in the outro of the
chunk that ends where that call begins — so `defineExtension(createCommand('X'))`
inlined to `(createCommand('X'))` with the annotation gone. The overwrites
that rewrite a call's own syntax now pass `contentOnly`.

**An overloaded factory was invisible to a relative import.** TypeScript puts
the documentation, and so the `@__NO_SIDE_EFFECTS__`, on the first overload
signature, which parses as a `TSDeclareFunction`; only `FunctionDeclaration`
was checked, so a relatively imported `domOverride` got no annotation.

**Removing adjacent unused imports stranded a comma.** Two overlapping
`remove` ranges left `import {createCommand, } from 'lexical';`. Each run of
removable specifiers is now taken out as a single range.

**A `@lexical-inline` marker naming an unknown form was silent**, which is
how the stale `tuple` form in the public docs went unnoticed: the factory
simply did not get inlined. An unknown or missing form now throws, naming the
file and the forms it accepts, and the marker is only recognized as a JSDoc
tag so that prose describing it (including this package's own) is not one.
While fixing that: a marker on a factory of your own now authorizes inlining
it, which is what the README already claimed but the table lookup did not do.

**The lint rule matched on the callee's name alone**, so it could delete an
annotation the build would not put back — somebody's own `safeCast` from
`./utils`. It now asks the transform which names it would annotate, through
a new `pureFactoryNames` export, instead of keeping a second hand-copy of
`PURE_FACTORY_FUNCTIONS`. Its scope also no longer includes `scripts/**`,
which the transform never runs over.

`node:[a-z]+` in the build's externals is now `node:[a-z_]+`, so
`node:child_process` and friends match.

## Test plan

### Before

```
$ node probe.mjs   # transformPureAnnotations(..., {inline: true})
--- ASI hazard: args form at statement start ---
const x = f()
[A, {}].length;

--- nested annotated call inside an inlined one ---
export const E = (createCommand('X'));
```

### After

```
$ node probe.mjs
--- ASI hazard: args form at statement start ---
const x = f()
([A, {}]).length;

--- nested annotated call inside an inlined one ---
export const E = (/* @__PURE__ */createCommand('X'));

$ npx vitest --project unit --no-watch packages/lexical-pure-annotations packages/lexical-eslint-plugin-internal
 Test Files  4 passed (4)
      Tests  70 passed (70)

$ node scripts/build.mjs && node scripts/build.mjs --prod
DEV=0
PROD=0

$ npx vitest --project integration --no-watch scripts/__tests__/integration/pure-annotations.test.mjs
 Test Files  1 passed (1)
      Tests  34 passed (34)

$ npx vitest --project unit --project scripts-unit --no-watch
 Test Files  265 passed (265)
      Tests  5246 passed | 1 skipped (5247)

$ pnpm run ci-check
(no output; all clean)
```

Co-Authored-By: Claude Opus 5 <[email protected]>
…ion's arguments are tree-shakeable

## Description

An annotated definition is only droppable when everything it is built from is
droppable too, so a single unannotated call in its arguments quietly pins it
into every bundle that imports the module — however well annotated the
definition itself is. Nothing checked for that, and the only way to keep such
a call from pinning a definition was to notice it and write
`/* @__PURE__ */` by hand, which is what the rest of this branch set out to
stop doing.

Two changes, together making that a guarantee rather than a habit.

**`strict`** walks the arguments of every module-scope definition and fails
on a call nothing has established is side-effect free, naming it:

```
1145:25 gfmFootnoteFromMarkdown(...) inside defineExtension(...)
```

Calls that only run later (a `nodes: () => [...]` callback, a `register`
method body) are not counted — they pin nothing — and neither are the
built-ins every bundler already treats as pure (`new Map(...)`, `Object`,
`Symbol`, …). `scripts/build.mjs` and the monorepo's Vite plugin both turn it
on, so the published bundles and everything built from source are covered.

**Pure namespaces** make `sel.tag('span').attr('data-x', true)` the
transform's business rather than the author's. An object whose methods build
values and touch nothing else is marked `@lexical-pure-namespace` where it is
declared — `sel` and `selBase` in `@lexical/html` are — and calls to its
methods are annotated like a factory call. Only the outermost call of a chain
gets the annotation: rollup, terser and esbuild all drop the whole chain from
that one. The four hand-written `sel` annotations left in the tree are gone,
removed by `lint:fix` now that the rule understands namespaces too.

Two smaller changes fell out of making the check pass:

- A declaration marked `@__NO_SIDE_EFFECTS__` is now evidence on its own,
  whether it is in the module or one it imports relatively, so a factory of
  your own no longer has to be named in `functions` to have its calls
  annotated. This is also what makes the built bundles consistent with their
  sources: `$withContext` is annotated in `@lexical/html`'s dist because the
  modules that call it now annotate it.
- The two per-file caches became one, so a relatively imported module is
  parsed once for both questions rather than twice.

The check found four real pins outside the packages: `createStyleImportRule`
in the node-state-style example (now declared side-effect free) and three
micromark extensions in the mdast-editor example (annotated at the call site,
as `@lexical/mdast` already does for the others).

## Test plan

### Before

```
$ node survey.mjs   # transformPureAnnotations(..., {strict: true}) over the tree
packages/lexical-html/src/import/coreImportRules.ts
  246:10 sel.tag(...) inside defineImportRule(...)
  ...
examples/node-state-style/src/styleState.ts
  379:15 createStyleImportRule(...) inside defineExtension(...)
dev-examples/mdast-editor/src/extensions/MdastFootnoteExtension.ts
  1145:25 gfmFootnoteFromMarkdown(...) inside defineExtension(...)
  1146:29 gfmFootnote(...) inside defineExtension(...)
  1147:30 gfmFootnoteToMarkdown(...) inside defineExtension(...)

13 violation(s) of 967 files scanned
```

### After

```
$ node survey.mjs
0 violation(s) of 967 files scanned

$ node scripts/build.mjs && node scripts/build.mjs --prod
DEV=0
PROD=0

$ npx vitest --project integration --no-watch scripts/__tests__/integration/pure-annotations.test.mjs
 Test Files  1 passed (1)
      Tests  34 passed (34)

$ npx vitest --project unit --project scripts-unit --no-watch
 Test Files  266 passed (266)
      Tests  5259 passed | 1 skipped (5260)

$ pnpm run lint
(no output)

$ pnpm run ci-check
(no output; all clean)
```

That a single annotation on the outermost call of a chain is enough was
checked against all three bundlers rather than assumed:

```
none         rollup: KEPT     terser: KEPT     esbuild: KEPT
outer only   rollup: dropped  terser: dropped  esbuild: dropped
each link    rollup: dropped  terser: dropped  esbuild: dropped
```

Build time is unchanged in substance: 28s for the dev build, 75s for prod.

Co-Authored-By: Claude Opus 5 <[email protected]>
@etrepum etrepum changed the title [lexical-pure-annotations][lexical-eslint-plugin-internal] Feature: inject /* @__PURE__ */ annotations at build time [lexical-compiler][lexical-eslint-plugin-internal] Feature: inject /* @__PURE__ */ annotations at build time Aug 22, 2026
@etrepum etrepum added the extended-tests Run extended e2e tests on a PR label Aug 22, 2026
…pty stubs

## Description

Both `.js.flow` files were the generated placeholder — a header and the
module name — so a Flow consumer importing `@lexical/compiler` would find a
module with no exports rather than the API. `@lexical/eslint-plugin` ships
the same placeholder, but that is a gap to fix rather than a pattern to copy,
and AGENTS.md asks for types in both systems.

`LexicalCompilerPureAnnotations.js.flow` now declares the pass: the option,
result, source map and plugin object types, the three tables, and
`transformPureAnnotations` / `pureCallNames` / `pureAnnotations`.
`LexicalCompiler.js.flow` re-exports it, mirroring what `src/index.ts` does
for the entry that carries every pass.

The libdefs use `ReadonlyArray`/`ReadonlySet`/`ReadonlyMap` and `unknown`
rather than the `$ReadOnly*`/`mixed` spellings, which this Flow version
reports as deprecated.

## Test plan

### Before

```
$ cat packages/lexical-compiler/flow/LexicalCompiler.js.flow
/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * ...
 * @flow strict
 */

/**
 * LexicalCompiler
 */
```

Nothing an importer can use.

### After

```
$ npx flow check
No errors!

$ pnpm run lint
(no output)

$ npx prettier --check packages/lexical-compiler/flow/*.js.flow
All matched files use Prettier code style!
```

Co-Authored-By: Claude Opus 5 <[email protected]>
… explicitly

## Description

`src/LexicalCompiler.mjs` read as the implementation of the package's root
entry, which it is not: the root entry is built from `src/index.ts`, and that
file is the tree-shaking pass behind `@lexical/compiler/PureAnnotations`. It
is now `src/passes/pureAnnotations.mjs`, which also gives the next pass an
obvious home and keeps the top level of `src/` to what it means there — one
`.ts` per published entry point, since `update-version` generates an entry
for each of them.

The mix of `.ts` and `.mjs` is deliberate but was under-explained. A pass is
plain JavaScript because `scripts/build.mjs` runs under plain node and
imports it from source to annotate the packages it is building, before
anything has been compiled; node cannot load TypeScript. Its types are JSDoc,
and the `.ts` facade beside it is the published API — which is not a second
copy of the types so much as a checked one: the facade calls into the pass,
so a mismatch between them is a compile error (that is how the `namespaces`
option's type was caught while it was being added).

That checking was incidental, though: `tsconfig.scripts.json` covers
`scripts/`, and the pass was only reached because `build.mjs` imports it — if
that import ever went away, the file would silently stop being checked.
`packages/lexical-compiler/src/passes` is now in that project's `include`, so
it is checked on its own terms, with `checkJs` and `strict`.

## Test plan

### Before

```
$ npx tsc -p tsconfig.scripts.json   # with a deliberate error in the file
packages/lexical-compiler/src/LexicalCompiler.mjs(1297,9): error TS2322: Type 'string' is not assignable to type 'number'.

$ npx tsc --noEmit                   # the root project does not see it
(no output)
```

Checked, but only through `scripts/build.mjs`'s import.

### After

```
$ npx tsc -p tsconfig.scripts.json   # same deliberate error, now via `include`
packages/lexical-compiler/src/passes/pureAnnotations.mjs(1370,9): error TS2322: Type 'string' is not assignable to type 'number'.

$ npx tsc -p tsconfig.scripts.json   # reverted
(no output)

$ npx vitest --project unit --project scripts-unit --no-watch
 Test Files  266 passed (266)
      Tests  5270 passed | 1 skipped (5271)

$ npx vitest --project integration --no-watch
 Test Files  4 passed (4)
      Tests  190 passed (190)

$ node scripts/build.mjs && node scripts/build.mjs --prod
DEV=0
PROD=0

$ pnpm run ci-check
(no output; all clean)
```

Co-Authored-By: Claude Opus 5 <[email protected]>
## Description

`History › Can coalesce when switching inline styles (meta#1151)` fails
intermittently on WebKit in CI, leaving part of a typed run behind after an
undo — `bar` undone to `b`, or `baz` to `b` one step later.

The test types three bursts and asserts that undo walks back exactly three
entries. Whether a burst is one entry depends on `@lexical/history`'s merge
window, which is wall-clock: consecutive same-type changes merge only while
`changeTime < prevChangeTime + delay`, with `delay` 300ms by default. On a
loaded runner a single inter-keystroke gap can exceed that, so the burst
splits across two entries and the first undo removes only its tail — exactly
the leftover character in the CI output. Nothing about the split is
WebKit-specific; WebKit is just where the runner is slowest.

`advanceHistoryClock` already exists for this: it freezes the injectable
`now` past the merge window, so bursts after it coalesce regardless of how
long the keystrokes actually take. The sibling test in this file was fixed
the same way. Frozen, the only boundaries left in this test are the style
switches — which is the property meta#1151 is about, so the test now asserts it
without the wall clock participating.

## Test plan

WebKit cannot run in this environment (the image ships `webkit-2336` against
a Playwright pinned to `webkit-2287`, and it is missing system libraries
besides), so the race was made deterministic instead: typing each burst with
a 400ms inter-keystroke delay exceeds the 300ms window on any engine and
reproduces the CI signature.

### Before

```
$ pnpm exec playwright test --project=chromium -g "Can coalesce when switching inline styles"
   # with {delay: 400} on each burst
    Error: innerHTML of contenteditable in page did not match
    - Expected  - 0
    + Received  + 3

      <p class="PlaygroundEditorTheme__paragraph" dir="auto">
        <strong class="PlaygroundEditorTheme__textBold" data-lexical-text="true">foo</strong>
        <span data-lexical-text="true">bar</span>
    +   <strong class="PlaygroundEditorTheme__textBold" data-lexical-text="true">
    +     ba
    +   </strong>
      </p>
```

### After

The same 400ms-per-keystroke run, with the clock frozen:

```
  ✓  1 [chromium] › History.spec.mjs:447:3 › History › Can coalesce when switching inline styles (meta#1151) (20.7s)
  1 passed
```

And at normal typing speed, repeated, plus the rest of the file:

```
$ pnpm exec playwright test --project=chromium -g "Can coalesce when switching inline styles" --repeat-each=3
  3 passed (39.7s)

$ pnpm exec playwright test --project=chromium packages/lexical-playground/__tests__/e2e/History.spec.mjs
  6 passed (52.0s)
```

Co-Authored-By: Claude Opus 5 <[email protected]>
@etrepum
etrepum added this pull request to the merge queue Aug 24, 2026
Merged via the queue into meta:main with commit 74b0a17 Aug 24, 2026
44 checks passed
etrepum pushed a commit to etrepum/lexical that referenced this pull request Aug 24, 2026
The build injects `/* @__PURE__ */` now, so the 142 annotations this branch had
written by hand are redundant and `@lexical/internal/no-pure-annotation`
removes them. Its autofixer did all of it.

Two things needed a hand.

The three conflicts are all the same shape: this branch replaced a hand-rolled
`parse` function with a schema combinator and annotated the call, and meta#9086
removed the annotation. Keep the combinator, drop the annotation.
`require-pure-annotation.js` conflicts as modify/delete — this branch had added
the combinators to its default list, and the file is gone.

The combinators had to be registered with the compiler the same way, for the
same reason. Without that, strict mode fails the release build on a nested call
it cannot prove pure, which is exactly what the setting is for:

```
PureAnnotationsError: @lexical/compiler: 1 call(s) evaluated inside a definition in
packages/lexical-extension/src/DecoratorTextExtension.ts are not known to be
side-effect free, so the definition cannot be tree-shaken:
  11:10 numberValue(...) inside createState(...)
```

Registering them also taught `no-pure-annotation` about 118 further annotations
it had not recognized, which its autofixer then removed too.

The only annotations left in this branch's own code are the three in the
generated module, on `Object.assign(Object.create(null), ...)`. Those are not
calls the build annotates, so they stay hand-written.

## Test plan

```
$ pnpm run ci-check
No errors!
$ echo $?
0
```

```
$ pnpm run prepare-release
$ echo $?
0
```

```
$ npx vitest run

 Test Files  302 passed (302)
      Tests  5802 passed | 2 skipped (5804)
   Duration  469.08s
```

```
$ grep -rn "@__PURE__" packages/lexical/src | grep -v LexicalGeneratedJSON
$
```

Co-Authored-By: Claude Opus 5 <[email protected]>
etrepum pushed a commit to etrepum/lexical that referenced this pull request Aug 25, 2026
…ild-time transform

Main now injects /* @__PURE__ */ on module-scope factory calls at build
time (@lexical/compiler, meta#9086) and the no-pure-annotation lint rule flags
hand-written ones, which is what broke CI on this branch. Apply the
documented migration (pnpm run lint:fix + prettier) to the annotations this
branch added (listSemanticNestingState, listItemPlainState, the
DOMRenderExtension override wiring), and drop the $findMatchingParent
import left unused by upstream's removal of the decorator-adjacent
backspace handler.

pnpm run ci-check passes (tsc, tsc-scripts, tsc-extension, tsc-website,
flow, prettier, lint), along with 4583 unit + browser tests on the merged
tree.

Co-Authored-By: Claude Fable 5 <[email protected]>
unix-max pushed a commit to unix-max/lexical that referenced this pull request Aug 28, 2026
… @__PURE__ */ annotations at build time (meta#9086)

Co-authored-by: Claude <[email protected]>
etrepum pushed a commit to etrepum/lexical that referenced this pull request Aug 30, 2026
…y bugs

## Description

Applies the review fixes for the `examples/react-mathtype` example added on
this branch. The example currently reopens a formula the user just cancelled
and then inserts it twice, puts an `aria-hidden` element in the tab order, and
fails `pnpm run ci-check` against current `main`.

Bugs

- A cancelled edit reopened the formula it had just dismissed, and then
  inserted it a second time. `editFormula` sets
  `core.editionProperties.temporalImage`, but only a completed insertion
  cleared it, and `GenericIntegration.openNewFormulaEditor()` takes the
  *existing*-formula branch whenever that property is still set. The
  overridden `openNewFormulaEditor` now clears it before delegating, which is
  enough - the vendor implementation restores `dbclick` and `isNewElement`
  itself once it reaches the new-formula branch. Because the override also
  resets `pendingNodeKey`, the reopened formula was committed as a new node
  rather than replacing the original.
- The offscreen MathType edition target is `aria-hidden` but
  `contentEditable`, so it was focusable and sat in the tab order: keyboard
  users landed on an element hidden from assistive technology. It now carries
  `tabIndex={-1}`.
- `createDOM` and `exportDOM` built elements from the `document` global, which
  is the wrong realm for an editor in an iframe and is undefined when
  `$generateHtmlFromNodes` runs headlessly. They use `$getDocument()`, and
  `createImageFromFormula` now takes the owning `Document`, per the Shadow DOM
  and iframe guidance in AGENTS.md.

Lint

- Removes nine hand-written `/* @__PURE__ */` annotations. They were correct
  when this example was written, but meta#9086 has since moved that injection into
  the build and made hand-written annotations an error under
  `@lexical/internal/no-pure-annotation`, which covers `examples/**`. Merging
  main in is what surfaced them.

Cleanup

- The extension no longer overrides `ReactExtension`'s
  `EditorChildrenComponent` to inject a React context. That config is a single
  last-one-wins slot, so taking it silently breaks any other extension in the
  editor that needs it. The bridge state now lives in the extension's own
  `build`, reached with `useExtensionDependency`, and `MathTypeContext.tsx` is
  gone. `nodes` became a thunk so the resulting import cycle cannot hit a
  temporal dead zone.
- Drops the hand-rolled `encodeMathML`/`decodeMathML` fallbacks that mirrored
  WIRIS' own encoding table. `@wiris/mathtype-generic` is imported at module
  scope, so `window.WirisPlugin` is always installed before these run.
- Extracts `isWirisFormulaImage` instead of repeating the predicate in
  `importDOM` and the conversion function, and checks `nodeName` rather than
  `instanceof HTMLImageElement` so it holds for a node from another realm.
- Replaces the inline ref callbacks, which React re-invoked with `null` and
  then the element on every render, with plain ref objects.
- Moves `editor.focus()` into the update's `onUpdate`; `editor.update()` is
  batched, so focusing straight after it ran before reconciliation.
- Sets the version and lexical dependencies to 0.49.0 to match the monorepo
  and every other example (they were 0.45.0), and adds the
  `@rollup/wasm-node` optionalDependency the other examples carry.

## Test plan

### Before

```
$ node_modules/.bin/eslint --no-warn-ignored examples/react-mathtype/
examples/react-mathtype/src/App.tsx
  30:22  error  Remove this /* @__PURE__ */ annotation: the build injects it
  for every module-scope call to defineExtension  @lexical/internal/no-pure-annotation
examples/react-mathtype/src/MathTypeExtension.tsx
  188:34  error  ... defineExtension  @lexical/internal/no-pure-annotation
  191:5   error  ... configExtension  @lexical/internal/no-pure-annotation
examples/react-mathtype/src/MathTypeNode.tsx
  44:21  error  ... createState  @lexical/internal/no-pure-annotation
  48:18  error  ... createState  @lexical/internal/no-pure-annotation
  52:22  error  ... createState  @lexical/internal/no-pure-annotation
  56:20  error  ... createState  @lexical/internal/no-pure-annotation
  60:21  error  ... createState  @lexical/internal/no-pure-annotation
  64:27  error  ... createState  @lexical/internal/no-pure-annotation

✖ 9 problems (9 errors, 0 warnings)
```

The two runtime bugs, driven in Chromium against the production build with
WIRIS' hosted services stubbed. The first result leaves `temporalImage` set
the way a cancelled edit does and then takes the toolbar's insert-formula
route; the second walks the tab order from the editor:

```
{
  "cancelledEditThenInsert": ["opened EXISTING formula editor"],
  "report": {"targetAriaHidden": "true", "targetTabIndex": null},
  "tabReachesHiddenTarget": true
}
```

### After

```
$ node_modules/.bin/eslint --no-warn-ignored examples/react-mathtype/
$ node_modules/.bin/prettier --check examples/react-mathtype/
Checking formatting...
All matched files use Prettier code style!
$ (cd examples/react-mathtype && pnpm run typecheck)
> tsc --noEmit
$ (cd examples/react-mathtype && pnpm run build)
✓ built in 3.28s
```

Same browser checks, same build, no page errors:

```
{
  "cancelledEditThenInsert": ["opened new formula editor"],
  "errors": [],
  "report": {
    "editorText": "Use the MathType toolbar to insert a formula. ",
    "targetAriaHidden": "true",
    "targetTabIndex": "-1"
  },
  "tabReachesHiddenTarget": false
}
```

Not exercised: the MathType toolbar buttons and the formula dialog itself.
Both need WIRIS' hosted services at `www.wiris.net`, which this sandbox cannot
reach; the checks above stub the configuration request, which is enough to
mount the integration but not to render its UI.

Co-Authored-By: Claude Opus 5 <[email protected]>
@etrepum etrepum mentioned this pull request Aug 31, 2026

This branch was successfully deployed

2 active deployments
Preview – lexical — 151f5553 Deployed Aug 24, 2026 by vercel[bot]
Preview – lexical-playground — 151f5553 Deployed Aug 24, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. extended-tests Run extended e2e tests on a PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants