@octanejs/codemod 0.2.1 → 0.2.2

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 |
@@ -108,6 +108,9 @@ selected React function component declares an element-only `children` prop,
108
108
  `<Frame><Badge /></Frame>` as `<Frame children={<Badge />} />`. This works for
109
109
  a top-level function in the same file or a direct relative import from another
110
110
  selected input. The `element-child-prop` count records the calls converted.
111
+ The `element-child-path-alias` error blocks writes for a single nested element
112
+ when TypeScript resolves a path alias to a selected element-only component.
113
+ Verify the runtime target before passing the element with `children={...}`.
111
114
 
112
115
  The `element-children` note flags recognized React or JSX element annotations
113
116
  for review at other callers. Spreads, comments, meaningful whitespace, multiple
@@ -191,13 +194,16 @@ stops before editing the project. `--dry-run` and `--print` report the colliding
191
194
  sources and preview the rest. Imports of colliding sources keep their existing
192
195
  paths, so check those dependencies before adopting the preview.
193
196
 
197
+ An unresolved React type projection also stops before edits. Use `--print`
198
+ to inspect the proposed changes, then resolve the React type before migrating.
199
+
194
200
  The codemod warns when JSX renders an SVG imported with `?react` or the named
195
201
  `ReactComponent` export. If your loader returns React components for bare
196
202
  `.svg` imports, check those tags too. A loader that emits Octane components
197
203
  can keep its existing imports.
198
204
 
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
205
+ If the codemod keeps an import on React, the generated comment identifies the
206
+ retained import. Keep React as a dependency. When the project
201
207
  has React and React DOM 19.2 or newer in the React 19 series, a component of that package renders in
202
208
  its own React root through `ReactCompat` if its element gives React nothing
203
209
  Octane renders: text children and props without elements. The package's hooks
@@ -207,9 +213,9 @@ in a local `NoOctanePort`, which throws the reported error where the component
207
213
  would render, so the page names the package instead of failing deep in
208
214
  Octane's renderer. Once you have checked that nothing Octane renders reaches
209
215
  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.
216
+ wrapper for `ReactCompat`. **Retained React imports** lists each such package
217
+ with the modules that import it, the elements hosted in islands, and the uses
218
+ that need review.
213
219
 
214
220
  A patch the project applies to a React package the codemod replaces, through
215
221
  `patchedDependencies` (pnpm, Bun) or `patches/` (patch-package), patches the
@@ -237,7 +243,7 @@ when verifying a smaller batch for adoption.
237
243
 
238
244
  ## React Intl
239
245
 
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.
246
+ 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
247
 
242
248
  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
249
 
@@ -245,15 +251,96 @@ For a literal message descriptor with optional scalar substitutions, the codemod
245
251
 
246
252
  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
253
 
254
+ 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.
255
+
248
256
  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
257
 
250
258
  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
259
 
252
260
  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
261
 
262
+ ### Keep formatting in React while migrating a child
263
+
264
+ 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.
265
+
266
+ ```tsx
267
+ /** @jsxImportSource react */
268
+ import { OctaneCompatInline } from 'octane/react';
269
+ import { useIntl } from 'react-intl';
270
+ import { Label } from './Label.tsrx';
271
+
272
+ export function ReactLabel({ name }: { name: string }) {
273
+ const intl = useIntl();
274
+ const label = intl.formatMessage(
275
+ { id: 'welcome', defaultMessage: 'Welcome, {name}' },
276
+ { name },
277
+ );
278
+ return typeof label === 'string' ? (
279
+ <OctaneCompatInline component={Label} props={{ label }} />
280
+ ) : (
281
+ <strong>{label}</strong>
282
+ );
283
+ }
284
+ ```
285
+
286
+ ```tsrx
287
+ "use strong";
288
+
289
+ export function Label({ label }: { label: string }) @{
290
+ <strong>{label as string}</strong>
291
+ }
292
+ ```
293
+
294
+ 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.
295
+
296
+ ### Extracting FormatJS messages
297
+
298
+ `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.
299
+
300
+ Save the script below as `extract-formatjs.mjs` in a project with Octane and the FormatJS CLI installed.
301
+
302
+ ```js
303
+ import { execFileSync } from 'node:child_process';
304
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
305
+ import { tmpdir } from 'node:os';
306
+ import { isAbsolute, join, sep } from 'node:path';
307
+ import { compileToVolarMappings } from 'octane/compiler';
308
+
309
+ // FormatJS interprets positional paths as glob patterns.
310
+ function filePattern(file) {
311
+ const absolute = isAbsolute(file) ? file : process.cwd() + sep + file;
312
+ return absolute.split(sep).join('/').replace(/[\\[\]{}()*?+@!|]/g, '\\$&');
313
+ }
314
+
315
+ const directory = mkdtempSync(join(tmpdir(), 'octane-formatjs-'));
316
+ try {
317
+ const files = process.argv.slice(2).map((file, index) => {
318
+ if (!file.endsWith('.tsrx')) return file;
319
+ const { code, errors } = compileToVolarMappings(readFileSync(file, 'utf8'), file);
320
+ if (errors.length) throw new Error(`Cannot project ${file} for message extraction`);
321
+ const projection = join(directory, `${index}.tsx`);
322
+ writeFileSync(projection, code);
323
+ return projection;
324
+ });
325
+ execFileSync(
326
+ 'formatjs',
327
+ ['extract', '--throws', '--out-file', 'messages.json', '--', ...files.map(filePattern)],
328
+ { stdio: 'inherit' },
329
+ );
330
+ } finally {
331
+ rmSync(directory, { recursive: true, force: true });
332
+ }
333
+ ```
334
+
335
+ ```sh
336
+ pnpm exec node extract-formatjs.mjs src/retained.tsx src/migrated.tsrx
337
+ ```
338
+
339
+ 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.
340
+
254
341
  ## Store hooks in linked workspace packages
255
342
 
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.
343
+ 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
344
 
258
345
  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
346
 
@@ -301,6 +388,8 @@ An inline style can set a single `transform` declaration. The value can be a str
301
388
 
302
389
  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
390
 
391
+ 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.
392
+
304
393
  Shared component values, React island uses, refs, spread props, and SVGs with unsupported elements keep their original imports.
305
394
 
306
395
  ## 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,16 @@ 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 rootHandleEscapes(refs: ts.Identifier[], inOwner?: (ref: ts.Identifier) => boolean): boolean;
7
10
  type RenderTypes = {
8
11
  typeOf: (node: ts.Node) => ts.Type;
9
12
  text: (node: ts.Node) => boolean;
10
13
  };
11
14
  /** 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;
15
+ 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
16
  export declare function literalJsxAttribute(attr: ts.JsxAttributeLike): boolean;
14
17
  /** Follow one stored SVG value to its only runtime read, inside the same component body. */
15
18
  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 rootHandleEscapes(refs, inOwner) {
98
+ return renderUses(refs).some((ref) => {
99
+ const member = ref.parent;
100
+ return (!ts.isPropertyAccessExpression(member) ||
101
+ member.expression !== ref ||
102
+ (member.name.text !== 'render' && member.name.text !== 'unmount') ||
103
+ !ts.isCallExpression(member.parent) ||
104
+ member.parent.expression !== member ||
105
+ inOwner?.(ref) === false);
106
+ });
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,7 +1,12 @@
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;
@@ -9,7 +14,7 @@ export declare function nativeSetupHook(ref: ts.Identifier, uses: ReturnType<typ
9
14
  privateContext?: boolean;
10
15
  }, allowAnonymousDefault?: 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') {
@@ -256,31 +260,56 @@ function declaredVariable(statement) {
256
260
  return (ts.isVariableStatement(statement) &&
257
261
  !!statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.DeclareKeyword));
258
262
  }
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) };
263
+ function firstRendererCall(body) {
264
+ if (!body)
265
+ return;
266
+ const first = ts.isBlock(body) ? body.statements[0] : undefined;
267
+ const value = ts.isBlock(body)
268
+ ? first &&
269
+ (ts.isVariableStatement(first)
270
+ ? first.declarationList.declarations[0]?.initializer
271
+ : ts.isReturnStatement(first) || ts.isExpressionStatement(first)
272
+ ? first.expression
273
+ : undefined)
274
+ : skipWrappers(body);
275
+ if (value && ts.isCallExpression(value))
276
+ return { call: value, callee: value.expression, ambient: !!first && declaredVariable(first) };
269
277
  }
270
278
  function privateContextCall(sf, checker, uses, outer, callee) {
271
279
  if (ts.isOptionalChain(outer) || outer.arguments.length)
272
280
  return false;
273
- const helper = checker.getSymbolAtLocation(callee)?.valueDeclaration;
281
+ const binding = checker.getSymbolAtLocation(callee)?.valueDeclaration;
282
+ if (!binding || (!ts.isFunctionDeclaration(binding) && !ts.isVariableDeclaration(binding)))
283
+ return false;
284
+ const name = binding.name;
285
+ if (!name || !ts.isIdentifier(name))
286
+ return false;
287
+ let helper;
288
+ if (ts.isFunctionDeclaration(binding)) {
289
+ if (binding.parent === sf)
290
+ helper = binding;
291
+ }
292
+ else {
293
+ const list = binding.parent;
294
+ const statement = list.parent;
295
+ if (ts.isVariableDeclarationList(list) &&
296
+ (list.flags & ts.NodeFlags.BlockScoped) === ts.NodeFlags.Const &&
297
+ ts.isVariableStatement(statement) &&
298
+ statement.parent === sf &&
299
+ !statement.modifiers?.length &&
300
+ binding.initializer) {
301
+ const initializer = skipWrappers(binding.initializer);
302
+ if (ts.isArrowFunction(initializer))
303
+ helper = initializer;
304
+ }
305
+ }
274
306
  if (!helper ||
275
- !ts.isFunctionDeclaration(helper) ||
276
- !helper.name ||
277
- helper.parent !== sf ||
278
307
  helper.modifiers?.length ||
279
308
  helper.asteriskToken ||
280
309
  helper.parameters.length ||
281
- renderUses(uses(helper.name)).some((ref) => !ts.isCallExpression(ref.parent) || ref.parent.expression !== ref))
310
+ renderUses(uses(name)).some((ref) => !ts.isCallExpression(ref.parent) || ref.parent.expression !== ref))
282
311
  return false;
283
- const read = firstRendererCall(helper);
312
+ const read = firstRendererCall(helper.body);
284
313
  if (!read ||
285
314
  read.ambient ||
286
315
  ts.isOptionalChain(read.call) ||
@@ -341,41 +370,67 @@ export function directRendererCalls(sf, checker, module, accepts, privateContext
341
370
  if (contains(sf, (n) => ts.isIdentifier(n) && n.text === 'eval'))
342
371
  return calls;
343
372
  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 ||
373
+ const record = (binding, fn) => {
374
+ if (!fn.body ||
351
375
  fn.parameters.some((p) => !ts.isIdentifier(p.name) ||
352
376
  (p.initializer &&
353
377
  (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;
378
+ return;
379
+ const arrow = ts.isArrowFunction(fn);
380
+ const forward = typeof module === 'function';
381
+ // A retained wrapper forwards directly and has a stable exported binding.
382
+ const first = firstRendererCall(forward ? (arrow ? undefined : returned(fn)) : fn.body);
383
+ if (forward && (!first || ts.isOptionalChain(first.call)))
384
+ return;
385
+ if ((arrow && (!first || first.ambient || ts.isOptionalChain(first.call))) ||
386
+ (module === 'react-intl' &&
387
+ (!first || first.ambient || ts.isOptionalChain(first.call) || first.call.arguments.length)))
388
+ return;
389
+ // Check escapes before asking the workspace planner to inspect a foreign package.
390
+ if (renderUses(uses(binding)).some((ref) => !ts.isCallExpression(ref.parent) || ref.parent.expression !== ref))
391
+ return;
392
+ const imported = first && ts.isIdentifier(first.callee)
393
+ ? namedRuntimeImport(first.callee, checker)
394
+ : undefined;
395
+ const direct = imported &&
396
+ (forward
397
+ ? module(imported.module, imported.name)
398
+ : imported.module === module && accepts?.(imported.name))
399
+ ? imported.name
400
+ : undefined;
401
+ if (!direct && (arrow || (!(first && privateContextExports) && module !== 'react')))
402
+ return;
366
403
  if (direct)
367
- calls.set(fn.name.text, direct);
404
+ calls.set(binding.text, direct);
368
405
  else if (privateContextExports &&
369
406
  first &&
370
407
  ts.isIdentifier(first.callee) &&
371
408
  !first.ambient &&
372
409
  !fn.parameters.length &&
373
410
  privateContextCall(sf, checker, uses, first.call, first.callee))
374
- privateContextExports.add(fn.name.text);
375
- else if (module === 'react') {
411
+ privateContextExports.add(binding.text);
412
+ else if (module === 'react' && ts.isBlock(fn.body)) {
376
413
  const effect = setupEffect(fn.body, checker);
377
414
  if (effect)
378
- calls.set(fn.name.text, effect);
415
+ calls.set(binding.text, effect);
416
+ }
417
+ };
418
+ for (const statement of sf.statements) {
419
+ if ((!ts.isFunctionDeclaration(statement) && !ts.isVariableStatement(statement)) ||
420
+ statement.modifiers?.length !== 1 ||
421
+ statement.modifiers[0].kind !== ts.SyntaxKind.ExportKeyword)
422
+ continue;
423
+ if (ts.isFunctionDeclaration(statement)) {
424
+ if (statement.name && !statement.asteriskToken)
425
+ record(statement.name, statement);
426
+ }
427
+ else if (module === 'react' &&
428
+ (statement.declarationList.flags & ts.NodeFlags.BlockScoped) === ts.NodeFlags.Const) {
429
+ for (const { name, initializer } of statement.declarationList.declarations) {
430
+ const arrow = initializer && skipWrappers(initializer);
431
+ if (ts.isIdentifier(name) && arrow && ts.isArrowFunction(arrow) && !arrow.modifiers?.length)
432
+ record(name, arrow);
433
+ }
379
434
  }
380
435
  }
381
436
  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) {
@@ -45,8 +45,12 @@ export declare function mapReactImport(module: string, name: string, typeOnly: b
45
45
  module: string;
46
46
  name: string;
47
47
  } | null;
48
+ /** React-family hooks that need a compiled call site and the original ref allocator. */
49
+ export declare function isComputedReactHookOrRef(name: string): boolean;
50
+ /** Whether a React value type query can name an actual Octane export. */
51
+ export declare function hasOctaneValue(name: string): boolean;
48
52
  /** The Octane name for `React.<name>` in a type position. */
49
- export declare function mapQualifiedType(name: string): string | null;
53
+ export declare function mapQualifiedType(name: string, module: string, typeOf: boolean, typeArgumentCount: number): string | null;
50
54
  /** Built-in hooks whose omitted dependency list Octane infers. * */
51
55
  export declare const DEPENDENCY_HOOKS: Record<string, number>;
52
56
  /** `<input type>` values whose native `change` fires on commit, not per edit. */
package/dist/mappings.js CHANGED
@@ -94,7 +94,7 @@ const OCTANE_TYPES = new Set(('AllHTMLAttributes AnchorHTMLAttributes AnimationE
94
94
  'SVGAttributes SVGLineElementAttributes SVGProps SVGTextElementAttributes ScriptHTMLAttributes ' +
95
95
  'SelectHTMLAttributes SetStateAction SlotHTMLAttributes SourceHTMLAttributes StrictModeProps ' +
96
96
  'StyleHTMLAttributes SuspenseProps TableHTMLAttributes TdHTMLAttributes TextareaHTMLAttributes ' +
97
- 'ThHTMLAttributes TimeHTMLAttributes ToggleEvent ToggleEventHandler TouchEvent TouchEventHandler ' +
97
+ 'ThHTMLAttributes TimeHTMLAttributes ToggleEvent ToggleEventHandler Touch TouchEvent TouchEventHandler ' +
98
98
  'TrackHTMLAttributes TransitionEvent TransitionEventHandler UIEvent UIEventHandler ' +
99
99
  'VideoHTMLAttributes WebViewHTMLAttributes WheelEvent WheelEventHandler').split(' '));
100
100
  /**
@@ -303,14 +303,27 @@ export function mapReactImport(module, name, typeOnly) {
303
303
  }
304
304
  if (!typeOnly && OCTANE_VALUES.has(name))
305
305
  return { module: 'octane', name };
306
- if (OCTANE_TYPES.has(name))
306
+ if (OCTANE_TYPES.has(name) && (name !== 'Touch' || (module === 'react' && typeOnly)))
307
307
  return { module: 'octane', name };
308
308
  if (name in RENAMED_TYPES)
309
309
  return { module: 'octane', name: RENAMED_TYPES[name] };
310
310
  return null;
311
311
  }
312
+ /** React-family hooks that need a compiled call site and the original ref allocator. */
313
+ export function isComputedReactHookOrRef(name) {
314
+ return name === 'createRef' || (name.startsWith('use') && OCTANE_VALUES.has(name));
315
+ }
316
+ /** Whether a React value type query can name an actual Octane export. */
317
+ export function hasOctaneValue(name) {
318
+ return OCTANE_VALUES.has(name);
319
+ }
312
320
  /** The Octane name for `React.<name>` in a type position. */
313
- export function mapQualifiedType(name) {
321
+ export function mapQualifiedType(name, module, typeOf, typeArgumentCount) {
322
+ if (name === 'Touch' && (module !== 'react' || typeOf))
323
+ return null;
324
+ // OctaneElement only accepts props. The migration alias preserves an explicit element type.
325
+ if (name === 'ReactElement' && typeArgumentCount > 1)
326
+ return name;
314
327
  if (name in QUALIFIED_TYPE_PREFERENCES)
315
328
  return QUALIFIED_TYPE_PREFERENCES[name];
316
329
  if (OCTANE_TYPES.has(name))