@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,480 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import ts from 'typescript';
|
|
5
|
+
function walk(node, visit) {
|
|
6
|
+
visit(node);
|
|
7
|
+
ts.forEachChild(node, (child) => walk(child, visit));
|
|
8
|
+
}
|
|
9
|
+
function localSymbol(checker, node) {
|
|
10
|
+
if (ts.isShorthandPropertyAssignment(node.parent))
|
|
11
|
+
return checker.getShorthandAssignmentValueSymbol(node.parent);
|
|
12
|
+
if (ts.isExportSpecifier(node.parent))
|
|
13
|
+
return checker.getExportSpecifierLocalTargetSymbol(node.parent);
|
|
14
|
+
return checker.getSymbolAtLocation(node);
|
|
15
|
+
}
|
|
16
|
+
/** The recipe recognizes bindings in their own lexical scope, including local aliases. */
|
|
17
|
+
function imported(checker, node, binding) {
|
|
18
|
+
const decl = checker.getSymbolAtLocation(node)?.declarations?.[0];
|
|
19
|
+
return (ts.isIdentifier(node) &&
|
|
20
|
+
decl &&
|
|
21
|
+
ts.isImportSpecifier(decl) &&
|
|
22
|
+
!decl.isTypeOnly &&
|
|
23
|
+
!decl.parent.parent.isTypeOnly &&
|
|
24
|
+
(decl.propertyName ?? decl.name).text === binding.name &&
|
|
25
|
+
decl.parent.parent.parent.moduleSpecifier.getText().slice(1, -1) === binding.module);
|
|
26
|
+
}
|
|
27
|
+
function unsupported(node, message) {
|
|
28
|
+
const file = node.getSourceFile();
|
|
29
|
+
throw new Error(file.fileName +
|
|
30
|
+
':' +
|
|
31
|
+
(file.getLineAndCharacterOfPosition(node.getStart()).line + 1) +
|
|
32
|
+
': ' +
|
|
33
|
+
message);
|
|
34
|
+
}
|
|
35
|
+
function literal(checker, expression) {
|
|
36
|
+
if (ts.isIdentifier(expression)) {
|
|
37
|
+
const symbol = checker.getSymbolAtLocation(expression);
|
|
38
|
+
return expression.text === 'undefined' && symbol && checker.isUndefinedSymbol(symbol);
|
|
39
|
+
}
|
|
40
|
+
return (ts.isStringLiteral(expression) ||
|
|
41
|
+
ts.isNumericLiteral(expression) ||
|
|
42
|
+
[ts.SyntaxKind.NullKeyword, ts.SyntaxKind.TrueKeyword, ts.SyntaxKind.FalseKeyword].includes(expression.kind));
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Locate direct importers before binding. Loading every transitive library through a large
|
|
46
|
+
* application's tsconfig would be unnecessary for these local binding checks.
|
|
47
|
+
*/
|
|
48
|
+
function consumers(root, producer, options) {
|
|
49
|
+
const cache = ts.createModuleResolutionCache(root, ts.sys.useCaseSensitiveFileNames ? (s) => s : (s) => s.toLowerCase(), options);
|
|
50
|
+
const resolve = (spec, file) => {
|
|
51
|
+
const resolveMode = (mode) => ts.resolveModuleName(spec, file, options, ts.sys, cache, undefined, mode).resolvedModule
|
|
52
|
+
?.resolvedFileName;
|
|
53
|
+
const esm = resolveMode(ts.ModuleKind.ESNext);
|
|
54
|
+
const cjs = resolveMode(ts.ModuleKind.CommonJS);
|
|
55
|
+
if (esm === cjs)
|
|
56
|
+
return esm;
|
|
57
|
+
if (esm === producer || cjs === producer)
|
|
58
|
+
throw new Error('Review the mode-dependent producer import ' + spec + ' in ' + file);
|
|
59
|
+
// Binding identity is only certain when the two modes agree.
|
|
60
|
+
return undefined;
|
|
61
|
+
};
|
|
62
|
+
const references = new Map([
|
|
63
|
+
[producer, { source: fs.readFileSync(producer, 'utf8'), positions: new Set() }],
|
|
64
|
+
]);
|
|
65
|
+
for (const file of ts.sys.readDirectory(root, ['.ts', '.tsx', '.js', '.jsx', '.mts', '.cts', '.mjs', '.cjs', '.tsrx'], ['**/node_modules/**'])) {
|
|
66
|
+
const source = references.get(file)?.source ?? fs.readFileSync(file, 'utf8');
|
|
67
|
+
const positions = ts
|
|
68
|
+
.preProcessFile(source, true, true)
|
|
69
|
+
.importedFiles.filter((ref) => resolve(ref.fileName, file) === producer)
|
|
70
|
+
.map((ref) => ref.pos);
|
|
71
|
+
if (positions.length) {
|
|
72
|
+
if (fs.realpathSync(file) !== file)
|
|
73
|
+
throw new Error('Review the symlinked consumer ' + file);
|
|
74
|
+
if (!/\.[cm]?[jt]sx?$/.test(file) || file.endsWith('.d.ts'))
|
|
75
|
+
throw new Error('Review the reference to the producer in ' + file);
|
|
76
|
+
references.set(file, { source, positions: new Set(positions) });
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return { references, resolve };
|
|
80
|
+
}
|
|
81
|
+
function declaration(file, checker, config) {
|
|
82
|
+
const found = [];
|
|
83
|
+
for (const stmt of file.statements) {
|
|
84
|
+
if (!ts.isVariableStatement(stmt))
|
|
85
|
+
continue;
|
|
86
|
+
for (const decl of stmt.declarationList.declarations) {
|
|
87
|
+
const call = decl.initializer;
|
|
88
|
+
if (!call || !ts.isCallExpression(call))
|
|
89
|
+
continue;
|
|
90
|
+
const native = imported(checker, call.expression, config.factory);
|
|
91
|
+
if (!native &&
|
|
92
|
+
!imported(checker, call.expression, { module: config.sourceModule, name: 'signal' }))
|
|
93
|
+
continue;
|
|
94
|
+
if (!ts.isIdentifier(decl.name) ||
|
|
95
|
+
!(stmt.declarationList.flags & ts.NodeFlags.Const) ||
|
|
96
|
+
!stmt.modifiers?.some((mod) => mod.kind === ts.SyntaxKind.ExportKeyword) ||
|
|
97
|
+
call.questionDotToken ||
|
|
98
|
+
call.typeArguments ||
|
|
99
|
+
call.arguments.length !== 2)
|
|
100
|
+
unsupported(decl, 'Expected an exported const initialized by a two-argument signal call.');
|
|
101
|
+
const key = path.relative(config.sourceRoot, file.fileName).split(path.sep).join('/') +
|
|
102
|
+
':' +
|
|
103
|
+
decl.name.getText();
|
|
104
|
+
const [scope, init] = call.arguments;
|
|
105
|
+
if (native
|
|
106
|
+
? !ts.isStringLiteral(scope) || scope.text !== key
|
|
107
|
+
: !imported(checker, scope, config.scope))
|
|
108
|
+
unsupported(scope, 'Unrecognized declaring scope or adapter key.');
|
|
109
|
+
const factory = ts.isArrowFunction(init);
|
|
110
|
+
if (factory
|
|
111
|
+
? init.parameters.length ||
|
|
112
|
+
init.modifiers?.length ||
|
|
113
|
+
ts.isBlock(init.body) ||
|
|
114
|
+
!literal(checker, init.body)
|
|
115
|
+
: native || !literal(checker, init))
|
|
116
|
+
unsupported(init, 'Expected a primitive initializer or a zero-argument factory returning one.');
|
|
117
|
+
found.push({ decl, call, key, native, factory });
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
if (found.length !== 1)
|
|
121
|
+
throw new Error('Select a module defining exactly one supported exported signal.');
|
|
122
|
+
return found[0];
|
|
123
|
+
}
|
|
124
|
+
function convert(file, checker, config, target, references, resolve) {
|
|
125
|
+
const edits = new Map();
|
|
126
|
+
const signals = new Set();
|
|
127
|
+
const replaced = new Map();
|
|
128
|
+
const additions = new Map();
|
|
129
|
+
const existingImports = file.statements.flatMap((stmt) => {
|
|
130
|
+
const bindings = ts.isImportDeclaration(stmt) && stmt.importClause?.namedBindings;
|
|
131
|
+
return bindings && ts.isNamedImports(bindings) ? [...bindings.elements] : [];
|
|
132
|
+
});
|
|
133
|
+
const producer = target.decl.getSourceFile();
|
|
134
|
+
let imperative = false;
|
|
135
|
+
// A relative specifier or nested installation can resolve differently for each consumer.
|
|
136
|
+
for (const spec of [config.sourceModule, config.scope.module]) {
|
|
137
|
+
const module = resolve(spec, producer.fileName);
|
|
138
|
+
if (!module || resolve(spec, file.fileName) !== module)
|
|
139
|
+
throw new Error('Cannot verify a common module for ' + spec + ' in ' + file.fileName);
|
|
140
|
+
}
|
|
141
|
+
function edit(node, text) {
|
|
142
|
+
edits.set(node.getStart(), { end: node.end, text });
|
|
143
|
+
}
|
|
144
|
+
function replaceImportUse(node, replacement) {
|
|
145
|
+
const decl = checker.getSymbolAtLocation(node)?.declarations?.[0];
|
|
146
|
+
if (!decl || !ts.isImportSpecifier(decl))
|
|
147
|
+
throw new Error('Expected a named import.');
|
|
148
|
+
const uses = replaced.get(decl) ?? new Set();
|
|
149
|
+
uses.add(node);
|
|
150
|
+
replaced.set(decl, uses);
|
|
151
|
+
if (replacement) {
|
|
152
|
+
const module = resolve(replacement.module, file.fileName);
|
|
153
|
+
if (!module || module !== resolve(replacement.module, producer.fileName))
|
|
154
|
+
unsupported(node, 'Cannot resolve a shared destination module: ' + replacement.module);
|
|
155
|
+
const matches = existingImports.filter((item) => imported(checker, item.name, replacement));
|
|
156
|
+
if (matches.length) {
|
|
157
|
+
const local = matches[0].name;
|
|
158
|
+
if (matches.length !== 1 ||
|
|
159
|
+
existingImports.some((item) => item.name !== local && item.name.text === local.text) ||
|
|
160
|
+
checker.resolveName(local.text, node, ts.SymbolFlags.Value, false) !==
|
|
161
|
+
checker.getSymbolAtLocation(local))
|
|
162
|
+
unsupported(node, 'Ambiguous or shadowed destination import: ' + local.text);
|
|
163
|
+
edit(node, local.text);
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
if (additions.has(replacement.name) &&
|
|
167
|
+
additions.get(replacement.name)?.module !== replacement.module)
|
|
168
|
+
unsupported(node, 'Conflicting destination name: ' + replacement.name);
|
|
169
|
+
additions.set(replacement.name, replacement);
|
|
170
|
+
edit(node, replacement.name);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
if (file === producer) {
|
|
174
|
+
signals.add(checker.getSymbolAtLocation(target.decl.name));
|
|
175
|
+
if (!target.native) {
|
|
176
|
+
const [scope, init] = target.call.arguments;
|
|
177
|
+
replaceImportUse(target.call.expression, config.factory);
|
|
178
|
+
replaceImportUse(scope);
|
|
179
|
+
edit(scope, JSON.stringify(target.key));
|
|
180
|
+
if (!target.factory)
|
|
181
|
+
edit(init, '() => ' + init.getText());
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
const name = target.decl.name.getText();
|
|
185
|
+
// Every discovered edge must be an ordinary named import. This also catches CommonJS
|
|
186
|
+
// and dynamic imports without maintaining a second classifier for module-reference syntax.
|
|
187
|
+
for (const statement of file.statements) {
|
|
188
|
+
if (!ts.isImportDeclaration(statement) ||
|
|
189
|
+
!references.delete(statement.moduleSpecifier.getStart()))
|
|
190
|
+
continue;
|
|
191
|
+
const bindings = statement.importClause?.namedBindings;
|
|
192
|
+
if (!bindings || !ts.isNamedImports(bindings) || statement.importClause?.name)
|
|
193
|
+
return unsupported(statement, 'Expected a static named import from the producer.');
|
|
194
|
+
for (const item of bindings.elements) {
|
|
195
|
+
if ((item.propertyName ?? item.name).text === name)
|
|
196
|
+
signals.add(checker.getSymbolAtLocation(item.name));
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
if (references.size)
|
|
200
|
+
throw new Error('Review the non-static or re-exported producer reference in ' + file.fileName);
|
|
201
|
+
walk(file, (node) => {
|
|
202
|
+
if (!ts.isIdentifier(node))
|
|
203
|
+
return;
|
|
204
|
+
const parent = node.parent;
|
|
205
|
+
const symbol = localSymbol(checker, node);
|
|
206
|
+
if (!symbol ||
|
|
207
|
+
!signals.has(symbol) ||
|
|
208
|
+
ts.isImportSpecifier(parent) ||
|
|
209
|
+
node === target.decl.name)
|
|
210
|
+
return;
|
|
211
|
+
if (target.native &&
|
|
212
|
+
ts.isPropertyAccessExpression(parent) &&
|
|
213
|
+
parent.expression === node &&
|
|
214
|
+
['get', 'set'].includes(parent.name.text) &&
|
|
215
|
+
ts.isCallExpression(parent.parent) &&
|
|
216
|
+
parent.parent.expression === parent)
|
|
217
|
+
return;
|
|
218
|
+
if (!ts.isCallExpression(parent) ||
|
|
219
|
+
parent.arguments[0] !== node ||
|
|
220
|
+
parent.questionDotToken ||
|
|
221
|
+
parent.typeArguments)
|
|
222
|
+
return unsupported(node, 'Unsupported use of ' + name + '.');
|
|
223
|
+
const fn = parent.expression;
|
|
224
|
+
if (parent.arguments.length === 1 &&
|
|
225
|
+
imported(checker, fn, { module: config.sourceModule, name: 'useSignal' })) {
|
|
226
|
+
replaceImportUse(fn, config.reader);
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
if (target.native && imported(checker, fn, config.reader) && parent.arguments.length === 1)
|
|
230
|
+
return;
|
|
231
|
+
if (!ts.isPropertyAccessExpression(fn) ||
|
|
232
|
+
fn.questionDotToken ||
|
|
233
|
+
!ts.isIdentifier(fn.expression) ||
|
|
234
|
+
!((fn.name.text === 'get' && parent.arguments.length === 1) ||
|
|
235
|
+
(fn.name.text === 'set' &&
|
|
236
|
+
parent.arguments.length === 2 &&
|
|
237
|
+
!ts.isSpreadElement(parent.arguments[1]))))
|
|
238
|
+
return unsupported(fn, 'Expected a scoped get, set, or reader.');
|
|
239
|
+
const owner = checker.getSymbolAtLocation(fn.expression)?.valueDeclaration;
|
|
240
|
+
const init = owner && ts.isVariableDeclaration(owner) && owner.initializer;
|
|
241
|
+
if (!owner ||
|
|
242
|
+
!ts.isVariableDeclarationList(owner.parent) ||
|
|
243
|
+
!(owner.parent.flags & ts.NodeFlags.Const) ||
|
|
244
|
+
!init ||
|
|
245
|
+
!ts.isCallExpression(init) ||
|
|
246
|
+
init.questionDotToken ||
|
|
247
|
+
init.typeArguments ||
|
|
248
|
+
init.arguments.length !== 1 ||
|
|
249
|
+
!imported(checker, init.expression, { module: config.sourceModule, name: 'useScope' }) ||
|
|
250
|
+
!imported(checker, init.arguments[0], config.scope))
|
|
251
|
+
return unsupported(fn.expression, 'Cannot establish the owner of this scoped access.');
|
|
252
|
+
// A source-library callback can track reads or defer writes to a transaction.
|
|
253
|
+
for (let ancestor = parent.parent; ancestor; ancestor = ancestor.parent) {
|
|
254
|
+
if (!ts.isCallExpression(ancestor))
|
|
255
|
+
continue;
|
|
256
|
+
const callee = ts.isPropertyAccessExpression(ancestor.expression)
|
|
257
|
+
? ancestor.expression.expression
|
|
258
|
+
: ancestor.expression;
|
|
259
|
+
const symbol = checker.getSymbolAtLocation(callee)?.declarations?.[0];
|
|
260
|
+
const module = symbol &&
|
|
261
|
+
(ts.isImportSpecifier(symbol)
|
|
262
|
+
? symbol.parent.parent.parent
|
|
263
|
+
: ts.isNamespaceImport(symbol)
|
|
264
|
+
? symbol.parent.parent
|
|
265
|
+
: undefined);
|
|
266
|
+
if (module &&
|
|
267
|
+
ts.isStringLiteral(module.moduleSpecifier) &&
|
|
268
|
+
module.moduleSpecifier.text === config.sourceModule)
|
|
269
|
+
unsupported(parent, 'Scoped access inside a source-library call requires manual migration.');
|
|
270
|
+
}
|
|
271
|
+
imperative = true;
|
|
272
|
+
edit(fn.expression, node.text);
|
|
273
|
+
edit(node, fn.expression.text);
|
|
274
|
+
});
|
|
275
|
+
if (imperative) {
|
|
276
|
+
const relative = path.relative(config.sourceRoot, file.fileName).split(path.sep).join('/');
|
|
277
|
+
const digest = createHash('sha256').update(file.text).digest('hex');
|
|
278
|
+
if (config.reviewedAccess?.[relative] !== digest)
|
|
279
|
+
throw new Error('Review the imperative accesses in ' +
|
|
280
|
+
relative +
|
|
281
|
+
' and their callers, including tracked effects and transactions. Reviewed file SHA-256: ' +
|
|
282
|
+
digest);
|
|
283
|
+
}
|
|
284
|
+
// Remove only the named imports whose last use was converted; keep aliases and other state users.
|
|
285
|
+
walk(file, (node) => {
|
|
286
|
+
if (!ts.isIdentifier(node) || ts.isImportSpecifier(node.parent))
|
|
287
|
+
return;
|
|
288
|
+
if (additions.has(node.text))
|
|
289
|
+
unsupported(node, 'Destination name already in scope: ' + node.text);
|
|
290
|
+
const symbol = localSymbol(checker, node);
|
|
291
|
+
const decl = symbol?.declarations?.[0];
|
|
292
|
+
if (decl && ts.isImportSpecifier(decl) && replaced.has(decl) && !replaced.get(decl)?.has(node))
|
|
293
|
+
replaced.delete(decl);
|
|
294
|
+
});
|
|
295
|
+
for (const stmt of file.statements) {
|
|
296
|
+
if (!ts.isImportDeclaration(stmt))
|
|
297
|
+
continue;
|
|
298
|
+
const bindings = stmt.importClause?.namedBindings;
|
|
299
|
+
if (!bindings || !ts.isNamedImports(bindings))
|
|
300
|
+
continue;
|
|
301
|
+
if (bindings.elements.some((item) => additions.has(item.name.text)))
|
|
302
|
+
unsupported(bindings, 'Conflicting adapter import.');
|
|
303
|
+
const keep = bindings.elements.filter((item) => !replaced.has(item));
|
|
304
|
+
if (keep.length === bindings.elements.length)
|
|
305
|
+
continue;
|
|
306
|
+
if (/\/\*|\/\//.test(stmt.getText()))
|
|
307
|
+
unsupported(stmt, 'Preserve the annotated import manually.');
|
|
308
|
+
if (keep.length)
|
|
309
|
+
edit(bindings, '{ ' + keep.map((item) => item.getText()).join(', ') + ' }');
|
|
310
|
+
else if (stmt.importClause?.name)
|
|
311
|
+
edit(stmt.importClause, stmt.importClause.name.text);
|
|
312
|
+
else {
|
|
313
|
+
// Consume the rest of the import's line without swallowing a trailing comment.
|
|
314
|
+
const blank = /^[ \t]*(?:\r?\n[ \t]*)*/.exec(file.text.slice(stmt.end))?.[0] ?? '';
|
|
315
|
+
edits.set(stmt.getStart(), {
|
|
316
|
+
end: stmt.end + (blank.includes('\n') ? blank.lastIndexOf('\n') + 1 : 0),
|
|
317
|
+
text: '',
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
let code = file.text;
|
|
322
|
+
for (const [start, { end, text }] of [...edits].sort((a, b) => b[0] - a[0]))
|
|
323
|
+
code = code.slice(0, start) + text + code.slice(end);
|
|
324
|
+
if (additions.size) {
|
|
325
|
+
const imports = [...additions.values()]
|
|
326
|
+
.map((b) => 'import { ' + b.name + ' } from ' + JSON.stringify(b.module) + ';')
|
|
327
|
+
.join('\n');
|
|
328
|
+
// Insert after any shebang and directive prologue, before the first module statement.
|
|
329
|
+
const start = file.statements
|
|
330
|
+
.find((s) => !(ts.isExpressionStatement(s) && ts.isStringLiteral(s.expression)))
|
|
331
|
+
?.getStart() ?? 0;
|
|
332
|
+
code = code.slice(0, start) + imports + '\n' + code.slice(start);
|
|
333
|
+
}
|
|
334
|
+
return code;
|
|
335
|
+
}
|
|
336
|
+
/** Create a CLI recipe for one scoped producer and its direct consumers. */
|
|
337
|
+
export function createScopedSignalRecipe(config) {
|
|
338
|
+
return async (paths, options = {}) => {
|
|
339
|
+
const root = fs.realpathSync(config.sourceRoot);
|
|
340
|
+
const result = {
|
|
341
|
+
root,
|
|
342
|
+
files: [],
|
|
343
|
+
packages: [],
|
|
344
|
+
dependencies: [],
|
|
345
|
+
patched: [],
|
|
346
|
+
missing: [],
|
|
347
|
+
html: [],
|
|
348
|
+
compiler: null,
|
|
349
|
+
};
|
|
350
|
+
const rule = 'scoped-signal';
|
|
351
|
+
try {
|
|
352
|
+
const producer = fs.realpathSync(paths[0]);
|
|
353
|
+
const relative = path.relative(root, producer);
|
|
354
|
+
if (paths.length !== 1 ||
|
|
355
|
+
relative.startsWith('..' + path.sep) ||
|
|
356
|
+
path.isAbsolute(relative) ||
|
|
357
|
+
!relative.endsWith('.ts') ||
|
|
358
|
+
relative.endsWith('.d.ts'))
|
|
359
|
+
throw new Error('Select one .ts signal declaration inside sourceRoot.');
|
|
360
|
+
const parsed = ts.getParsedCommandLineOfConfigFile(path.resolve(config.tsconfig), {}, { ...ts.sys, onUnRecoverableConfigFileDiagnostic: () => { } });
|
|
361
|
+
if (!parsed || parsed.errors.length)
|
|
362
|
+
throw new Error('Cannot load ' +
|
|
363
|
+
config.tsconfig +
|
|
364
|
+
': ' +
|
|
365
|
+
ts.flattenDiagnosticMessageText(parsed?.errors[0]?.messageText ?? 'configuration error', '\n'));
|
|
366
|
+
const { references, resolve } = consumers(root, producer, parsed.options);
|
|
367
|
+
const compilerOptions = {
|
|
368
|
+
...parsed.options,
|
|
369
|
+
allowJs: true,
|
|
370
|
+
noResolve: true,
|
|
371
|
+
noLib: true,
|
|
372
|
+
types: [],
|
|
373
|
+
};
|
|
374
|
+
// Preserve the exact UTF-8 input, including a BOM, for source positions, review hashes, and writes.
|
|
375
|
+
const host = ts.createCompilerHost(compilerOptions);
|
|
376
|
+
const readFile = host.readFile;
|
|
377
|
+
host.readFile = (name) => references.get(name)?.source ?? readFile(name);
|
|
378
|
+
const program = ts.createProgram([...references.keys()], compilerOptions, host);
|
|
379
|
+
const checker = program.getTypeChecker();
|
|
380
|
+
const getFile = (name) => {
|
|
381
|
+
const file = program.getSourceFile(name);
|
|
382
|
+
if (!file || program.getSyntacticDiagnostics(file).length)
|
|
383
|
+
throw new Error('Cannot parse ' + name);
|
|
384
|
+
return file;
|
|
385
|
+
};
|
|
386
|
+
const normalized = { ...config, sourceRoot: root };
|
|
387
|
+
const target = declaration(getFile(producer), checker, normalized);
|
|
388
|
+
for (const [absolute, { positions }] of references) {
|
|
389
|
+
const src = getFile(absolute);
|
|
390
|
+
const code = convert(src, checker, normalized, target, positions, resolve);
|
|
391
|
+
const file = path.relative(root, absolute);
|
|
392
|
+
const changed = code !== src.text;
|
|
393
|
+
result.files.push({
|
|
394
|
+
file,
|
|
395
|
+
output: file,
|
|
396
|
+
changed,
|
|
397
|
+
code,
|
|
398
|
+
rules: changed ? { [rule]: 1 } : {},
|
|
399
|
+
strong: null,
|
|
400
|
+
strongFixes: [],
|
|
401
|
+
notes: [],
|
|
402
|
+
diagnostics: [],
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
if (options.write !== false)
|
|
406
|
+
applyChanges(root, result.files, (name) => getFile(name).text);
|
|
407
|
+
}
|
|
408
|
+
catch (error) {
|
|
409
|
+
const file = paths[0] ?? root;
|
|
410
|
+
result.files = [
|
|
411
|
+
{
|
|
412
|
+
file,
|
|
413
|
+
output: file,
|
|
414
|
+
code: '',
|
|
415
|
+
changed: false,
|
|
416
|
+
rules: {},
|
|
417
|
+
strong: null,
|
|
418
|
+
strongFixes: [],
|
|
419
|
+
diagnostics: [],
|
|
420
|
+
notes: [
|
|
421
|
+
{
|
|
422
|
+
rule,
|
|
423
|
+
severity: 'error',
|
|
424
|
+
line: 1,
|
|
425
|
+
message: error instanceof Error ? error.message : String(error),
|
|
426
|
+
},
|
|
427
|
+
],
|
|
428
|
+
},
|
|
429
|
+
];
|
|
430
|
+
return result;
|
|
431
|
+
}
|
|
432
|
+
return result;
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
/**
|
|
436
|
+
* Stage complete files and their originals before replacing any of them. The directory
|
|
437
|
+
* excludes concurrent recipe writes and retains the originals if rollback is interrupted.
|
|
438
|
+
*/
|
|
439
|
+
function applyChanges(root, files, original) {
|
|
440
|
+
const changed = files.filter((file) => file.changed);
|
|
441
|
+
if (!changed.length)
|
|
442
|
+
return;
|
|
443
|
+
const stage = path.join(root, '.octane-scoped-signal');
|
|
444
|
+
fs.mkdirSync(stage);
|
|
445
|
+
let committed = 0;
|
|
446
|
+
let keepBackups = false;
|
|
447
|
+
try {
|
|
448
|
+
fs.writeFileSync(path.join(stage, 'paths.json'), JSON.stringify(changed.map((f) => f.file)));
|
|
449
|
+
for (const [i, file] of changed.entries()) {
|
|
450
|
+
const name = path.join(root, file.file);
|
|
451
|
+
if (fs.realpathSync(name) !== name || fs.readFileSync(name, 'utf8') !== original(name))
|
|
452
|
+
throw new Error('Source changed during migration: ' + file.file);
|
|
453
|
+
fs.copyFileSync(name, path.join(stage, i + '.before'));
|
|
454
|
+
fs.copyFileSync(name, path.join(stage, i + '.after'));
|
|
455
|
+
fs.writeFileSync(path.join(stage, i + '.after'), file.code);
|
|
456
|
+
}
|
|
457
|
+
for (const [i, file] of changed.entries()) {
|
|
458
|
+
const name = path.join(root, file.file);
|
|
459
|
+
if (fs.realpathSync(name) !== name || fs.readFileSync(name, 'utf8') !== original(name))
|
|
460
|
+
throw new Error('Source changed during migration: ' + file.file);
|
|
461
|
+
fs.renameSync(path.join(stage, i + '.after'), name);
|
|
462
|
+
committed++;
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
catch (error) {
|
|
466
|
+
keepBackups = true;
|
|
467
|
+
while (committed) {
|
|
468
|
+
const i = --committed, file = changed[i], name = path.join(root, file.file);
|
|
469
|
+
if (fs.realpathSync(name) !== name || fs.readFileSync(name, 'utf8') !== file.code)
|
|
470
|
+
throw new Error('Source changed during rollback. Recover originals from ' + stage + '.');
|
|
471
|
+
fs.renameSync(path.join(stage, i + '.before'), name);
|
|
472
|
+
}
|
|
473
|
+
keepBackups = false;
|
|
474
|
+
throw error;
|
|
475
|
+
}
|
|
476
|
+
finally {
|
|
477
|
+
if (!keepBackups)
|
|
478
|
+
fs.rmSync(stage, { recursive: true });
|
|
479
|
+
}
|
|
480
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import ts from 'typescript';
|
|
2
|
+
export interface ScopedStoreHookPlan {
|
|
3
|
+
/** The authored native module and the actual export behind any re-export. */
|
|
4
|
+
entry: string;
|
|
5
|
+
name: string;
|
|
6
|
+
files: ReadonlyMap<string, string>;
|
|
7
|
+
/** Checks a store factory against its original, renderer-independent declaration. */
|
|
8
|
+
isSharedExport(module: string, imported: string, from: string): boolean;
|
|
9
|
+
}
|
|
10
|
+
declare function runtime(s: ts.ImportDeclaration | ts.ExportDeclaration): boolean;
|
|
11
|
+
export { runtime as hasRuntimeDependency };
|
|
12
|
+
/** Read linked, authored packages only. All output belongs to the consuming project. */
|
|
13
|
+
export declare function createScopedStorePlanner(outputDir: string, contextBridge: string, compilerOptions?: ts.CompilerOptions): (specifier: string, importedName: string, importer: string) => ScopedStoreHookPlan | null;
|