@octanejs/codemod 0.1.3 → 0.2.0

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.
Files changed (58) hide show
  1. package/README.md +305 -5
  2. package/dist/bin.d.ts +2 -0
  3. package/dist/bin.js +162 -0
  4. package/dist/compiler.d.ts +11 -0
  5. package/dist/compiler.js +48 -0
  6. package/dist/effect-receivers.d.ts +11 -0
  7. package/dist/effect-receivers.js +315 -0
  8. package/dist/expression-wrappers.d.ts +6 -0
  9. package/dist/expression-wrappers.js +16 -0
  10. package/dist/forwarded-props.d.ts +27 -0
  11. package/dist/forwarded-props.js +489 -0
  12. package/dist/index.d.ts +6 -0
  13. package/{src → dist}/index.js +1 -0
  14. package/dist/linked-state.d.ts +17 -0
  15. package/dist/linked-state.js +126 -0
  16. package/dist/local-calls.d.ts +20 -0
  17. package/dist/local-calls.js +143 -0
  18. package/dist/local-react-hook.d.ts +15 -0
  19. package/dist/local-react-hook.js +353 -0
  20. package/dist/local-uses.d.ts +13 -0
  21. package/dist/local-uses.js +987 -0
  22. package/dist/mappings.d.ts +57 -0
  23. package/dist/mappings.js +343 -0
  24. package/dist/path-svg.d.ts +60 -0
  25. package/dist/path-svg.js +207 -0
  26. package/dist/project.d.ts +9 -0
  27. package/dist/project.js +1568 -0
  28. package/dist/react-intl.d.ts +4 -0
  29. package/dist/react-intl.js +389 -0
  30. package/dist/react-renderer.d.ts +9 -0
  31. package/dist/react-renderer.js +106 -0
  32. package/dist/scoped-signal.d.ts +4 -0
  33. package/dist/scoped-signal.js +480 -0
  34. package/dist/scoped-store-contract.d.ts +13 -0
  35. package/dist/scoped-store-contract.js +741 -0
  36. package/dist/store-hook-uses.d.ts +18 -0
  37. package/dist/store-hook-uses.js +403 -0
  38. package/dist/store-inputs.d.ts +16 -0
  39. package/dist/store-inputs.js +391 -0
  40. package/dist/strong.d.ts +24 -0
  41. package/dist/strong.js +142 -0
  42. package/dist/transform.d.ts +27 -0
  43. package/dist/transform.js +4890 -0
  44. package/dist/types.d.ts +203 -0
  45. package/dist/types.js +1 -0
  46. package/package.json +19 -6
  47. package/src/path-svg.ts +218 -0
  48. package/templates/octane-path-svg.ts +56 -0
  49. package/templates/octane-store-context.tsrx +49 -0
  50. package/templates/octane-store-hooks.ts +61 -0
  51. package/templates/react-intl.tsrx +116 -0
  52. package/src/bin.js +0 -151
  53. package/src/compiler.js +0 -61
  54. package/src/index.d.ts +0 -95
  55. package/src/mappings.js +0 -429
  56. package/src/project.js +0 -670
  57. package/src/strong.js +0 -149
  58. package/src/transform.js +0 -3425
package/README.md CHANGED
@@ -50,9 +50,13 @@ bundler plugin and `tsconfig` over to Octane and install the dependencies.
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 |
52
52
 
53
+ React submit event annotations become Octane's native `NativeEvent<T, globalThis.SubmitEvent>` or its `EventHandler`. Uses of the synthetic event, an untyped target, or an event passed into another function need review. A callback's `currentTarget` still refers to the listener's element.
54
+
53
55
  Every rewrite keeps React's behavior. Where it cannot be proven equal, the code
54
56
  is left alone: `{count && <X />}` stays a hole, because React renders `0` there
55
- and `@if` would not. `template-text` reads types through the project's
57
+ and `@if` would not. A strict TypeScript project can prove that a guard's value
58
+ is boolean or nullish, so `{visible && <X />}` can become an `@if` even when
59
+ `visible` is optional. `template-text` reads types through the project's
56
60
  `tsconfig.json` and runs only on TypeScript modules when that config enables
57
61
  `strictNullChecks`; otherwise a `string` may hold null, which React renders as
58
62
  nothing.
@@ -62,35 +66,119 @@ keeps its React shape, but Octane's leaves the commit's `useEffect`s queued
62
66
  where React runs them before returning. React Three Fiber scenes need moving
63
67
  into `.three.tsrx` modules by hand.
64
68
 
69
+ When an exported native host component begins setup with a call to an unselected
70
+ local TypeScript hook, the codemod reports a binding error if the original named
71
+ export begins by calling a named React import of `useState` or
72
+ `useSyncExternalStore`. Give native callers a compiled Octane hook and retain the
73
+ original for React callers.
74
+
65
75
  Every module with JSX becomes `.tsrx`, entries and helpers without a component
66
76
  included, so Strong mode can reach all of them; one that was JavaScript gains
67
77
  `// @ts-nocheck`, so it stays as unchecked as it was. Every import of a renamed
68
78
  module, dynamic imports and `index.html` entry scripts included, is updated.
79
+ So is each string elsewhere in the project that is exactly a renamed module's
80
+ path, from its own file or from the project root, such as Vite's
81
+ `server.warmup.clientFiles: ['./src/main.tsx']`: the `module-paths` rule.
82
+ Globs and paths without an extension stay as they are.
83
+
84
+ ### Element-only children
85
+
86
+ A nested component call in a DOM template supplies a render block. When a
87
+ selected React function component declares an element-only `children` prop,
88
+ `runCodemod` can preserve a single descriptor by rewriting
89
+ `<Frame><Badge /></Frame>` as `<Frame children={<Badge />} />`. This works for
90
+ a top-level function in the same file or a direct relative import from another
91
+ selected input. The `element-child-prop` count records the calls converted.
92
+
93
+ The `element-children` note flags recognized React or JSX element annotations
94
+ for review at other callers. Spreads, comments, meaningful whitespace, multiple
95
+ children, and array-only or parameterized element types need review. A named
96
+ prop such as `icon={<Badge />}` already supplies a descriptor.
97
+
98
+ For a slot that simply renders its contents and should also accept arbitrary
99
+ nested templates, add `ChildrenBlock` to **only that slot**:
100
+
101
+ ```ts
102
+ import type { JSX } from 'octane/strong/jsx-runtime';
103
+ import type { ChildrenBlock } from 'octane/tsrx-boundary';
104
+
105
+ type FrameProps = {
106
+ children?: JSX.Element | ChildrenBlock;
107
+ icon?: JSX.Element;
108
+ };
109
+ ```
110
+
111
+ This permits nested text and multiple children as well as one element. Render
112
+ the block with `{props.children}`. Keep the element type for APIs that inspect
113
+ a descriptor or require exactly one child.
114
+
115
+ The descriptor-children rule also follows arguments passed to directly called
116
+ helper functions in the same module. If a helper inspects a parameter with a
117
+ React element API, the component passing its children gets the same marker as a
118
+ component that inspects them directly. When both files are selected, a direct
119
+ relative import of a marked, named export keeps its nested JSX as descriptor
120
+ values, including an array produced by `.map()`. Intrinsic descriptors retain
121
+ their `className` prop.
122
+
123
+ Octane's Vite and Rspack integrations resolve descriptor markers across imports.
124
+ If a custom build compiles each file in isolation, supply the compiler's
125
+ `isDescriptorChildrenImport` option or pass explicit `children={elements}`.
126
+ With `--strong`, descriptor inspection still requires compatibility mode.
69
127
 
70
128
  ## Strong mode
71
129
 
130
+ A React layout effect with no dependency list runs after every commit. When its
131
+ only work is copying a local element's width, height, or form membership into
132
+ adjacent state, the compiler can replace both hooks with `useLayoutSnapshot`.
133
+ The original state initializer supplies the server and first-render value.
134
+ The migrated hook measures after synchronous layout updates settle. For a
135
+ measurement that must run at a specific point among layout effects, keep
136
+ `useLayoutEffect(measure, null)` in compatibility mode. The explicit `null`
137
+ keeps the every-commit schedule.
138
+
72
139
  With `--strong`, each template module starts with `"use strong"` and is
73
140
  compiled in Strong mode. The codemod applies the compiler's own suggested fixes
74
141
  (`useLazyRef` for lazily initialized refs) and the rewrites that keep React's
75
142
  meaning exactly: a dependency list the compiler infers identically is dropped,
76
143
  and `useState(prop)` becomes `useState(() => prop)`. A module with Strong
77
144
  errors left falls back to compatibility mode, so the app still builds, and the
78
- errors are listed as the work remaining. `--force-strong` keeps the directive
79
- anyway.
145
+ errors are listed as the work remaining. A React effect with omitted or literal
146
+ `undefined` dependencies keeps its every-commit schedule. In a filtered array
147
+ list, the filter and map callbacks may reuse a parameter name.
148
+ `--force-strong` keeps the directive even when Strong errors remain.
80
149
 
81
150
  ## What it reports
82
151
 
83
- Class components, `createRef`, `defaultProps`, and anything else without an
152
+ Class components, `defaultProps`, and anything else without an
84
153
  automatic rewrite are listed under **Needs attention** with a file and line.
85
154
  The process exits with status 1 when any error remains.
86
155
 
156
+ Named imports and re-exports, dotted namespace access, and direct type queries
157
+ for React's `createRef` keep the original allocator. Octane can attach and
158
+ clear the ref object it returns.
159
+
160
+ If a migration target already exists or two sources share a target, write mode
161
+ stops before editing the project. `--dry-run` and `--print` report the colliding
162
+ sources and preview the rest. Imports of colliding sources keep their existing
163
+ paths, so check those dependencies before adopting the preview.
164
+
165
+ The codemod warns when JSX renders an SVG imported with `?react` or the named
166
+ `ReactComponent` export. If your loader returns React components for bare
167
+ `.svg` imports, check those tags too. A loader that emits Octane components
168
+ can keep its existing imports.
169
+
87
170
  A React package with no Octane binding still runs on React, so React stays a
88
171
  dependency, and a comment above each import of it says so. When the project
89
172
  has React and React DOM 19.2 or newer in the React 19 series, a component of that package renders in
90
173
  its own React root through `ReactCompat` if its element gives React nothing
91
174
  Octane renders: text children and props without elements. The package's hooks
92
175
  and contexts, and its components that take Octane children or render
93
- callbacks, are reported where they are used. **No Octane port** lists each such
176
+ callbacks, are reported where they are used. Each such component is wrapped
177
+ in a local `NoOctanePort`, which throws the reported error where the component
178
+ would render, so the page names the package instead of failing deep in
179
+ Octane's renderer. Once you have checked that nothing Octane renders reaches
180
+ it, such as a spread of props whose `children` no caller passes, swap the
181
+ wrapper for `ReactCompat`. **No Octane port** lists each such
94
182
  package with the modules that import it, the elements hosted in islands, and
95
183
  the uses that need a port.
96
184
 
@@ -103,10 +191,222 @@ hand.
103
191
 
104
192
  | Flag | |
105
193
  | --- | --- |
194
+ | `--recipe <file>` | Run a local ESM recipe, resolved from the current directory |
106
195
  | `--strong` | Make modules Strong where the compiler accepts it |
107
196
  | `--force-strong` | Keep `"use strong"` even with Strong errors left |
108
197
  | `--target tsx` | Keep JSX and `.tsx`; port only the React APIs |
109
198
  | `--dry-run` | Report without writing |
110
199
  | `--print` | Print each migrated module (implies `--dry-run`) |
111
200
  | `--no-verify` | Skip compiling the result |
201
+ | `--no-project-types` | Use module-local types without loading the project type graph |
112
202
  | `--json` | Machine-readable result |
203
+
204
+ For a first pass over a large project, `--dry-run --strong --no-project-types`
205
+ keeps import path resolution and compiler verification. Rewrites that require
206
+ types from other files may be skipped. Use the default project type analysis
207
+ when verifying a smaller batch for adoption.
208
+
209
+ ## React Intl
210
+
211
+ 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.
212
+
213
+ 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
+
215
+ For a literal message descriptor with optional scalar substitutions, the codemod also follows the result through local components and directly imported named components selected in the same run. For example, a field can read its disabled state and forward a localized placeholder through a props spread to a native input. The codemod checks the uses of the props object on every branch, including when the caller supplies a fallback label. This sibling-property check assumes ordinary data props and defers when either module accesses object prototypes. A wrapper that gives the formatted value or its props bag to a custom renderer still needs review. When both selected functions return their markup directly, the prop can also pass through one named attribute on an imported function before reaching the native attribute.
216
+
217
+ 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
+
219
+ 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
+
221
+ 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
+
223
+ ## Store hooks in linked workspace packages
224
+
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 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.
226
+
227
+ 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
+
229
+ Hosted components inherit the original React provider. To render a converted component in a standalone Octane root, pass its **original React context** and the active store value to the generated provider.
230
+
231
+ ```tsx
232
+ <NativeStoreProvider context={ReadingContext} value={activeStore}>
233
+ <ReadingPanel />
234
+ </NativeStoreProvider>
235
+ ```
236
+
237
+ The codemod checks how each component uses the hook. Conditions, scalar output, and dependency comparisons can qualify. This includes branded primitive IDs, conditional choices of verified inputs, and named re-exports of the original store handle from local TypeScript modules. A named method on the returned store can take an imported handle created by that store’s verified factory, followed by literals or constants initialized with literals. A named import initialized by a call to a local function declaration keeps the binding diagnostic when passed to a hook or store method. Even a primitive key can dispatch to renderer-owned callbacks in the active store.
238
+
239
+ 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
+
241
+ When the file uses the project’s React 19.2+ automatic JSX runtime, a 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
+
243
+ Dynamic JSX payloads, opaque store values rendered as children, and components passed to unknown renderers still require manual migration.
244
+
245
+ <a id="path-only-svg-components"></a>
246
+
247
+ ## Static SVG components
248
+
249
+ When a file becomes `.tsrx`, its bundler may resolve a bare default SVG import to an asset URL. The codemod reports an error at each JSX tag that still uses that import, including tags selected through local aliases, fallback expressions or default values on parameters and destructured bindings, and tags inside `ReactCompat`. The check follows a binding’s declared default even when a caller always supplies the property. Configure the SVG loader for `.tsrx`, or move the import and rendering into a React-owned `.tsx` component hosted by `ReactCompat`. Using an SVG URL as an image source is unaffected.
250
+
251
+ 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
+
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 rectangles, optionally nested in groups. 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. Gradients, masks and other element references require review. 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
+
255
+ 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
+
257
+ The SVG class can also come from a CSS Module. For example, after `import styles from './badge.module.css'`, both `className={styles.mark}` and `className={cx(styles.mark, styles.accent)}` keep the stylesheet's scoped and composed class names. A `clsx` call that reads the stylesheet must use only string literals and direct class reads. This requires the original and migrated modules to load the same CSS class map, with stable, side-effect-free string exports throughout the application. The codemod checks plain relative default imports and their uses in the current source file. Passing the imported map to another function or assigning to a property keeps the SVG diagnostic.
258
+
259
+ Quoted `fill` and `focusable` props can override the corresponding SVG root attributes. For example, `<Mark fill="currentColor" focusable="false" />` uses the caller's paint and focusability. Omitting either prop preserves the value from the asset. The override must pass the same validation as the corresponding attribute in the SVG file.
260
+
261
+ A component can also store an SVG with literal attributes directly in a local before rendering it. For example, `let icon = null; if (active) icon = <Mark />; return <span>{icon}</span>;` has a single render outlet. The local must be declared directly in the component body with `let` or `const`, and that body must end in a single return. Each additional write must be a standalone assignment, and the only runtime read must lead to a proven render destination in the same function. A captured local, a second read, or a recognized hook call in that function keeps the SVG diagnostic.
262
+
263
+ 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
+
265
+ The generated SVG uses the native SVG namespace. In a client mount, Octane places an explicit `xmlns` attribute in the XMLNS namespace; React sets that attribute without a namespace. Applications that inspect the namespace of the attribute itself should keep their existing rendering path.
266
+
267
+ 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
+
269
+ Shared component values, React island uses, refs, spread props, and SVGs with unsupported elements keep their original imports.
270
+
271
+ ## Local recipes
272
+
273
+ Pass a recipe explicitly to use it for a migration:
274
+
275
+ ```sh
276
+ octane-codemod src --recipe ./migrate.mjs --print --json
277
+ ```
278
+
279
+ Export a named `runCodemod` function with the same arguments and result as the
280
+ package API. For example, this recipe uses its own directory as the project root:
281
+
282
+ ```js
283
+ import { runCodemod as migrate } from '@octanejs/codemod';
284
+
285
+ /** @type {typeof import('@octanejs/codemod').runCodemod} */
286
+ export const runCodemod = (paths, options) =>
287
+ migrate(paths, { ...options, root: import.meta.dirname });
288
+ ```
289
+
290
+ Install `@octanejs/codemod` in the recipe's project to use the import above.
291
+ The CLI loads the module only when you pass `--recipe`. It executes the module
292
+ even for a preview, so the recipe must honor `write: false` for all changes
293
+ when invoked with `--dry-run` or `--print`. The CLI formats the returned report
294
+ and exits with status 1 for reported errors, or status 2 if it cannot load the recipe.
295
+
296
+ ### Migrating scoped signals
297
+
298
+ Use `createScopedSignalRecipe` to convert one exported writable signal and its
299
+ direct consumers together. Supply the source API, the named scope, and the
300
+ destination imports that bind an Octane signal to the lifetime of that scope.
301
+
302
+ ```js
303
+ import { createScopedSignalRecipe } from '@octanejs/codemod';
304
+ import { fileURLToPath } from 'node:url';
305
+
306
+ export const runCodemod = createScopedSignalRecipe({
307
+ sourceRoot: fileURLToPath(new URL('./src', import.meta.url)),
308
+ tsconfig: fileURLToPath(new URL('./tsconfig.json', import.meta.url)),
309
+ sourceModule: '@example/state',
310
+ scope: { module: '@example/owners', name: 'Workspace' },
311
+ factory: { module: '@example/native-state', name: 'defineCell' },
312
+ reader: { module: '@example/react-state', name: 'useCellValue' },
313
+ // Fill from the preview after reviewing this file and its callers.
314
+ reviewedAccess: { 'palette-controls.ts': '<reviewed SHA-256>' },
315
+ });
316
+ ```
317
+
318
+ ```sh
319
+ octane-codemod --recipe ./scoped.mjs --print --json src/palette.ts
320
+ ```
321
+
322
+ For an exported `color = signal(Workspace, () => 'blue')` in that file, the
323
+ recipe emits `color = defineCell("palette.ts:color", () => 'blue')`. The
324
+ key is the source-root-relative path and export name. It converts
325
+ `owner.set(color, value)` to `color.set(owner, value)` and
326
+ `owner.get(color)` to `color.get(owner)` when the owner is a constant
327
+ initialized by `useScope(Workspace)`. A one-argument `useSignal(color)`
328
+ becomes `useCellValue(color)`. Aliases on named imports are supported.
329
+
330
+ The factory must provide one cell per live owner and stable key, accept a
331
+ zero-argument initializer, and preserve the source API's get, set, and updater
332
+ semantics. The reader must obtain the same owner from the active provider
333
+ and preserve subscription and server snapshot behavior. Supply adapters
334
+ appropriate to the application's ownership, disposal and rendering model.
335
+
336
+ For example, a client can keep each cell in its owner's native Octane scope.
337
+ Here `nativeScopeFor(owner)` is the application's adapter. It returns the
338
+ same live Octane `Scope` for that owner and disposes it with the owner.
339
+
340
+ ```js
341
+ // @example/native-state
342
+ import { nativeScopeFor } from '@example/owners';
343
+
344
+ export function defineCell(key, initial) {
345
+ const cells = new WeakMap();
346
+ function bind(owner) {
347
+ const scope = nativeScopeFor(owner);
348
+ if (!cells.has(scope)) {
349
+ const first = initial();
350
+ const cell = scope.signal$(key, first);
351
+ cells.set(scope, {
352
+ cell,
353
+ subscribe: (notify) => cell.subscribe(notify),
354
+ get: () => cell.get(),
355
+ getServer: () => first,
356
+ });
357
+ }
358
+ return cells.get(scope);
359
+ }
360
+ return {
361
+ bind,
362
+ get: (owner) => bind(owner).get(),
363
+ set: (owner, update) => bind(owner).cell.set(update),
364
+ };
365
+ }
366
+ ```
367
+
368
+ A React consumer can subscribe to that same cell. This example assumes that
369
+ the server snapshot is the initial value. Applications that hydrate persisted
370
+ or server-provided state should supply their corresponding snapshot.
371
+
372
+ ```js
373
+ // @example/react-state
374
+ import { useSyncExternalStore } from 'react';
375
+ import { useScope } from '@example/state';
376
+ import { Workspace } from '@example/owners';
377
+
378
+ export function useCellValue(definition) {
379
+ const { subscribe, get, getServer } = definition.bind(useScope(Workspace));
380
+ return useSyncExternalStore(subscribe, get, getServer);
381
+ }
382
+ ```
383
+
384
+ 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
+
386
+ For a component that already receives an Octane writable signal, Strong migration can
387
+ replace `useSyncExternalStore(notify => cell.subscribe(notify), () => cell.get(), () => cell.get())`
388
+ with `cell.get()` in a module that already opts in to native signal tracking. The receiver must
389
+ be a `const` initialized by `signal$()`, or have the public `WritableSignal` type
390
+ resolved from `octane/signals` in a strict TypeScript project. Import
391
+ `'octane/signals'` for its side effects when you want to enable native tracking
392
+ for all render reads in a module that previously imported only its types. A distinct server
393
+ snapshot or a project-specific reader keeps its original subscription.
394
+
395
+ Choose a source root containing all consumers. The recipe discovers static
396
+ module references under that root using the supplied TypeScript configuration.
397
+ It accepts primitive initial values (including global `undefined`) and simple
398
+ zero-argument factories returning them. It reports unsupported owners, escaped
399
+ signals, re-exports, and selector or namespace reads before writing. Review
400
+ external consumers, computed imports, tracked effects and transaction boundaries
401
+ when deciding whether the source and destination APIs have matching semantics.
402
+ The recipe reports a SHA-256 hash for each file with imperative accesses.
403
+ Record it under `reviewedAccess` after checking that the file and its callers
404
+ can use the destination API. The hash identifies the reviewed file. Revisit the
405
+ review when a caller or its execution context changes. A scoped access nested
406
+ inside a source-library call requires manual migration.
407
+
408
+ Remove `--print` to apply the preview, then run the application's typecheck and
409
+ behavioral tests. Writes stage originals and replacements under
410
+ `.octane-scoped-signal` in the source root. If the process is interrupted,
411
+ `paths.json` maps each staged number to its source path. Inspect the files
412
+ and originals before removing the staging directory and retrying.
package/dist/bin.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/bin.js ADDED
@@ -0,0 +1,162 @@
1
+ #!/usr/bin/env node
2
+ import path from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+ import { parseArgs } from 'node:util';
5
+ import colors from 'picocolors';
6
+ import { runCodemod } from './project.js';
7
+ const HELP = `octane-codemod — migrate React + TSX/JSX to Octane + TSRX
8
+
9
+ Usage: octane-codemod [paths...] [options]
10
+
11
+ paths files or directories to migrate (default: .)
12
+
13
+ Options:
14
+ --recipe <file> run a local module's exported runCodemod function
15
+ --strong make each migrated module Strong where the compiler
16
+ accepts it; the rest stay in compatibility mode
17
+ --force-strong keep "use strong" even where Strong errors remain
18
+ --target <tsrx|tsx> tsrx (default) rewrites components as templates;
19
+ tsx keeps JSX and only ports the React APIs
20
+ --svg-paths migrate static SVG geometry when bare SVGs render their authored
21
+ geometry with caller props and ?raw imports read their source;
22
+ pass SVG file paths to prepare native components separately
23
+ --dry-run report without writing
24
+ --print print each migrated module (implies --dry-run)
25
+ --no-verify skip compiling the result
26
+ --no-project-types use module-local types without loading the project graph
27
+ --json print the result as JSON
28
+ -h, --help show this help
29
+ `;
30
+ process.exitCode = await main();
31
+ async function main() {
32
+ const { values, positionals } = parseArgs({
33
+ allowPositionals: true,
34
+ allowNegative: true,
35
+ options: {
36
+ recipe: { type: 'string' },
37
+ strong: { type: 'boolean', default: false },
38
+ 'force-strong': { type: 'boolean', default: false },
39
+ 'svg-paths': { type: 'boolean' },
40
+ target: { type: 'string', default: 'tsrx' },
41
+ 'dry-run': { type: 'boolean', default: false },
42
+ print: { type: 'boolean', default: false },
43
+ verify: { type: 'boolean', default: true },
44
+ 'project-types': { type: 'boolean', default: true },
45
+ json: { type: 'boolean', default: false },
46
+ help: { type: 'boolean', short: 'h', default: false },
47
+ },
48
+ });
49
+ if (values.help) {
50
+ process.stdout.write(HELP);
51
+ return 0;
52
+ }
53
+ if (values.target !== 'tsrx' && values.target !== 'tsx') {
54
+ process.stderr.write(`--target must be tsrx or tsx, got "${values.target}".\n`);
55
+ return 2;
56
+ }
57
+ let run = runCodemod;
58
+ if (values.recipe !== undefined) {
59
+ try {
60
+ const recipe = await import(pathToFileURL(path.resolve(values.recipe)).href);
61
+ if (typeof recipe.runCodemod !== 'function')
62
+ throw new TypeError('expected a named runCodemod function export');
63
+ run = recipe.runCodemod;
64
+ }
65
+ catch (error) {
66
+ const message = error instanceof Error ? error.message : String(error);
67
+ process.stderr.write(`Cannot load --recipe ${values.recipe}: ${message}\n`);
68
+ return 2;
69
+ }
70
+ }
71
+ const dryRun = values['dry-run'] || values.print;
72
+ const result = await run(positionals.length > 0 ? positionals : ['.'], {
73
+ target: values.target,
74
+ strong: values.strong || values['force-strong'],
75
+ forceStrong: values['force-strong'],
76
+ svgPaths: values['svg-paths'],
77
+ verify: values.verify,
78
+ projectTypes: values['project-types'],
79
+ write: !dryRun,
80
+ });
81
+ // The codemod's own notes, at the original file's lines, and the compiler's
82
+ // diagnostics, at the written file's, as one list.
83
+ const findings = result.files.flatMap((file) => [
84
+ ...file.notes
85
+ .filter((note) => note.severity !== 'info')
86
+ .map((note) => ({ file: file.file, ...note, code: note.rule })),
87
+ ...file.diagnostics.map((diagnostic) => ({ file: file.output, ...diagnostic })),
88
+ ]);
89
+ const isError = (finding) => finding.severity === 'error';
90
+ const errors = findings.filter(isError);
91
+ if (values.json) {
92
+ const files = result.files.map(({ code, ...file }) => values.print ? { ...file, code } : file);
93
+ process.stdout.write(JSON.stringify({ ...result, files }, null, 2) + '\n');
94
+ return errors.length > 0 ? 1 : 0;
95
+ }
96
+ const changed = result.files.filter((file) => file.changed);
97
+ for (const file of changed) {
98
+ const arrow = file.output === file.file ? '' : ` → ${file.output}`;
99
+ const rules = Object.entries(file.rules)
100
+ .map(([rule, count]) => (count > 1 ? `${rule}×${count}` : rule))
101
+ .join(', ');
102
+ const mode = file.strong === null ? '' : file.strong ? colors.green(' strong') : colors.yellow(' compat');
103
+ const mark = file.notes.some(isError) || file.diagnostics.some(isError)
104
+ ? colors.red('✗')
105
+ : colors.green('✓');
106
+ process.stdout.write(`${mark} ${file.file}${arrow}${mode} ${colors.dim(rules)}\n`);
107
+ if (values.print)
108
+ process.stdout.write(colors.dim('─'.repeat(60)) + '\n' + file.code + '\n');
109
+ }
110
+ if (findings.length > 0) {
111
+ process.stdout.write(`\n${colors.bold('Needs attention')}\n`);
112
+ for (const finding of findings) {
113
+ const tag = finding.severity === 'error' ? colors.red : colors.yellow;
114
+ const message = finding.message.split('\n')[0];
115
+ process.stdout.write(` ${finding.file}:${finding.line} ${tag(finding.severity)} ${colors.dim(finding.code)} ${message}\n`);
116
+ }
117
+ }
118
+ if (result.packages.length > 0) {
119
+ process.stdout.write(`\n${colors.bold('Dependencies')}\n`);
120
+ const ranges = new Map(result.dependencies.map(({ name, range }) => [name, range]));
121
+ for (const { from, to } of result.packages) {
122
+ const range = ranges.get(to);
123
+ process.stdout.write(` ${from} → ${to}${range ? colors.dim(` ${range}`) : ''}\n`);
124
+ }
125
+ if (ranges.size > 0) {
126
+ process.stdout.write(colors.dim(` ${dryRun ? 'Would add' : 'Added'} ${ranges.size} to package.json\n`));
127
+ }
128
+ for (const { name, patch } of result.patched) {
129
+ process.stdout.write(` ${colors.yellow('warning')} ${name} is patched by ${patch}, which does not apply to its binding: port the patch there.\n`);
130
+ }
131
+ }
132
+ if (result.missing.length > 0) {
133
+ process.stdout.write(`\n${colors.bold('No Octane port')} ${colors.dim('(still runs on React)')}\n`);
134
+ for (const { name, modules, islands, blocked } of result.missing) {
135
+ const uses = [
136
+ `${modules} module(s)`,
137
+ islands > 0 ? `${islands} element(s) in ReactCompat islands` : null,
138
+ blocked > 0 ? colors.red(`${blocked} use(s) need a port`) : null,
139
+ ].filter(Boolean);
140
+ process.stdout.write(` ${name} ${colors.dim(uses.join(', '))}\n`);
141
+ }
142
+ }
143
+ for (const page of result.html)
144
+ process.stdout.write(`\nUpdated the entry script in ${page}\n`);
145
+ const strong = changed.filter((file) => file.strong !== null);
146
+ const summary = [
147
+ `${changed.length} module(s) migrated`,
148
+ `${changed.filter((file) => file.output !== file.file).length} renamed to .tsrx`,
149
+ strong.length > 0
150
+ ? `${strong.filter((file) => file.strong).length}/${strong.length} Strong`
151
+ : null,
152
+ `${errors.length} error(s)`,
153
+ ].filter(Boolean);
154
+ process.stdout.write(`\n${summary.join(', ')}${dryRun ? colors.dim(' (dry run)') : ''}\n`);
155
+ if (changed.length > 0 && !dryRun) {
156
+ // A project outside this directory is named in full, not by `../` steps.
157
+ const relative = path.relative(process.cwd(), result.root);
158
+ const root = relative.startsWith('..') ? result.root : relative || '.';
159
+ process.stdout.write(colors.dim(`Next: run \`npx @octanejs/cli init\` in ${root} to wire Octane into the build.\n`));
160
+ }
161
+ return errors.length > 0 ? 1 : 0;
162
+ }
@@ -0,0 +1,11 @@
1
+ import type { CompileDiagnostic } from 'octane/compiler';
2
+ import type { Compiler, Finding } from './types.js';
3
+ /**
4
+ * The Octane compiler that judges the migrated code: the project's own when it
5
+ * has one, so the result matches what its build will do, else the copy this
6
+ * package ships with, since a React project has no Octane installed yet.
7
+ */
8
+ export declare function loadCompiler(root: string): Promise<Compiler>;
9
+ export declare function finding(diagnostic: CompileDiagnostic): Finding;
10
+ /** A compiler exception, including parser failures with a source location. */
11
+ export declare function thrown(error: unknown): Finding;
@@ -0,0 +1,48 @@
1
+ import { createRequire } from 'node:module';
2
+ import path from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+ /**
5
+ * The Octane compiler that judges the migrated code: the project's own when it
6
+ * has one, so the result matches what its build will do, else the copy this
7
+ * package ships with, since a React project has no Octane installed yet.
8
+ */
9
+ export async function loadCompiler(root) {
10
+ for (const base of [path.join(root, 'noop.js'), import.meta.url]) {
11
+ let entry;
12
+ try {
13
+ entry = createRequire(base).resolve('octane/compiler');
14
+ }
15
+ catch {
16
+ continue;
17
+ }
18
+ const module = await import(pathToFileURL(entry).href);
19
+ if (typeof module.collectDiagnostics === 'function') {
20
+ return { collectDiagnostics: module.collectDiagnostics, from: entry };
21
+ }
22
+ }
23
+ throw new Error('Could not load `octane/compiler`.');
24
+ }
25
+ export function finding(diagnostic) {
26
+ return {
27
+ code: diagnostic.code,
28
+ severity: diagnostic.severity,
29
+ message: String(diagnostic.message).replace(`[${diagnostic.code}] `, ''),
30
+ line: diagnostic.start?.line ?? 1,
31
+ };
32
+ }
33
+ /** A compiler exception, including parser failures with a source location. */
34
+ export function thrown(error) {
35
+ const object = typeof error === 'object' && error !== null ? error : null;
36
+ const location = object && 'loc' in object ? object.loc : null;
37
+ return {
38
+ code: 'COMPILE_ERROR',
39
+ severity: 'error',
40
+ message: String(object && 'message' in object ? (object.message ?? error) : error),
41
+ line: location &&
42
+ typeof location === 'object' &&
43
+ 'line' in location &&
44
+ typeof location.line === 'number'
45
+ ? location.line
46
+ : 1,
47
+ };
48
+ }
@@ -0,0 +1,11 @@
1
+ import ts from 'typescript';
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>): boolean;
4
+ /** An identifier moved past a getter must already be initialized, even across switch cases. */
5
+ export declare function initializedBefore(checker: ts.TypeChecker, name: ts.Identifier, call: ts.Node): boolean;
6
+ /**
7
+ * An explicit [owner] observes object identity even when the callback reads
8
+ * owner.value or calls owner.method(). Read the binding inside the callback
9
+ * and leave property accesses where React executed them, including cleanup.
10
+ */
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, helperUses?: (name: ts.Identifier) => ts.Identifier[], emitHelper?: (arrow: ts.ArrowFunction) => string): string[];