@octanejs/codemod 0.2.0 → 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 +140 -12
- package/dist/bin.js +2 -2
- package/dist/effect-receivers.d.ts +14 -2
- package/dist/effect-receivers.js +171 -22
- package/dist/expression-wrappers.d.ts +2 -0
- package/dist/expression-wrappers.js +19 -0
- package/dist/forwarded-props.d.ts +4 -1
- package/dist/forwarded-props.js +18 -3
- package/dist/linked-state.d.ts +1 -1
- package/dist/linked-state.js +7 -3
- package/dist/local-react-hook.d.ts +13 -6
- package/dist/local-react-hook.js +316 -53
- package/dist/local-uses.d.ts +10 -1
- package/dist/local-uses.js +87 -5
- package/dist/mappings.d.ts +7 -1
- package/dist/mappings.js +21 -3
- package/dist/path-svg.d.ts +68 -4
- package/dist/path-svg.js +162 -56
- package/dist/project.js +1589 -147
- package/dist/react-intl.d.ts +1 -1
- package/dist/react-intl.js +43 -6
- package/dist/react-island-sources.d.ts +53 -0
- package/dist/react-island-sources.js +979 -0
- package/dist/react-renderer.d.ts +2 -0
- package/dist/react-renderer.js +94 -0
- package/dist/scoped-store-contract.d.ts +9 -2
- package/dist/scoped-store-contract.js +209 -33
- package/dist/store-hook-uses.d.ts +7 -5
- package/dist/store-hook-uses.js +218 -62
- package/dist/store-inputs.d.ts +9 -2
- package/dist/store-inputs.js +213 -16
- package/dist/strong.d.ts +2 -2
- package/dist/strong.js +72 -18
- package/dist/transform.d.ts +14 -0
- package/dist/transform.js +2856 -292
- package/dist/types.d.ts +40 -10
- package/package.json +4 -3
- package/src/path-svg.ts +183 -62
- package/templates/octane-path-svg.ts +5 -1
- package/templates/react-intl.tsrx +64 -11
package/README.md
CHANGED
|
@@ -32,7 +32,7 @@ bundler plugin and `tsconfig` over to Octane and install the dependencies.
|
|
|
32
32
|
| `template-component` | `function C() { …; return <div /> }` | `function C() @{ …; <div /> }` |
|
|
33
33
|
| `template-if` | `{a ? <A /> : <B />}`, `{a > 0 && <A />}` (also through a `const`) | `@if (a) { <A /> } @else { <B /> }` |
|
|
34
34
|
| `template-if` | `if (a) return <A />; …; return <B />` in a component | `@if (a) { <A /> } @else { …; <B /> }` |
|
|
35
|
-
| `template-for` | `{
|
|
35
|
+
| `template-for` | `{[1, 2].map(x => <li key={x} />)}` | `@for (const x of [1, 2]; key x) { <li /> }` |
|
|
36
36
|
| `template-try` | `<Suspense fallback={f}>…</Suspense>` | `@try { … } @pending { f }` |
|
|
37
37
|
| `template-text` | `{title}` with `title: string`, `{count}` with `count: number` | `{title as string}`, `{String(count)}`: text bindings, not renderable holes |
|
|
38
38
|
| `hook-dependencies` | `useEffect(fn)` (runs every render) | `useEffect(fn, null)`: an omitted list is inferred in Octane |
|
|
@@ -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
|
|
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 |
|
|
@@ -66,12 +66,24 @@ keeps its React shape, but Octane's leaves the commit's `useEffect`s queued
|
|
|
66
66
|
where React runs them before returning. React Three Fiber scenes need moving
|
|
67
67
|
into `.three.tsrx` modules by hand.
|
|
68
68
|
|
|
69
|
+
On a text input or textarea with no spreads, an explicit `onInput` and a
|
|
70
|
+
single `onChangeCapture` can both run. The codemod retains those handlers and
|
|
71
|
+
warns about callback order.
|
|
72
|
+
React calls `onInput` before its synthetic change capture. Renaming the capture
|
|
73
|
+
handler to `onInputCapture` would run it first. Review the event scheduling for
|
|
74
|
+
the migrated control. The retained `onChangeCapture` runs on native change.
|
|
75
|
+
|
|
69
76
|
When an exported native host component begins setup with a call to an unselected
|
|
70
77
|
local TypeScript hook, the codemod reports a binding error if the original named
|
|
71
78
|
export begins by calling a named React import of `useState` or
|
|
72
79
|
`useSyncExternalStore`. Give native callers a compiled Octane hook and retain the
|
|
73
80
|
original for React callers.
|
|
74
81
|
|
|
82
|
+
The codemod also warns when native setup calls an unchanged local hook that
|
|
83
|
+
forwards to a private helper with a direct React `useContext` read. The warning
|
|
84
|
+
describes what happens after the helper module initializes. Earlier imports in
|
|
85
|
+
a cycle can enter a component while that module's context is still uninitialized.
|
|
86
|
+
|
|
75
87
|
Every module with JSX becomes `.tsrx`, entries and helpers without a component
|
|
76
88
|
included, so Strong mode can reach all of them; one that was JavaScript gains
|
|
77
89
|
`// @ts-nocheck`, so it stays as unchecked as it was. Every import of a renamed
|
|
@@ -81,6 +93,13 @@ path, from its own file or from the project root, such as Vite's
|
|
|
81
93
|
`server.warmup.clientFiles: ['./src/main.tsx']`: the `module-paths` rule.
|
|
82
94
|
Globs and paths without an extension stay as they are.
|
|
83
95
|
|
|
96
|
+
A retained React server entry can still render a component selected for migration.
|
|
97
|
+
The codemod warns when `renderToString(<Leaf />)` or
|
|
98
|
+
`renderToStaticMarkup(createElement(Leaf))` directly uses a relative JSX import
|
|
99
|
+
whose local component returns an intrinsic element. Migrate the server entry
|
|
100
|
+
with that component or keep the component in React. Review custom bundler
|
|
101
|
+
resolution, indirect calls, and dynamic imports.
|
|
102
|
+
|
|
84
103
|
### Element-only children
|
|
85
104
|
|
|
86
105
|
A nested component call in a DOM template supplies a render block. When a
|
|
@@ -89,6 +108,9 @@ selected React function component declares an element-only `children` prop,
|
|
|
89
108
|
`<Frame><Badge /></Frame>` as `<Frame children={<Badge />} />`. This works for
|
|
90
109
|
a top-level function in the same file or a direct relative import from another
|
|
91
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={...}`.
|
|
92
114
|
|
|
93
115
|
The `element-children` note flags recognized React or JSX element annotations
|
|
94
116
|
for review at other callers. Spreads, comments, meaningful whitespace, multiple
|
|
@@ -125,6 +147,16 @@ If a custom build compiles each file in isolation, supply the compiler's
|
|
|
125
147
|
`isDescriptorChildrenImport` option or pass explicit `children={elements}`.
|
|
126
148
|
With `--strong`, descriptor inspection still requires compatibility mode.
|
|
127
149
|
|
|
150
|
+
The `@for` rewrite handles fresh array literals without holes and assumes the
|
|
151
|
+
standard `Array.prototype.map`. An array supplied by a caller can override
|
|
152
|
+
`.map()` and inspect the React elements its callback returns. The codemod keeps
|
|
153
|
+
that call for review. Keep the list in React if its method relies on element identity.
|
|
154
|
+
|
|
155
|
+
React's automatic JSX runtime evaluates a row's props and children before its
|
|
156
|
+
separate key argument. For a simple row where that order is observable, the
|
|
157
|
+
codemod keeps the map callback and evaluates the children as an explicit prop
|
|
158
|
+
before the key. It reports more complex rows for review.
|
|
159
|
+
|
|
128
160
|
## Strong mode
|
|
129
161
|
|
|
130
162
|
A React layout effect with no dependency list runs after every commit. When its
|
|
@@ -162,13 +194,16 @@ stops before editing the project. `--dry-run` and `--print` report the colliding
|
|
|
162
194
|
sources and preview the rest. Imports of colliding sources keep their existing
|
|
163
195
|
paths, so check those dependencies before adopting the preview.
|
|
164
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
|
+
|
|
165
200
|
The codemod warns when JSX renders an SVG imported with `?react` or the named
|
|
166
201
|
`ReactComponent` export. If your loader returns React components for bare
|
|
167
202
|
`.svg` imports, check those tags too. A loader that emits Octane components
|
|
168
203
|
can keep its existing imports.
|
|
169
204
|
|
|
170
|
-
|
|
171
|
-
|
|
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
|
|
172
207
|
has React and React DOM 19.2 or newer in the React 19 series, a component of that package renders in
|
|
173
208
|
its own React root through `ReactCompat` if its element gives React nothing
|
|
174
209
|
Octane renders: text children and props without elements. The package's hooks
|
|
@@ -178,9 +213,9 @@ in a local `NoOctanePort`, which throws the reported error where the component
|
|
|
178
213
|
would render, so the page names the package instead of failing deep in
|
|
179
214
|
Octane's renderer. Once you have checked that nothing Octane renders reaches
|
|
180
215
|
it, such as a spread of props whose `children` no caller passes, swap the
|
|
181
|
-
wrapper for `ReactCompat`. **
|
|
182
|
-
|
|
183
|
-
|
|
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.
|
|
184
219
|
|
|
185
220
|
A patch the project applies to a React package the codemod replaces, through
|
|
186
221
|
`patchedDependencies` (pnpm, Bun) or `patches/` (patch-package), patches the
|
|
@@ -208,7 +243,7 @@ when verifying a smaller batch for adoption.
|
|
|
208
243
|
|
|
209
244
|
## React Intl
|
|
210
245
|
|
|
211
|
-
When an application has React Intl 7, React and React DOM 19.2 or later in the 19 series, and
|
|
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.
|
|
212
247
|
|
|
213
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.
|
|
214
249
|
|
|
@@ -216,13 +251,96 @@ For a literal message descriptor with optional scalar substitutions, the codemod
|
|
|
216
251
|
|
|
217
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).
|
|
218
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
|
+
|
|
219
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.
|
|
220
257
|
|
|
221
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.
|
|
222
259
|
|
|
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.
|
|
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
|
+
|
|
223
341
|
## Store hooks in linked workspace packages
|
|
224
342
|
|
|
225
|
-
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
|
|
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.
|
|
226
344
|
|
|
227
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.
|
|
228
346
|
|
|
@@ -238,7 +356,9 @@ The codemod checks how each component uses the hook. Conditions, scalar output,
|
|
|
238
356
|
|
|
239
357
|
A verified hook result can also go to a named function exported directly from an unchanged local TypeScript module whose local runtime dependencies also remain unchanged. The call must run inside a React effect, its cleanup, or an inline click handler on an intrinsic element in the component’s rendered output. For example, `useEffect(() => { syncSettings(store, 'startup'); }, [store])` keeps the same function and store. The other arguments must be literal data or local constants initialized with literals, and the call must discard the result. Calls during render and callbacks passed to custom components need review.
|
|
240
358
|
|
|
241
|
-
|
|
359
|
+
The codemod preserves reads of provider-owned store members in proven post-render paths, such as inline effects and intrinsic click handlers. A verified handle establishes the input’s origin. The active provider supplies the store methods and getters.
|
|
360
|
+
|
|
361
|
+
When the file uses the project’s React 19.2+ automatic JSX runtime, a deferred service read with a verified handle can receive a self-closing component from an installed React package with literal props, for example `store.read(notices).show(<Message id="saved" />)`. The generated code creates the original React element, so the service can render it later under its React provider.
|
|
242
362
|
|
|
243
363
|
Dynamic JSX payloads, opaque store values rendered as children, and components passed to unknown renderers still require manual migration.
|
|
244
364
|
|
|
@@ -250,7 +370,7 @@ When a file becomes `.tsrx`, its bundler may resolve a bare default SVG import t
|
|
|
250
370
|
|
|
251
371
|
Use `--svg-paths` (or `svgPaths: true` in the JavaScript API) when your bundler's bare default SVG import renders the authored SVG geometry, applies caller props to its root, and the same asset with `?raw` imports its XML as a string. For aliased requests, the bundler and TypeScript paths must resolve to the same local file. Check both your development and production loaders before enabling this option. Custom SVG templates, optimizers that rewrite the rendered geometry, and URL-producing loaders can have different behavior.
|
|
252
372
|
|
|
253
|
-
For example, `<Mark className="icon" aria-hidden data-testid="status-icon" />` can remain a direct SVG child of a button. The codemod checks the asset and each use of the import. The generated component forwards quoted string values for lowercase `data-*` attributes outside Octane's reserved renderer markers. It also accepts classes such as `className={cx("icon", open && "expanded")}` when `cx` imports the default or named `clsx` export from the installed package. A truth test can use a local const initialized earlier in the same function or a parameter that the function never reassigns. A class token can also come from a fixed string parameter or a local const initialized with a string literal. Passing objects to `clsx` or calling an arbitrary class builder keeps the import for review. A direct conditional such as `className={open ? "expanded" : "collapsed"}` can also select between string literals using a fixed, initialized binding. Supported geometry includes ordered, self-closing paths and
|
|
373
|
+
For example, `<Mark className="icon" aria-hidden data-testid="status-icon" />` can remain a direct SVG child of a button. The codemod checks the asset and each use of the import. The generated component forwards quoted string values for lowercase `data-*` attributes outside Octane's reserved renderer markers. It also accepts classes such as `className={cx("icon", open && "expanded")}` when `cx` imports the default or named `clsx` export from the installed package. A truth test can use a local const initialized earlier in the same function or a parameter that the function never reassigns. A class token can also come from a fixed string parameter or a local const initialized with a string literal. Passing objects to `clsx` or calling an arbitrary class builder keeps the import for review. A direct conditional such as `className={open ? "expanded" : "collapsed"}` can also select between string literals using a fixed, initialized binding. Supported geometry includes ordered, self-closing paths, rectangles, and circles, optionally nested in groups. The asset can also provide plain lowercase text or empty values for supported root data attributes. A literal caller value overrides the matching asset value. Paths and groups support scale, translate and six-number matrix transforms. The helper preserves supported dimensions, fills, strokes, opacity (including leading-dot decimals), and single CSS custom-property paints such as `var(--icon-fill)`. A root-level group can reference a rectangular clip with `clip-path="url(#id)"`. The SVG must contain one root-level `<defs>` with one matching `<clipPath id="…">` and one rectangle. The native component preserves the authored ID across instances. Enable this option only when your SVG loaders preserve that ID and its references. A root rectangle can use one local repeating pattern containing a single path. The pattern must declare `patternUnits="userSpaceOnUse"` and positive integer tile dimensions. The helper preserves the authored ID and document order. Each asset may use a rectangular clip or a single-path pattern. Each supported import points to a small native component beside the asset. That component reads the live SVG through `?raw`, so changes to supported geometry appear on the next build. Editing the asset to use unsupported markup produces an explicit error.
|
|
254
374
|
|
|
255
375
|
A directly returned SVG can use a fixed color such as `style={{ color: 'var(--icon-color)' }}`, including through intrinsic parents. This requires one JSX use of the import and a lowercase custom property with no fallback. The generated component keeps the fixed color on its SVG root.
|
|
256
376
|
|
|
@@ -262,10 +382,14 @@ A component can also store an SVG with literal attributes directly in a local be
|
|
|
262
382
|
|
|
263
383
|
The codemod follows an icon through local components and directly imported components selected in the same migration. For example, with `function Button({ children }) { return <button>{children}</button>; }`, it can follow `<Button><Mark /></Button>` to the native button. The same check applies to a named prop such as `icon`. A receiver can also test an explicitly named prop for presence and render it, for example `icon ? <span>{icon}</span> : null` or `<span>{preferred ?? icon}</span>`. Each use must reach native output or only test presence in the receiving function. At least one use must render the value. Presence checks on JSX children and on slots forwarded through another receiver need review because an empty JSX child can be a truthy render function. The caller’s surrounding JSX must also reach an exported native component. A type query such as `ComponentProps<typeof Button>` can still refer to the component after migration. A query on the imported SVG itself keeps its original component type and import. The check defers recognizable hook calls and props compiled as text. When an icon reaches an unverified renderer, you can prepare its native module separately with `octane-codemod --svg-paths src/icons/mark.svg`. This writes the native component beside the asset and leaves callers available for review. Confirm the receiving component renders Octane elements before switching its import to `./mark.svg.octane`.
|
|
264
384
|
|
|
265
|
-
The generated SVG uses the native SVG namespace.
|
|
385
|
+
The generated SVG uses the native SVG namespace. On a fresh client mount, Octane places an explicit `xmlns` attribute in the XMLNS namespace. If the original React loader forwards it as a prop, React sets it without a namespace. The codemod warns once per admitted asset with this attribute. Applications that inspect the attribute namespace should keep their existing rendering path.
|
|
266
386
|
|
|
267
387
|
An inline style can set a single `transform` declaration. The value can be a string literal or a template with numeric literals selected by a fixed, initialized binding, such as `style={{ transform: \`rotate(\${open ? 0 : -90}deg)\` }}`. Octane preserves the declaration across updates and can add a trailing semicolon to the server-rendered style attribute.
|
|
268
388
|
|
|
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.
|
|
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
|
+
|
|
269
393
|
Shared component values, React island uses, refs, spread props, and SVGs with unsupported elements keep their original imports.
|
|
270
394
|
|
|
271
395
|
## Local recipes
|
|
@@ -381,8 +505,12 @@ export function useCellValue(definition) {
|
|
|
381
505
|
}
|
|
382
506
|
```
|
|
383
507
|
|
|
508
|
+
Strong migration can preserve a typed `useState<Element | null>(null)` setter used only as one native host `ref` in an ordinary React JSX project. The generated component uses `useSyncExternalStore` to observe attachment and detachment. This also covers ref commits owned by an ancestor Suspense boundary.
|
|
509
|
+
|
|
384
510
|
When an effect with dependencies such as `[controller]` reads `controller.value` or calls `controller.start()`, Strong migration can preserve the original object-identity dependency. For an unused dependency such as `revision` in `[controller, revision]`, the codemod can emit `void revision` inside the effect so a revision change still triggers cleanup and setup. It attempts these rewrites for immutable bindings and verifies the resulting dependencies with the project compiler. An imperative handle can use the same rewrite with a list of fixed bindings, keeping property reads inside its factory.
|
|
385
511
|
|
|
512
|
+
A property in an explicit dependency list for a React effect, memo, callback, or imperative handle is read during rendering. The codemod reports reads that can invoke an opaque getter, including in compatibility output. A private, fixed local object with a known own data field can still be used as a dependency.
|
|
513
|
+
|
|
386
514
|
For a component that already receives an Octane writable signal, Strong migration can
|
|
387
515
|
replace `useSyncExternalStore(notify => cell.subscribe(notify), () => cell.get(), () => cell.get())`
|
|
388
516
|
with `cell.get()` in a module that already opts in to native signal tracking. The receiver must
|
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('
|
|
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
|
|
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
|
}
|
|
@@ -1,11 +1,23 @@
|
|
|
1
1
|
import ts from 'typescript';
|
|
2
2
|
/** A const already initialized in this function, or a parameter it never reassigns. */
|
|
3
|
-
export declare function fixedBinding(checker: ts.TypeChecker, name: ts.Identifier, read: ts.Expression, parameters?: Map<ts.Symbol, boolean
|
|
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;
|
|
8
|
+
/** Trust a destructured prop only when this file cannot change or supply it. */
|
|
9
|
+
export declare function stableExportedProp(symbol: ts.Symbol | undefined, checker: ts.TypeChecker): boolean;
|
|
10
|
+
/** Keep calls to ref-only helpers at their original effect, event or cleanup phase. */
|
|
11
|
+
export declare function effectHelpers(effect: ts.CallExpression, checker: ts.TypeChecker, reactHook: (name: ts.Expression) => string | null, uses: (name: ts.Identifier) => ts.Identifier[], canMove: boolean): {
|
|
12
|
+
callback: ts.ArrowFunction;
|
|
13
|
+
declarations: {
|
|
14
|
+
statement: ts.VariableStatement;
|
|
15
|
+
move: boolean;
|
|
16
|
+
}[];
|
|
17
|
+
} | undefined;
|
|
6
18
|
/**
|
|
7
19
|
* An explicit [owner] observes object identity even when the callback reads
|
|
8
20
|
* owner.value or calls owner.method(). Read the binding inside the callback
|
|
9
21
|
* and leave property accesses where React executed them, including cleanup.
|
|
10
22
|
*/
|
|
11
|
-
export declare function effectReceivers(callback: ts.ArrowFunction, checker: ts.TypeChecker, reactHook: (name: ts.Expression) => string | null, aliases: Map<ts.Expression, string>, snapshot?: (statement: ts.ExpressionStatement, member: ts.PropertyAccessExpression, name: string) => void, bridgeLayout?: (statement: ts.ExpressionStatement, name: string) => void
|
|
23
|
+
export declare function effectReceivers(callback: ts.ArrowFunction, checker: ts.TypeChecker, reactHook: (name: ts.Expression) => string | null, aliases: Map<ts.Expression, string>, snapshot?: (statement: ts.ExpressionStatement, member: ts.PropertyAccessExpression, name: string) => void, bridgeLayout?: (statement: ts.ExpressionStatement, name: string) => void): string[];
|
package/dist/effect-receivers.js
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import ts from 'typescript';
|
|
2
|
+
import { skipWrappers } from './expression-wrappers.js';
|
|
3
|
+
import { inTypeNode, localSymbol, localUses } from './local-uses.js';
|
|
2
4
|
function visit(node, read) {
|
|
3
5
|
read(node);
|
|
4
6
|
ts.forEachChild(node, (child) => visit(child, read));
|
|
5
7
|
}
|
|
6
8
|
/** A const already initialized in this function, or a parameter it never reassigns. */
|
|
7
|
-
export function fixedBinding(checker, name, read, parameters) {
|
|
9
|
+
export function fixedBinding(checker, name, read, parameters, mayEval) {
|
|
8
10
|
const symbol = checker.getSymbolAtLocation(name);
|
|
9
11
|
if (symbol?.declarations?.length !== 1 || !symbol.valueDeclaration)
|
|
10
12
|
return false;
|
|
@@ -26,7 +28,8 @@ export function fixedBinding(checker, name, read, parameters) {
|
|
|
26
28
|
return known;
|
|
27
29
|
let fixed = true;
|
|
28
30
|
visit(owner, (node) => {
|
|
29
|
-
|
|
31
|
+
// Without a caller's syntax proof, any eval identifier can hide a write.
|
|
32
|
+
if (ts.isIdentifier(node) && node.text === 'eval' && (!mayEval || mayEval(node)))
|
|
30
33
|
fixed = false;
|
|
31
34
|
let target;
|
|
32
35
|
if (ts.isBinaryExpression(node) &&
|
|
@@ -69,18 +72,153 @@ export function initializedBefore(checker, name, call) {
|
|
|
69
72
|
statement.end <= call.getStart() &&
|
|
70
73
|
!!ts.findAncestor(call, (n) => n === statement.parent));
|
|
71
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
|
+
}
|
|
85
|
+
const propScopes = new WeakMap();
|
|
86
|
+
function propScope(file, checker) {
|
|
87
|
+
const uses = localUses(file, checker);
|
|
88
|
+
const imported = new Set();
|
|
89
|
+
let opaque = false;
|
|
90
|
+
const target = (symbol) => symbol && symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
|
|
91
|
+
// An authored declaration can describe a different runtime export.
|
|
92
|
+
const localDeclaration = (symbol) => symbol?.declarations?.some((declaration) => {
|
|
93
|
+
const source = declaration.getSourceFile();
|
|
94
|
+
return source.isDeclarationFile && !/[/\\]node_modules[/\\]/.test(source.fileName);
|
|
95
|
+
});
|
|
96
|
+
function mark(symbol) {
|
|
97
|
+
const resolved = target(symbol);
|
|
98
|
+
if (!resolved?.declarations?.length) {
|
|
99
|
+
// The checker also exposes erased re-exports when reading a namespace.
|
|
100
|
+
const declarations = symbol?.declarations;
|
|
101
|
+
if (!declarations?.length || !declarations.every(ts.isTypeOnlyImportOrExportDeclaration))
|
|
102
|
+
opaque = true;
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
if (resolved.flags & ts.SymbolFlags.ValueModule || localDeclaration(resolved))
|
|
106
|
+
opaque = true;
|
|
107
|
+
const decl = resolved?.valueDeclaration;
|
|
108
|
+
const source = decl?.getSourceFile();
|
|
109
|
+
if (decl && source === file)
|
|
110
|
+
imported.add(decl);
|
|
111
|
+
else if (source?.text === file.text &&
|
|
112
|
+
ts.sys.realpath?.(source.fileName) === ts.sys.realpath?.(file.fileName)) {
|
|
113
|
+
// Relative symlinks can give one runtime module two checker source files.
|
|
114
|
+
opaque = true;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
function markModule(symbol) {
|
|
118
|
+
const module = target(symbol);
|
|
119
|
+
if (module && module.flags & ts.SymbolFlags.Module && !localDeclaration(module))
|
|
120
|
+
for (const entry of checker.getExportsOfModule(module))
|
|
121
|
+
mark(entry);
|
|
122
|
+
else
|
|
123
|
+
opaque = true;
|
|
124
|
+
}
|
|
125
|
+
visit(file, (node) => {
|
|
126
|
+
if (ts.isImportClause(node) && !node.isTypeOnly) {
|
|
127
|
+
if (node.name)
|
|
128
|
+
mark(checker.getSymbolAtLocation(node.name));
|
|
129
|
+
const bindings = node.namedBindings;
|
|
130
|
+
if ((node.name ||
|
|
131
|
+
(bindings &&
|
|
132
|
+
(ts.isNamespaceImport(bindings) ||
|
|
133
|
+
bindings.elements.some((item) => !item.isTypeOnly)))) &&
|
|
134
|
+
localDeclaration(checker.getSymbolAtLocation(node.parent.moduleSpecifier)))
|
|
135
|
+
opaque = true;
|
|
136
|
+
if (bindings && ts.isNamespaceImport(bindings))
|
|
137
|
+
markModule(checker.getSymbolAtLocation(bindings.name));
|
|
138
|
+
else if (bindings)
|
|
139
|
+
for (const item of bindings.elements)
|
|
140
|
+
if (!item.isTypeOnly)
|
|
141
|
+
mark(checker.getSymbolAtLocation(item.name));
|
|
142
|
+
}
|
|
143
|
+
else if (ts.isCallExpression(node)) {
|
|
144
|
+
const expression = skipWrappers(node.expression);
|
|
145
|
+
const args = node.arguments;
|
|
146
|
+
if (expression.kind === ts.SyntaxKind.ImportKeyword)
|
|
147
|
+
markModule(args[0] && ts.isStringLiteralLike(args[0])
|
|
148
|
+
? checker.getSymbolAtLocation(args[0])
|
|
149
|
+
: undefined);
|
|
150
|
+
else if (ts.isIdentifier(expression) && expression.text === 'require')
|
|
151
|
+
opaque = true;
|
|
152
|
+
}
|
|
153
|
+
else if (ts.isImportEqualsDeclaration(node) && !node.isTypeOnly)
|
|
154
|
+
opaque = true;
|
|
155
|
+
});
|
|
156
|
+
return { checker, uses, imported, opaque, fixed: new Map() };
|
|
157
|
+
}
|
|
158
|
+
function plainObjectBinding(name) {
|
|
159
|
+
return (ts.isIdentifier(name) ||
|
|
160
|
+
(ts.isObjectBindingPattern(name) &&
|
|
161
|
+
name.elements.every((element) => !element.initializer &&
|
|
162
|
+
!element.dotDotDotToken &&
|
|
163
|
+
(!element.propertyName || !ts.isComputedPropertyName(element.propertyName)) &&
|
|
164
|
+
plainObjectBinding(element.name))));
|
|
165
|
+
}
|
|
166
|
+
/** Trust a destructured prop only when this file cannot change or supply it. */
|
|
167
|
+
export function stableExportedProp(symbol, checker) {
|
|
168
|
+
const binding = symbol?.valueDeclaration;
|
|
169
|
+
if (!binding || !ts.isBindingElement(binding) || !ts.isIdentifier(binding.name))
|
|
170
|
+
return false;
|
|
171
|
+
let declaration = binding;
|
|
172
|
+
while (ts.isBindingElement(declaration))
|
|
173
|
+
declaration = declaration.parent.parent;
|
|
174
|
+
if (!ts.isParameter(declaration) ||
|
|
175
|
+
declaration.initializer ||
|
|
176
|
+
!plainObjectBinding(declaration.name))
|
|
177
|
+
return false;
|
|
178
|
+
const owner = declaration.parent;
|
|
179
|
+
if (!ts.isFunctionDeclaration(owner) ||
|
|
180
|
+
!owner.name ||
|
|
181
|
+
!/^[A-Z]/.test(owner.name.text) ||
|
|
182
|
+
declaration !== owner.parameters[0] ||
|
|
183
|
+
!(ts.getCombinedModifierFlags(owner) & ts.ModifierFlags.Export))
|
|
184
|
+
return false;
|
|
185
|
+
const file = owner.getSourceFile();
|
|
186
|
+
let scope = propScopes.get(file);
|
|
187
|
+
if (scope?.checker !== checker)
|
|
188
|
+
propScopes.set(file, (scope = propScope(file, checker)));
|
|
189
|
+
return (!scope.opaque &&
|
|
190
|
+
!scope.imported.has(owner) &&
|
|
191
|
+
scope.uses(owner.name).every((ref) => ts.isExportSpecifier(ref.parent) || inTypeNode(ref)) &&
|
|
192
|
+
fixedBinding(checker, binding.name, binding.name, scope.fixed));
|
|
193
|
+
}
|
|
72
194
|
/** Keep calls to ref-only helpers at their original effect, event or cleanup phase. */
|
|
73
|
-
function effectHelpers(
|
|
74
|
-
|
|
195
|
+
export function effectHelpers(effect, checker, reactHook, uses, canMove) {
|
|
196
|
+
if (effect.questionDotToken || effect.arguments.length !== 2)
|
|
197
|
+
return;
|
|
198
|
+
const hook = reactHook(effect.expression);
|
|
199
|
+
if (hook !== 'useEffect' && hook !== 'useLayoutEffect')
|
|
200
|
+
return;
|
|
201
|
+
const [callback, deps] = effect.arguments;
|
|
202
|
+
if (!ts.isArrowFunction(callback) ||
|
|
203
|
+
callback.parameters.length ||
|
|
204
|
+
!ts.isBlock(callback.body) ||
|
|
205
|
+
!ts.isArrayLiteralExpression(deps) ||
|
|
206
|
+
deps.elements.length)
|
|
207
|
+
return;
|
|
208
|
+
const body = callback.body;
|
|
75
209
|
const scope = effect.parent.parent;
|
|
76
210
|
const destination = body.statements[0];
|
|
77
211
|
if (!destination ||
|
|
212
|
+
(ts.isExpressionStatement(destination) && ts.isStringLiteral(destination.expression)) ||
|
|
78
213
|
!ts.isExpressionStatement(effect.parent) ||
|
|
79
214
|
!ts.isBlock(scope) ||
|
|
80
215
|
!ts.isFunctionLike(scope.parent))
|
|
81
|
-
return
|
|
216
|
+
return;
|
|
82
217
|
const helpers = new Set();
|
|
218
|
+
let hasEval = false;
|
|
83
219
|
visit(body, (node) => {
|
|
220
|
+
if (ts.isIdentifier(node) && node.text === 'eval')
|
|
221
|
+
hasEval = true;
|
|
84
222
|
if (!ts.isCallExpression(node) || !ts.isIdentifier(node.expression))
|
|
85
223
|
return;
|
|
86
224
|
const decl = checker.getSymbolAtLocation(node.expression)?.valueDeclaration;
|
|
@@ -97,6 +235,8 @@ function effectHelpers(body, checker, reactHook, uses, emit) {
|
|
|
97
235
|
ts.isArrowFunction(decl.initializer))
|
|
98
236
|
helpers.add(decl);
|
|
99
237
|
});
|
|
238
|
+
if (hasEval)
|
|
239
|
+
return;
|
|
100
240
|
const declarations = [];
|
|
101
241
|
for (const decl of helpers) {
|
|
102
242
|
const arrow = decl.initializer;
|
|
@@ -109,9 +249,16 @@ function effectHelpers(body, checker, reactHook, uses, emit) {
|
|
|
109
249
|
continue;
|
|
110
250
|
const refs = uses(decl.name);
|
|
111
251
|
const inside = refs.filter((ref) => ref.pos >= body.pos && ref.end <= body.end);
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
252
|
+
const statement = decl.parent.parent;
|
|
253
|
+
const source = statement.getSourceFile().text;
|
|
254
|
+
const move = canMove &&
|
|
255
|
+
inside.length === refs.length &&
|
|
256
|
+
!/\/[/*]/.test(source.slice(statement.pos, statement.getStart())) &&
|
|
257
|
+
!ts.getTrailingCommentRanges(source, statement.end)?.length;
|
|
258
|
+
if ((!move &&
|
|
259
|
+
!refs.some((ref) => (ref.pos < body.pos || ref.end > body.end) &&
|
|
260
|
+
ts.isCallExpression(ref.parent) &&
|
|
261
|
+
ref.parent.expression === ref)) ||
|
|
115
262
|
!inside.length ||
|
|
116
263
|
!inside.every((ref) => ts.isCallExpression(ref.parent) &&
|
|
117
264
|
ref.parent.expression === ref &&
|
|
@@ -174,16 +321,17 @@ function effectHelpers(body, checker, reactHook, uses, emit) {
|
|
|
174
321
|
safe = false;
|
|
175
322
|
});
|
|
176
323
|
if (safe && readsRef)
|
|
177
|
-
declarations.push(
|
|
324
|
+
declarations.push({ statement, move });
|
|
178
325
|
}
|
|
179
|
-
|
|
326
|
+
if (declarations.length)
|
|
327
|
+
return { callback, declarations };
|
|
180
328
|
}
|
|
181
329
|
/**
|
|
182
330
|
* An explicit [owner] observes object identity even when the callback reads
|
|
183
331
|
* owner.value or calls owner.method(). Read the binding inside the callback
|
|
184
332
|
* and leave property accesses where React executed them, including cleanup.
|
|
185
333
|
*/
|
|
186
|
-
export function effectReceivers(callback, checker, reactHook, aliases, snapshot, bridgeLayout
|
|
334
|
+
export function effectReceivers(callback, checker, reactHook, aliases, snapshot, bridgeLayout) {
|
|
187
335
|
const { body } = callback;
|
|
188
336
|
if (callback.parameters.length ||
|
|
189
337
|
(ts.isBlock(body) &&
|
|
@@ -210,11 +358,17 @@ export function effectReceivers(callback, checker, reactHook, aliases, snapshot,
|
|
|
210
358
|
// A property snapshot would run before the imperative handle evaluates its ref.
|
|
211
359
|
if (hasProperties && (imperative || !snapshot))
|
|
212
360
|
return [];
|
|
361
|
+
const dependencies = new Map(identifiers.map((dep) => [dep.text, checker.getSymbolAtLocation(dep)]));
|
|
362
|
+
const captured = new Set();
|
|
213
363
|
const names = new Set();
|
|
214
364
|
const members = new Map();
|
|
215
365
|
visit(body, (node) => {
|
|
216
|
-
if (ts.isIdentifier(node))
|
|
366
|
+
if (ts.isIdentifier(node)) {
|
|
217
367
|
names.add(node.text);
|
|
368
|
+
const dependency = dependencies.get(node.text);
|
|
369
|
+
if (dependency && !inTypeNode(node) && localSymbol(checker, node) === dependency)
|
|
370
|
+
captured.add(dependency);
|
|
371
|
+
}
|
|
218
372
|
if ((!ts.isPropertyAccessExpression(node) && !ts.isElementAccessExpression(node)) ||
|
|
219
373
|
!ts.isIdentifier(node.expression))
|
|
220
374
|
return;
|
|
@@ -228,13 +382,6 @@ export function effectReceivers(callback, checker, reactHook, aliases, snapshot,
|
|
|
228
382
|
});
|
|
229
383
|
if (names.has('eval') || !identifiers.every((dep) => fixedBinding(checker, dep, call)))
|
|
230
384
|
return [];
|
|
231
|
-
if (helperUses &&
|
|
232
|
-
emitHelper &&
|
|
233
|
-
!deps.elements.length &&
|
|
234
|
-
ts.isBlock(body) &&
|
|
235
|
-
!call.questionDotToken &&
|
|
236
|
-
(hook === 'useEffect' || hook === 'useLayoutEffect'))
|
|
237
|
-
return effectHelpers(body, checker, reactHook, helperUses, emitHelper);
|
|
238
385
|
const declarations = [];
|
|
239
386
|
if (hasProperties) {
|
|
240
387
|
const properties = deps.elements.filter(ts.isPropertyAccessExpression);
|
|
@@ -290,9 +437,11 @@ export function effectReceivers(callback, checker, reactHook, aliases, snapshot,
|
|
|
290
437
|
return declarations;
|
|
291
438
|
}
|
|
292
439
|
}
|
|
293
|
-
//
|
|
294
|
-
for (const
|
|
295
|
-
if (
|
|
440
|
+
// A property label can share the name of a deliberate restart trigger.
|
|
441
|
+
for (const [text, symbol] of dependencies) {
|
|
442
|
+
if (!symbol ||
|
|
443
|
+
captured.has(symbol) ||
|
|
444
|
+
checker.resolveName(text, body, ts.SymbolFlags.Value, false) !== symbol)
|
|
296
445
|
continue;
|
|
297
446
|
declarations.push(`void ${text};`);
|
|
298
447
|
names.add(text);
|
|
@@ -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
|
+
}
|