Open History to see the last commit
1import * as babel from '@babel/core'
2import { isIdentifier, isVariableDeclarator } from '@babel/types'
3import { codeFrameColumns } from '@babel/code-frame'
4import {
5 deadCodeElimination,
6 findReferencedIdentifiers,
7} from 'babel-dead-code-elimination'
8import path from 'pathe'
9import { generateFromAst, parseAst } from '@tanstack/router-utils'
10import type { GeneratorResult, ParseAstOptions } from '@tanstack/router-utils'
11β
12export interface DirectiveFn {
13 nodePath: SupportedFunctionPath
14 functionName: string
15 functionId: string
16 extractedFilename: string
17 filename: string
18 chunkName: string
19}
20β
21export type SupportedFunctionPath =
22 | babel.NodePath<babel.types.FunctionDeclaration>
23 | babel.NodePath<babel.types.FunctionExpression>
24 | babel.NodePath<babel.types.ArrowFunctionExpression>
25β
26export type GenerateFunctionIdFn = (opts: {
27 filename: string
28 functionName: string
29 extractedFilename: string
30}) => string
31β
32export type ReplacerFn = (opts: {
33 fn: string
34 extractedFilename: string
35 filename: string
36 functionId: string
37 isSourceFn: boolean
38}) => string
39β
40// const debug = process.env.TSR_VITE_DEBUG === 'true'
41β
42export type CompileDirectivesOpts = ParseAstOptions & {
43 directive: string
44 directiveLabel: string
45 getRuntimeCode?: (opts: {
46 directiveFnsById: Record<string, DirectiveFn>
47 }) => string
48 generateFunctionId: GenerateFunctionIdFn
49 replacer: ReplacerFn
50 filename: string
51 root: string
52}
53β
54function buildDirectiveSplitParam(opts: CompileDirectivesOpts) {
55 return `tsr-directive-${opts.directive.replace(/[^a-zA-Z0-9]/g, '-')}`
56}
57β
58export function compileDirectives(opts: CompileDirectivesOpts): {
59 compiledResult: GeneratorResult
60 directiveFnsById: Record<string, DirectiveFn>
61 isDirectiveSplitParam: boolean
62} {
63 const directiveSplitParam = buildDirectiveSplitParam(opts)
64 const isDirectiveSplitParam = opts.filename.includes(directiveSplitParam)
65β
66 const ast = parseAst(opts)
67 const refIdents = findReferencedIdentifiers(ast)
68 const directiveFnsById = findDirectives(ast, {
69 ...opts,
70 directiveSplitParam,
71 isDirectiveSplitParam,
72 })
73β
74 // Add runtime code if there are directives
75 if (Object.keys(directiveFnsById).length > 0) {
76 if (opts.getRuntimeCode) {
77 const runtimeImport = babel.template.statement(
78 opts.getRuntimeCode({ directiveFnsById }),
79 )()
80 ast.program.body.unshift(runtimeImport)
81 }
82 }
83β
84 // If we are in the source file, we need to remove all exports
85 // then make sure that all of our functions are exported under their
86 // directive name
87 if (isDirectiveSplitParam) {
88 safeRemoveExports(ast)
89β
90 // Export a single object with all of the functions
91 // e.g. export { directiveFn1, directiveFn2 }
92 ast.program.body.push(
93 babel.types.exportNamedDeclaration(
94 undefined,
95 Object.values(directiveFnsById).map((fn) =>
96 babel.types.exportSpecifier(
97 babel.types.identifier(fn.functionName),
98 babel.types.identifier(fn.functionName),
99 ),
100 ),
101 ),
102 )
103 }
104β
105 deadCodeElimination(ast, refIdents)
106β
107 const compiledResult = generateFromAst(ast, {
108 sourceMaps: true,
109 sourceFileName: opts.filename,
110 filename: opts.filename,
111 })
112β
113 return {
114 compiledResult,
115 directiveFnsById,
116 isDirectiveSplitParam,
117 }
118}
119β
120function findNearestVariableName(
121 path: babel.NodePath,
122 directiveLabel: string,
123): string {
124 let currentPath: babel.NodePath | null = path
125 const nameParts: Array<string> = []
126β
127 while (currentPath) {
128 const name = (() => {
129 // Check for named function expression
130 if (
131 babel.types.isFunctionExpression(currentPath.node) &&
132 currentPath.node.id
133 ) {
134 return currentPath.node.id.name
135 }
136β
137 // Handle method chains
138 if (babel.types.isCallExpression(currentPath.node)) {
139 const current = currentPath.node.callee
140 const chainParts: Array<string> = []
141β
142 // Get the nearest method name (if it's a method call)
143 if (babel.types.isMemberExpression(current)) {
144 if (babel.types.isIdentifier(current.property)) {
145 chainParts.unshift(current.property.name)
146 }
147β
148 // Get the base callee
149 let base = current.object
150 while (!babel.types.isIdentifier(base)) {
151 if (babel.types.isCallExpression(base)) {
152 base = base.callee as babel.types.Expression
153 } else if (babel.types.isMemberExpression(base)) {
154 base = base.object
155 } else {
156 break
157 }
158 }
159 if (babel.types.isIdentifier(base)) {
160 chainParts.unshift(base.name)
161 }
162 } else if (babel.types.isIdentifier(current)) {
163 chainParts.unshift(current.name)
164 }
165β
166 if (chainParts.length > 0) {
167 return chainParts.join('_')
168 }
169 }
170β
171 // Rest of the existing checks...
172 if (babel.types.isFunctionDeclaration(currentPath.node)) {
173 return currentPath.node.id?.name
174 }
175β
176 if (babel.types.isIdentifier(currentPath.node)) {
177 return currentPath.node.name
178 }
179β
180 if (
181 isVariableDeclarator(currentPath.node) &&
182 isIdentifier(currentPath.node.id)
183 ) {
184 return currentPath.node.id.name
185 }
186β
187 if (
188 babel.types.isClassMethod(currentPath.node) ||
189 babel.types.isObjectMethod(currentPath.node)
190 ) {
191 throw new Error(
192 `${directiveLabel} in ClassMethod or ObjectMethod not supported`,
193 )
194 }
195β
196 return ''
197 })()
198β
199 if (name) {
200 nameParts.unshift(name)
201 }
202β
203 currentPath = currentPath.parentPath
204 }
205β
206 return nameParts.length > 0 ? nameParts.join('_') : 'anonymous'
207}
208β
209function makeIdentifierSafe(identifier: string): string {
210 return identifier
211 .replace(/[^a-zA-Z0-9_$]/g, '_') // Replace unsafe chars with underscore
212 .replace(/^[0-9]/, '_$&') // Prefix leading number with underscore
213 .replace(/^\$/, '_$') // Prefix leading $ with underscore
214 .replace(/_{2,}/g, '_') // Collapse multiple underscores
215 .replace(/^_|_$/g, '') // Trim leading/trailing underscores
216}
217β
218export function findDirectives(
219 ast: babel.types.File,
220 opts: ParseAstOptions & {
221 directive: string
222 directiveLabel: string
223 replacer?: ReplacerFn
224 generateFunctionId: GenerateFunctionIdFn
225 directiveSplitParam: string
226 filename: string
227 root: string
228 isDirectiveSplitParam: boolean
229 },
230): Record<string, DirectiveFn> {
231 const directiveFnsById: Record<string, DirectiveFn> = {}
232 const functionNameSet: Set<string> = new Set()
233β
234 let programPath: babel.NodePath<babel.types.Program>
235β
236 babel.traverse(ast, {
237 Program(path) {
238 programPath = path
239 },
240 })
241β
242 // Does the file have the directive in the program body?
243 const hasFileDirective = ast.program.directives.some(
244 (directive) => directive.value.value === opts.directive,
245 )
246 const compileDirectiveOpts = {
247 isDirectiveSplitParam: opts.isDirectiveSplitParam,
248 }
249β
250 // If the entire file has a directive, we need to compile all of the functions that are
251 // exported by the file.
252 if (hasFileDirective) {
253 // Find all of the exported functions
254 // They must be either function declarations or const function/anonymous function declarations
255 babel.traverse(ast, {
256 ExportDefaultDeclaration(path) {
257 if (babel.types.isFunctionDeclaration(path.node.declaration)) {
258 compileDirective(
259 path.get('declaration') as SupportedFunctionPath,
260 compileDirectiveOpts,
261 )
262 }
263 },
264 ExportNamedDeclaration(path) {
265 if (babel.types.isFunctionDeclaration(path.node.declaration)) {
266 compileDirective(
267 path.get('declaration') as SupportedFunctionPath,
268 compileDirectiveOpts,
269 )
270 }
271 },
272 ExportDeclaration(path) {
273 if (
274 babel.types.isExportNamedDeclaration(path.node) &&
275 babel.types.isVariableDeclaration(path.node.declaration) &&
276 (babel.types.isFunctionExpression(
277 path.node.declaration.declarations[0]?.init,
278 ) ||
279 babel.types.isArrowFunctionExpression(
280 path.node.declaration.declarations[0]?.init,
281 ))
282 ) {
283 compileDirective(
284 path.get(
285 'declaration.declarations.0.init',
286 ) as SupportedFunctionPath,
287 compileDirectiveOpts,
288 )
289 }
290 },
291 })
292 } else {
293 // Find all directives
294 babel.traverse(ast, {
295 DirectiveLiteral(nodePath) {
296 if (nodePath.node.value === opts.directive) {
297 const directiveFn = nodePath.findParent((p) => p.isFunction())
298β
299 if (!directiveFn) return
300β
301 // Handle class and object methods which are not supported
302 const isClassMethod = directiveFn.isClassMethod()
303 const isObjectMethod = directiveFn.isObjectMethod()
304β
305 if (isClassMethod || isObjectMethod) {
306 throw codeFrameError(
307 opts.code,
308 directiveFn.node.loc,
309 `"${opts.directive}" in ${isClassMethod ? 'class' : isObjectMethod ? 'object method' : ''} not supported`,
310 )
311 }
312β
313 // If the function is inside another block that isn't the program,
314 // Error out. This is not supported.
315 const nearestBlock = directiveFn.findParent(
316 (p) => (p.isBlockStatement() || p.isScopable()) && !p.isProgram(),
317 )
318β
319 if (nearestBlock) {
320 throw codeFrameError(
321 opts.code,
322 nearestBlock.node.loc,
323 `${opts.directiveLabel}s cannot be nested in other blocks or functions`,
324 )
325 }
326β
327 if (
328 !directiveFn.isFunctionDeclaration() &&
329 !directiveFn.isFunctionExpression() &&
330 !(
331 directiveFn.isArrowFunctionExpression() &&
332 babel.types.isBlockStatement(directiveFn.node.body)
333 )
334 ) {
335 throw codeFrameError(
336 opts.code,
337 directiveFn.node.loc,
338 `${opts.directiveLabel}s must be function declarations or function expressions`,
339 )
340 }
341β
342 compileDirective(directiveFn, compileDirectiveOpts)
343 }
344 },
345 })
346 }
347β
348 return directiveFnsById
349β
350 function compileDirective(
351 directiveFn: SupportedFunctionPath,
352 compileDirectiveOpts: { isDirectiveSplitParam: boolean },
353 ) {
354 // Move the function to program level while preserving its position
355 // in the program body
356 const programBody = programPath.node.body
357β
358 // Remove the directive directive from the function body
359 if (
360 babel.types.isFunction(directiveFn.node) &&
361 babel.types.isBlockStatement(directiveFn.node.body)
362 ) {
363 directiveFn.node.body.directives =
364 directiveFn.node.body.directives.filter(
365 (directive) => directive.value.value !== opts.directive,
366 )
367 }
368β
369 // if the directive function is a top-level function, we need to create a const declaration
370 // using the same name as the function and replace the function with the variable declaration
371 // that points to the function
372 if (directiveFn.parentPath.isProgram()) {
373 if (!babel.types.isFunctionDeclaration(directiveFn.node)) {
374 throw new Error('Top level functions must be function declarations')
375 }
376β
377 const index = programBody.indexOf(directiveFn.node)
378β
379 // First get the name of the function
380 const originalFunctionName = directiveFn.node.id!.name
381β
382 // Now turn the function into an anonymous function
383 directiveFn.node.id = null
384β
385 const variableDeclaration = babel.types.variableDeclaration('const', [
386 babel.types.variableDeclarator(
387 babel.types.identifier(originalFunctionName),
388 babel.types.toExpression(directiveFn.node as any),
389 ),
390 ])
391β
392 directiveFn.replaceWith(variableDeclaration)
393β
394 directiveFn = programPath.get(
395 `body.${index}.declarations.0.init`,
396 ) as SupportedFunctionPath
397 }
398β
399 // Find the nearest variable name
400 let functionName = findNearestVariableName(directiveFn, opts.directiveLabel)
401β
402 const incrementFunctionNameVersion = (functionName: string) => {
403 const [realReferenceName, count] = functionName.split(/_(\d+)$/)
404 const resolvedCount = Number(count || '0')
405 const suffix = `_${resolvedCount + 1}`
406 return makeIdentifierSafe(realReferenceName!) + suffix
407 }
408β
409 while (functionNameSet.has(functionName)) {
410 functionName = incrementFunctionNameVersion(functionName)
411 }
412β
413 functionNameSet.add(functionName)
414β
415 while (programPath.scope.hasBinding(functionName)) {
416 functionName = incrementFunctionNameVersion(functionName)
417 programPath.scope.crawl()
418 }
419β
420 functionNameSet.add(functionName)
421β
422 const topParent =
423 directiveFn.findParent((p) => !!p.parentPath?.isProgram()) || directiveFn
424β
425 const topParentIndex = programBody.indexOf(topParent.node as any)
426β
427 // If the function has a parent that isn't the program,
428 // we need to replace it with an identifier and
429 // hoist the function to the top level as a const declaration
430 if (directiveFn.parentPath.isProgram()) {
431 throw new Error(
432 'Top level functions should have already been compiled to variable declarations by this point',
433 )
434 }
435 // Then place the function at the top level
436 programBody.splice(
437 topParentIndex,
438 0,
439 babel.types.variableDeclaration('const', [
440 babel.types.variableDeclarator(
441 babel.types.identifier(functionName),
442 babel.types.toExpression(directiveFn.node as any),
443 ),
444 ]),
445 )
446β
447 // If it's an exported named function, we need to swap it with an
448 // export const originalFunctionName = functionName
449 if (
450 (babel.types.isExportNamedDeclaration(directiveFn.parentPath.node) ||
451 (compileDirectiveOpts.isDirectiveSplitParam &&
452 babel.types.isExportDefaultDeclaration(
453 directiveFn.parentPath.node,
454 ))) &&
455 (babel.types.isFunctionDeclaration(directiveFn.node) ||
456 babel.types.isFunctionExpression(directiveFn.node)) &&
457 babel.types.isIdentifier(directiveFn.node.id)
458 ) {
459 const originalFunctionName = directiveFn.node.id.name
460 programBody.splice(
461 topParentIndex + 1,
462 0,
463 babel.types.exportNamedDeclaration(
464 babel.types.variableDeclaration('const', [
465 babel.types.variableDeclarator(
466 babel.types.identifier(originalFunctionName),
467 babel.types.identifier(functionName),
468 ),
469 ]),
470 ),
471 )
472β
473 directiveFn.remove()
474 } else {
475 directiveFn.replaceWith(babel.types.identifier(functionName))
476 }
477β
478 directiveFn = programPath.get(
479 `body.${topParentIndex}.declarations.0.init`,
480 ) as SupportedFunctionPath
481β
482 const [baseFilename, ..._searchParams] = opts.filename.split('?') as [
483 string,
484 ...Array<string>,
485 ]
486 const searchParams = new URLSearchParams(_searchParams.join('&'))
487 searchParams.set(opts.directiveSplitParam, '')
488β
489 const extractedFilename = `${baseFilename}?${searchParams.toString()}`
490β
491 // Relative to have constant functionId regardless of the machine
492 // that we are executing
493 const relativeFilename = path.relative(opts.root, baseFilename)
494 const functionId = opts.generateFunctionId({
495 filename: relativeFilename,
496 functionName,
497 extractedFilename,
498 })
499 // If a replacer is provided, replace the function with the replacer
500 if (opts.replacer) {
501 const replacer = opts.replacer({
502 fn: '$$fn$$',
503 extractedFilename,
504 filename: opts.filename,
505 functionId,
506 isSourceFn: !!opts.directiveSplitParam,
507 })
508β
509 const replacement = babel.template.expression(replacer, {
510 placeholderPattern: false,
511 placeholderWhitelist: new Set(['$$fn$$']),
512 })({
513 ...(replacer.includes('$$fn$$')
514 ? { $$fn$$: babel.types.toExpression(directiveFn.node) }
515 : {}),
516 })
517β
518 directiveFn.replaceWith(replacement)
519 }
520β
521 // Finally register the directive to
522 // our map of directives
523 directiveFnsById[functionId] = {
524 nodePath: directiveFn,
525 functionName,
526 functionId,
527 extractedFilename,
528 filename: opts.filename,
529 chunkName: fileNameToChunkName(opts.root, extractedFilename),
530 }
531 }
532}
533β
534function codeFrameError(
535 code: string,
536 loc:
537 | {
538 start: { line: number; column: number }
539 end: { line: number; column: number }
540 }
541 | undefined
542 | null,
543 message: string,
544) {
545 if (!loc) {
546 return new Error(`${message} at unknown location`)
547 }
548β
549 const frame = codeFrameColumns(
550 code,
551 {
552 start: loc.start,
553 end: loc.end,
554 },
555 {
556 highlightCode: true,
557 message,
558 },
559 )
560β
561 return new Error(frame)
562}
563β
564const safeRemoveExports = (ast: babel.types.File) => {
565 ast.program.body = ast.program.body.flatMap((node) => {
566 if (
567 babel.types.isExportNamedDeclaration(node) ||
568 babel.types.isExportDefaultDeclaration(node)
569 ) {
570 if (
571 babel.types.isFunctionDeclaration(node.declaration) ||
572 babel.types.isClassDeclaration(node.declaration) ||
573 babel.types.isVariableDeclaration(node.declaration)
574 ) {
575 // do not remove export if it is an anonymous function / class, otherwise this would produce a syntax error
576 if (
577 babel.types.isFunctionDeclaration(node.declaration) ||
578 babel.types.isClassDeclaration(node.declaration)
579 ) {
580 if (!node.declaration.id) {
581 return node
582 }
583 }
584 return node.declaration
585 } else if (node.declaration === null) {
586 // remove e.g. `export { RouteComponent as component }`
587 return []
588 }
589 }
590 return node
591 })
592}
593β
594function fileNameToChunkName(root: string, fileName: string) {
595 // Replace anything that can't go into an import statement
596 return fileName.replace(root, '').replace(/[^a-zA-Z0-9_]/g, '_')
597}