@getchomp/cli 0.0.0-stage → 0.2.42
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 +39 -2
- package/dist/commands/analyze.d.ts +49 -0
- package/dist/commands/analyze.js +280 -0
- package/dist/commands/connect.d.ts +12 -0
- package/dist/commands/connect.js +255 -0
- package/dist/commands/export.d.ts +29 -0
- package/dist/commands/export.js +356 -0
- package/dist/commands/health.d.ts +19 -0
- package/dist/commands/health.js +259 -0
- package/dist/commands/init.d.ts +40 -0
- package/dist/commands/init.js +654 -0
- package/dist/commands/mcp.d.ts +2 -0
- package/dist/commands/mcp.js +12 -0
- package/dist/commands/plugin.d.ts +8 -0
- package/dist/commands/plugin.js +198 -0
- package/dist/commands/ui.d.ts +20 -0
- package/dist/commands/ui.js +250 -0
- package/dist/commands/uninstall.d.ts +8 -0
- package/dist/commands/uninstall.js +238 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +37 -0
- package/dist/ports/portHydrator.d.ts +63 -0
- package/dist/ports/portHydrator.js +954 -0
- package/dist/ports/portHydratorWorker.d.ts +22 -0
- package/dist/ports/portHydratorWorker.js +75 -0
- package/dist/server/buildStatusTracker.d.ts +45 -0
- package/dist/server/buildStatusTracker.js +122 -0
- package/dist/server/graphLayoutState.d.ts +205 -0
- package/dist/server/graphLayoutState.js +930 -0
- package/dist/server/loopbackSecurity.d.ts +18 -0
- package/dist/server/loopbackSecurity.js +57 -0
- package/dist/server/routes/authSourceRoutes.d.ts +18 -0
- package/dist/server/routes/authSourceRoutes.js +231 -0
- package/dist/server/routes/layoutRoutes.d.ts +3 -0
- package/dist/server/routes/layoutRoutes.js +857 -0
- package/dist/server/routes/pluginRoutes.d.ts +3 -0
- package/dist/server/routes/pluginRoutes.js +368 -0
- package/dist/server/routes/viewRulesRoutes.d.ts +3 -0
- package/dist/server/routes/viewRulesRoutes.js +173 -0
- package/dist/server/uiHotkeys.d.ts +26 -0
- package/dist/server/uiHotkeys.js +160 -0
- package/dist/utils/branding.d.ts +126 -0
- package/dist/utils/branding.js +976 -0
- package/dist/utils/credentials.d.ts +22 -0
- package/dist/utils/credentials.js +126 -0
- package/dist/utils/git.d.ts +95 -0
- package/dist/utils/git.js +780 -0
- package/dist/utils/masterContext.d.ts +102 -0
- package/dist/utils/masterContext.js +559 -0
- package/dist/visualizer/cloudLayoutClient.d.ts +84 -0
- package/dist/visualizer/cloudLayoutClient.js +1200 -0
- package/dist/visualizer/layoutCache.d.ts +25 -0
- package/dist/visualizer/layoutCache.js +406 -0
- package/dist/visualizer/localEngineBridge.d.ts +50 -0
- package/dist/visualizer/localEngineBridge.js +80 -0
- package/dist/visualizer/pluginPresentationApi.d.ts +111 -0
- package/dist/visualizer/pluginPresentationApi.js +432 -0
- package/dist/visualizer/rulesConfig.d.ts +11 -0
- package/dist/visualizer/rulesConfig.js +266 -0
- package/dist/visualizer/sourceAccess.d.ts +45 -0
- package/dist/visualizer/sourceAccess.js +204 -0
- package/package.json +51 -3
|
@@ -0,0 +1,954 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Speed 2 Incremental Port Valve Hydrator (`[PAT-VIS-14]`, `[PAT-DB-03]`, `[PAT-DB-05]`).
|
|
3
|
+
*
|
|
4
|
+
* Uses TypeScript's `ts.createIncrementalProgram` (persisting `.tsbuildinfo` inside `.chomp/cache/`)
|
|
5
|
+
* to resolve inferred return types, cross-file interface/type fields, and boundary port diagnostics
|
|
6
|
+
* (`TS_CALL_MISMATCH`, `TS_RETURN_MISMATCH`) into `entity_overlays` (`layer: "L1_PORTS"`,
|
|
7
|
+
* `source: "chomp-ports"`, `derivation: "EXTRACTED"`).
|
|
8
|
+
*
|
|
9
|
+
* Unchanged contracts (`stale === false` on both `bodyHash` and referenced `inputs` file hashes)
|
|
10
|
+
* are skipped in `<2ms` without constructing a TypeScript `Program`.
|
|
11
|
+
*/
|
|
12
|
+
import { fork } from 'node:child_process';
|
|
13
|
+
import { createHash } from 'node:crypto';
|
|
14
|
+
import { existsSync, mkdirSync, readFileSync } from 'node:fs';
|
|
15
|
+
import { dirname, relative, resolve } from 'node:path';
|
|
16
|
+
import { fileURLToPath } from 'node:url';
|
|
17
|
+
import ts from 'typescript';
|
|
18
|
+
export const CHOMP_PORTS_LAYER = 'L1_PORTS';
|
|
19
|
+
export const CHOMP_PORTS_SOURCE = 'chomp-ports';
|
|
20
|
+
const MAX_CHECKER_FIELDS = 24;
|
|
21
|
+
const MAX_CHECKER_DEPTH = 2;
|
|
22
|
+
const MAX_TYPE_STR_LEN = 120;
|
|
23
|
+
const CALL_MISMATCH_TS_CODES = new Set([
|
|
24
|
+
2345, // Argument of type 'X' is not assignable to parameter of type 'Y'
|
|
25
|
+
2554, // Expected N arguments, but got M
|
|
26
|
+
2555, // Expected at least N arguments, but got M
|
|
27
|
+
2769, // No overload matches this call
|
|
28
|
+
2353, // Object literal may only specify known properties
|
|
29
|
+
2739, // Type 'X' is missing the following properties from type 'Y'
|
|
30
|
+
2741, // Property 'X' is missing in type 'Y' but required in type 'Z'
|
|
31
|
+
]);
|
|
32
|
+
const RETURN_MISMATCH_TS_CODES = new Set([
|
|
33
|
+
2322, // Type 'X' is not assignable to type 'Y'
|
|
34
|
+
2355, // A function whose declared type is neither 'undefined', 'void', nor 'any' must return a value
|
|
35
|
+
]);
|
|
36
|
+
const BUILTIN_OBJECT_TYPE_NAMES = new Set([
|
|
37
|
+
'String',
|
|
38
|
+
'Number',
|
|
39
|
+
'Boolean',
|
|
40
|
+
'Symbol',
|
|
41
|
+
'BigInt',
|
|
42
|
+
'Function',
|
|
43
|
+
'Array',
|
|
44
|
+
'ReadonlyArray',
|
|
45
|
+
'Promise',
|
|
46
|
+
'Date',
|
|
47
|
+
'RegExp',
|
|
48
|
+
'Error',
|
|
49
|
+
'Map',
|
|
50
|
+
'Set',
|
|
51
|
+
'WeakMap',
|
|
52
|
+
'WeakSet',
|
|
53
|
+
'Uint8Array',
|
|
54
|
+
'Buffer',
|
|
55
|
+
]);
|
|
56
|
+
function normalizeSlash(p) {
|
|
57
|
+
return p.replace(/\\/g, '/');
|
|
58
|
+
}
|
|
59
|
+
function primaryEvidenceOf(node) {
|
|
60
|
+
const ev = Array.isArray(node.evidence) ? node.evidence[0] : node.evidence;
|
|
61
|
+
if (!ev || typeof ev.filePath !== 'string' || !ev.filePath.trim())
|
|
62
|
+
return null;
|
|
63
|
+
return {
|
|
64
|
+
filePath: normalizeSlash(ev.filePath.trim()),
|
|
65
|
+
...(typeof ev.lineNumber === 'number' ? { lineNumber: ev.lineNumber } : {}),
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
function isSupportedSourcePath(filePath) {
|
|
69
|
+
return /\.(?:ts|tsx|mts|cts|js|jsx|mjs|cjs)$/i.test(filePath);
|
|
70
|
+
}
|
|
71
|
+
function findNearestTsconfig(absFilePath, repoRoot, cache) {
|
|
72
|
+
const startDir = dirname(absFilePath);
|
|
73
|
+
if (cache.has(startDir))
|
|
74
|
+
return cache.get(startDir);
|
|
75
|
+
const visited = [];
|
|
76
|
+
let cur = startDir;
|
|
77
|
+
const normalizedRoot = resolve(repoRoot);
|
|
78
|
+
let found = null;
|
|
79
|
+
while (true) {
|
|
80
|
+
if (cache.has(cur)) {
|
|
81
|
+
found = cache.get(cur);
|
|
82
|
+
break;
|
|
83
|
+
}
|
|
84
|
+
visited.push(cur);
|
|
85
|
+
const candidate = resolve(cur, 'tsconfig.json');
|
|
86
|
+
if (existsSync(candidate)) {
|
|
87
|
+
found = candidate;
|
|
88
|
+
break;
|
|
89
|
+
}
|
|
90
|
+
if (cur === normalizedRoot)
|
|
91
|
+
break;
|
|
92
|
+
const parent = dirname(cur);
|
|
93
|
+
if (parent === cur || !parent.startsWith(normalizedRoot))
|
|
94
|
+
break;
|
|
95
|
+
cur = parent;
|
|
96
|
+
}
|
|
97
|
+
for (const dir of visited) {
|
|
98
|
+
cache.set(dir, found);
|
|
99
|
+
}
|
|
100
|
+
return found;
|
|
101
|
+
}
|
|
102
|
+
function hashFileShort(absPath, cache) {
|
|
103
|
+
if (cache.has(absPath))
|
|
104
|
+
return cache.get(absPath);
|
|
105
|
+
try {
|
|
106
|
+
const content = readFileSync(absPath);
|
|
107
|
+
const digest = createHash('sha256').update(content).digest('hex').slice(0, 16);
|
|
108
|
+
cache.set(absPath, digest);
|
|
109
|
+
return digest;
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
cache.set(absPath, null);
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
function formatTypeConcise(checker, type, enclosingNode, isOptional = false) {
|
|
117
|
+
let raw = checker
|
|
118
|
+
.typeToString(type, enclosingNode, ts.TypeFormatFlags.NoTruncation | ts.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope)
|
|
119
|
+
.replace(/\s+/g, ' ')
|
|
120
|
+
.trim();
|
|
121
|
+
if (isOptional && raw !== 'undefined') {
|
|
122
|
+
const stripped = raw
|
|
123
|
+
.replace(/\s*\|\s*undefined\b/g, '')
|
|
124
|
+
.replace(/\bundefined\s*\|\s*/g, '')
|
|
125
|
+
.trim();
|
|
126
|
+
if (stripped)
|
|
127
|
+
raw = stripped;
|
|
128
|
+
}
|
|
129
|
+
if (raw.length <= MAX_TYPE_STR_LEN)
|
|
130
|
+
return raw;
|
|
131
|
+
return `${raw.slice(0, MAX_TYPE_STR_LEN - 1)}…`;
|
|
132
|
+
}
|
|
133
|
+
function stripOptionalUndefined(checker, type) {
|
|
134
|
+
if (!type.isUnion())
|
|
135
|
+
return type;
|
|
136
|
+
const kept = type.types.filter((t) => (t.flags & ts.TypeFlags.Undefined) === 0 && (t.flags & ts.TypeFlags.Void) === 0);
|
|
137
|
+
if (kept.length === 0)
|
|
138
|
+
return type;
|
|
139
|
+
if (kept.length === 1)
|
|
140
|
+
return kept[0];
|
|
141
|
+
if (kept.length === 2 &&
|
|
142
|
+
kept.every((t) => (t.flags & ts.TypeFlags.BooleanLiteral) !== 0)) {
|
|
143
|
+
return checker.getBaseTypeOfLiteralType(kept[0]);
|
|
144
|
+
}
|
|
145
|
+
return type;
|
|
146
|
+
}
|
|
147
|
+
function unwrapArrayOrNullableForFields(checker, type) {
|
|
148
|
+
const stripped = stripOptionalUndefined(checker, type);
|
|
149
|
+
if (stripped.isUnion()) {
|
|
150
|
+
const nonNull = stripped.types.filter((t) => (t.flags & ts.TypeFlags.Null) === 0);
|
|
151
|
+
if (nonNull.length === 1) {
|
|
152
|
+
return unwrapArrayOrNullableForFields(checker, nonNull[0]);
|
|
153
|
+
}
|
|
154
|
+
return stripped;
|
|
155
|
+
}
|
|
156
|
+
if (checker.isArrayType(stripped) || checker.isTupleType(stripped)) {
|
|
157
|
+
const typeArgs = checker.getTypeArguments(stripped);
|
|
158
|
+
if (typeArgs.length === 1) {
|
|
159
|
+
return stripOptionalUndefined(checker, typeArgs[0]);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return stripped;
|
|
163
|
+
}
|
|
164
|
+
function isPrimitiveOrBuiltinType(type) {
|
|
165
|
+
if ((type.flags &
|
|
166
|
+
(ts.TypeFlags.StringLike |
|
|
167
|
+
ts.TypeFlags.NumberLike |
|
|
168
|
+
ts.TypeFlags.BooleanLike |
|
|
169
|
+
ts.TypeFlags.BigIntLike |
|
|
170
|
+
ts.TypeFlags.ESSymbolLike |
|
|
171
|
+
ts.TypeFlags.Void |
|
|
172
|
+
ts.TypeFlags.Undefined |
|
|
173
|
+
ts.TypeFlags.Null |
|
|
174
|
+
ts.TypeFlags.Never |
|
|
175
|
+
ts.TypeFlags.Any |
|
|
176
|
+
ts.TypeFlags.Unknown)) !==
|
|
177
|
+
0) {
|
|
178
|
+
return true;
|
|
179
|
+
}
|
|
180
|
+
const symName = type.aliasSymbol?.getName() ?? type.getSymbol()?.getName();
|
|
181
|
+
if (symName && BUILTIN_OBJECT_TYPE_NAMES.has(symName)) {
|
|
182
|
+
return true;
|
|
183
|
+
}
|
|
184
|
+
if (type.getCallSignatures().length > 0 && type.getProperties().length === 0) {
|
|
185
|
+
return true;
|
|
186
|
+
}
|
|
187
|
+
return false;
|
|
188
|
+
}
|
|
189
|
+
function resolveTypeDeclarationRef(type, repoRoot, ownRelFilePath, depPathsOut) {
|
|
190
|
+
const sym = type.aliasSymbol ?? type.getSymbol();
|
|
191
|
+
const decl = sym?.getDeclarations()?.[0];
|
|
192
|
+
if (!decl)
|
|
193
|
+
return undefined;
|
|
194
|
+
const sf = decl.getSourceFile();
|
|
195
|
+
if (!sf || (sf.isDeclarationFile && normalizeSlash(sf.fileName).includes('/node_modules/'))) {
|
|
196
|
+
return undefined;
|
|
197
|
+
}
|
|
198
|
+
const absDeclFile = resolve(sf.fileName);
|
|
199
|
+
const absRepoRoot = resolve(repoRoot);
|
|
200
|
+
if (!absDeclFile.startsWith(absRepoRoot) || normalizeSlash(absDeclFile).includes('/node_modules/')) {
|
|
201
|
+
return undefined;
|
|
202
|
+
}
|
|
203
|
+
const relPath = normalizeSlash(relative(absRepoRoot, absDeclFile));
|
|
204
|
+
if (!relPath || relPath.startsWith('..'))
|
|
205
|
+
return undefined;
|
|
206
|
+
if (relPath !== ownRelFilePath) {
|
|
207
|
+
depPathsOut.add(relPath);
|
|
208
|
+
}
|
|
209
|
+
const lineNumber = sf.getLineAndCharacterOfPosition(decl.getStart(sf)).line + 1;
|
|
210
|
+
return { filePath: relPath, lineNumber };
|
|
211
|
+
}
|
|
212
|
+
function extractCheckerFields(checker, rawType, enclosingNode, repoRoot, ownRelFilePath, depPathsOut, depth, seenTypes) {
|
|
213
|
+
const target = unwrapArrayOrNullableForFields(checker, rawType);
|
|
214
|
+
if (isPrimitiveOrBuiltinType(target))
|
|
215
|
+
return undefined;
|
|
216
|
+
if (seenTypes.has(target))
|
|
217
|
+
return undefined;
|
|
218
|
+
if (target.getCallSignatures().length > 0)
|
|
219
|
+
return undefined;
|
|
220
|
+
const props = checker.getPropertiesOfType(target);
|
|
221
|
+
if (props.length === 0 || props.length > 80)
|
|
222
|
+
return undefined;
|
|
223
|
+
// Skip DOM/global ambient prototypes that carry dozens of built-in methods
|
|
224
|
+
const firstDeclSf = props[0]?.valueDeclaration?.getSourceFile() ?? props[0]?.declarations?.[0]?.getSourceFile();
|
|
225
|
+
if (firstDeclSf && normalizeSlash(firstDeclSf.fileName).includes('/typescript/lib/lib.')) {
|
|
226
|
+
return undefined;
|
|
227
|
+
}
|
|
228
|
+
seenTypes.add(target);
|
|
229
|
+
resolveTypeDeclarationRef(target, repoRoot, ownRelFilePath, depPathsOut);
|
|
230
|
+
const fields = [];
|
|
231
|
+
for (const prop of props) {
|
|
232
|
+
if (fields.length >= MAX_CHECKER_FIELDS)
|
|
233
|
+
break;
|
|
234
|
+
const propName = prop.getName();
|
|
235
|
+
if (!propName || propName.startsWith('__@'))
|
|
236
|
+
continue;
|
|
237
|
+
// Exclude private/protected class fields from public port schemas
|
|
238
|
+
const decl = prop.valueDeclaration ?? prop.declarations?.[0];
|
|
239
|
+
if (decl && ts.canHaveModifiers(decl)) {
|
|
240
|
+
const mods = ts.getModifiers(decl);
|
|
241
|
+
if (mods?.some((m) => m.kind === ts.SyntaxKind.PrivateKeyword ||
|
|
242
|
+
m.kind === ts.SyntaxKind.ProtectedKeyword)) {
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
const propType = checker.getTypeOfSymbolAtLocation(prop, enclosingNode);
|
|
247
|
+
const isOptional = (prop.flags & ts.SymbolFlags.Optional) !== 0;
|
|
248
|
+
const cleanPropType = isOptional
|
|
249
|
+
? stripOptionalUndefined(checker, propType)
|
|
250
|
+
: propType;
|
|
251
|
+
const typeStr = formatTypeConcise(checker, cleanPropType, enclosingNode, isOptional);
|
|
252
|
+
let nested;
|
|
253
|
+
if (depth + 1 < MAX_CHECKER_DEPTH) {
|
|
254
|
+
nested = extractCheckerFields(checker, cleanPropType, enclosingNode, repoRoot, ownRelFilePath, depPathsOut, depth + 1, new Set(seenTypes));
|
|
255
|
+
}
|
|
256
|
+
fields.push({
|
|
257
|
+
name: propName,
|
|
258
|
+
type: typeStr,
|
|
259
|
+
...(isOptional ? { optional: true } : {}),
|
|
260
|
+
...(nested ? { fields: nested } : {}),
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
return fields.length > 0 ? fields : undefined;
|
|
264
|
+
}
|
|
265
|
+
function unwrapExprToFunction(expr) {
|
|
266
|
+
if (!expr)
|
|
267
|
+
return null;
|
|
268
|
+
let cur = expr;
|
|
269
|
+
while (ts.isParenthesizedExpression(cur) ||
|
|
270
|
+
ts.isAsExpression(cur) ||
|
|
271
|
+
ts.isSatisfiesExpression(cur) ||
|
|
272
|
+
ts.isNonNullExpression(cur)) {
|
|
273
|
+
cur = cur.expression;
|
|
274
|
+
}
|
|
275
|
+
if (ts.isArrowFunction(cur) || ts.isFunctionExpression(cur))
|
|
276
|
+
return cur;
|
|
277
|
+
if (ts.isCallExpression(cur) && cur.arguments.length > 0) {
|
|
278
|
+
for (let i = cur.arguments.length - 1; i >= 0; i--) {
|
|
279
|
+
const inner = unwrapExprToFunction(cur.arguments[i]);
|
|
280
|
+
if (inner)
|
|
281
|
+
return inner;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
return null;
|
|
285
|
+
}
|
|
286
|
+
function findContractDeclarationInSourceFile(sf, targetLine) {
|
|
287
|
+
if (!targetLine || targetLine < 1)
|
|
288
|
+
return null;
|
|
289
|
+
let best = null;
|
|
290
|
+
const consider = (cand, sig) => {
|
|
291
|
+
const startLine = sf.getLineAndCharacterOfPosition(cand.getStart(sf)).line + 1;
|
|
292
|
+
const dist = Math.abs(startLine - targetLine);
|
|
293
|
+
if (dist > 2)
|
|
294
|
+
return;
|
|
295
|
+
if (!best || dist < best.dist || (dist === best.dist && sig && !best.sig)) {
|
|
296
|
+
best = { node: cand, sig, dist };
|
|
297
|
+
}
|
|
298
|
+
};
|
|
299
|
+
const walk = (n) => {
|
|
300
|
+
if (ts.isFunctionDeclaration(n) ||
|
|
301
|
+
ts.isMethodDeclaration(n) ||
|
|
302
|
+
ts.isGetAccessorDeclaration(n)) {
|
|
303
|
+
consider(n, n);
|
|
304
|
+
}
|
|
305
|
+
else if (ts.isPropertyDeclaration(n) && n.initializer) {
|
|
306
|
+
const fn = unwrapExprToFunction(n.initializer);
|
|
307
|
+
if (fn)
|
|
308
|
+
consider(n, fn);
|
|
309
|
+
}
|
|
310
|
+
else if (ts.isVariableDeclaration(n)) {
|
|
311
|
+
const fn = unwrapExprToFunction(n.initializer);
|
|
312
|
+
consider(n, fn);
|
|
313
|
+
}
|
|
314
|
+
else if (ts.isVariableStatement(n) && n.declarationList.declarations.length === 1) {
|
|
315
|
+
const decl = n.declarationList.declarations[0];
|
|
316
|
+
const fn = unwrapExprToFunction(decl.initializer);
|
|
317
|
+
consider(n, fn);
|
|
318
|
+
}
|
|
319
|
+
else if (ts.isCallExpression(n)) {
|
|
320
|
+
const fn = unwrapExprToFunction(n);
|
|
321
|
+
if (fn)
|
|
322
|
+
consider(n, fn);
|
|
323
|
+
}
|
|
324
|
+
ts.forEachChild(n, walk);
|
|
325
|
+
};
|
|
326
|
+
walk(sf);
|
|
327
|
+
return best ? { ownerAstNode: best.node, signatureNode: best.sig } : null;
|
|
328
|
+
}
|
|
329
|
+
function hasAsyncModifier(node) {
|
|
330
|
+
if (!ts.canHaveModifiers(node))
|
|
331
|
+
return false;
|
|
332
|
+
const mods = ts.getModifiers(node);
|
|
333
|
+
return Boolean(mods?.some((m) => m.kind === ts.SyntaxKind.AsyncKeyword));
|
|
334
|
+
}
|
|
335
|
+
function isInsideReturnOrConciseBody(pos, ownerAstNode, sigNode) {
|
|
336
|
+
if (sigNode &&
|
|
337
|
+
ts.isArrowFunction(sigNode) &&
|
|
338
|
+
!ts.isBlock(sigNode.body) &&
|
|
339
|
+
pos >= sigNode.body.getStart() &&
|
|
340
|
+
pos <= sigNode.body.getEnd()) {
|
|
341
|
+
return true;
|
|
342
|
+
}
|
|
343
|
+
let insideReturn = false;
|
|
344
|
+
const walk = (n) => {
|
|
345
|
+
if (insideReturn)
|
|
346
|
+
return;
|
|
347
|
+
if (pos < n.getFullStart() || pos > n.getEnd())
|
|
348
|
+
return;
|
|
349
|
+
if (ts.isReturnStatement(n)) {
|
|
350
|
+
insideReturn = true;
|
|
351
|
+
return;
|
|
352
|
+
}
|
|
353
|
+
if (n !== ownerAstNode &&
|
|
354
|
+
n !== sigNode &&
|
|
355
|
+
(ts.isFunctionDeclaration(n) ||
|
|
356
|
+
ts.isFunctionExpression(n) ||
|
|
357
|
+
ts.isArrowFunction(n) ||
|
|
358
|
+
ts.isMethodDeclaration(n))) {
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
ts.forEachChild(n, walk);
|
|
362
|
+
};
|
|
363
|
+
walk(ownerAstNode);
|
|
364
|
+
return insideReturn;
|
|
365
|
+
}
|
|
366
|
+
function isInsideCallOrJsxExpression(pos, ownerAstNode) {
|
|
367
|
+
let matched = false;
|
|
368
|
+
const walk = (n) => {
|
|
369
|
+
if (matched)
|
|
370
|
+
return;
|
|
371
|
+
if (pos < n.getFullStart() || pos > n.getEnd())
|
|
372
|
+
return;
|
|
373
|
+
if (ts.isCallExpression(n) ||
|
|
374
|
+
ts.isNewExpression(n) ||
|
|
375
|
+
ts.isJsxOpeningElement(n) ||
|
|
376
|
+
ts.isJsxSelfClosingElement(n)) {
|
|
377
|
+
matched = true;
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
380
|
+
ts.forEachChild(n, walk);
|
|
381
|
+
};
|
|
382
|
+
walk(ownerAstNode);
|
|
383
|
+
return matched;
|
|
384
|
+
}
|
|
385
|
+
function buildIncrementalProgramGroup(tsconfigPath, repoPath, dirtyAbsFiles, cacheDirOption) {
|
|
386
|
+
let tsBuildInfoFile;
|
|
387
|
+
if (cacheDirOption !== false) {
|
|
388
|
+
const cacheDir = cacheDirOption ?? resolve(repoPath, '.chomp', 'cache');
|
|
389
|
+
if (!existsSync(cacheDir)) {
|
|
390
|
+
mkdirSync(cacheDir, { recursive: true });
|
|
391
|
+
}
|
|
392
|
+
const groupKey = tsconfigPath ?? `synthetic:${resolve(repoPath)}`;
|
|
393
|
+
const slug = createHash('sha1').update(groupKey).digest('hex').slice(0, 12);
|
|
394
|
+
tsBuildInfoFile = resolve(cacheDir, `ports-${slug}.tsbuildinfo`);
|
|
395
|
+
}
|
|
396
|
+
let baseOptions = {
|
|
397
|
+
target: ts.ScriptTarget.ES2022,
|
|
398
|
+
module: ts.ModuleKind.NodeNext,
|
|
399
|
+
moduleResolution: ts.ModuleResolutionKind.NodeNext,
|
|
400
|
+
allowJs: true,
|
|
401
|
+
jsx: ts.JsxEmit.ReactJSX,
|
|
402
|
+
strict: true,
|
|
403
|
+
};
|
|
404
|
+
let rootNames = [...dirtyAbsFiles];
|
|
405
|
+
if (tsconfigPath && existsSync(tsconfigPath)) {
|
|
406
|
+
const readRes = ts.readConfigFile(tsconfigPath, ts.sys.readFile);
|
|
407
|
+
if (!readRes.error && readRes.config) {
|
|
408
|
+
const parsed = ts.parseJsonConfigFileContent(readRes.config, ts.sys, dirname(tsconfigPath));
|
|
409
|
+
baseOptions = { ...baseOptions, ...parsed.options };
|
|
410
|
+
const fileSet = new Set(parsed.fileNames.map((f) => resolve(f)));
|
|
411
|
+
for (const df of dirtyAbsFiles) {
|
|
412
|
+
fileSet.add(resolve(df));
|
|
413
|
+
}
|
|
414
|
+
rootNames = Array.from(fileSet);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
const options = {
|
|
418
|
+
...baseOptions,
|
|
419
|
+
noEmit: true,
|
|
420
|
+
emitDeclarationOnly: false,
|
|
421
|
+
declaration: false,
|
|
422
|
+
sourceMap: false,
|
|
423
|
+
incremental: Boolean(tsBuildInfoFile),
|
|
424
|
+
composite: false,
|
|
425
|
+
...(tsBuildInfoFile ? { tsBuildInfoFile } : {}),
|
|
426
|
+
skipLibCheck: true,
|
|
427
|
+
skipDefaultLibCheck: true,
|
|
428
|
+
};
|
|
429
|
+
return ts.createIncrementalProgram({
|
|
430
|
+
rootNames,
|
|
431
|
+
options,
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
/**
|
|
435
|
+
* Runs Speed 2 incremental TypeScript Port Valve verification on `graph` and persists
|
|
436
|
+
* `L1_PORTS` (`source: "chomp-ports"`) cache rows to `storage`.
|
|
437
|
+
*
|
|
438
|
+
* @param options Repository path, ID, storage adapter, and extracted Layer 0 `RepresentationGraph`.
|
|
439
|
+
* @returns Counts of hydrated, cached, and pruned `L1_PORTS` overlays plus boundary diagnostic totals.
|
|
440
|
+
*/
|
|
441
|
+
export async function hydrateRepositoryPortValves(options) {
|
|
442
|
+
const t0 = Date.now();
|
|
443
|
+
const { repoPath, repoId, storage, graph, force = false, cacheDir } = options;
|
|
444
|
+
const existingOverlays = await storage.getEntityOverlays(repoId, {
|
|
445
|
+
layer: CHOMP_PORTS_LAYER,
|
|
446
|
+
source: CHOMP_PORTS_SOURCE,
|
|
447
|
+
});
|
|
448
|
+
const existingByEntityId = new Map(existingOverlays.map((o) => [o.entityId, o]));
|
|
449
|
+
const currentNodeIds = new Set(graph.nodes.map((n) => n.id));
|
|
450
|
+
let prunedCount = 0;
|
|
451
|
+
for (const oldOv of existingOverlays) {
|
|
452
|
+
if (!currentNodeIds.has(oldOv.entityId)) {
|
|
453
|
+
await storage.deleteEntityOverlay({
|
|
454
|
+
repositoryId: repoId,
|
|
455
|
+
entityId: oldOv.entityId,
|
|
456
|
+
layer: CHOMP_PORTS_LAYER,
|
|
457
|
+
source: CHOMP_PORTS_SOURCE,
|
|
458
|
+
});
|
|
459
|
+
existingByEntityId.delete(oldOv.entityId);
|
|
460
|
+
prunedCount++;
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
const candidateContracts = graph.nodes.filter((n) => {
|
|
464
|
+
if (n.type !== 'CONTRACT' || n.entityType === 'EXPORTED_TYPE')
|
|
465
|
+
return false;
|
|
466
|
+
const ev = primaryEvidenceOf(n);
|
|
467
|
+
return Boolean(ev && isSupportedSourcePath(ev.filePath));
|
|
468
|
+
});
|
|
469
|
+
const dirtyContracts = candidateContracts.filter((n) => {
|
|
470
|
+
if (force)
|
|
471
|
+
return true;
|
|
472
|
+
const existing = existingByEntityId.get(n.id);
|
|
473
|
+
if (!existing)
|
|
474
|
+
return true;
|
|
475
|
+
return existing.stale === true;
|
|
476
|
+
});
|
|
477
|
+
if (dirtyContracts.length === 0) {
|
|
478
|
+
let existingDiagCount = 0;
|
|
479
|
+
for (const ov of existingByEntityId.values()) {
|
|
480
|
+
const diags = ov.payload?.diagnostics;
|
|
481
|
+
if (Array.isArray(diags))
|
|
482
|
+
existingDiagCount += diags.length;
|
|
483
|
+
}
|
|
484
|
+
return {
|
|
485
|
+
hydratedCount: 0,
|
|
486
|
+
cachedCount: existingByEntityId.size,
|
|
487
|
+
prunedCount,
|
|
488
|
+
diagnosticCount: existingDiagCount,
|
|
489
|
+
durationMs: Date.now() - t0,
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
const outEdgesBySource = new Map();
|
|
493
|
+
for (const edge of graph.edges) {
|
|
494
|
+
if (!edge.sourceId)
|
|
495
|
+
continue;
|
|
496
|
+
let list = outEdgesBySource.get(edge.sourceId);
|
|
497
|
+
if (!list) {
|
|
498
|
+
list = [];
|
|
499
|
+
outEdgesBySource.set(edge.sourceId, list);
|
|
500
|
+
}
|
|
501
|
+
list.push(edge);
|
|
502
|
+
}
|
|
503
|
+
const tsconfigCache = new Map();
|
|
504
|
+
const fileHashCache = new Map();
|
|
505
|
+
const contractsByGroup = new Map();
|
|
506
|
+
for (const node of dirtyContracts) {
|
|
507
|
+
const ev = primaryEvidenceOf(node);
|
|
508
|
+
const absFile = resolve(repoPath, ev.filePath);
|
|
509
|
+
if (!existsSync(absFile))
|
|
510
|
+
continue;
|
|
511
|
+
const tsconfig = findNearestTsconfig(absFile, repoPath, tsconfigCache);
|
|
512
|
+
let bucket = contractsByGroup.get(tsconfig);
|
|
513
|
+
if (!bucket) {
|
|
514
|
+
bucket = [];
|
|
515
|
+
contractsByGroup.set(tsconfig, bucket);
|
|
516
|
+
}
|
|
517
|
+
bucket.push(node);
|
|
518
|
+
}
|
|
519
|
+
const overlaysToUpsert = [];
|
|
520
|
+
let newDiagCount = 0;
|
|
521
|
+
const yieldEventLoop = () => new Promise((resolveYield) => setImmediate(resolveYield));
|
|
522
|
+
for (const [tsconfigPath, groupNodes] of contractsByGroup) {
|
|
523
|
+
await yieldEventLoop();
|
|
524
|
+
const nodesByAbsFile = new Map();
|
|
525
|
+
for (const n of groupNodes) {
|
|
526
|
+
const ev = primaryEvidenceOf(n);
|
|
527
|
+
const absFile = resolve(repoPath, ev.filePath);
|
|
528
|
+
let list = nodesByAbsFile.get(absFile);
|
|
529
|
+
if (!list) {
|
|
530
|
+
list = [];
|
|
531
|
+
nodesByAbsFile.set(absFile, list);
|
|
532
|
+
}
|
|
533
|
+
list.push(n);
|
|
534
|
+
}
|
|
535
|
+
const builder = buildIncrementalProgramGroup(tsconfigPath, repoPath, Array.from(nodesByAbsFile.keys()), cacheDir);
|
|
536
|
+
const program = builder.getProgram();
|
|
537
|
+
const checker = program.getTypeChecker();
|
|
538
|
+
let processedFilesInGroup = 0;
|
|
539
|
+
for (const [absFile, fileContracts] of nodesByAbsFile) {
|
|
540
|
+
if (++processedFilesInGroup % 6 === 0) {
|
|
541
|
+
await yieldEventLoop();
|
|
542
|
+
}
|
|
543
|
+
const sf = program.getSourceFile(absFile);
|
|
544
|
+
if (!sf)
|
|
545
|
+
continue;
|
|
546
|
+
const relFilePath = normalizeSlash(relative(resolve(repoPath), absFile));
|
|
547
|
+
const resolvedTargets = [];
|
|
548
|
+
for (const contract of fileContracts) {
|
|
549
|
+
const ev = primaryEvidenceOf(contract);
|
|
550
|
+
const found = findContractDeclarationInSourceFile(sf, ev?.lineNumber);
|
|
551
|
+
if (!found)
|
|
552
|
+
continue;
|
|
553
|
+
resolvedTargets.push({
|
|
554
|
+
contract,
|
|
555
|
+
ownerAstNode: found.ownerAstNode,
|
|
556
|
+
signatureNode: found.signatureNode,
|
|
557
|
+
spanStart: found.ownerAstNode.getStart(sf),
|
|
558
|
+
spanEnd: found.ownerAstNode.getEnd(),
|
|
559
|
+
});
|
|
560
|
+
}
|
|
561
|
+
// Collect semantic diagnostics for this dirty file and bind port mismatches to their owning contract
|
|
562
|
+
const diagsByContractId = new Map();
|
|
563
|
+
const fileDiagnostics = builder.getSemanticDiagnostics(sf);
|
|
564
|
+
for (const d of fileDiagnostics) {
|
|
565
|
+
if (d.start === undefined)
|
|
566
|
+
continue;
|
|
567
|
+
const isCallCode = CALL_MISMATCH_TS_CODES.has(d.code);
|
|
568
|
+
const isReturnCode = RETURN_MISMATCH_TS_CODES.has(d.code);
|
|
569
|
+
if (!isCallCode && !isReturnCode)
|
|
570
|
+
continue;
|
|
571
|
+
// Pick the tightest enclosing contract AST span containing `d.start`
|
|
572
|
+
let bestOwner = null;
|
|
573
|
+
for (const rt of resolvedTargets) {
|
|
574
|
+
if (d.start >= rt.spanStart && d.start <= rt.spanEnd) {
|
|
575
|
+
if (!bestOwner ||
|
|
576
|
+
rt.spanEnd - rt.spanStart < bestOwner.spanEnd - bestOwner.spanStart) {
|
|
577
|
+
bestOwner = rt;
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
if (!bestOwner)
|
|
582
|
+
continue;
|
|
583
|
+
let kind = null;
|
|
584
|
+
if (isReturnCode &&
|
|
585
|
+
isInsideReturnOrConciseBody(d.start, bestOwner.ownerAstNode, bestOwner.signatureNode)) {
|
|
586
|
+
kind = 'TS_RETURN_MISMATCH';
|
|
587
|
+
}
|
|
588
|
+
else if ((isCallCode || d.code === 2322) &&
|
|
589
|
+
isInsideCallOrJsxExpression(d.start, bestOwner.ownerAstNode)) {
|
|
590
|
+
kind = 'TS_CALL_MISMATCH';
|
|
591
|
+
}
|
|
592
|
+
else if (d.code === 2355) {
|
|
593
|
+
kind = 'TS_RETURN_MISMATCH';
|
|
594
|
+
}
|
|
595
|
+
if (!kind)
|
|
596
|
+
continue;
|
|
597
|
+
const diagLine = sf.getLineAndCharacterOfPosition(d.start).line + 1;
|
|
598
|
+
const msg = ts
|
|
599
|
+
.flattenDiagnosticMessageText(d.messageText, ' ')
|
|
600
|
+
.replace(/\s+/g, ' ')
|
|
601
|
+
.trim();
|
|
602
|
+
let peerEntityId;
|
|
603
|
+
if (kind === 'TS_CALL_MISMATCH') {
|
|
604
|
+
const outEdges = outEdgesBySource.get(bestOwner.contract.id) ?? [];
|
|
605
|
+
const matchingEdge = outEdges.find((e) => {
|
|
606
|
+
if (!e.targetId)
|
|
607
|
+
return false;
|
|
608
|
+
const eEvs = Array.isArray(e.evidence) ? e.evidence : [e.evidence];
|
|
609
|
+
return eEvs.some((ev) => ev &&
|
|
610
|
+
typeof ev.lineNumber === 'number' &&
|
|
611
|
+
Math.abs(ev.lineNumber - diagLine) <= 2);
|
|
612
|
+
});
|
|
613
|
+
if (matchingEdge?.targetId) {
|
|
614
|
+
peerEntityId = matchingEdge.targetId;
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
let bucket = diagsByContractId.get(bestOwner.contract.id);
|
|
618
|
+
if (!bucket) {
|
|
619
|
+
bucket = [];
|
|
620
|
+
diagsByContractId.set(bestOwner.contract.id, bucket);
|
|
621
|
+
}
|
|
622
|
+
if (bucket.length < 8) {
|
|
623
|
+
bucket.push({
|
|
624
|
+
kind,
|
|
625
|
+
tsCode: d.code,
|
|
626
|
+
message: msg.length > 220 ? `${msg.slice(0, 219)}…` : msg,
|
|
627
|
+
filePath: relFilePath,
|
|
628
|
+
lineNumber: diagLine,
|
|
629
|
+
...(peerEntityId ? { peerEntityId } : {}),
|
|
630
|
+
});
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
for (const rt of resolvedTargets) {
|
|
634
|
+
const { contract, signatureNode } = rt;
|
|
635
|
+
const depRelPaths = new Set();
|
|
636
|
+
let inputs;
|
|
637
|
+
let output;
|
|
638
|
+
let zeroInputs = false;
|
|
639
|
+
if (signatureNode) {
|
|
640
|
+
const sig = checker.getSignatureFromDeclaration(signatureNode);
|
|
641
|
+
if (sig) {
|
|
642
|
+
const sigParams = sig.getParameters();
|
|
643
|
+
const parsedParams = [];
|
|
644
|
+
for (let i = 0; i < sigParams.length; i++) {
|
|
645
|
+
const sym = sigParams[i];
|
|
646
|
+
if (sym.getName() === 'this')
|
|
647
|
+
continue;
|
|
648
|
+
const paramDecl = signatureNode.parameters[i];
|
|
649
|
+
const isOptional = Boolean((sym.flags & ts.SymbolFlags.Optional) !== 0 ||
|
|
650
|
+
paramDecl?.questionToken ||
|
|
651
|
+
paramDecl?.initializer ||
|
|
652
|
+
paramDecl?.dotDotDotToken);
|
|
653
|
+
const rawParamType = checker.getTypeOfSymbolAtLocation(sym, signatureNode);
|
|
654
|
+
const cleanParamType = isOptional
|
|
655
|
+
? stripOptionalUndefined(checker, rawParamType)
|
|
656
|
+
: rawParamType;
|
|
657
|
+
const typeStr = formatTypeConcise(checker, cleanParamType, signatureNode, isOptional);
|
|
658
|
+
const fields = extractCheckerFields(checker, cleanParamType, signatureNode, repoPath, relFilePath, depRelPaths, 0, new Set());
|
|
659
|
+
const declaration = resolveTypeDeclarationRef(unwrapArrayOrNullableForFields(checker, cleanParamType), repoPath, relFilePath, depRelPaths);
|
|
660
|
+
parsedParams.push({
|
|
661
|
+
name: paramDecl?.dotDotDotToken ? `...${sym.getName()}` : sym.getName(),
|
|
662
|
+
type: typeStr,
|
|
663
|
+
...(isOptional ? { optional: true } : {}),
|
|
664
|
+
...(fields ? { fields } : {}),
|
|
665
|
+
...(declaration ? { declaration } : {}),
|
|
666
|
+
});
|
|
667
|
+
}
|
|
668
|
+
if (parsedParams.length > 0) {
|
|
669
|
+
inputs = parsedParams;
|
|
670
|
+
}
|
|
671
|
+
else {
|
|
672
|
+
zeroInputs = true;
|
|
673
|
+
}
|
|
674
|
+
const rawReturnType = checker.getReturnTypeOfSignature(sig);
|
|
675
|
+
const awaitedReturnType = checker.getAwaitedType(rawReturnType) ?? rawReturnType;
|
|
676
|
+
const unwrappedPromise = awaitedReturnType !== rawReturnType;
|
|
677
|
+
const isAsync = unwrappedPromise || hasAsyncModifier(signatureNode);
|
|
678
|
+
const outTypeStr = formatTypeConcise(checker, awaitedReturnType, signatureNode);
|
|
679
|
+
const outFields = extractCheckerFields(checker, awaitedReturnType, signatureNode, repoPath, relFilePath, depRelPaths, 0, new Set());
|
|
680
|
+
const outDecl = resolveTypeDeclarationRef(unwrapArrayOrNullableForFields(checker, awaitedReturnType), repoPath, relFilePath, depRelPaths);
|
|
681
|
+
output = {
|
|
682
|
+
type: outTypeStr,
|
|
683
|
+
...(isAsync ? { async: true } : {}),
|
|
684
|
+
...(outFields ? { fields: outFields } : {}),
|
|
685
|
+
...(outDecl ? { declaration: outDecl } : {}),
|
|
686
|
+
};
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
const contractDiags = diagsByContractId.get(contract.id);
|
|
690
|
+
if (contractDiags) {
|
|
691
|
+
newDiagCount += contractDiags.length;
|
|
692
|
+
}
|
|
693
|
+
const basePv = contract.metadata?.portValves;
|
|
694
|
+
if (!inputs && basePv?.inputs) {
|
|
695
|
+
inputs = basePv.inputs;
|
|
696
|
+
}
|
|
697
|
+
if (!output && basePv?.output) {
|
|
698
|
+
output = basePv.output;
|
|
699
|
+
}
|
|
700
|
+
const payload = {
|
|
701
|
+
tier: 'typechecked',
|
|
702
|
+
origin: basePv?.origin &&
|
|
703
|
+
(basePv.origin === 'zod' ||
|
|
704
|
+
basePv.origin === 'drizzle' ||
|
|
705
|
+
basePv.origin === 'mcp-schema')
|
|
706
|
+
? basePv.origin
|
|
707
|
+
: 'ts-typecheck',
|
|
708
|
+
...(contract.metadata?.inputTypes
|
|
709
|
+
? { inputTypes: contract.metadata.inputTypes }
|
|
710
|
+
: {}),
|
|
711
|
+
...(output?.type
|
|
712
|
+
? { outputType: output.type }
|
|
713
|
+
: contract.metadata?.outputType
|
|
714
|
+
? { outputType: contract.metadata.outputType }
|
|
715
|
+
: {}),
|
|
716
|
+
...(inputs && inputs.length > 0 ? { inputs } : {}),
|
|
717
|
+
...(output ? { output } : {}),
|
|
718
|
+
...(zeroInputs && (!inputs || inputs.length === 0)
|
|
719
|
+
? { zeroInputs: true }
|
|
720
|
+
: {}),
|
|
721
|
+
...(contractDiags && contractDiags.length > 0
|
|
722
|
+
? { diagnostics: contractDiags }
|
|
723
|
+
: {}),
|
|
724
|
+
};
|
|
725
|
+
const inputDeps = [];
|
|
726
|
+
for (const depRel of depRelPaths) {
|
|
727
|
+
const absDep = resolve(repoPath, depRel);
|
|
728
|
+
const hash = hashFileShort(absDep, fileHashCache);
|
|
729
|
+
if (hash) {
|
|
730
|
+
inputDeps.push({ path: depRel, hash });
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
overlaysToUpsert.push({
|
|
734
|
+
repositoryId: repoId,
|
|
735
|
+
entityId: contract.id,
|
|
736
|
+
layer: CHOMP_PORTS_LAYER,
|
|
737
|
+
source: CHOMP_PORTS_SOURCE,
|
|
738
|
+
payload: payload,
|
|
739
|
+
bodyHash: typeof contract.metadata?.bodyHash === 'string'
|
|
740
|
+
? contract.metadata.bodyHash
|
|
741
|
+
: undefined,
|
|
742
|
+
derivation: 'EXTRACTED',
|
|
743
|
+
...(inputDeps.length > 0 ? { inputs: inputDeps } : {}),
|
|
744
|
+
});
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
// Persist incremental `.tsbuildinfo` strictly inside `.chomp/cache/` (never emitting JS/DTS)
|
|
748
|
+
if (cacheDir !== false) {
|
|
749
|
+
try {
|
|
750
|
+
builder.emit(undefined, (fileName, text) => {
|
|
751
|
+
if (fileName.endsWith('.tsbuildinfo')) {
|
|
752
|
+
ts.sys.writeFile(fileName, text);
|
|
753
|
+
}
|
|
754
|
+
});
|
|
755
|
+
}
|
|
756
|
+
catch {
|
|
757
|
+
// Non-fatal if cache directory is read-only
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
if (overlaysToUpsert.length > 0) {
|
|
762
|
+
await storage.upsertEntityOverlays(overlaysToUpsert);
|
|
763
|
+
}
|
|
764
|
+
let totalDiagnostics = newDiagCount;
|
|
765
|
+
let cachedCount = 0;
|
|
766
|
+
const refreshedIds = new Set(overlaysToUpsert.map((o) => o.entityId));
|
|
767
|
+
for (const [eid, ov] of existingByEntityId) {
|
|
768
|
+
if (refreshedIds.has(eid))
|
|
769
|
+
continue;
|
|
770
|
+
cachedCount++;
|
|
771
|
+
const diags = ov.payload?.diagnostics;
|
|
772
|
+
if (Array.isArray(diags))
|
|
773
|
+
totalDiagnostics += diags.length;
|
|
774
|
+
}
|
|
775
|
+
return {
|
|
776
|
+
hydratedCount: overlaysToUpsert.length,
|
|
777
|
+
cachedCount,
|
|
778
|
+
prunedCount,
|
|
779
|
+
diagnosticCount: totalDiagnostics,
|
|
780
|
+
durationMs: Date.now() - t0,
|
|
781
|
+
};
|
|
782
|
+
}
|
|
783
|
+
/**
|
|
784
|
+
* Filters `process.execArgv` down to safe loader/runtime flags (`--require`, `--import`,
|
|
785
|
+
* `--loader`, `--conditions`, `--max-old-space-size`, etc.) so forked child workers inherit
|
|
786
|
+
* `tsx` loaders in dev mode without inheriting `--test`, `--eval`, or `--inspect` flags.
|
|
787
|
+
*/
|
|
788
|
+
export function filterExecArgvForChild(execArgv = process.execArgv) {
|
|
789
|
+
const out = [];
|
|
790
|
+
const flagsWithValue = new Set([
|
|
791
|
+
'--require',
|
|
792
|
+
'-r',
|
|
793
|
+
'--import',
|
|
794
|
+
'--loader',
|
|
795
|
+
'--experimental-loader',
|
|
796
|
+
'--conditions',
|
|
797
|
+
'-C',
|
|
798
|
+
'--max-old-space-size',
|
|
799
|
+
]);
|
|
800
|
+
const standaloneFlags = new Set([
|
|
801
|
+
'--no-warnings',
|
|
802
|
+
'--enable-source-maps',
|
|
803
|
+
'--experimental-vm-modules',
|
|
804
|
+
]);
|
|
805
|
+
for (let i = 0; i < execArgv.length; i++) {
|
|
806
|
+
const arg = execArgv[i];
|
|
807
|
+
if (flagsWithValue.has(arg)) {
|
|
808
|
+
if (i + 1 < execArgv.length) {
|
|
809
|
+
out.push(arg, execArgv[i + 1]);
|
|
810
|
+
i++;
|
|
811
|
+
}
|
|
812
|
+
continue;
|
|
813
|
+
}
|
|
814
|
+
if (arg.startsWith('--require=') ||
|
|
815
|
+
arg.startsWith('--import=') ||
|
|
816
|
+
arg.startsWith('--loader=') ||
|
|
817
|
+
arg.startsWith('--experimental-loader=') ||
|
|
818
|
+
arg.startsWith('--conditions=') ||
|
|
819
|
+
arg.startsWith('--max-old-space-size=') ||
|
|
820
|
+
standaloneFlags.has(arg)) {
|
|
821
|
+
out.push(arg);
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
return out;
|
|
825
|
+
}
|
|
826
|
+
function resolvePortHydratorWorkerPath() {
|
|
827
|
+
const currentFile = fileURLToPath(import.meta.url);
|
|
828
|
+
const dir = dirname(currentFile);
|
|
829
|
+
const ext = currentFile.endsWith('.ts') ? '.ts' : '.js';
|
|
830
|
+
const primary = resolve(dir, `portHydratorWorker${ext}`);
|
|
831
|
+
if (existsSync(primary))
|
|
832
|
+
return primary;
|
|
833
|
+
return resolve(dir, `portHydratorWorker${ext === '.ts' ? '.js' : '.ts'}`);
|
|
834
|
+
}
|
|
835
|
+
/**
|
|
836
|
+
* Runs Speed 2 Port Valve hydration inside an isolated forked child process so heavy
|
|
837
|
+
* TypeScript `Program` creation and semantic diagnostics never block the `chomp ui`
|
|
838
|
+
* main event loop, HTTP polling, or raw-mode terminal input (`[q]` / `Ctrl+C`).
|
|
839
|
+
*/
|
|
840
|
+
export function runPortHydrationInChildProcess(options) {
|
|
841
|
+
if (!options.dbPath || !existsSync(options.dbPath)) {
|
|
842
|
+
return {
|
|
843
|
+
promise: Promise.resolve(null),
|
|
844
|
+
cancel: () => { },
|
|
845
|
+
};
|
|
846
|
+
}
|
|
847
|
+
const workerPath = resolvePortHydratorWorkerPath();
|
|
848
|
+
if (!existsSync(workerPath)) {
|
|
849
|
+
return {
|
|
850
|
+
promise: Promise.resolve(null),
|
|
851
|
+
cancel: () => { },
|
|
852
|
+
};
|
|
853
|
+
}
|
|
854
|
+
let settled = false;
|
|
855
|
+
let cancelled = false;
|
|
856
|
+
let child = null;
|
|
857
|
+
let timeoutHandle = null;
|
|
858
|
+
let resolvePromise;
|
|
859
|
+
const finish = (value) => {
|
|
860
|
+
if (settled)
|
|
861
|
+
return;
|
|
862
|
+
settled = true;
|
|
863
|
+
if (timeoutHandle) {
|
|
864
|
+
clearTimeout(timeoutHandle);
|
|
865
|
+
timeoutHandle = null;
|
|
866
|
+
}
|
|
867
|
+
resolvePromise(value);
|
|
868
|
+
};
|
|
869
|
+
const terminateChild = () => {
|
|
870
|
+
if (!child || child.killed)
|
|
871
|
+
return;
|
|
872
|
+
try {
|
|
873
|
+
child.kill('SIGTERM');
|
|
874
|
+
}
|
|
875
|
+
catch {
|
|
876
|
+
// Ignore already-exited child
|
|
877
|
+
}
|
|
878
|
+
const doomed = child;
|
|
879
|
+
setTimeout(() => {
|
|
880
|
+
if (doomed.exitCode === null && doomed.signalCode === null) {
|
|
881
|
+
try {
|
|
882
|
+
doomed.kill('SIGKILL');
|
|
883
|
+
}
|
|
884
|
+
catch {
|
|
885
|
+
// Ignore
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
}, 1500).unref();
|
|
889
|
+
};
|
|
890
|
+
const promise = new Promise((resolveFn) => {
|
|
891
|
+
resolvePromise = resolveFn;
|
|
892
|
+
});
|
|
893
|
+
try {
|
|
894
|
+
child = fork(workerPath, [], {
|
|
895
|
+
execArgv: filterExecArgvForChild(),
|
|
896
|
+
stdio: ['ignore', 'ignore', 'pipe', 'ipc'],
|
|
897
|
+
});
|
|
898
|
+
}
|
|
899
|
+
catch {
|
|
900
|
+
finish(null);
|
|
901
|
+
return { promise, cancel: () => { } };
|
|
902
|
+
}
|
|
903
|
+
// Drain stderr so the pipe buffer can never stall the child process
|
|
904
|
+
child.stderr?.resume();
|
|
905
|
+
child.on('message', (msg) => {
|
|
906
|
+
if (cancelled) {
|
|
907
|
+
finish(null);
|
|
908
|
+
return;
|
|
909
|
+
}
|
|
910
|
+
if (msg && typeof msg === 'object' && msg.ok && 'result' in msg) {
|
|
911
|
+
finish(msg.result ?? null);
|
|
912
|
+
}
|
|
913
|
+
else {
|
|
914
|
+
finish(null);
|
|
915
|
+
}
|
|
916
|
+
});
|
|
917
|
+
child.on('error', () => {
|
|
918
|
+
finish(null);
|
|
919
|
+
});
|
|
920
|
+
child.on('exit', () => {
|
|
921
|
+
finish(null);
|
|
922
|
+
});
|
|
923
|
+
const timeoutMs = options.timeoutMs ?? 120_000;
|
|
924
|
+
if (timeoutMs > 0) {
|
|
925
|
+
timeoutHandle = setTimeout(() => {
|
|
926
|
+
cancelled = true;
|
|
927
|
+
terminateChild();
|
|
928
|
+
finish(null);
|
|
929
|
+
}, timeoutMs);
|
|
930
|
+
timeoutHandle.unref();
|
|
931
|
+
}
|
|
932
|
+
try {
|
|
933
|
+
child.send({
|
|
934
|
+
dbPath: options.dbPath,
|
|
935
|
+
repoPath: options.repoPath,
|
|
936
|
+
force: Boolean(options.force),
|
|
937
|
+
...(options.cacheDir !== undefined ? { cacheDir: options.cacheDir } : {}),
|
|
938
|
+
});
|
|
939
|
+
}
|
|
940
|
+
catch {
|
|
941
|
+
terminateChild();
|
|
942
|
+
finish(null);
|
|
943
|
+
}
|
|
944
|
+
return {
|
|
945
|
+
promise,
|
|
946
|
+
cancel: () => {
|
|
947
|
+
if (cancelled)
|
|
948
|
+
return;
|
|
949
|
+
cancelled = true;
|
|
950
|
+
terminateChild();
|
|
951
|
+
finish(null);
|
|
952
|
+
},
|
|
953
|
+
};
|
|
954
|
+
}
|