@octanejs/codemod 0.1.4 → 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.
- package/README.md +295 -4
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +162 -0
- package/dist/compiler.d.ts +11 -0
- package/dist/compiler.js +48 -0
- package/dist/effect-receivers.d.ts +11 -0
- package/dist/effect-receivers.js +315 -0
- package/dist/expression-wrappers.d.ts +6 -0
- package/dist/expression-wrappers.js +16 -0
- package/dist/forwarded-props.d.ts +27 -0
- package/dist/forwarded-props.js +489 -0
- package/dist/index.d.ts +6 -0
- package/{src → dist}/index.js +1 -0
- package/dist/linked-state.d.ts +17 -0
- package/dist/linked-state.js +126 -0
- package/dist/local-calls.d.ts +20 -0
- package/dist/local-calls.js +143 -0
- package/dist/local-react-hook.d.ts +15 -0
- package/dist/local-react-hook.js +353 -0
- package/dist/local-uses.d.ts +13 -0
- package/dist/local-uses.js +987 -0
- package/dist/mappings.d.ts +57 -0
- package/dist/mappings.js +343 -0
- package/dist/path-svg.d.ts +60 -0
- package/dist/path-svg.js +207 -0
- package/dist/project.d.ts +9 -0
- package/dist/project.js +1568 -0
- package/dist/react-intl.d.ts +4 -0
- package/dist/react-intl.js +389 -0
- package/dist/react-renderer.d.ts +9 -0
- package/dist/react-renderer.js +106 -0
- package/dist/scoped-signal.d.ts +4 -0
- package/dist/scoped-signal.js +480 -0
- package/dist/scoped-store-contract.d.ts +13 -0
- package/dist/scoped-store-contract.js +741 -0
- package/dist/store-hook-uses.d.ts +18 -0
- package/dist/store-hook-uses.js +403 -0
- package/dist/store-inputs.d.ts +16 -0
- package/dist/store-inputs.js +391 -0
- package/dist/strong.d.ts +24 -0
- package/dist/strong.js +142 -0
- package/dist/transform.d.ts +27 -0
- package/dist/transform.js +4890 -0
- package/dist/types.d.ts +203 -0
- package/dist/types.js +1 -0
- package/package.json +18 -6
- package/src/path-svg.ts +218 -0
- package/templates/octane-path-svg.ts +56 -0
- package/templates/octane-store-context.tsrx +49 -0
- package/templates/octane-store-hooks.ts +61 -0
- package/templates/react-intl.tsrx +116 -0
- package/src/bin.js +0 -151
- package/src/compiler.js +0 -61
- package/src/index.d.ts +0 -95
- package/src/mappings.js +0 -429
- package/src/project.js +0 -738
- package/src/strong.js +0 -149
- package/src/transform.js +0 -3455
|
@@ -0,0 +1,741 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import { createRequire } from 'node:module';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import ts from 'typescript';
|
|
6
|
+
// The application's React compiler must not synthesize dispatcher calls in Octane hooks.
|
|
7
|
+
const nativeDirective = "'use no memo';\n";
|
|
8
|
+
const hooks = new Set([
|
|
9
|
+
'use',
|
|
10
|
+
'useContext',
|
|
11
|
+
'useRef',
|
|
12
|
+
'useMemo',
|
|
13
|
+
'useCallback',
|
|
14
|
+
'useLayoutEffect',
|
|
15
|
+
'useSyncExternalStore',
|
|
16
|
+
]);
|
|
17
|
+
const sourceFile = /(?<!\.d)\.[cm]?tsx?$/;
|
|
18
|
+
const renderer = (spec) => /^(?:react|react-dom)(?:\/|$)/.test(spec);
|
|
19
|
+
const nodeModules = /[/\\]node_modules[/\\]/;
|
|
20
|
+
const request = (n) => (ts.isStringLiteral(n) ? n.text : null);
|
|
21
|
+
function walk(node, visit) {
|
|
22
|
+
visit(node);
|
|
23
|
+
ts.forEachChild(node, (n) => walk(n, visit));
|
|
24
|
+
}
|
|
25
|
+
function referenced(checker, n) {
|
|
26
|
+
const s = checker.getSymbolAtLocation(n);
|
|
27
|
+
return s && (s.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(s) : s);
|
|
28
|
+
}
|
|
29
|
+
function relative(from, to) {
|
|
30
|
+
const spec = path.relative(path.dirname(from), to).split(path.sep).join('/').replace(/\.ts$/, '');
|
|
31
|
+
return spec.startsWith('../') || spec.startsWith('./') ? spec : './' + spec;
|
|
32
|
+
}
|
|
33
|
+
function runtime(s) {
|
|
34
|
+
if ((ts.isImportDeclaration(s) ? s.importClause : s)?.isTypeOnly)
|
|
35
|
+
return false;
|
|
36
|
+
const bindings = ts.isExportDeclaration(s)
|
|
37
|
+
? s.exportClause
|
|
38
|
+
: s.importClause?.name
|
|
39
|
+
? undefined
|
|
40
|
+
: s.importClause?.namedBindings;
|
|
41
|
+
const items = bindings && (ts.isNamedImports(bindings) || ts.isNamedExports(bindings))
|
|
42
|
+
? bindings.elements
|
|
43
|
+
: undefined;
|
|
44
|
+
// An empty import/export still evaluates its module when preserved.
|
|
45
|
+
return !items?.length || items.some((item) => !item.isTypeOnly);
|
|
46
|
+
}
|
|
47
|
+
export { runtime as hasRuntimeDependency };
|
|
48
|
+
function resolveOptions(importer) {
|
|
49
|
+
const file = ts.findConfigFile(path.dirname(importer), ts.sys.fileExists);
|
|
50
|
+
const settings = file && ts.readConfigFile(file, ts.sys.readFile);
|
|
51
|
+
const options = settings &&
|
|
52
|
+
!settings.error &&
|
|
53
|
+
ts.parseJsonConfigFileContent(settings.config, { ...ts.sys, readDirectory: () => [] }, path.dirname(file)).options;
|
|
54
|
+
return (options || { module: ts.ModuleKind.ESNext, moduleResolution: ts.ModuleResolutionKind.Bundler });
|
|
55
|
+
}
|
|
56
|
+
function installed(spec, from) {
|
|
57
|
+
try {
|
|
58
|
+
return fs.realpathSync(createRequire(from).resolve(spec));
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
function manifest(file) {
|
|
65
|
+
try {
|
|
66
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/** Audit every executable target of a bare dependency, including browser and server conditions. */
|
|
73
|
+
function runtimeTargets(spec, resolved, from) {
|
|
74
|
+
if (spec.startsWith('.')) {
|
|
75
|
+
const executable = installed(spec, from);
|
|
76
|
+
return executable && executable !== resolved ? [resolved, executable] : [resolved];
|
|
77
|
+
}
|
|
78
|
+
const parts = spec.split('/'), length = spec.startsWith('@') ? 2 : 1;
|
|
79
|
+
const name = parts.slice(0, length).join('/'), subpath = ['.', ...parts.slice(length)].join('/');
|
|
80
|
+
let dir = path.dirname(resolved);
|
|
81
|
+
while (path.dirname(dir) !== dir) {
|
|
82
|
+
const pkg = manifest(path.join(dir, 'package.json'));
|
|
83
|
+
if (typeof pkg?.name === 'string' && renderer(pkg.name))
|
|
84
|
+
return [];
|
|
85
|
+
if (pkg?.name === name) {
|
|
86
|
+
if (pkg.browser)
|
|
87
|
+
return [];
|
|
88
|
+
if (!pkg.exports) {
|
|
89
|
+
if (subpath !== '.')
|
|
90
|
+
return [resolved];
|
|
91
|
+
return [
|
|
92
|
+
...new Set([
|
|
93
|
+
resolved,
|
|
94
|
+
...[pkg.main, pkg.module]
|
|
95
|
+
.filter((value) => typeof value === 'string')
|
|
96
|
+
.map((value) => path.resolve(dir, value)),
|
|
97
|
+
]),
|
|
98
|
+
];
|
|
99
|
+
}
|
|
100
|
+
const map = typeof pkg.exports === 'object' && Object.keys(pkg.exports).some((k) => k.startsWith('.'))
|
|
101
|
+
? pkg.exports
|
|
102
|
+
: { '.': pkg.exports };
|
|
103
|
+
let branch = map[subpath], wildcard = '';
|
|
104
|
+
if (!branch) {
|
|
105
|
+
const key = Object.keys(map)
|
|
106
|
+
.filter((k) => k.includes('*'))
|
|
107
|
+
.sort((a, b) => b.indexOf('*') - a.indexOf('*') || b.length - a.length)
|
|
108
|
+
.find((k) => {
|
|
109
|
+
const [start, end] = k.split('*');
|
|
110
|
+
return subpath.startsWith(start) && subpath.endsWith(end);
|
|
111
|
+
});
|
|
112
|
+
if (!key)
|
|
113
|
+
return [];
|
|
114
|
+
const [start, end] = key.split('*');
|
|
115
|
+
wildcard = subpath.slice(start.length, subpath.length - end.length);
|
|
116
|
+
branch = map[key];
|
|
117
|
+
}
|
|
118
|
+
const leaves = (v) => {
|
|
119
|
+
if (typeof v === 'string')
|
|
120
|
+
return v.startsWith('./') ? [path.resolve(dir, v.replaceAll('*', wildcard))] : [];
|
|
121
|
+
if (Array.isArray(v))
|
|
122
|
+
return v.flatMap(leaves);
|
|
123
|
+
return v && typeof v === 'object'
|
|
124
|
+
? Object.entries(v).flatMap(([k, x]) => k === 'types' || k.startsWith('types@') ? [] : leaves(x))
|
|
125
|
+
: [];
|
|
126
|
+
};
|
|
127
|
+
return [...new Set(leaves(branch))];
|
|
128
|
+
}
|
|
129
|
+
dir = path.dirname(dir);
|
|
130
|
+
}
|
|
131
|
+
return [];
|
|
132
|
+
}
|
|
133
|
+
function modulePlan(pkg, project, entry, candidates, link, options, outputDir, bridge) {
|
|
134
|
+
const program = ts.createProgram([entry, ...candidates], { ...options, noEmit: true });
|
|
135
|
+
const checker = program.getTypeChecker();
|
|
136
|
+
const root = program.getSourceFile(entry);
|
|
137
|
+
if (!root)
|
|
138
|
+
return null;
|
|
139
|
+
function exports(sf) {
|
|
140
|
+
const sym = checker.getSymbolAtLocation(sf);
|
|
141
|
+
return sym
|
|
142
|
+
? checker
|
|
143
|
+
.getExportsOfModule(sym)
|
|
144
|
+
.filter((s) => (s.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(s) : s).flags &
|
|
145
|
+
ts.SymbolFlags.Value)
|
|
146
|
+
: [];
|
|
147
|
+
}
|
|
148
|
+
const exportsOfRoot = exports(root);
|
|
149
|
+
const identity = (s) => s.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(s) : s;
|
|
150
|
+
const publicValues = new Set(exportsOfRoot.map(identity));
|
|
151
|
+
const owned = (file) => file.startsWith(pkg + path.sep) && !nodeModules.test(path.relative(pkg, file));
|
|
152
|
+
const cache = ts.createModuleResolutionCache(project, (s) => s, options);
|
|
153
|
+
const runtimeHost = {
|
|
154
|
+
...ts.sys,
|
|
155
|
+
fileExists: (file) => !/\.d\.[cm]?ts$/.test(file) && ts.sys.fileExists(file),
|
|
156
|
+
};
|
|
157
|
+
const jsOptions = {
|
|
158
|
+
moduleResolution: ts.ModuleResolutionKind.Bundler,
|
|
159
|
+
module: ts.ModuleKind.ESNext,
|
|
160
|
+
allowJs: true,
|
|
161
|
+
customConditions: options.customConditions,
|
|
162
|
+
};
|
|
163
|
+
const jsCache = ts.createModuleResolutionCache(project, (s) => s, jsOptions);
|
|
164
|
+
const metadata = manifest(path.join(pkg, 'package.json'));
|
|
165
|
+
const packageId = metadata.name + '\0' + (metadata.version ?? '');
|
|
166
|
+
const shim = path.join(path.dirname(bridge), 'octane-store-hooks.ts');
|
|
167
|
+
function target(spec, from) {
|
|
168
|
+
return ts.resolveModuleName(spec, from, options, ts.sys, cache).resolvedModule
|
|
169
|
+
?.resolvedFileName;
|
|
170
|
+
}
|
|
171
|
+
function output(sf) {
|
|
172
|
+
const id = createHash('sha256')
|
|
173
|
+
.update(packageId + '\0' + path.relative(pkg, sf.fileName).split(path.sep).join('/'))
|
|
174
|
+
.digest('hex')
|
|
175
|
+
.slice(0, 16);
|
|
176
|
+
const stem = path
|
|
177
|
+
.basename(sf.fileName)
|
|
178
|
+
.replace(/\.[^.]+$/, '')
|
|
179
|
+
.replace(/[^a-zA-Z0-9_-]/g, '-');
|
|
180
|
+
return path.join(outputDir, 'octane-' + stem + '-' + id + '-impl.ts');
|
|
181
|
+
}
|
|
182
|
+
// Follow executable imports, including published JavaScript. A declaration
|
|
183
|
+
// file cannot establish that a shared store can run outside React.
|
|
184
|
+
const neutral = new Set();
|
|
185
|
+
function validateShared(file, visiting, contextFactory) {
|
|
186
|
+
if (neutral.has(file) || visiting.has(file))
|
|
187
|
+
return true;
|
|
188
|
+
if (!/\.[cm]?[jt]sx?$/.test(file) || /\.d\.[cm]?ts$/.test(file))
|
|
189
|
+
return false;
|
|
190
|
+
visiting.add(file);
|
|
191
|
+
const sf = program.getSourceFile(file) ??
|
|
192
|
+
ts.createSourceFile(file, fs.readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true);
|
|
193
|
+
let valid = true;
|
|
194
|
+
function edge(spec, commonjs = false) {
|
|
195
|
+
if (!valid)
|
|
196
|
+
return;
|
|
197
|
+
if (renderer(spec)) {
|
|
198
|
+
valid = false;
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
const resolved = ts.resolveModuleName(spec, file, jsOptions, runtimeHost, jsCache, undefined, commonjs ? ts.ModuleKind.CommonJS : ts.ModuleKind.ESNext).resolvedModule?.resolvedFileName;
|
|
202
|
+
const targets = resolved ? runtimeTargets(spec, resolved, file) : [];
|
|
203
|
+
if (!targets.length ||
|
|
204
|
+
!targets.every((f) => validateShared(fs.realpathSync(f), visiting, false)))
|
|
205
|
+
valid = false;
|
|
206
|
+
}
|
|
207
|
+
walk(sf, (n) => {
|
|
208
|
+
if (!valid)
|
|
209
|
+
return;
|
|
210
|
+
if ((ts.isImportDeclaration(n) || ts.isExportDeclaration(n)) &&
|
|
211
|
+
n.moduleSpecifier &&
|
|
212
|
+
runtime(n)) {
|
|
213
|
+
const spec = request(n.moduleSpecifier);
|
|
214
|
+
if (!spec) {
|
|
215
|
+
valid = false;
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
if (renderer(spec)) {
|
|
219
|
+
const imported = ts.isImportDeclaration(n) && n.importClause;
|
|
220
|
+
const named = imported && !imported.name && imported.namedBindings;
|
|
221
|
+
valid = Boolean(owned(file) &&
|
|
222
|
+
contextFactory &&
|
|
223
|
+
spec === 'react' &&
|
|
224
|
+
named &&
|
|
225
|
+
ts.isNamedImports(named) &&
|
|
226
|
+
named.elements.every((x) => x.isTypeOnly || (x.propertyName ?? x.name).text === 'createContext'));
|
|
227
|
+
}
|
|
228
|
+
else
|
|
229
|
+
edge(spec);
|
|
230
|
+
}
|
|
231
|
+
if (ts.isJsxElement(n) ||
|
|
232
|
+
ts.isJsxSelfClosingElement(n) ||
|
|
233
|
+
ts.isJsxFragment(n) ||
|
|
234
|
+
n.kind === ts.SyntaxKind.ImportKeyword ||
|
|
235
|
+
(ts.isIdentifier(n) && n.text === 'eval'))
|
|
236
|
+
valid = false;
|
|
237
|
+
if (ts.isIdentifier(n) && n.text === 'require') {
|
|
238
|
+
const call = n.parent;
|
|
239
|
+
if (!ts.isCallExpression(call) ||
|
|
240
|
+
call.expression !== n ||
|
|
241
|
+
call.arguments.length !== 1 ||
|
|
242
|
+
!ts.isStringLiteral(call.arguments[0]))
|
|
243
|
+
valid = false;
|
|
244
|
+
else
|
|
245
|
+
edge(call.arguments[0].text, true);
|
|
246
|
+
}
|
|
247
|
+
});
|
|
248
|
+
return valid;
|
|
249
|
+
}
|
|
250
|
+
for (const file of candidates) {
|
|
251
|
+
const core = program.getSourceFile(file);
|
|
252
|
+
if (!core || !exports(core).some((s) => publicValues.has(identity(s))))
|
|
253
|
+
continue;
|
|
254
|
+
const graph = new Set();
|
|
255
|
+
if (validateShared(file, graph, false))
|
|
256
|
+
for (const dep of graph)
|
|
257
|
+
neutral.add(dep);
|
|
258
|
+
}
|
|
259
|
+
if (!neutral.size)
|
|
260
|
+
return null;
|
|
261
|
+
const contextReaders = new Set();
|
|
262
|
+
function discover(sf, files, seen, shared) {
|
|
263
|
+
if (seen.has(sf.fileName))
|
|
264
|
+
return true;
|
|
265
|
+
if (!owned(sf.fileName) || !sourceFile.test(sf.fileName) || sf.isDeclarationFile)
|
|
266
|
+
return false;
|
|
267
|
+
seen.add(sf.fileName);
|
|
268
|
+
const out = output(sf), edits = [];
|
|
269
|
+
const replace = (n, text) => edits.push({ start: n.getStart(sf), end: n.end, text });
|
|
270
|
+
const contextual = new Map();
|
|
271
|
+
const importedHooks = new Map();
|
|
272
|
+
const helpers = new Set();
|
|
273
|
+
const cleanups = new Set();
|
|
274
|
+
const subscriptions = new Set();
|
|
275
|
+
const native = new Set();
|
|
276
|
+
const hookOwner = (node) => {
|
|
277
|
+
const owner = ts.findAncestor(node, ts.isFunctionLike);
|
|
278
|
+
return owner &&
|
|
279
|
+
ts.isFunctionDeclaration(owner) &&
|
|
280
|
+
owner.parent === sf &&
|
|
281
|
+
owner.name &&
|
|
282
|
+
/^use[A-Z0-9]/.test(owner.name.text)
|
|
283
|
+
? owner
|
|
284
|
+
: null;
|
|
285
|
+
};
|
|
286
|
+
for (const s of sf.statements) {
|
|
287
|
+
if (ts.isInterfaceDeclaration(s) || ts.isTypeAliasDeclaration(s))
|
|
288
|
+
continue;
|
|
289
|
+
if (ts.isFunctionDeclaration(s)) {
|
|
290
|
+
if (!s.name ||
|
|
291
|
+
s.asteriskToken ||
|
|
292
|
+
s.modifiers?.some((m) => m.kind === ts.SyntaxKind.AsyncKeyword || m.kind === ts.SyntaxKind.DefaultKeyword) ||
|
|
293
|
+
(s.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword) &&
|
|
294
|
+
!/^use[A-Z0-9]/.test(s.name.text)))
|
|
295
|
+
return false;
|
|
296
|
+
const sym = checker.getSymbolAtLocation(s.name);
|
|
297
|
+
if (!sym?.declarations?.some((d) => ts.isFunctionDeclaration(d) && d.body))
|
|
298
|
+
return false;
|
|
299
|
+
helpers.add(sym);
|
|
300
|
+
continue;
|
|
301
|
+
}
|
|
302
|
+
if (ts.isVariableStatement(s)) {
|
|
303
|
+
if (s.modifiers?.length ||
|
|
304
|
+
!(s.declarationList.flags & ts.NodeFlags.Const) ||
|
|
305
|
+
!s.declarationList.declarations.every((d) => d.initializer &&
|
|
306
|
+
ts.isIdentifier(d.name) &&
|
|
307
|
+
(ts.isArrowFunction(d.initializer) ||
|
|
308
|
+
ts.isStringLiteralLike(d.initializer) ||
|
|
309
|
+
ts.isNumericLiteral(d.initializer) ||
|
|
310
|
+
ts.isBigIntLiteral(d.initializer) ||
|
|
311
|
+
[
|
|
312
|
+
ts.SyntaxKind.FalseKeyword,
|
|
313
|
+
ts.SyntaxKind.TrueKeyword,
|
|
314
|
+
ts.SyntaxKind.NullKeyword,
|
|
315
|
+
].includes(d.initializer.kind))))
|
|
316
|
+
return false;
|
|
317
|
+
for (const d of s.declarationList.declarations) {
|
|
318
|
+
if (!d.initializer || !ts.isArrowFunction(d.initializer))
|
|
319
|
+
continue;
|
|
320
|
+
const sym = checker.getSymbolAtLocation(d.name);
|
|
321
|
+
if (!sym || d.initializer.parameters.length)
|
|
322
|
+
return false;
|
|
323
|
+
const body = d.initializer.body;
|
|
324
|
+
if (ts.isBlock(body) && !body.statements.length)
|
|
325
|
+
cleanups.add(sym);
|
|
326
|
+
else if (ts.isIdentifier(body) && cleanups.has(checker.getSymbolAtLocation(body)))
|
|
327
|
+
subscriptions.add(sym);
|
|
328
|
+
else
|
|
329
|
+
return false;
|
|
330
|
+
helpers.add(sym);
|
|
331
|
+
}
|
|
332
|
+
continue;
|
|
333
|
+
}
|
|
334
|
+
if (!ts.isImportDeclaration(s) ||
|
|
335
|
+
!s.importClause ||
|
|
336
|
+
s.attributes ||
|
|
337
|
+
!ts.isStringLiteral(s.moduleSpecifier))
|
|
338
|
+
return false;
|
|
339
|
+
const spec = s.moduleSpecifier.text, clause = s.importClause;
|
|
340
|
+
if (spec === 'react' && runtime(s)) {
|
|
341
|
+
const named = clause.namedBindings;
|
|
342
|
+
if (clause.name || !named || !ts.isNamedImports(named))
|
|
343
|
+
return false;
|
|
344
|
+
const react = checker.getSymbolAtLocation(s.moduleSpecifier);
|
|
345
|
+
const ctx = react && checker.getExportsOfModule(react).find((x) => x.name === 'Context');
|
|
346
|
+
const imports = [], contexts = [];
|
|
347
|
+
for (const item of named.elements) {
|
|
348
|
+
const n = (item.propertyName ?? item.name).text, sym = checker.getSymbolAtLocation(item.name);
|
|
349
|
+
if (item.isTypeOnly || !hooks.has(n) || !sym)
|
|
350
|
+
return false;
|
|
351
|
+
native.add(sym);
|
|
352
|
+
importedHooks.set(sym, n);
|
|
353
|
+
if (n === 'use' || n === 'useContext') {
|
|
354
|
+
if (!ctx)
|
|
355
|
+
return false;
|
|
356
|
+
contextual.set(sym, identity(ctx));
|
|
357
|
+
contexts.push('useStoreContext as ' + item.name.text);
|
|
358
|
+
}
|
|
359
|
+
else
|
|
360
|
+
imports.push(item.getText(sf));
|
|
361
|
+
}
|
|
362
|
+
if (!contexts.length)
|
|
363
|
+
replace(s.moduleSpecifier, JSON.stringify(relative(out, shim)));
|
|
364
|
+
else {
|
|
365
|
+
if (/\/\*|\/\//.test(s.getText(sf)))
|
|
366
|
+
return false;
|
|
367
|
+
const lines = [
|
|
368
|
+
'import { ' +
|
|
369
|
+
contexts.join(', ') +
|
|
370
|
+
' } from ' +
|
|
371
|
+
JSON.stringify(relative(out, bridge)) +
|
|
372
|
+
';',
|
|
373
|
+
];
|
|
374
|
+
if (imports.length)
|
|
375
|
+
lines.push('import { ' +
|
|
376
|
+
imports.join(', ') +
|
|
377
|
+
' } from ' +
|
|
378
|
+
JSON.stringify(relative(out, shim)) +
|
|
379
|
+
';');
|
|
380
|
+
replace(s, lines.join('\n'));
|
|
381
|
+
}
|
|
382
|
+
continue;
|
|
383
|
+
}
|
|
384
|
+
if (runtime(s) && !spec.startsWith('.'))
|
|
385
|
+
return false;
|
|
386
|
+
const resolved = target(spec, sf.fileName);
|
|
387
|
+
if (!resolved)
|
|
388
|
+
return false;
|
|
389
|
+
const file = fs.realpathSync(resolved);
|
|
390
|
+
// JS and TS siblings can both be renderer-neutral while implementing different stores.
|
|
391
|
+
const originalRuntime = runtime(s) && installed(spec, sf.fileName);
|
|
392
|
+
if (originalRuntime && originalRuntime !== file)
|
|
393
|
+
return false;
|
|
394
|
+
if (!owned(file)) {
|
|
395
|
+
if (runtime(s))
|
|
396
|
+
return false;
|
|
397
|
+
// Type-only imports must resolve to the same declaration from the new module.
|
|
398
|
+
const moved = target(spec, out);
|
|
399
|
+
if (moved && fs.realpathSync(moved) === file)
|
|
400
|
+
continue;
|
|
401
|
+
return false;
|
|
402
|
+
}
|
|
403
|
+
const child = program.getSourceFile(file);
|
|
404
|
+
if (!child)
|
|
405
|
+
return false;
|
|
406
|
+
const hookModule = child.statements.some((x) => ts.isImportDeclaration(x) &&
|
|
407
|
+
ts.isStringLiteral(x.moduleSpecifier) &&
|
|
408
|
+
x.moduleSpecifier.text === 'react' &&
|
|
409
|
+
runtime(x) &&
|
|
410
|
+
x.importClause?.namedBindings &&
|
|
411
|
+
ts.isNamedImports(x.importClause.namedBindings) &&
|
|
412
|
+
x.importClause.namedBindings.elements.some((n) => !n.isTypeOnly && hooks.has((n.propertyName ?? n.name).text)));
|
|
413
|
+
if (runtime(s) && hookModule) {
|
|
414
|
+
const named = clause.namedBindings;
|
|
415
|
+
if (clause.name ||
|
|
416
|
+
!named ||
|
|
417
|
+
!ts.isNamedImports(named) ||
|
|
418
|
+
!named.elements.every((x) => x.isTypeOnly || /^use[A-Z0-9]/.test((x.propertyName ?? x.name).text)) ||
|
|
419
|
+
!discover(child, files, seen, shared))
|
|
420
|
+
return false;
|
|
421
|
+
for (const x of named.elements) {
|
|
422
|
+
const sym = checker.getSymbolAtLocation(x.name);
|
|
423
|
+
if (sym && !x.isTypeOnly)
|
|
424
|
+
native.add(sym);
|
|
425
|
+
}
|
|
426
|
+
replace(s.moduleSpecifier, JSON.stringify(relative(out, output(child))));
|
|
427
|
+
}
|
|
428
|
+
else {
|
|
429
|
+
if (runtime(s) && !validateShared(file, new Set(), true))
|
|
430
|
+
return false;
|
|
431
|
+
if (runtime(s) && neutral.has(file))
|
|
432
|
+
shared.add(file);
|
|
433
|
+
const moved = relative(out, path.join(link, path.relative(pkg, file))).replace(/\.[cm]?tsx?$/, '');
|
|
434
|
+
const resolved = target(moved, out);
|
|
435
|
+
const movedRuntime = runtime(s) && installed(moved, out);
|
|
436
|
+
if (!resolved ||
|
|
437
|
+
fs.realpathSync(resolved) !== file ||
|
|
438
|
+
(movedRuntime && movedRuntime !== file))
|
|
439
|
+
return false;
|
|
440
|
+
replace(s.moduleSpecifier, JSON.stringify(moved));
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
// A fallback callback may be selected for this render. Validate all uses
|
|
444
|
+
// of its const alias too, including references in an earlier closure.
|
|
445
|
+
const fallbackRefs = new Set();
|
|
446
|
+
walk(sf, (n) => {
|
|
447
|
+
if (!ts.isVariableDeclaration(n) ||
|
|
448
|
+
!ts.isIdentifier(n.name) ||
|
|
449
|
+
!n.initializer ||
|
|
450
|
+
!ts.isVariableDeclarationList(n.parent) ||
|
|
451
|
+
!(n.parent.flags & ts.NodeFlags.Const) ||
|
|
452
|
+
!ts.isBinaryExpression(n.initializer) ||
|
|
453
|
+
n.initializer.operatorToken.kind !== ts.SyntaxKind.QuestionQuestionToken)
|
|
454
|
+
return;
|
|
455
|
+
const right = n.initializer.right;
|
|
456
|
+
const sym = checker.getSymbolAtLocation(n.name);
|
|
457
|
+
if (ts.isIdentifier(right) && cleanups.has(checker.getSymbolAtLocation(right)) && sym) {
|
|
458
|
+
helpers.add(sym);
|
|
459
|
+
fallbackRefs.add(right);
|
|
460
|
+
}
|
|
461
|
+
});
|
|
462
|
+
let valid = true;
|
|
463
|
+
walk(sf, (node) => {
|
|
464
|
+
if (!valid)
|
|
465
|
+
return;
|
|
466
|
+
if (ts.isJsxElement(node) ||
|
|
467
|
+
ts.isJsxSelfClosingElement(node) ||
|
|
468
|
+
ts.isJsxFragment(node) ||
|
|
469
|
+
node.kind === ts.SyntaxKind.ImportKeyword ||
|
|
470
|
+
(ts.isIdentifier(node) &&
|
|
471
|
+
[
|
|
472
|
+
'require',
|
|
473
|
+
'eval',
|
|
474
|
+
'Function',
|
|
475
|
+
'globalThis',
|
|
476
|
+
'window',
|
|
477
|
+
'document',
|
|
478
|
+
'exports',
|
|
479
|
+
'module',
|
|
480
|
+
'__dirname',
|
|
481
|
+
'__filename',
|
|
482
|
+
].includes(node.text)) ||
|
|
483
|
+
ts.isMetaProperty(node)) {
|
|
484
|
+
valid = false;
|
|
485
|
+
return;
|
|
486
|
+
}
|
|
487
|
+
if (!ts.isIdentifier(node) || ts.isImportSpecifier(node.parent))
|
|
488
|
+
return;
|
|
489
|
+
const sym = ts.isShorthandPropertyAssignment(node.parent)
|
|
490
|
+
? checker.getShorthandAssignmentValueSymbol(node.parent)
|
|
491
|
+
: checker.getSymbolAtLocation(node);
|
|
492
|
+
if (!sym)
|
|
493
|
+
return;
|
|
494
|
+
const call = node.parent;
|
|
495
|
+
if (helpers.has(sym)) {
|
|
496
|
+
if (fallbackRefs.has(node))
|
|
497
|
+
return;
|
|
498
|
+
if ((ts.isFunctionDeclaration(call) || ts.isVariableDeclaration(call)) &&
|
|
499
|
+
call.name === node)
|
|
500
|
+
return;
|
|
501
|
+
if (ts.isCallExpression(call) && call.expression === node && !subscriptions.has(sym)) {
|
|
502
|
+
if (/^use[A-Z0-9]/.test(node.text) && !hookOwner(node))
|
|
503
|
+
valid = false;
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
const enclosing = ts.isArrayLiteralExpression(call) ? call.parent : call;
|
|
507
|
+
if (ts.isCallExpression(enclosing) && ts.isIdentifier(enclosing.expression)) {
|
|
508
|
+
const hook = importedHooks.get(checker.getSymbolAtLocation(enclosing.expression));
|
|
509
|
+
const arg = enclosing.arguments.indexOf(ts.isArrayLiteralExpression(call) ? call : node);
|
|
510
|
+
if (hook === 'useSyncExternalStore' && (subscriptions.has(sym) ? arg === 0 : arg >= 0))
|
|
511
|
+
return;
|
|
512
|
+
if (hook === 'useLayoutEffect' && !subscriptions.has(sym) && arg >= 0)
|
|
513
|
+
return;
|
|
514
|
+
}
|
|
515
|
+
if (cleanups.has(sym) &&
|
|
516
|
+
ts.isArrowFunction(call) &&
|
|
517
|
+
call.body === node &&
|
|
518
|
+
ts.isVariableDeclaration(call.parent) &&
|
|
519
|
+
subscriptions.has(checker.getSymbolAtLocation(call.parent.name)))
|
|
520
|
+
return;
|
|
521
|
+
valid = false;
|
|
522
|
+
return;
|
|
523
|
+
}
|
|
524
|
+
if (!native.has(sym))
|
|
525
|
+
return;
|
|
526
|
+
if (!ts.isCallExpression(call) || call.expression !== node || !hookOwner(node)) {
|
|
527
|
+
valid = false;
|
|
528
|
+
return;
|
|
529
|
+
}
|
|
530
|
+
const ctx = contextual.get(sym);
|
|
531
|
+
if (ctx)
|
|
532
|
+
contextReaders.add(checker.getSymbolAtLocation(hookOwner(node).name));
|
|
533
|
+
if (ctx &&
|
|
534
|
+
(call.arguments.length !== 1 ||
|
|
535
|
+
checker.getTypeAtLocation(call.arguments[0]).getSymbol() !== ctx))
|
|
536
|
+
valid = false;
|
|
537
|
+
});
|
|
538
|
+
if (!valid || !native.size)
|
|
539
|
+
return false;
|
|
540
|
+
let code = sf.text;
|
|
541
|
+
for (const e of edits.sort((a, b) => b.start - a.start))
|
|
542
|
+
code = code.slice(0, e.start) + e.text + code.slice(e.end);
|
|
543
|
+
const start = sf.statements[0].getStart(sf);
|
|
544
|
+
files.set(out, code.slice(0, start) + nativeDirective + code.slice(start));
|
|
545
|
+
return true;
|
|
546
|
+
}
|
|
547
|
+
function readsContext(fn, seen, files) {
|
|
548
|
+
const symbol = fn.name && checker.getSymbolAtLocation(fn.name);
|
|
549
|
+
if (!symbol || !fn.body || !files.has(output(fn.getSourceFile())) || seen.has(symbol))
|
|
550
|
+
return false;
|
|
551
|
+
if (contextReaders.has(symbol))
|
|
552
|
+
return true;
|
|
553
|
+
seen.add(symbol);
|
|
554
|
+
// A thin exported forwarding hook may share another hook's contextual read.
|
|
555
|
+
const [only] = fn.body.statements;
|
|
556
|
+
if (fn.body.statements.length !== 1 ||
|
|
557
|
+
!ts.isReturnStatement(only) ||
|
|
558
|
+
!only.expression ||
|
|
559
|
+
!ts.isCallExpression(only.expression) ||
|
|
560
|
+
!ts.isIdentifier(only.expression.expression))
|
|
561
|
+
return false;
|
|
562
|
+
const called = referenced(checker, only.expression.expression);
|
|
563
|
+
const body = called?.declarations?.find((d) => ts.isFunctionDeclaration(d) && !!d.body);
|
|
564
|
+
return !!body && readsContext(body, seen, files);
|
|
565
|
+
}
|
|
566
|
+
const sharedExports = new Map();
|
|
567
|
+
function isSharedExport(module, imported, from) {
|
|
568
|
+
if (!module || module.startsWith('.') || path.isAbsolute(module))
|
|
569
|
+
return false;
|
|
570
|
+
const key = path.dirname(from) + '\0' + module + '\0' + imported;
|
|
571
|
+
if (!sharedExports.has(key)) {
|
|
572
|
+
const file = installed(module, from), resolved = target(module, from);
|
|
573
|
+
const sf = file &&
|
|
574
|
+
resolved &&
|
|
575
|
+
fs.realpathSync(resolved) === file &&
|
|
576
|
+
(file === entry || (candidates.includes(file) && neutral.has(file)))
|
|
577
|
+
? program.getSourceFile(file)
|
|
578
|
+
: undefined;
|
|
579
|
+
const value = sf && exports(sf).find((s) => s.name === imported);
|
|
580
|
+
const symbol = value && identity(value), d = symbol?.valueDeclaration;
|
|
581
|
+
sharedExports.set(key, !!(d &&
|
|
582
|
+
neutral.has(d.getSourceFile().fileName) &&
|
|
583
|
+
checker.getTypeOfSymbolAtLocation(symbol, d).getCallSignatures().length));
|
|
584
|
+
}
|
|
585
|
+
return sharedExports.get(key) ?? false;
|
|
586
|
+
}
|
|
587
|
+
const result = new Map();
|
|
588
|
+
return (requested) => {
|
|
589
|
+
if (!result.has(requested)) {
|
|
590
|
+
let plan = null;
|
|
591
|
+
const ex = exportsOfRoot.find((s) => s.name === requested), sym = ex && identity(ex);
|
|
592
|
+
const fn = sym?.declarations?.find((s) => ts.isFunctionDeclaration(s) && !!s.body);
|
|
593
|
+
if (fn?.name && /^use[A-Z0-9]/.test(fn.name.text)) {
|
|
594
|
+
const sf = fn.getSourceFile(), files = new Map();
|
|
595
|
+
const shared = new Set();
|
|
596
|
+
if (discover(sf, files, new Set(), shared) &&
|
|
597
|
+
shared.size &&
|
|
598
|
+
readsContext(fn, new Set(), files)) {
|
|
599
|
+
const raw = output(sf), entry = raw.replace(/-impl\.ts$/, '.ts');
|
|
600
|
+
const bound = exports(sf).flatMap((sym) => {
|
|
601
|
+
const impl = identity(sym).declarations?.find((d) => ts.isFunctionDeclaration(d) && !!d.body);
|
|
602
|
+
return impl &&
|
|
603
|
+
impl.getSourceFile() === sf &&
|
|
604
|
+
impl.name &&
|
|
605
|
+
readsContext(impl, new Set(), files)
|
|
606
|
+
? [impl.name.text]
|
|
607
|
+
: [];
|
|
608
|
+
});
|
|
609
|
+
const code = [
|
|
610
|
+
`import { bindStoreHook } from ${JSON.stringify(relative(entry, shim))};`,
|
|
611
|
+
`import * as implementations from ${JSON.stringify(relative(entry, raw))};`,
|
|
612
|
+
...bound.map((name) => `export const ${name} = bindStoreHook(implementations.${name});`),
|
|
613
|
+
'',
|
|
614
|
+
].join('\n');
|
|
615
|
+
files.set(entry, nativeDirective + code);
|
|
616
|
+
plan = { entry, name: fn.name.text, files, isSharedExport };
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
result.set(requested, plan);
|
|
620
|
+
}
|
|
621
|
+
return result.get(requested) ?? null;
|
|
622
|
+
};
|
|
623
|
+
}
|
|
624
|
+
/** Read linked, authored packages only. All output belongs to the consuming project. */
|
|
625
|
+
export function createScopedStorePlanner(outputDir, contextBridge, compilerOptions) {
|
|
626
|
+
// All generated companions live together. Nested consumers can each declare
|
|
627
|
+
// a different symlink to the same workspace dependency.
|
|
628
|
+
const outputManifest = ts.findConfigFile(outputDir, ts.sys.fileExists, 'package.json');
|
|
629
|
+
function outputLink(pkg, packageName, imported, fallback) {
|
|
630
|
+
if (outputManifest) {
|
|
631
|
+
const modules = path.join(path.dirname(outputManifest), 'node_modules');
|
|
632
|
+
for (const name of [packageName, imported]) {
|
|
633
|
+
const link = path.join(modules, name);
|
|
634
|
+
if (fs.existsSync(link) && fs.realpathSync(link) === pkg)
|
|
635
|
+
return link;
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
return fallback;
|
|
639
|
+
}
|
|
640
|
+
const packages = new Map();
|
|
641
|
+
const lookups = new Map();
|
|
642
|
+
function lookup(specifier, importer) {
|
|
643
|
+
const app = ts.findConfigFile(path.dirname(importer), ts.sys.fileExists, 'package.json');
|
|
644
|
+
if (!app)
|
|
645
|
+
return null;
|
|
646
|
+
const project = path.dirname(app), meta = manifest(app);
|
|
647
|
+
const dep = meta?.dependencies?.[specifier] ??
|
|
648
|
+
meta?.devDependencies?.[specifier] ??
|
|
649
|
+
meta?.peerDependencies?.[specifier];
|
|
650
|
+
if (typeof dep !== 'string' || !dep.startsWith('workspace:'))
|
|
651
|
+
return null;
|
|
652
|
+
const link = path.join(project, 'node_modules', specifier);
|
|
653
|
+
if (!fs.lstatSync(link, { throwIfNoEntry: false })?.isSymbolicLink())
|
|
654
|
+
return null;
|
|
655
|
+
const pkg = fs.realpathSync(link), manifestFile = manifest(path.join(pkg, 'package.json'));
|
|
656
|
+
if (!manifestFile ||
|
|
657
|
+
nodeModules.test(pkg) ||
|
|
658
|
+
manifestFile.browser ||
|
|
659
|
+
(manifestFile.name !== specifier && !dep.startsWith('workspace:' + manifestFile.name + '@')))
|
|
660
|
+
return null;
|
|
661
|
+
const publicEntries = manifestFile.exports;
|
|
662
|
+
if (!publicEntries ||
|
|
663
|
+
typeof publicEntries !== 'object' ||
|
|
664
|
+
typeof publicEntries['.'] !== 'string')
|
|
665
|
+
return null;
|
|
666
|
+
const options = compilerOptions ?? resolveOptions(importer);
|
|
667
|
+
const resolveEntry = (key) => {
|
|
668
|
+
const spec = key === '.' ? specifier : specifier + key.slice(1);
|
|
669
|
+
const runtime = installed(spec, importer);
|
|
670
|
+
const typed = ts.resolveModuleName(spec, importer, options, ts.sys).resolvedModule
|
|
671
|
+
?.resolvedFileName;
|
|
672
|
+
return runtime &&
|
|
673
|
+
sourceFile.test(runtime) &&
|
|
674
|
+
runtime.startsWith(pkg + path.sep) &&
|
|
675
|
+
typed &&
|
|
676
|
+
fs.realpathSync(typed) === runtime
|
|
677
|
+
? runtime
|
|
678
|
+
: null;
|
|
679
|
+
};
|
|
680
|
+
const entry = resolveEntry('.');
|
|
681
|
+
if (!entry)
|
|
682
|
+
return null;
|
|
683
|
+
const react = installed('react', importer), octane = installed('octane', importer);
|
|
684
|
+
if (!react ||
|
|
685
|
+
!octane ||
|
|
686
|
+
installed('react', entry) !== react ||
|
|
687
|
+
installed('react', contextBridge) !== react ||
|
|
688
|
+
installed('octane', contextBridge) !== octane)
|
|
689
|
+
return null;
|
|
690
|
+
const config = compilerOptions
|
|
691
|
+
? ''
|
|
692
|
+
: (ts.findConfigFile(path.dirname(importer), ts.sys.fileExists) ?? '');
|
|
693
|
+
const generatedLink = outputLink(pkg, manifestFile.name, specifier, link);
|
|
694
|
+
if (generatedLink !== link) {
|
|
695
|
+
const relocated = path.join(generatedLink, path.relative(pkg, entry));
|
|
696
|
+
// Raw require resolution retains the logical path when Node preserves symlinks.
|
|
697
|
+
if (options.preserveSymlinks ||
|
|
698
|
+
ts.findConfigFile(path.dirname(importer), ts.sys.fileExists) !==
|
|
699
|
+
ts.findConfigFile(outputDir, ts.sys.fileExists) ||
|
|
700
|
+
createRequire(importer).resolve(specifier) !== entry ||
|
|
701
|
+
installed('react', relocated) !== react ||
|
|
702
|
+
installed('octane', relocated) !== octane)
|
|
703
|
+
return null;
|
|
704
|
+
}
|
|
705
|
+
const key = [generatedLink, entry, config].join('\0');
|
|
706
|
+
if (!packages.has(key)) {
|
|
707
|
+
const candidates = [];
|
|
708
|
+
for (const [key, value] of Object.entries(publicEntries)) {
|
|
709
|
+
if (!key.startsWith('./') ||
|
|
710
|
+
key.includes('*') ||
|
|
711
|
+
typeof value !== 'string' ||
|
|
712
|
+
!sourceFile.test(value))
|
|
713
|
+
continue;
|
|
714
|
+
const file = resolveEntry(key);
|
|
715
|
+
if (file && file !== entry)
|
|
716
|
+
candidates.push(file);
|
|
717
|
+
}
|
|
718
|
+
packages.set(key, candidates.length
|
|
719
|
+
? modulePlan(pkg, project, entry, candidates, generatedLink, options, outputDir, contextBridge)
|
|
720
|
+
: null);
|
|
721
|
+
}
|
|
722
|
+
return packages.get(key) ?? null;
|
|
723
|
+
}
|
|
724
|
+
return (specifier, importedName, importer) => {
|
|
725
|
+
if (!/^use[A-Z0-9]/.test(importedName) || !/^(?:@[\w.-]+\/)?[\w-][\w.-]*$/.test(specifier))
|
|
726
|
+
return null;
|
|
727
|
+
const key = path.dirname(importer) + '\0' + specifier;
|
|
728
|
+
try {
|
|
729
|
+
if (!lookups.has(key))
|
|
730
|
+
lookups.set(key, lookup(specifier, importer));
|
|
731
|
+
return lookups.get(key)?.(importedName) ?? null;
|
|
732
|
+
}
|
|
733
|
+
catch (error) {
|
|
734
|
+
if (error instanceof Error &&
|
|
735
|
+
'code' in error &&
|
|
736
|
+
['ENOENT', 'ENOTDIR', 'ELOOP', 'EACCES'].includes(String(error.code)))
|
|
737
|
+
return null;
|
|
738
|
+
throw error;
|
|
739
|
+
}
|
|
740
|
+
};
|
|
741
|
+
}
|