@octanejs/codemod 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -45,7 +45,7 @@ bundler plugin and `tsconfig` over to Octane and install the dependencies.
45
45
  | `event-object` | `e.nativeEvent`, `e.persist()`, `e.target` on a control, also through a component typed for one | `e`, removed, `e.currentTarget` |
46
46
  | `class-attribute` | `className` on an HTML element | `class` |
47
47
  | `legacy-root` | `ReactDOM.render(el, c)` | `createRoot(c).render(el)` |
48
- | `root-render` | `root.render(<App a={1} />)`, `hydrateRoot(c, createElement(App, p))` | `root.render(App, { a: 1 })`, `hydrateRoot(c, App, p)`: no generic element renderer |
48
+ | `root-render` | `root.render(<App a={1} />)`, `hydrateRoot(c, createElement(App))` | `root.render(App, { a: 1 })`, `hydrateRoot(c, App)`: no generic element renderer. Factory calls with a config keep the element so the factory extracts its key and copies its props. |
49
49
  | `server-render` | `renderToString(<App />)` | `renderToString(App).html`: Octane returns `{ html, css }` |
50
50
  | `strict-mode` | `<StrictMode>…</StrictMode>` | its children (Octane's is a pass-through) |
51
51
  | `react-compat` | `<Toaster position="top-right" />` from a React package with no Octane port | `<ReactCompat><Toaster position="top-right" /></ReactCompat>`, rendered by React |
@@ -100,6 +100,16 @@ whose local component returns an intrinsic element. Migrate the server entry
100
100
  with that component or keep the component in React. Review custom bundler
101
101
  resolution, indirect calls, and dynamic imports.
102
102
 
103
+ A retained React DOM client root also keeps ownership of its elements.
104
+ The codemod blocks writes when a direct `createRoot(...).render(...)`, a local
105
+ root handle, or `hydrateRoot(...)` renders a direct local TSX import that would
106
+ become an Octane template. It also covers a root stored in a JavaScript private
107
+ field when the constructor starts by assigning `createRoot(...)`, the field is
108
+ used only for direct `render` and `unmount` calls, and React's named
109
+ `createElement` creates the element. Migrate the root and component
110
+ together, keep the component in React, or give React an authored
111
+ `OctaneCompatInline` boundary.
112
+
103
113
  ### Element-only children
104
114
 
105
115
  A nested component call in a DOM template supplies a render block. When a
@@ -108,6 +118,9 @@ selected React function component declares an element-only `children` prop,
108
118
  `<Frame><Badge /></Frame>` as `<Frame children={<Badge />} />`. This works for
109
119
  a top-level function in the same file or a direct relative import from another
110
120
  selected input. The `element-child-prop` count records the calls converted.
121
+ The `element-child-path-alias` error blocks writes for a single nested element
122
+ when TypeScript resolves a path alias to a selected element-only component.
123
+ Verify the runtime target before passing the element with `children={...}`.
111
124
 
112
125
  The `element-children` note flags recognized React or JSX element annotations
113
126
  for review at other callers. Spreads, comments, meaningful whitespace, multiple
@@ -191,13 +204,16 @@ stops before editing the project. `--dry-run` and `--print` report the colliding
191
204
  sources and preview the rest. Imports of colliding sources keep their existing
192
205
  paths, so check those dependencies before adopting the preview.
193
206
 
207
+ An unresolved React type projection also stops before edits. Use `--print`
208
+ to inspect the proposed changes, then resolve the React type before migrating.
209
+
194
210
  The codemod warns when JSX renders an SVG imported with `?react` or the named
195
211
  `ReactComponent` export. If your loader returns React components for bare
196
212
  `.svg` imports, check those tags too. A loader that emits Octane components
197
213
  can keep its existing imports.
198
214
 
199
- A React package with no Octane binding still runs on React, so React stays a
200
- dependency, and a comment above each import of it says so. When the project
215
+ If the codemod keeps an import on React, the generated comment identifies the
216
+ retained import. Keep React as a dependency. When the project
201
217
  has React and React DOM 19.2 or newer in the React 19 series, a component of that package renders in
202
218
  its own React root through `ReactCompat` if its element gives React nothing
203
219
  Octane renders: text children and props without elements. The package's hooks
@@ -207,9 +223,9 @@ in a local `NoOctanePort`, which throws the reported error where the component
207
223
  would render, so the page names the package instead of failing deep in
208
224
  Octane's renderer. Once you have checked that nothing Octane renders reaches
209
225
  it, such as a spread of props whose `children` no caller passes, swap the
210
- wrapper for `ReactCompat`. **No Octane port** lists each such
211
- package with the modules that import it, the elements hosted in islands, and
212
- the uses that need a port.
226
+ wrapper for `ReactCompat`. **Retained React imports** lists each such package
227
+ with the modules that import it, the elements hosted in islands, and the uses
228
+ that need review.
213
229
 
214
230
  A patch the project applies to a React package the codemod replaces, through
215
231
  `patchedDependencies` (pnpm, Bun) or `patches/` (patch-package), patches the
@@ -237,7 +253,7 @@ when verifying a smaller batch for adoption.
237
253
 
238
254
  ## React Intl
239
255
 
240
- When an application has React Intl 7, React and React DOM 19.2 or later in the 19 series, and either Octane 0.16.7 or later in the 0.16 series or a stable Octane 0.17 release, the codemod can generate one shared `octane-react-intl.tsrx` source file. It places it in the project's existing `src` directory or at the project root, and subsequent migrations reuse it. Preview and print include the helper before a write. If an earlier migration created the original helper and its contents still match, the codemod previews and upgrades it at the same path so existing providers continue to share context. A locally edited helper requires a manual merge. The app keeps its installed React Intl formatter, messages, and cache.
256
+ When an application has React Intl 7, React and React DOM 19.2 or later in the 19 series, and a stable Octane release from 0.16.7 through the 0.19 series, the codemod can generate one shared `octane-react-intl.tsrx` source file. It places it in the project's existing `src` directory or at the project root, and subsequent migrations reuse it. Preview and print include the helper before a write. If an earlier migration created the original helper and its contents still match, the codemod previews and upgrades it at the same path so existing providers continue to share context. A locally edited helper requires a manual merge. The app keeps its installed React Intl formatter, messages, and cache.
241
257
 
242
258
  Named `useIntl` imports can move when a component calls a supported scalar formatter. A locale read can also move when a private component displays the value from its own literal `IntlProvider`. An external provider can supply a getter that performs React DOM work during server rendering. A provider's rich-text defaults can make `formatMessage` return React elements even with zero substitution values. For these calls the codemod follows local constants to known text or comparison uses, including ARIA attributes on intrinsic elements, input placeholders, image alt text, and option labels. Escaping formatters and unproven renderable results retain a binding diagnostic.
243
259
 
@@ -245,15 +261,96 @@ For a literal message descriptor with optional scalar substitutions, the codemod
245
261
 
246
262
  Self-closing `FormattedMessage` elements can render text directly, including ICU substitutions such as `values={{ count }}` when the named values are scalar and evaluating them keeps JSX in its original renderer. Custom text wrappers and provider-defined rich content use the installed React component. Supported React display islands receive the nearest real Intl context. A React-hosted Octane component reads the original provider. A standalone Octane root uses the generated `IntlProvider` or `RawIntlProvider`. The codemod moves providers with a closed subtree of native elements and scalar children. Providers surrounding other components need a review of which renderer owns their descendants. React islands retain the [ReactCompat rendering limits](../../docs/react-compat.md).
247
263
 
264
+ For a message directly inside a paragraph, the codemod uses `ReactCompatInline` for the fallback when the installed Octane package exports it on the client and server. Verify that any provider-supplied rich text or custom wrapper produces phrasing content allowed inside a paragraph.
265
+
248
266
  Inside an authored `ReactCompat` boundary, a single original React component can be selected by a ternary that supplies different props on either branch. A namespaced bridge becomes a named import so the compiler can transport that child. Lists, optional children, and JSX-valued props require a React component to own their rendering.
249
267
 
250
268
  Inside a retained React component, a rich-text callback such as `chunks => <strong>{chunks}</strong>` can keep producing a genuine React element. When the codemod creates a React island for `FormattedMessage`, an inline substitution such as `values={{ lineBreak: <br /> }}` also stays in React if the other props and substitutions cannot observe a change in evaluation timing. The codemod recognizes a single intrinsic tag with literal attributes and an optional literal key. Callbacks can use their parameter as the sole child. Spreads, refs, and event handlers retain a migration diagnostic.
251
269
 
252
270
  A native `formatMessage` call or a generated native `FormattedMessage` can return the expected string while losing resource hints scheduled by a provider-supplied formatter. A generated formatter can also lose access to other React ancestor contexts. The codemod retains the preview and reports a blocking diagnostic for these calls and islands. Review the actual provider and formatter before adopting them. A local `IntlProvider` can inherit configuration from its mutable class defaults. Explicitly authored React boundaries keep their existing contract.
253
271
 
272
+ ### Keep formatting in React while migrating a child
273
+
274
+ With a retained React `IntlProvider`, keep `useIntl` and `formatMessage` in the React component that already owns the call. Pass the resulting string as a prop to an Octane child. This preserves the nearest provider and keeps its formatter callbacks in React's render.
275
+
276
+ ```tsx
277
+ /** @jsxImportSource react */
278
+ import { OctaneCompatInline } from 'octane/react';
279
+ import { useIntl } from 'react-intl';
280
+ import { Label } from './Label.tsrx';
281
+
282
+ export function ReactLabel({ name }: { name: string }) {
283
+ const intl = useIntl();
284
+ const label = intl.formatMessage(
285
+ { id: 'welcome', defaultMessage: 'Welcome, {name}' },
286
+ { name },
287
+ );
288
+ return typeof label === 'string' ? (
289
+ <OctaneCompatInline component={Label} props={{ label }} />
290
+ ) : (
291
+ <strong>{label}</strong>
292
+ );
293
+ }
294
+ ```
295
+
296
+ ```tsrx
297
+ "use strong";
298
+
299
+ export function Label({ label }: { label: string }) @{
300
+ <strong>{label as string}</strong>
301
+ }
302
+ ```
303
+
304
+ The `typeof` check keeps a rich-text result in React. `OctaneCompatInline` adds a span host for the inline Octane child. Compile the React and Octane files with the [mixed-app setup](../../docs/react-compat.md#compiler-ownership), and use `octane/react/server` in the server build. Select the prop-only child when running the codemod. The wrapper stays in React and its import follows the child's new extension.
305
+
306
+ ### Extracting FormatJS messages
307
+
308
+ `formatjs extract` expects ordinary TypeScript and JSX. After converting files to `.tsrx`, use `compileToVolarMappings` from `octane/compiler` to project those files to temporary TSX for extraction. Pass retained files and projected files to the same FormatJS invocation so it can check message IDs across both.
309
+
310
+ Save the script below as `extract-formatjs.mjs` in a project with Octane and the FormatJS CLI installed.
311
+
312
+ ```js
313
+ import { execFileSync } from 'node:child_process';
314
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
315
+ import { tmpdir } from 'node:os';
316
+ import { isAbsolute, join, sep } from 'node:path';
317
+ import { compileToVolarMappings } from 'octane/compiler';
318
+
319
+ // FormatJS interprets positional paths as glob patterns.
320
+ function filePattern(file) {
321
+ const absolute = isAbsolute(file) ? file : process.cwd() + sep + file;
322
+ return absolute.split(sep).join('/').replace(/[\\[\]{}()*?+@!|]/g, '\\$&');
323
+ }
324
+
325
+ const directory = mkdtempSync(join(tmpdir(), 'octane-formatjs-'));
326
+ try {
327
+ const files = process.argv.slice(2).map((file, index) => {
328
+ if (!file.endsWith('.tsrx')) return file;
329
+ const { code, errors } = compileToVolarMappings(readFileSync(file, 'utf8'), file);
330
+ if (errors.length) throw new Error(`Cannot project ${file} for message extraction`);
331
+ const projection = join(directory, `${index}.tsx`);
332
+ writeFileSync(projection, code);
333
+ return projection;
334
+ });
335
+ execFileSync(
336
+ 'formatjs',
337
+ ['extract', '--throws', '--out-file', 'messages.json', '--', ...files.map(filePattern)],
338
+ { stdio: 'inherit' },
339
+ );
340
+ } finally {
341
+ rmSync(directory, { recursive: true, force: true });
342
+ }
343
+ ```
344
+
345
+ ```sh
346
+ pnpm exec node extract-formatjs.mjs src/retained.tsx src/migrated.tsrx
347
+ ```
348
+
349
+ Apply the existing include and exclude rules when choosing which filenames to pass to the script. Keep your other FormatJS extraction options. Aliased message components may need `--additional-component-names` with your extractor version. This example writes a catalog without source locations. With `--extract-source-location`, FormatJS reports the temporary TSX paths and offsets for projected files. If your workflow needs authored locations, keep message definitions in ordinary TypeScript or use the codemod's `--target tsx` option.
350
+
254
351
  ## Store hooks in linked workspace packages
255
352
 
256
- The codemod can migrate a named hook from a local `workspace:` dependency when it can read the TypeScript implementation, trace a React context read, and verify that the hook uses the same store code as a renderer-independent public entry. The public entry and hook names can vary. The supported runtime versions match the React Intl adapter above. A top-level `const` can expose a second name for a handle already created by a verified shared factory. Consumers keep the original handle identity.
353
+ The codemod can migrate a named hook from a local `workspace:` dependency when it can read the TypeScript implementation, trace a React context read, and verify that the hook uses the same store code as a renderer-independent public entry. The public entry and hook names can vary. The generated store adapter uses the same Octane version range as the React Intl adapter above. A top-level `const` can expose a second name for a handle already created by a verified shared factory. Consumers keep the original handle identity.
257
354
 
258
355
  Preview shows the native hook sources the codemod would add alongside the shared `octane-store-context.tsrx` and `octane-store-hooks.ts` helpers. The generated hooks call the original store, subscription, and snapshot functions. They retain React’s dependency lists and hook order. The application compiles these sources with its installed toolchain. When the workspace hook implementation changes, rerun the migration from its original React inputs in a clean checkout and review the new companions. A differing file at a generated path blocks the write.
259
356
 
@@ -301,6 +398,8 @@ An inline style can set a single `transform` declaration. The value can be a str
301
398
 
302
399
  Static SVGs can also use local linear gradients, alpha masks, and simple filters. Linear gradients declare `gradientUnits="userSpaceOnUse"`, both endpoints and at least two stops. An alpha mask is a direct child of the SVG, declares `style="mask-type:alpha"` and contains paths or rectangles. The adapter preserves the fixed style attribute in server output and sets the declaration through CSSOM on the client. Filters use `filterUnits="userSpaceOnUse"` and can contain flood, normal blend, and Gaussian blur primitives. Named blend inputs must be the source graphic, source alpha, or a result declared earlier in that filter. Every definition has a unique, referenced ID within the asset. The adapter preserves authored IDs and reference order across instances. XML declarations, external references, and other inline styles require review.
303
400
 
401
+ A supported SVG may start with one plain `<title>` containing nonempty text. The helper keeps the title inside the SVG in the same position. Title attributes, entities, multiline text, embedded markup and additional titles require review.
402
+
304
403
  Shared component values, React island uses, refs, spread props, and SVGs with unsupported elements keep their original imports.
305
404
 
306
405
  ## Local recipes
package/dist/bin.js CHANGED
@@ -130,12 +130,12 @@ async function main() {
130
130
  }
131
131
  }
132
132
  if (result.missing.length > 0) {
133
- process.stdout.write(`\n${colors.bold('No Octane port')} ${colors.dim('(still runs on React)')}\n`);
133
+ process.stdout.write(`\n${colors.bold('Retained React imports')}\n`);
134
134
  for (const { name, modules, islands, blocked } of result.missing) {
135
135
  const uses = [
136
136
  `${modules} module(s)`,
137
137
  islands > 0 ? `${islands} element(s) in ReactCompat islands` : null,
138
- blocked > 0 ? colors.red(`${blocked} use(s) need a port`) : null,
138
+ blocked > 0 ? colors.red(`${blocked} use(s) need review`) : null,
139
139
  ].filter(Boolean);
140
140
  process.stdout.write(` ${name} ${colors.dim(uses.join(', '))}\n`);
141
141
  }
@@ -3,6 +3,8 @@ import ts from 'typescript';
3
3
  export declare function fixedBinding(checker: ts.TypeChecker, name: ts.Identifier, read: ts.Expression, parameters?: Map<ts.Symbol, boolean>, mayEval?: (name: ts.Identifier) => boolean): boolean;
4
4
  /** An identifier moved past a getter must already be initialized, even across switch cases. */
5
5
  export declare function initializedBefore(checker: ts.TypeChecker, name: ts.Identifier, call: ts.Node): boolean;
6
+ /** A top-level call can use a previously initialized handle in the same module. */
7
+ export declare function atInitializedModuleHandle(declaration: ts.VariableDeclaration, call: ts.CallExpression): boolean;
6
8
  /** Trust a destructured prop only when this file cannot change or supply it. */
7
9
  export declare function stableExportedProp(symbol: ts.Symbol | undefined, checker: ts.TypeChecker): boolean;
8
10
  /** Keep calls to ref-only helpers at their original effect, event or cleanup phase. */
@@ -72,6 +72,16 @@ export function initializedBefore(checker, name, call) {
72
72
  statement.end <= call.getStart() &&
73
73
  !!ts.findAncestor(call, (n) => n === statement.parent));
74
74
  }
75
+ /** A top-level call can use a previously initialized handle in the same module. */
76
+ export function atInitializedModuleHandle(declaration, call) {
77
+ const statement = declaration.parent.parent;
78
+ const file = call.getSourceFile();
79
+ return (ts.isVariableStatement(statement) &&
80
+ statement.parent === file &&
81
+ ts.isExpressionStatement(call.parent) &&
82
+ call.parent.parent === file &&
83
+ statement.end <= call.getStart(file));
84
+ }
75
85
  const propScopes = new WeakMap();
76
86
  function propScope(file, checker) {
77
87
  const uses = localUses(file, checker);
@@ -4,3 +4,5 @@ import ts from 'typescript';
4
4
  */
5
5
  export declare function isWrapper(node: ts.Node): node is ts.ParenthesizedExpression | ts.AsExpression | ts.SatisfiesExpression | ts.NonNullExpression | ts.TypeAssertion;
6
6
  export declare function skipWrappers(node: ts.Expression): ts.Expression;
7
+ /** Short-circuit behavior if this expression finishes evaluating. */
8
+ export declare function literalCondition(expr: ts.Expression): "nullish" | "truthy" | "falsy" | undefined;
@@ -14,3 +14,22 @@ export function skipWrappers(node) {
14
14
  node = node.expression;
15
15
  return node;
16
16
  }
17
+ /** Short-circuit behavior if this expression finishes evaluating. */
18
+ export function literalCondition(expr) {
19
+ const value = skipWrappers(expr);
20
+ if (value.kind === ts.SyntaxKind.NullKeyword || ts.isVoidExpression(value))
21
+ return 'nullish';
22
+ if (ts.isStringLiteralLike(value))
23
+ return value.text.length ? 'truthy' : 'falsy';
24
+ if (ts.isNumericLiteral(value))
25
+ return Number(value.text) ? 'truthy' : 'falsy';
26
+ if (value.kind === ts.SyntaxKind.FalseKeyword)
27
+ return 'falsy';
28
+ if (value.kind === ts.SyntaxKind.TrueKeyword ||
29
+ ts.isArrowFunction(value) ||
30
+ ts.isFunctionExpression(value) ||
31
+ ts.isClassExpression(value) ||
32
+ ts.isArrayLiteralExpression(value) ||
33
+ ts.isObjectLiteralExpression(value))
34
+ return 'truthy';
35
+ }
@@ -3,13 +3,17 @@ import { localUses } from './local-uses.js';
3
3
  export declare function contains(node: ts.Node, matches: (node: ts.Node) => boolean): boolean;
4
4
  export declare function hasEval(file: ts.SourceFile): boolean;
5
5
  export declare function hasPrototypeAccess(file: ts.SourceFile): boolean;
6
+ export declare function rendersElementChildren(element: ts.JsxOpeningLikeElement): boolean;
6
7
  export declare function renderUses(refs: ts.Identifier[]): ts.Identifier[];
8
+ /** A local root handle stays owned while callers only invoke its two root methods. */
9
+ export declare function callsRootMethod(root: ts.Expression): boolean;
10
+ export declare function rootHandleEscapes(refs: ts.Identifier[], inOwner?: (ref: ts.Identifier) => boolean): boolean;
7
11
  type RenderTypes = {
8
12
  typeOf: (node: ts.Node) => ts.Type;
9
13
  text: (node: ts.Node) => boolean;
10
14
  };
11
15
  /** Follow the value being rendered all the way to its containing component's return. */
12
- export declare function nativeOutputOwner(value: ts.Node, slot: (tag: ts.Identifier, prop: string) => boolean, { typeOf, text }: RenderTypes): ts.ArrowFunction | ts.FunctionDeclaration | ts.FunctionExpression | undefined;
16
+ export declare function nativeOutputOwner(value: ts.Node, slot: (tag: ts.Identifier, prop: string) => boolean, { typeOf, text }: RenderTypes): ts.ArrowFunction | ts.FunctionExpression | ts.FunctionDeclaration | undefined;
13
17
  export declare function literalJsxAttribute(attr: ts.JsxAttributeLike): boolean;
14
18
  /** Follow one stored SVG value to its only runtime read, inside the same component body. */
15
19
  export declare function svgLocalReads(checker: ts.TypeChecker, uses: ReturnType<typeof localUses>, typeOf: RenderTypes['typeOf'], reactNode: (annotation: ts.TypeNode) => boolean): (element: ts.JsxSelfClosingElement) => ts.Identifier | undefined;
@@ -73,6 +73,11 @@ function incoming(param, prop) {
73
73
  // Raw-text and void HTML elements do not render ordinary child elements.
74
74
  const nonElementHosts = /^(?:textarea|title|script|style|option|noscript|iframe|noembed|noframes|xmp|plaintext|area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)$/;
75
75
  const hookName = /^use(?:[A-Z0-9]|$)/;
76
+ export function rendersElementChildren(element) {
77
+ return (ts.isIdentifier(element.tagName) &&
78
+ !nonElementHosts.test(element.tagName.text) &&
79
+ !element.attributes.properties.some((attr) => ts.isJsxAttribute(attr) && attr.name.getText() === 'dangerouslySetInnerHTML'));
80
+ }
76
81
  // A scalar assertion can turn a child into a text binding. Require a member
77
82
  // that the compiler cannot classify as primitive text, even through aliases.
78
83
  function renderType(type) {
@@ -88,6 +93,18 @@ export function renderUses(refs) {
88
93
  return !ts.isTypeQueryNode(name.parent) && !ts.isTypeOnlyExportDeclaration(ref.parent);
89
94
  });
90
95
  }
96
+ /** A local root handle stays owned while callers only invoke its two root methods. */
97
+ export function callsRootMethod(root) {
98
+ const member = root.parent;
99
+ return (ts.isPropertyAccessExpression(member) &&
100
+ member.expression === root &&
101
+ (member.name.text === 'render' || member.name.text === 'unmount') &&
102
+ ts.isCallExpression(member.parent) &&
103
+ member.parent.expression === member);
104
+ }
105
+ export function rootHandleEscapes(refs, inOwner) {
106
+ return renderUses(refs).some((ref) => !callsRootMethod(ref) || inOwner?.(ref) === false);
107
+ }
91
108
  /** Follow the value being rendered all the way to its containing component's return. */
92
109
  export function nativeOutputOwner(value, slot, { typeOf, text }) {
93
110
  for (;;) {
@@ -114,9 +131,7 @@ export function nativeOutputOwner(value, slot, { typeOf, text }) {
114
131
  : ts.isJsxElement(parent) && !parent.children.some((child) => child === value))
115
132
  return;
116
133
  if (/^[a-z]/.test(tag.text)) {
117
- if (attr ||
118
- nonElementHosts.test(tag.text) ||
119
- element.attributes.properties.some((a) => ts.isJsxAttribute(a) && a.name.getText() === 'dangerouslySetInnerHTML'))
134
+ if (attr || !rendersElementChildren(element))
120
135
  return;
121
136
  }
122
137
  else {
@@ -1,15 +1,20 @@
1
1
  import ts from 'typescript';
2
2
  import { localUses } from './local-uses.js';
3
+ export declare function namedRuntimeImport(name: ts.Identifier, checker: ts.TypeChecker): {
4
+ module: string;
5
+ name: string;
6
+ } | undefined;
7
+ export declare function safeSetupLiteral(node: ts.Expression, checker: ts.TypeChecker): boolean;
3
8
  /** A direct initialization in an ordinary component with native output. */
4
- export declare function nativeSetupHook(ref: ts.Identifier, uses: ReturnType<typeof localUses>, checker: ts.TypeChecker, diagnostic?: {
9
+ export declare function nativeSetupHook(ref: ts.Expression, uses: ReturnType<typeof localUses>, checker: ts.TypeChecker, diagnostic?: {
5
10
  calleeName(callee: ts.Expression): string | null;
6
11
  nativeOutput(element: ts.JsxElement | ts.JsxSelfClosingElement): boolean;
7
12
  originalReact(): boolean;
8
13
  contextSetup?: boolean;
9
14
  privateContext?: boolean;
10
- }, allowAnonymousDefault?: boolean): false | "diagnostic" | "first" | "afterRefs";
15
+ }, storeRoot?: boolean): false | "diagnostic" | "first" | "afterRefs";
11
16
  /** Find renderer calls at the start of an unchanged export's setup. */
12
- export declare function directRendererCalls(sf: ts.SourceFile, checker: ts.TypeChecker, module: 'react' | 'react-dom' | 'react-intl', accepts: (name: string) => boolean, privateContextExports?: Set<string>): Map<string, string>;
17
+ export declare function directRendererCalls(sf: ts.SourceFile, checker: ts.TypeChecker, module: 'react' | 'react-dom' | 'react-intl' | ((specifier: string, name: string) => boolean), accepts?: (name: string) => boolean, privateContextExports?: Set<string>): Map<string, string>;
13
18
  /** Clone a stateless hook while leaving its DOM reader and subscription shared. */
14
19
  export declare function nativeExternalStore(file: string, source: string, name: string, loadLeaf: (specifier: string) => {
15
20
  sf: ts.SourceFile;
@@ -3,7 +3,7 @@ import { contains, renderUses } from './forwarded-props.js';
3
3
  import { localUses } from './local-uses.js';
4
4
  import { fixedBinding, initializedBefore } from './effect-receivers.js';
5
5
  import { skipWrappers } from './expression-wrappers.js';
6
- function rendererImport(name, checker, module = 'react') {
6
+ export function namedRuntimeImport(name, checker) {
7
7
  const binding = checker.getSymbolAtLocation(name)?.declarations?.[0];
8
8
  if (!binding || !ts.isImportSpecifier(binding) || binding.isTypeOnly)
9
9
  return;
@@ -12,9 +12,13 @@ function rendererImport(name, checker, module = 'react') {
12
12
  if (!clause.isTypeOnly &&
13
13
  ts.isImportDeclaration(imp) &&
14
14
  !imp.attributes &&
15
- ts.isStringLiteral(imp.moduleSpecifier) &&
16
- imp.moduleSpecifier.text === module)
17
- return (binding.propertyName ?? binding.name).text;
15
+ ts.isStringLiteral(imp.moduleSpecifier))
16
+ return { module: imp.moduleSpecifier.text, name: (binding.propertyName ?? binding.name).text };
17
+ }
18
+ function rendererImport(name, checker, module = 'react') {
19
+ const imported = namedRuntimeImport(name, checker);
20
+ if (imported?.module === module)
21
+ return imported.name;
18
22
  }
19
23
  function privateContextReader(callee, checker) {
20
24
  if (ts.isIdentifier(callee))
@@ -65,7 +69,7 @@ function literalDeclaration(declaration) {
65
69
  value.kind === ts.SyntaxKind.FalseKeyword ||
66
70
  value.kind === ts.SyntaxKind.NullKeyword);
67
71
  }
68
- function safeSetupLiteral(node, checker) {
72
+ export function safeSetupLiteral(node, checker) {
69
73
  if (scalarLiteral(node))
70
74
  return true;
71
75
  if (ts.isIdentifier(node) && node.text === 'undefined') {
@@ -115,8 +119,8 @@ function conditionalOutput(value) {
115
119
  }
116
120
  /** A direct initialization in an ordinary component with native output. */
117
121
  export function nativeSetupHook(ref, uses, checker, diagnostic,
118
- // Store-root diagnostics can prove an anonymous declaration's default export.
119
- allowAnonymousDefault = false) {
122
+ // These shapes are used for store-root diagnostics, without adapting a hook.
123
+ storeRoot = false) {
120
124
  const call = ref.parent;
121
125
  if (!ts.isCallExpression(call) || call.expression !== ref)
122
126
  return false;
@@ -189,10 +193,12 @@ allowAnonymousDefault = false) {
189
193
  name = fn.name;
190
194
  }
191
195
  else {
192
- if (!diagnostic || (ts.isFunctionExpression(fn) && fn.name && renderUses(uses(fn.name)).length))
196
+ if ((!diagnostic && !storeRoot) ||
197
+ (ts.isFunctionExpression(fn) && fn.name && renderUses(uses(fn.name)).length))
193
198
  return false;
194
199
  let value = fn;
195
- while (ts.isCallExpression(value.parent) &&
200
+ while (diagnostic &&
201
+ ts.isCallExpression(value.parent) &&
196
202
  value.parent.arguments[0] === value &&
197
203
  /^(?:memo|forwardRef)$/.test(diagnostic.calleeName(value.parent.expression) ?? ''))
198
204
  value = value.parent;
@@ -209,8 +215,7 @@ allowAnonymousDefault = false) {
209
215
  }
210
216
  if ((name
211
217
  ? !/^[A-Z]/.test(name.text)
212
- : !allowAnonymousDefault ||
213
- !owner.modifiers?.some((m) => m.kind === ts.SyntaxKind.DefaultKeyword)) ||
218
+ : !storeRoot || !owner.modifiers?.some((m) => m.kind === ts.SyntaxKind.DefaultKeyword)) ||
214
219
  !ts.isSourceFile(owner.parent) ||
215
220
  !owner.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword) ||
216
221
  (name &&
@@ -256,31 +261,56 @@ function declaredVariable(statement) {
256
261
  return (ts.isVariableStatement(statement) &&
257
262
  !!statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.DeclareKeyword));
258
263
  }
259
- function firstRendererCall(fn) {
260
- const first = fn.body?.statements[0];
261
- const value = first &&
262
- (ts.isVariableStatement(first)
263
- ? first.declarationList.declarations[0]?.initializer
264
- : ts.isReturnStatement(first) || ts.isExpressionStatement(first)
265
- ? first.expression
266
- : undefined);
267
- if (first && value && ts.isCallExpression(value))
268
- return { call: value, callee: value.expression, ambient: declaredVariable(first) };
264
+ function firstRendererCall(body) {
265
+ if (!body)
266
+ return;
267
+ const first = ts.isBlock(body) ? body.statements[0] : undefined;
268
+ const value = ts.isBlock(body)
269
+ ? first &&
270
+ (ts.isVariableStatement(first)
271
+ ? first.declarationList.declarations[0]?.initializer
272
+ : ts.isReturnStatement(first) || ts.isExpressionStatement(first)
273
+ ? first.expression
274
+ : undefined)
275
+ : skipWrappers(body);
276
+ if (value && ts.isCallExpression(value))
277
+ return { call: value, callee: value.expression, ambient: !!first && declaredVariable(first) };
269
278
  }
270
279
  function privateContextCall(sf, checker, uses, outer, callee) {
271
280
  if (ts.isOptionalChain(outer) || outer.arguments.length)
272
281
  return false;
273
- const helper = checker.getSymbolAtLocation(callee)?.valueDeclaration;
282
+ const binding = checker.getSymbolAtLocation(callee)?.valueDeclaration;
283
+ if (!binding || (!ts.isFunctionDeclaration(binding) && !ts.isVariableDeclaration(binding)))
284
+ return false;
285
+ const name = binding.name;
286
+ if (!name || !ts.isIdentifier(name))
287
+ return false;
288
+ let helper;
289
+ if (ts.isFunctionDeclaration(binding)) {
290
+ if (binding.parent === sf)
291
+ helper = binding;
292
+ }
293
+ else {
294
+ const list = binding.parent;
295
+ const statement = list.parent;
296
+ if (ts.isVariableDeclarationList(list) &&
297
+ (list.flags & ts.NodeFlags.BlockScoped) === ts.NodeFlags.Const &&
298
+ ts.isVariableStatement(statement) &&
299
+ statement.parent === sf &&
300
+ !statement.modifiers?.length &&
301
+ binding.initializer) {
302
+ const initializer = skipWrappers(binding.initializer);
303
+ if (ts.isArrowFunction(initializer))
304
+ helper = initializer;
305
+ }
306
+ }
274
307
  if (!helper ||
275
- !ts.isFunctionDeclaration(helper) ||
276
- !helper.name ||
277
- helper.parent !== sf ||
278
308
  helper.modifiers?.length ||
279
309
  helper.asteriskToken ||
280
310
  helper.parameters.length ||
281
- renderUses(uses(helper.name)).some((ref) => !ts.isCallExpression(ref.parent) || ref.parent.expression !== ref))
311
+ renderUses(uses(name)).some((ref) => !ts.isCallExpression(ref.parent) || ref.parent.expression !== ref))
282
312
  return false;
283
- const read = firstRendererCall(helper);
313
+ const read = firstRendererCall(helper.body);
284
314
  if (!read ||
285
315
  read.ambient ||
286
316
  ts.isOptionalChain(read.call) ||
@@ -341,41 +371,67 @@ export function directRendererCalls(sf, checker, module, accepts, privateContext
341
371
  if (contains(sf, (n) => ts.isIdentifier(n) && n.text === 'eval'))
342
372
  return calls;
343
373
  const uses = localUses(sf, checker);
344
- for (const fn of sf.statements) {
345
- if (!ts.isFunctionDeclaration(fn) ||
346
- !fn.name ||
347
- !fn.body ||
348
- fn.asteriskToken ||
349
- fn.modifiers?.length !== 1 ||
350
- fn.modifiers[0].kind !== ts.SyntaxKind.ExportKeyword ||
374
+ const record = (binding, fn) => {
375
+ if (!fn.body ||
351
376
  fn.parameters.some((p) => !ts.isIdentifier(p.name) ||
352
377
  (p.initializer &&
353
378
  (module === 'react-dom' || !scalarLiteral(skipWrappers(p.initializer))))))
354
- continue;
355
- const first = firstRendererCall(fn);
356
- if (module === 'react-intl' &&
357
- (!first || first.ambient || ts.isOptionalChain(first.call) || first.call.arguments.length))
358
- continue;
359
- const name = first && ts.isIdentifier(first.callee) && rendererImport(first.callee, checker, module);
360
- const direct = name && accepts(name) ? name : undefined;
361
- if (!direct && !(first && privateContextExports) && module !== 'react')
362
- continue;
363
- // A local write can replace the exported function before the importer calls it.
364
- if (renderUses(uses(fn.name)).some((ref) => !ts.isCallExpression(ref.parent) || ref.parent.expression !== ref))
365
- continue;
379
+ return;
380
+ const arrow = ts.isArrowFunction(fn);
381
+ const forward = typeof module === 'function';
382
+ // A retained wrapper forwards directly and has a stable exported binding.
383
+ const first = firstRendererCall(forward ? (arrow ? undefined : returned(fn)) : fn.body);
384
+ if (forward && (!first || ts.isOptionalChain(first.call)))
385
+ return;
386
+ if ((arrow && (!first || first.ambient || ts.isOptionalChain(first.call))) ||
387
+ (module === 'react-intl' &&
388
+ (!first || first.ambient || ts.isOptionalChain(first.call) || first.call.arguments.length)))
389
+ return;
390
+ // Check escapes before asking the workspace planner to inspect a foreign package.
391
+ if (renderUses(uses(binding)).some((ref) => !ts.isCallExpression(ref.parent) || ref.parent.expression !== ref))
392
+ return;
393
+ const imported = first && ts.isIdentifier(first.callee)
394
+ ? namedRuntimeImport(first.callee, checker)
395
+ : undefined;
396
+ const direct = imported &&
397
+ (forward
398
+ ? module(imported.module, imported.name)
399
+ : imported.module === module && accepts?.(imported.name))
400
+ ? imported.name
401
+ : undefined;
402
+ if (!direct && (arrow || (!(first && privateContextExports) && module !== 'react')))
403
+ return;
366
404
  if (direct)
367
- calls.set(fn.name.text, direct);
405
+ calls.set(binding.text, direct);
368
406
  else if (privateContextExports &&
369
407
  first &&
370
408
  ts.isIdentifier(first.callee) &&
371
409
  !first.ambient &&
372
410
  !fn.parameters.length &&
373
411
  privateContextCall(sf, checker, uses, first.call, first.callee))
374
- privateContextExports.add(fn.name.text);
375
- else if (module === 'react') {
412
+ privateContextExports.add(binding.text);
413
+ else if (module === 'react' && ts.isBlock(fn.body)) {
376
414
  const effect = setupEffect(fn.body, checker);
377
415
  if (effect)
378
- calls.set(fn.name.text, effect);
416
+ calls.set(binding.text, effect);
417
+ }
418
+ };
419
+ for (const statement of sf.statements) {
420
+ if ((!ts.isFunctionDeclaration(statement) && !ts.isVariableStatement(statement)) ||
421
+ statement.modifiers?.length !== 1 ||
422
+ statement.modifiers[0].kind !== ts.SyntaxKind.ExportKeyword)
423
+ continue;
424
+ if (ts.isFunctionDeclaration(statement)) {
425
+ if (statement.name && !statement.asteriskToken)
426
+ record(statement.name, statement);
427
+ }
428
+ else if (module === 'react' &&
429
+ (statement.declarationList.flags & ts.NodeFlags.BlockScoped) === ts.NodeFlags.Const) {
430
+ for (const { name, initializer } of statement.declarationList.declarations) {
431
+ const arrow = initializer && skipWrappers(initializer);
432
+ if (ts.isIdentifier(name) && arrow && ts.isArrowFunction(arrow) && !arrow.modifiers?.length)
433
+ record(name, arrow);
434
+ }
379
435
  }
380
436
  }
381
437
  return calls;
@@ -16,5 +16,7 @@ export declare function transportedValue(value: ts.Node, checker: ts.TypeChecker
16
16
  export declare function portableArguments(checker: ts.TypeChecker, typeOf: (expr: ts.Expression) => ts.Type): (expr: ts.Expression, imported?: ImportedArgument) => boolean;
17
17
  /** Whether this value is only named as a JSX component or a module export. */
18
18
  export declare function componentTagOrExport(ref: ts.Identifier): boolean;
19
+ /** Lexical context reads allowed by the retained Provider advisory. */
20
+ export declare function unchangedContextProviderUse(ref: ts.Identifier, isReactContextRead: (callee: ts.Expression) => boolean): boolean;
19
21
  export declare function localUses(file: ts.SourceFile, checker: ts.TypeChecker): (id: ts.Identifier) => ts.Identifier[];
20
22
  export {};
@@ -1027,6 +1027,28 @@ export function componentTagOrExport(ref) {
1027
1027
  ? p.tagName === ref
1028
1028
  : ts.isExportSpecifier(p) || ts.isExportAssignment(p);
1029
1029
  }
1030
+ /** Lexical context reads allowed by the retained Provider advisory. */
1031
+ export function unchangedContextProviderUse(ref, isReactContextRead) {
1032
+ if (inTypeNode(ref) || componentTagOrExport(ref))
1033
+ return true;
1034
+ const member = ref.parent;
1035
+ if (ts.isCallExpression(member)) {
1036
+ return (!ts.isOptionalChain(member) &&
1037
+ member.arguments[0] === ref &&
1038
+ member.arguments.length === 1 &&
1039
+ isReactContextRead(member.expression));
1040
+ }
1041
+ if (!ts.isPropertyAccessExpression(member) || member.expression !== ref)
1042
+ return false;
1043
+ const use = member.parent;
1044
+ return (((ts.isJsxOpeningElement(use) ||
1045
+ ts.isJsxSelfClosingElement(use) ||
1046
+ ts.isJsxClosingElement(use)) &&
1047
+ use.tagName === member) ||
1048
+ (member.name.text === 'displayName' &&
1049
+ ((ts.isVariableDeclaration(use) && use.initializer === member) ||
1050
+ (ts.isReturnStatement(use) && use.expression === member))));
1051
+ }
1030
1052
  export function localUses(file, checker) {
1031
1053
  const refs = new Map();
1032
1054
  function visit(node) {