import * as babel from '@babel/core' import { isIdentifier, isVariableDeclarator } from '@babel/types' import { codeFrameColumns } from '@babel/code-frame' import { deadCodeElimination, findReferencedIdentifiers, } from 'babel-dead-code-elimination' import path from 'pathe' import { generateFromAst, parseAst } from '@tanstack/router-utils' import type { GeneratorResult, ParseAstOptions } from '@tanstack/router-utils' export interface DirectiveFn { nodePath: SupportedFunctionPath functionName: string functionId: string extractedFilename: string filename: string chunkName: string /** * True when this function was discovered by the client build. * Used to restrict HTTP access to only client-referenced functions. */ isClientReferenced?: boolean } export type SupportedFunctionPath = | babel.NodePath | babel.NodePath | babel.NodePath export type GenerateFunctionIdFn = (opts: { filename: string functionName: string extractedFilename: string }) => string export type ReplacerFn = (opts: { fn: string extractedFilename: string filename: string functionId: string functionName: string isSourceFn: boolean /** * True when this function was already discovered by a previous build (e.g., client). * For SSR callers, this means the function is in the manifest and doesn't need * an importer - the manifest lookup will find it. */ isClientReferenced: boolean }) => string // const debug = process.env.TSR_VITE_DEBUG === 'true' export type CompileDirectivesOpts = ParseAstOptions & { directive: string getRuntimeCode?: (opts: { directiveFnsById: Record }) => string generateFunctionId: GenerateFunctionIdFn replacer: ReplacerFn filename: string root: string isDirectiveSplitParam: boolean directiveSplitParam: string /** * Previously discovered directive functions from other builds (e.g., client build). * When provided, the compiler will use the canonical extractedFilename from this * registry instead of computing it locally. This ensures SSR callers import from * the same extracted file as the client. */ knownDirectiveFns?: Record /** * Whether the current environment is a client environment. * Functions discovered in client environments are always client-referenced. */ isClientEnvironment?: boolean } export function compileDirectives(opts: CompileDirectivesOpts): { compiledResult: GeneratorResult directiveFnsById: Record } { const ast = parseAst(opts) const refIdents = findReferencedIdentifiers(ast) const directiveFnsById = findDirectives(ast, { ...opts, directiveSplitParam: opts.directiveSplitParam, isDirectiveSplitParam: opts.isDirectiveSplitParam, }) // Add runtime code if there are directives if (Object.keys(directiveFnsById).length > 0) { if (opts.getRuntimeCode) { const runtimeImport = babel.template.statement( opts.getRuntimeCode({ directiveFnsById }), )() ast.program.body.unshift(runtimeImport) } } // If we are in the source file, we need to remove all exports // then make sure that all of our functions are exported under their // directive name if (opts.isDirectiveSplitParam) { safeRemoveExports(ast) // Export a single object with all of the functions // e.g. export { directiveFn1, directiveFn2 } ast.program.body.push( babel.types.exportNamedDeclaration( undefined, Object.values(directiveFnsById).map((fn) => babel.types.exportSpecifier( babel.types.identifier(fn.functionName), babel.types.identifier(fn.functionName), ), ), ), ) } deadCodeElimination(ast, refIdents) const compiledResult = generateFromAst(ast, { sourceMaps: true, sourceFileName: opts.filename, filename: opts.filename, }) return { compiledResult, directiveFnsById, } } function findNearestVariableName( path: babel.NodePath, directive: string, ): string { let currentPath: babel.NodePath | null = path const nameParts: Array = [] while (currentPath) { const name = (() => { // Check for named function expression if ( babel.types.isFunctionExpression(currentPath.node) && currentPath.node.id ) { return currentPath.node.id.name } // Handle method chains if (babel.types.isCallExpression(currentPath.node)) { const current = currentPath.node.callee const chainParts: Array = [] // Get the nearest method name (if it's a method call) if (babel.types.isMemberExpression(current)) { if (babel.types.isIdentifier(current.property)) { chainParts.unshift(current.property.name) } // Get the base callee let base = current.object while (!babel.types.isIdentifier(base)) { if (babel.types.isCallExpression(base)) { base = base.callee as babel.types.Expression } else if (babel.types.isMemberExpression(base)) { base = base.object } else { break } } if (babel.types.isIdentifier(base)) { chainParts.unshift(base.name) } } else if (babel.types.isIdentifier(current)) { chainParts.unshift(current.name) } if (chainParts.length > 0) { return chainParts.join('_') } } // Rest of the existing checks... if (babel.types.isFunctionDeclaration(currentPath.node)) { return currentPath.node.id?.name } if (babel.types.isIdentifier(currentPath.node)) { return currentPath.node.name } if ( isVariableDeclarator(currentPath.node) && isIdentifier(currentPath.node.id) ) { return currentPath.node.id.name } if ( babel.types.isClassMethod(currentPath.node) || babel.types.isObjectMethod(currentPath.node) ) { throw new Error( `"${directive}" in ClassMethod or ObjectMethod not supported`, ) } return '' })() if (name) { nameParts.unshift(name) } currentPath = currentPath.parentPath } return nameParts.length > 0 ? nameParts.join('_') : 'anonymous' } function makeIdentifierSafe(identifier: string): string { return identifier .replace(/[^a-zA-Z0-9_$]/g, '_') // Replace unsafe chars with underscore .replace(/^[0-9]/, '_$&') // Prefix leading number with underscore .replace(/^\$/, '_$') // Prefix leading $ with underscore .replace(/_{2,}/g, '_') // Collapse multiple underscores .replace(/^_|_$/g, '') // Trim leading/trailing underscores } export function findDirectives( ast: babel.types.File, opts: ParseAstOptions & { directive: string replacer?: ReplacerFn generateFunctionId: GenerateFunctionIdFn directiveSplitParam: string filename: string root: string isDirectiveSplitParam: boolean knownDirectiveFns?: Record isClientEnvironment?: boolean }, ): Record { const directiveFnsById: Record = {} const functionNameSet: Set = new Set() let programPath: babel.NodePath babel.traverse(ast, { Program(path) { programPath = path }, }) // Does the file have the directive in the program body? const hasFileDirective = ast.program.directives.some( (directive) => directive.value.value === opts.directive, ) const compileDirectiveOpts = { isDirectiveSplitParam: opts.isDirectiveSplitParam, } // If the entire file has a directive, we need to compile all of the functions that are // exported by the file. if (hasFileDirective) { // Find all of the exported functions // They must be either function declarations or const function/anonymous function declarations babel.traverse(ast, { ExportDefaultDeclaration(path) { if (babel.types.isFunctionDeclaration(path.node.declaration)) { compileDirective( path.get('declaration') as SupportedFunctionPath, compileDirectiveOpts, ) } }, ExportNamedDeclaration(path) { if (babel.types.isFunctionDeclaration(path.node.declaration)) { compileDirective( path.get('declaration') as SupportedFunctionPath, compileDirectiveOpts, ) } }, ExportDeclaration(path) { if ( babel.types.isExportNamedDeclaration(path.node) && babel.types.isVariableDeclaration(path.node.declaration) && (babel.types.isFunctionExpression( path.node.declaration.declarations[0]?.init, ) || babel.types.isArrowFunctionExpression( path.node.declaration.declarations[0]?.init, )) ) { compileDirective( path.get( 'declaration.declarations.0.init', ) as SupportedFunctionPath, compileDirectiveOpts, ) } }, }) } else { // Find all directives babel.traverse(ast, { DirectiveLiteral(nodePath) { if (nodePath.node.value === opts.directive) { const directiveFn = nodePath.findParent((p) => p.isFunction()) if (!directiveFn) return // Handle class and object methods which are not supported const isClassMethod = directiveFn.isClassMethod() const isObjectMethod = directiveFn.isObjectMethod() if (isClassMethod || isObjectMethod) { throw codeFrameError( opts.code, directiveFn.node.loc, `"${opts.directive}" in ${isClassMethod ? 'class' : isObjectMethod ? 'object method' : ''} not supported`, ) } // If the function is inside another block that isn't the program, // Error out. This is not supported. const nearestBlock = directiveFn.findParent( (p) => (p.isBlockStatement() || p.isScopable()) && !p.isProgram(), ) if (nearestBlock) { throw codeFrameError( opts.code, nearestBlock.node.loc, `"${opts.directive}" cannot be nested in other blocks or functions`, ) } if ( !directiveFn.isFunctionDeclaration() && !directiveFn.isFunctionExpression() && !( directiveFn.isArrowFunctionExpression() && babel.types.isBlockStatement(directiveFn.node.body) ) ) { throw codeFrameError( opts.code, directiveFn.node.loc, `"${opts.directive}" must be function declarations or function expressions`, ) } compileDirective(directiveFn, compileDirectiveOpts) } }, }) } return directiveFnsById function compileDirective( directiveFn: SupportedFunctionPath, compileDirectiveOpts: { isDirectiveSplitParam: boolean }, ) { // Move the function to program level while preserving its position // in the program body const programBody = programPath.node.body // Remove the directive directive from the function body if ( babel.types.isFunction(directiveFn.node) && babel.types.isBlockStatement(directiveFn.node.body) ) { directiveFn.node.body.directives = directiveFn.node.body.directives.filter( (directive) => directive.value.value !== opts.directive, ) } // if the directive function is a top-level function, we need to create a const declaration // using the same name as the function and replace the function with the variable declaration // that points to the function if (directiveFn.parentPath.isProgram()) { if (!babel.types.isFunctionDeclaration(directiveFn.node)) { throw new Error('Top level functions must be function declarations') } const index = programBody.indexOf(directiveFn.node) // First get the name of the function const originalFunctionName = directiveFn.node.id!.name // Now turn the function into an anonymous function directiveFn.node.id = null const variableDeclaration = babel.types.variableDeclaration('const', [ babel.types.variableDeclarator( babel.types.identifier(originalFunctionName), babel.types.toExpression(directiveFn.node as any), ), ]) directiveFn.replaceWith(variableDeclaration) directiveFn = programPath.get( `body.${index}.declarations.0.init`, ) as SupportedFunctionPath } // Find the nearest variable name let functionName = findNearestVariableName(directiveFn, opts.directive) const incrementFunctionNameVersion = (functionName: string) => { const [realReferenceName, count] = functionName.split(/_(\d+)$/) const resolvedCount = Number(count || '0') const suffix = `_${resolvedCount + 1}` return makeIdentifierSafe(realReferenceName!) + suffix } while (functionNameSet.has(functionName)) { functionName = incrementFunctionNameVersion(functionName) } functionNameSet.add(functionName) while (programPath.scope.hasBinding(functionName)) { functionName = incrementFunctionNameVersion(functionName) programPath.scope.crawl() } functionNameSet.add(functionName) // Use functionId to determine if this is a client-referenced function const [baseFilename, ..._searchParams] = opts.filename.split('?') as [ string, ...Array, ] const searchParams = new URLSearchParams(_searchParams.join('&')) searchParams.set(opts.directiveSplitParam, '') const localExtractedFilename = `${baseFilename}?${searchParams.toString()}` // Relative to have constant functionId regardless of the machine // that we are executing const relativeFilename = path.relative(opts.root, baseFilename) const functionId = opts.generateFunctionId({ filename: relativeFilename, functionName, extractedFilename: localExtractedFilename, }) // Use the canonical extracted filename from knownDirectiveFns if available. // This ensures SSR callers import from the same extracted file as the client, // avoiding duplicate chunks with the same server function. const knownFn = opts.knownDirectiveFns?.[functionId] const extractedFilename = knownFn?.extractedFilename ?? localExtractedFilename // A function is client-referenced if: // 1. It was discovered by the client environment (isClientEnvironment), OR // 2. It was already known from a previous (client) build (knownFn exists) const isClientReferenced = opts.isClientEnvironment || !!knownFn // For client-referenced functions in SSR caller files (not extracted files), // we remove the second argument of .handler() because: // 1. The RPC stub uses manifest lookup, which provides the implementation // 2. The full implementation shouldn't be in the caller file // We do this BEFORE hoisting/replacing to ensure we can still access the parent structure if (isClientReferenced && !compileDirectiveOpts.isDirectiveSplitParam) { // Find if this directive function is inside a .handler() call expression // The structure is: .handler(directiveFn, originalImpl) // We want to remove originalImpl (the second argument) let currentPath: babel.NodePath | null = directiveFn as babel.NodePath | null while (currentPath && !currentPath.parentPath?.isProgram()) { const parent: babel.NodePath | null = currentPath.parentPath if ( parent?.isCallExpression() && babel.types.isMemberExpression(parent.node.callee) && babel.types.isIdentifier(parent.node.callee.property) && parent.node.callee.property.name === 'handler' && parent.node.arguments.length === 2 ) { // Remove the second argument (the original implementation) parent.node.arguments.pop() break } currentPath = parent } } const topParent = directiveFn.findParent((p) => !!p.parentPath?.isProgram()) || directiveFn const topParentIndex = programBody.indexOf(topParent.node as any) // If the function has a parent that isn't the program, // we need to replace it with an identifier and // hoist the function to the top level as a const declaration if (directiveFn.parentPath.isProgram()) { throw new Error( 'Top level functions should have already been compiled to variable declarations by this point', ) } // Then place the function at the top level programBody.splice( topParentIndex, 0, babel.types.variableDeclaration('const', [ babel.types.variableDeclarator( babel.types.identifier(functionName), babel.types.toExpression(directiveFn.node as any), ), ]), ) // If it's an exported named function, we need to swap it with an // export const originalFunctionName = functionName if ( (babel.types.isExportNamedDeclaration(directiveFn.parentPath.node) || (compileDirectiveOpts.isDirectiveSplitParam && babel.types.isExportDefaultDeclaration( directiveFn.parentPath.node, ))) && (babel.types.isFunctionDeclaration(directiveFn.node) || babel.types.isFunctionExpression(directiveFn.node)) && babel.types.isIdentifier(directiveFn.node.id) ) { const originalFunctionName = directiveFn.node.id.name programBody.splice( topParentIndex + 1, 0, babel.types.exportNamedDeclaration( babel.types.variableDeclaration('const', [ babel.types.variableDeclarator( babel.types.identifier(originalFunctionName), babel.types.identifier(functionName), ), ]), ), ) directiveFn.remove() } else { directiveFn.replaceWith(babel.types.identifier(functionName)) } directiveFn = programPath.get( `body.${topParentIndex}.declarations.0.init`, ) as SupportedFunctionPath // If a replacer is provided, replace the function with the replacer if (opts.replacer) { const replacer = opts.replacer({ fn: '$$fn$$', extractedFilename, filename: opts.filename, functionId, functionName, isSourceFn: !!opts.directiveSplitParam, isClientReferenced, }) const replacement = babel.template.expression(replacer, { placeholderPattern: false, placeholderWhitelist: new Set(['$$fn$$']), })({ ...(replacer.includes('$$fn$$') ? { $$fn$$: babel.types.toExpression(directiveFn.node) } : {}), }) directiveFn.replaceWith(replacement) } // Finally register the directive to // our map of directives directiveFnsById[functionId] = { nodePath: directiveFn, functionName, functionId, extractedFilename, filename: opts.filename, chunkName: fileNameToChunkName(opts.root, extractedFilename), isClientReferenced, } } } function codeFrameError( code: string, loc: | { start: { line: number; column: number } end: { line: number; column: number } } | undefined | null, message: string, ) { if (!loc) { return new Error(`${message} at unknown location`) } const frame = codeFrameColumns( code, { start: loc.start, end: loc.end, }, { highlightCode: true, message, }, ) return new Error(frame) } const safeRemoveExports = (ast: babel.types.File) => { ast.program.body = ast.program.body.flatMap((node) => { if ( babel.types.isExportNamedDeclaration(node) || babel.types.isExportDefaultDeclaration(node) ) { if ( babel.types.isFunctionDeclaration(node.declaration) || babel.types.isClassDeclaration(node.declaration) || babel.types.isVariableDeclaration(node.declaration) ) { // do not remove export if it is an anonymous function / class, otherwise this would produce a syntax error if ( babel.types.isFunctionDeclaration(node.declaration) || babel.types.isClassDeclaration(node.declaration) ) { if (!node.declaration.id) { return node } } return node.declaration } else if (node.declaration === null) { // remove e.g. `export { RouteComponent as component }` return [] } } return node }) } function fileNameToChunkName(root: string, fileName: string) { // Replace anything that can't go into an import statement return fileName.replace(root, '').replace(/[^a-zA-Z0-9_]/g, '_') }