forked from colbymchenry/codegraph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsvelte.ts
More file actions
279 lines (246 loc) · 8.05 KB
/
Copy pathsvelte.ts
File metadata and controls
279 lines (246 loc) · 8.05 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
/**
* Svelte / SvelteKit Framework Resolver
*
* Handles Svelte component references, Svelte 5 runes,
* store auto-subscriptions, and SvelteKit route/module patterns.
*/
import { Node } from '../../types';
import { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from '../types';
/**
* Svelte 5 runes — compiler-provided, not user code
*/
const SVELTE_RUNES = new Set([
'$state',
'$state.raw',
'$state.snapshot',
'$derived',
'$derived.by',
'$effect',
'$effect.pre',
'$effect.root',
'$effect.tracking',
'$props',
'$bindable',
'$inspect',
'$host',
]);
/**
* SvelteKit framework-provided module prefixes
*/
const SVELTEKIT_MODULE_PREFIXES = [
'$app/navigation',
'$app/stores',
'$app/environment',
'$app/forms',
'$app/paths',
'$env/static/private',
'$env/static/public',
'$env/dynamic/private',
'$env/dynamic/public',
];
export const svelteResolver: FrameworkResolver = {
name: 'svelte',
languages: ['svelte'],
detect(context: ResolutionContext): boolean {
// Check for svelte or @sveltejs/kit in package.json
const packageJson = context.readFile('package.json');
if (packageJson) {
try {
const pkg = JSON.parse(packageJson);
const deps = { ...pkg.dependencies, ...pkg.devDependencies };
if (deps.svelte || deps['@sveltejs/kit']) {
return true;
}
} catch {
// Invalid JSON
}
}
// Check for .svelte files in project
const allFiles = context.getAllFiles();
return allFiles.some((f) => f.endsWith('.svelte'));
},
resolve(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null {
// Pattern 1: Svelte runes ($state, $derived, $effect, etc.)
if (isRuneReference(ref.referenceName)) {
// Runes are compiler-provided — return a high-confidence "framework" resolution
// so CodeGraph doesn't waste time searching for user-defined symbols.
// We use the fromNodeId as targetNodeId since runes don't have real targets.
return {
original: ref,
targetNodeId: ref.fromNodeId,
confidence: 1.0,
resolvedBy: 'framework',
};
}
// Pattern 2: Store auto-subscriptions ($storeName)
if (ref.referenceName.startsWith('$') && !ref.referenceName.startsWith('$$')) {
const storeName = ref.referenceName.substring(1);
const storeNode = context.getNodesByName(storeName).find(
(n) => n.kind === 'variable' || n.kind === 'constant'
);
if (storeNode) {
return {
original: ref,
targetNodeId: storeNode.id,
confidence: 0.85,
resolvedBy: 'framework',
};
}
}
// Pattern 3: SvelteKit module imports ($app/*, $env/*, $lib/*)
if (ref.referenceKind === 'imports' && ref.referenceName.startsWith('$')) {
// $lib/* resolves to src/lib/* — try to find the target file
if (ref.referenceName.startsWith('$lib/')) {
const libPath = ref.referenceName.replace('$lib/', 'src/lib/');
// Try common extensions
for (const ext of ['', '.ts', '.js', '.svelte', '/index.ts', '/index.js']) {
const fullPath = libPath + ext;
if (context.fileExists(fullPath)) {
const nodes = context.getNodesInFile(fullPath);
if (nodes.length > 0) {
return {
original: ref,
targetNodeId: nodes[0]!.id,
confidence: 0.9,
resolvedBy: 'framework',
};
}
}
}
}
// $app/* and $env/* are framework-provided
if (SVELTEKIT_MODULE_PREFIXES.some((prefix) => ref.referenceName.startsWith(prefix))) {
return {
original: ref,
targetNodeId: ref.fromNodeId,
confidence: 1.0,
resolvedBy: 'framework',
};
}
}
// Pattern 4: Component references (PascalCase) — resolve to .svelte files
if (isPascalCase(ref.referenceName) && ref.referenceKind === 'calls') {
const result = resolveComponent(ref.referenceName, ref.filePath, context);
if (result) {
return {
original: ref,
targetNodeId: result,
confidence: 0.8,
resolvedBy: 'framework',
};
}
}
return null;
},
extract(filePath, _content) {
const nodes: Node[] = [];
const now = Date.now();
// Detect SvelteKit route files
const fileName = filePath.split(/[/\\]/).pop() || '';
const routeMatch = getSvelteKitRouteInfo(fileName);
if (routeMatch) {
// Extract route path from directory structure
// e.g., src/routes/blog/[slug]/+page.svelte -> /blog/:slug
const routePath = filePathToSvelteKitRoute(filePath);
if (routePath) {
nodes.push({
id: `route:${filePath}:${routePath}:1`,
kind: 'route',
name: routePath,
qualifiedName: `${filePath}::route:${routePath}`,
filePath,
startLine: 1,
endLine: 1,
startColumn: 0,
endColumn: 0,
language: filePath.endsWith('.svelte') ? 'svelte' : 'typescript',
updatedAt: now,
});
}
}
return { nodes, references: [] };
},
};
/**
* Check if a reference name is a Svelte rune
*/
function isRuneReference(name: string): boolean {
// Direct match (e.g. $state, $derived)
if (SVELTE_RUNES.has(name)) return true;
// Rune method calls come through as the base rune name
// e.g. $state.raw -> the call is to "$state" with ".raw" accessed as property
// Check if it's a base rune that has sub-methods
if (name === '$state' || name === '$derived' || name === '$effect') return true;
return false;
}
/**
* Check if string is PascalCase
*/
function isPascalCase(str: string): boolean {
return /^[A-Z][a-zA-Z0-9]*$/.test(str);
}
/**
* Resolve a Svelte component reference using name-based lookup
*/
function resolveComponent(
name: string,
fromFile: string,
context: ResolutionContext
): string | null {
// Look for component nodes by name
const candidates = context.getNodesByName(name);
const components = candidates.filter((n) => n.kind === 'component');
if (components.length === 0) return null;
// Prefer same directory
const fromDir = fromFile.substring(0, fromFile.lastIndexOf('/'));
const sameDir = components.filter((n) => n.filePath.startsWith(fromDir));
if (sameDir.length > 0) return sameDir[0]!.id;
return components[0]!.id;
}
/**
* SvelteKit route file patterns
*/
const SVELTEKIT_ROUTE_FILES: Record<string, string> = {
'+page.svelte': 'page',
'+page.ts': 'page-load',
'+page.js': 'page-load',
'+page.server.ts': 'page-server-load',
'+page.server.js': 'page-server-load',
'+layout.svelte': 'layout',
'+layout.ts': 'layout-load',
'+layout.js': 'layout-load',
'+layout.server.ts': 'layout-server-load',
'+layout.server.js': 'layout-server-load',
'+server.ts': 'api-endpoint',
'+server.js': 'api-endpoint',
'+error.svelte': 'error-page',
};
/**
* Check if filename is a SvelteKit route file
*/
function getSvelteKitRouteInfo(fileName: string): string | null {
return SVELTEKIT_ROUTE_FILES[fileName] || null;
}
/**
* Convert a file path to a SvelteKit route path
*/
function filePathToSvelteKitRoute(filePath: string): string | null {
// Normalize to forward slashes
const normalized = filePath.replace(/\\/g, '/');
// Find the routes directory
const routesIndex = normalized.indexOf('/routes/');
if (routesIndex === -1) return null;
// Extract the path after routes/
const afterRoutes = normalized.substring(routesIndex + '/routes/'.length);
// Remove the file name
const lastSlash = afterRoutes.lastIndexOf('/');
const dirPath = lastSlash === -1 ? '' : afterRoutes.substring(0, lastSlash);
// Convert SvelteKit param syntax [param] to :param
let route = '/' + dirPath
.replace(/\[\.\.\.([^\]]+)\]/g, '*$1') // [...rest] -> *rest
.replace(/\[{2}([^\]]+)\]{2}/g, ':$1?') // [[optional]] -> :optional?
.replace(/\[([^\]]+)\]/g, ':$1'); // [param] -> :param
if (route === '/') return '/';
// Remove trailing slash
return route.replace(/\/$/, '');
}