-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreferences.util.ts
More file actions
380 lines (340 loc) · 14 KB
/
Copy pathreferences.util.ts
File metadata and controls
380 lines (340 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
import ts from "typescript";
import {ReferencePath, ReferenceValue} from "@code0-tech/sagittarius-graphql-types";
/**
* Extracts reference values from a collection of TypeScript symbols.
*
* This function processes symbols with specific prefixes (node_, p_, flow_) and creates
* corresponding ReferenceValue objects. It filters out invalid symbols and symbols that
* are declared after the current node position.
*
* @param checker - TypeScript TypeChecker instance for type information resolution
* @param node - The VariableDeclaration context in which symbols are analyzed
* @param paramType - The expected parameter type for property matching during extraction
* @param symbols - The array of symbols to process and analyze
* @returns An array of ReferenceValue objects representing extracted references with their paths
*
* @example
* // Extracts all references from symbols prefixed with node_, p_, or flow_
* const references = getReferences(checker, variableDecl, expectedType, [symbol1, symbol2]);
*/
export const getReferences = (
checker: ts.TypeChecker,
node: ts.VariableDeclaration,
paramType: ts.Type,
symbols: ts.Symbol[]
): ReferenceValue[] => {
return symbols.flatMap((symbol) => {
const name = symbol.getName();
// Filter symbols by required prefix
if (!isValidSymbolPrefix(name)) {
return [];
}
// Validate symbol declaration exists and is declared before current node
const symbolDeclaration = symbol.getDeclarations()?.[0];
if (!symbolDeclaration || symbolDeclaration.getEnd() >= node.getEnd()!) {
return [];
}
const symbolType = checker.getTypeOfSymbolAtLocation(symbol, node);
// Process symbol based on its prefix
if (name.startsWith("node_")) {
return processNodeSymbol(name, symbolType, checker, paramType);
} else if (name.startsWith("p_")) {
return processParameterSymbol(name, symbolType, checker, paramType);
} else if (name.startsWith("flow_")) {
return processFlowSymbol(symbolType, checker, paramType);
}
return [];
});
};
/**
* Checks if a symbol name has a valid prefix for reference extraction.
*
* Valid prefixes are: node_, p_, flow_
*
* @param name - The symbol name to validate
* @returns True if the name starts with a valid prefix, false otherwise
*/
const isValidSymbolPrefix = (name: string): boolean => {
return name.startsWith("node_") || name.startsWith("p_") || name.startsWith("flow_");
};
/**
* Processes a node symbol and creates corresponding reference values.
*
* Node symbols represent references to node functions. The function extracts the node ID
* from the symbol name by reversing the name encoding, then extracts all matching object
* properties from the symbol type.
*
* @param name - The symbol name starting with "node_"
* @param symbolType - The TypeScript type of the symbol
* @param checker - TypeScript TypeChecker for type operations
* @param paramType - The expected parameter type for property matching
* @returns Array of ReferenceValue objects for this node symbol
*/
const processNodeSymbol = (
name: string,
symbolType: ts.Type,
checker: ts.TypeChecker,
paramType: ts.Type
): ReferenceValue[] => {
// Skip void types
if ((symbolType.flags & ts.TypeFlags.Void) !== 0) {
return [];
}
// Decode the node function ID from the symbol name
const nodeFunctionId = decodeIdentifier(name.replace("node_", ""));
// Extract all properties that match the expected parameter type
const propertyPaths = extractObjectProperties(symbolType, checker, paramType);
return propertyPaths.flatMap(({ path }) => {
const referenceValue: ReferenceValue = {
__typename: "ReferenceValue",
nodeFunctionId: nodeFunctionId as any,
};
if (path.length > 0) {
referenceValue.referencePath = path;
}
return referenceValue;
});
};
/**
* Processes a parameter symbol and creates corresponding reference values.
*
* Parameter symbols represent references to function parameters. They contain encoded
* information about the node function ID, parameter index, and input index. If the symbol
* type is a tuple, each tuple element is processed separately.
*
* @param name - The symbol name starting with "p_"
* @param symbolType - The TypeScript type of the symbol
* @param checker - TypeScript TypeChecker for type operations
* @param paramType - The expected parameter type for property matching
* @returns Array of ReferenceValue objects for this parameter symbol
*/
const processParameterSymbol = (
name: string,
symbolType: ts.Type,
checker: ts.TypeChecker,
paramType: ts.Type
): ReferenceValue[] => {
// Decode parameter information from symbol name
const { nodeFunctionId, paramIndexFromName } = decodeParameterName(name);
// If the symbol type is not a tuple, return empty array
if (!checker.isTupleType(symbolType)) {
return [];
}
const typeReference = symbolType as ts.TypeReference;
const typeArguments = checker.getTypeArguments(typeReference);
return typeArguments.flatMap((tupleElementType, tupleIndex) => {
const propertyPaths = extractObjectProperties(tupleElementType, checker, paramType);
return propertyPaths.flatMap(({ path }) => {
const referenceValue: ReferenceValue = {
__typename: "ReferenceValue",
nodeFunctionId: nodeFunctionId as any,
parameterIndex: isNaN(paramIndexFromName) ? 0 : paramIndexFromName,
inputIndex: tupleIndex,
inputTypeIdentifier: (typeReference.target as any).labeledElementDeclarations?.[
tupleIndex
].name.getText(),
};
if (path.length > 0) {
referenceValue.referencePath = path;
}
return referenceValue;
});
});
};
/**
* Processes a flow symbol and creates corresponding reference values.
*
* Flow symbols represent references within data flows. They do not have an associated
* node function ID (it is null) and extract properties that match the expected type.
*
* @param symbolType - The TypeScript type of the symbol
* @param checker - TypeScript TypeChecker for type operations
* @param paramType - The expected parameter type for property matching
* @returns Array of ReferenceValue objects for this flow symbol
*/
const processFlowSymbol = (
symbolType: ts.Type,
checker: ts.TypeChecker,
paramType: ts.Type
): ReferenceValue[] => {
const propertyPaths = extractObjectProperties(symbolType, checker, paramType);
return propertyPaths.flatMap(({ path }) => {
const referenceValue: ReferenceValue = {
__typename: "ReferenceValue",
nodeFunctionId: null,
};
if (path.length > 0) {
referenceValue.referencePath = path;
}
return referenceValue;
});
};
/**
* Decodes an encoded identifier string back to its original form.
*
* The encoding scheme is:
* - ___ → ://
* - __ → /
* - _ → /
*
* @param encoded - The encoded identifier string
* @returns The decoded identifier
*/
const decodeIdentifier = (encoded: string): string => {
return encoded.replace(/___/g, "://").replace(/__/g, "/").replace(/_/g, "/");
};
/**
* Decodes parameter name to extract node function ID and parameter index.
*
* The parameter name format is: p_<rawId>_<paramIndex>
* The rawId is then decoded using decodeIdentifier.
*
* @param name - The parameter symbol name
* @returns Object containing decoded nodeFunctionId and paramIndexFromName
*/
const decodeParameterName = (name: string): { nodeFunctionId: string; paramIndexFromName: number } => {
const idPart = name.replace("p_", "");
const lastUnderscoreIndex = idPart.lastIndexOf("_");
const rawId = idPart.substring(0, lastUnderscoreIndex);
const paramIndexFromName = parseInt(idPart.substring(lastUnderscoreIndex + 1), 10);
const nodeFunctionId = decodeIdentifier(rawId);
return { nodeFunctionId, paramIndexFromName };
};
/**
* Maximum property depth for reference path extraction through recursive data
* types. Only applies to types that participate in a reference cycle: the
* visited set keeps each individual branch finite, but a cluster of mutually
* recursive types still allows combinatorially many simple paths, so those are
* additionally depth-capped. Non-recursive nesting is traversed exhaustively.
*/
const MAX_REFERENCE_DEPTH = 7;
/**
* Determines whether an object type participates in a reference cycle, i.e. can
* reach itself again through its (non-nullable) property types. Results are
* memoized in the given cache since the same named types repeat throughout a
* traversal. The DFS itself is guarded by its own seen set, so it terminates on
* cycles that do not lead back to the start type.
*/
const isRecursiveType = (
type: ts.Type,
checker: ts.TypeChecker,
cache: Map<ts.Type, boolean>
): boolean => {
const cached = cache.get(type);
if (cached !== undefined) return cached;
const seen = new Set<ts.Type>();
const reachesStart = (current: ts.Type): boolean => {
if (seen.has(current) || !isRealObjectType(current)) return false;
seen.add(current);
for (const property of current.getProperties()) {
if (!property.valueDeclaration) continue;
const propType = checker.getNonNullableType(
checker.getTypeOfSymbolAtLocation(property, property.valueDeclaration)
);
if (propType === type || reachesStart(propType)) return true;
}
return false;
};
const result = reachesStart(type);
cache.set(type, result);
return result;
};
/**
* Recursively extracts object properties from a type that match an expected type.
*
* This function performs a depth-first traversal of an object's property tree. It collects
* all paths (property chains) where the type at that path is assignable to the expected type.
* For example, if type is {a: {b: string}} and expectedType is string, it returns the path [a, b].
*
* The recursion continues into nested object properties, building up the path as it traverses.
* Primitive types (string, number, boolean, etc.) are treated as leaf nodes.
*
* @param type - The type to extract properties from
* @param checker - TypeScript TypeChecker for type comparison operations
* @param expectedType - The target type to match when extracting properties
* @param currentPath - The current property path being built during recursion (default: empty array)
* @param visited - Object types already on the current traversal branch, used to break cycles in recursive data types
* @param recursionCache - Memoization cache for isRecursiveType, shared across the whole traversal
* @returns An array of objects containing the property path and the type at that path
*
* @example
* // For type {user: {name: string, age: number}} with expectedType = string
* // Returns: [{path: [{path: 'user'}, {path: 'name'}], type: stringType}]
*/
const extractObjectProperties = (
type: ts.Type,
checker: ts.TypeChecker,
expectedType: ts.Type,
currentPath: ReferencePath[] = [],
visited: Set<ts.Type> = new Set(),
recursionCache: Map<ts.Type, boolean> = new Map()
): Array<{ path: ReferencePath[]; type: ts.Type }> => {
const results: Array<{ path: ReferencePath[]; type: ts.Type }> = [];
// Check if the current type matches the expected type. The nullish part of a
// candidate is ignored: a reference typed `string | null` (or an optional
// property `text?: string | null`) is still a valid suggestion for a plain
// `string` parameter — strict assignability would reject it under strictNullChecks.
// A purely nullish candidate strips down to `never` (assignable to anything),
// so it must be excluded explicitly.
const nonNullableType = checker.getNonNullableType(type);
if (
(nonNullableType.flags & ts.TypeFlags.Never) === 0 &&
checker.isTypeAssignableTo(nonNullableType, expectedType)
) {
results.push({ path: currentPath, type });
}
// Recursively traverse into object properties. Traversal also runs on the
// non-nullable type: a nullable object in the chain (e.g. `{bla?: TEXT} | null`)
// is a union whose getProperties() is empty, which would cut off all nested paths.
// Recursive data types (e.g. Order.delivery.order) are cut off via the visited
// set — the checker caches type identities, so a cycle revisits the same ts.Type
// object. The set only tracks the current branch (backtracked below) so the same
// type may still appear on sibling paths. The depth cap only applies to types
// that are part of a reference cycle (checked last, it's the expensive test);
// purely nested non-recursive objects are traversed to arbitrary depth.
if (
isRealObjectType(nonNullableType) &&
!visited.has(nonNullableType) &&
(currentPath.length < MAX_REFERENCE_DEPTH ||
!isRecursiveType(nonNullableType, checker, recursionCache))
) {
const properties = nonNullableType.getProperties();
if (properties && properties.length > 0) {
visited.add(nonNullableType);
properties.forEach((property) => {
const propType = checker.getTypeOfSymbolAtLocation(property, property.valueDeclaration!);
const propName = property.getName();
const newPath = [...currentPath, { path: propName }];
// Recurse into nested properties
results.push(...extractObjectProperties(propType, checker, expectedType, newPath, visited, recursionCache));
});
visited.delete(nonNullableType);
}
}
return results;
};
/**
* Determines whether a type is a real object type or a primitive.
*
* This function checks if a type is NOT one of the primitive types (string, number, boolean,
* undefined, null, bigint, symbol). Any type that is not a primitive is considered a real object type.
*
* @param type - The type to check
* @returns True if the type is a real object type, false if it's a primitive type
*
* @example
* isRealObjectType(stringType) // false
* isRealObjectType(objectType) // true
* isRealObjectType(numberType) // false
*/
const isRealObjectType = (type: ts.Type): boolean => {
const primitiveFlags =
ts.TypeFlags.String |
ts.TypeFlags.Number |
ts.TypeFlags.Boolean |
ts.TypeFlags.Undefined |
ts.TypeFlags.Null |
ts.TypeFlags.BigInt |
ts.TypeFlags.ESSymbol;
return (type.flags & primitiveFlags) === 0;
};