Open History to see the last commit
1import { b, is } from 'yuku-ast'
2import {
3 parseExpression,
4 parseStatements,
5 unwrapExport,
6} from '@tanstack/router-utils'
7import path from 'pathe'
8import {
9 cleanId,
10 codeFrameError,
11 getVariableDeclarator,
12 sourcePosition,
13 stripMethodCall,
14} from './utils'
15import type {
16 Program,
17 ProgramStatement,
18 VariableDeclaration,
19} from '@yuku-toolchain/types'
20import type { CompilationContext, RewriteCandidate, ServerFn } from './types'
21β
22const TSS_SERVERFN_SPLIT_PARAM = 'tss-serverfn-split'
23β
24export function handleCreateServerFn(
25 candidates: Array<RewriteCandidate>,
26 context: CompilationContext,
27) {
28 if (candidates.length === 0) {
29 return
30 }
31 const isProvider = context.id.includes(TSS_SERVERFN_SPLIT_PARAM)
32 const runtime = isProvider
33 ? 'provider'
34 : context.env === 'client'
35 ? 'client'
36 : 'ssr'
37 const runtimeName =
38 runtime === 'provider'
39 ? 'createServerRpc'
40 : runtime === 'client'
41 ? 'createClientRpc'
42 : 'createSsrRpc'
43 const functionNames = new Set<string>()
44 const exportNames = new Set<string>()
45 const serverFnsById: Record<string, ServerFn> = {}
46 const [baseFilename] = context.id.split('?') as [string]
47 const extractedFilename = `${baseFilename}?${TSS_SERVERFN_SPLIT_PARAM}`
48 const relativeFilename = path.relative(context.root, baseFilename)
49 const knownFns = context.getKnownServerFns()
50β
51 for (const { node, methodChain } of candidates) {
52 const declarator = getVariableDeclarator(node, context.parentOf)
53 if (!declarator) {
54 throw new Error('createServerFn must be assigned to a variable!')
55 }
56 if (!is.Identifier(declarator.id)) {
57 throw codeFrameError(
58 context.code,
59 declarator.id,
60 'createServerFn must be assigned to a simple identifier, not a destructuring pattern',
61 )
62 }
63 // The provider module exports the extracted handler next to the
64 // declaration, so only module-level declarations can be split.
65 const declaration = context.parentOf(declarator) as VariableDeclaration
66 const parent = context.parentOf(declaration)
67 const statement = is.ExportNamedDeclaration(parent) ? parent : declaration
68 if (!is.Program(context.parentOf(statement))) {
69 throw codeFrameError(
70 context.code,
71 declarator,
72 'createServerFn must be assigned to a top-level variable, not declared inside a function or block!',
73 )
74 }
75 const variableName = declarator.id.name
76 let functionName = `${variableName}_createServerFn_handler`
77 while (functionNames.has(functionName)) {
78 functionName = incrementFunctionNameVersion(functionName)
79 }
80 functionNames.add(functionName)
81 const functionId = context.generateFunctionId({
82 filename: relativeFilename,
83 functionName,
84 extractedFilename,
85 })
86 const knownFn = knownFns[functionId]
87 if (methodChain.inputValidator) {
88 const location = sourcePosition(
89 context.code,
90 methodChain.inputValidator.call.start,
91 )
92 context.warn?.(
93 `${context.id}:${location.line}:${location.column + 1} createServerFn().inputValidator() is deprecated. Use createServerFn().validator() instead.`,
94 )
95 }
96 for (const [name, method] of [
97 ['validator', methodChain.validator],
98 ['inputValidator', methodChain.inputValidator],
99 ] as const) {
100 if (!method) {
101 continue
102 }
103 if (!method.call.arguments[0]) {
104 throw new Error(
105 `createServerFn().${name}() must be called with a validator!`,
106 )
107 }
108 if (context.env === 'client') {
109 stripMethodCall(method.call, context)
110 }
111 }
112 const handler = methodChain.handler
113 if (!handler?.firstArg) {
114 throw codeFrameError(
115 context.code,
116 node.callee,
117 'createServerFn must be called with a "handler" property!',
118 )
119 }
120 if (!is.Expression(handler.firstArg)) {
121 throw codeFrameError(
122 context.code,
123 handler.firstArg,
124 `handler() must be called with an expression, not a ${handler.firstArg.type}`,
125 )
126 }
127 if (!isProvider) {
128 serverFnsById[functionId] = {
129 functionName,
130 functionId,
131 filename: cleanId(context.id),
132 extractedFilename: knownFn?.extractedFilename ?? extractedFilename,
133 isClientReferenced:
134 context.env === 'client' || !!knownFn || runtime === 'ssr',
135 }
136 context.replaceNode(
137 handler.firstArg,
138 parseExpression(`${runtimeName}(${JSON.stringify(functionId)})`),
139 )
140 continue
141 }
142 const metadata = JSON.stringify({
143 id: functionId,
144 name: variableName,
145 filename: relativeFilename,
146 })
147 const extracted = parseStatements(
148 `const ${functionName} = createServerRpc(${metadata}, (opts) => ${variableName}.__executeServer(opts));`,
149 )[0]!
150 context.ast.body.splice(context.ast.body.indexOf(statement), 0, extracted)
151 // Move the existing handler node; its source-binding identity remains intact.
152 handler.call.arguments = [parseExpression(functionName), handler.firstArg]
153 exportNames.add(functionName)
154 }
155β
156 if (isProvider) {
157 removeExports(context.ast)
158 if (exportNames.size) {
159 context.ast.body.push(
160 b.ExportNamedDeclaration({
161 declaration: null,
162 source: null,
163 attributes: [],
164 exportKind: 'value',
165 specifiers: [...exportNames].map((name) =>
166 b.ExportSpecifier({
167 local: b.Identifier({ name }),
168 exported: b.Identifier({ name }),
169 exportKind: 'value',
170 }),
171 ),
172 }),
173 )
174 }
175 if (context.mode === 'dev') {
176 context.ast.body.push(
177 ...parseStatements(
178 'if (import.meta.hot) { import.meta.hot.accept(() => {}); } if (import.meta.webpackHot) { import.meta.webpackHot.accept(() => {}); }',
179 ),
180 )
181 }
182 const existing = new Set(
183 context.ast.body.filter(is.Directive).map((node) => node.directive),
184 )
185 const missing = (context.serverFnProviderModuleDirectives ?? []).filter(
186 (directive) => {
187 if (!directive || existing.has(directive)) {
188 return false
189 }
190 existing.add(directive)
191 return true
192 },
193 )
194 context.ast.body.unshift(
195 ...parseStatements(
196 missing.map((directive) => `${JSON.stringify(directive)};`).join('\n'),
197 ),
198 )
199 } else if (Object.keys(serverFnsById).length) {
200 context.onServerFnsById?.(serverFnsById)
201 }
202 let importIndex = 0
203 while (is.Directive(context.ast.body[importIndex])) {
204 importIndex++
205 }
206 const importPath = runtime === 'provider' ? 'server-rpc' : `${runtime}-rpc`
207 context.ast.body.splice(
208 importIndex,
209 0,
210 ...parseStatements(
211 `import { ${runtimeName} } from '@tanstack/${context.framework}-start/${importPath}';`,
212 ),
213 )
214}
215β
216function incrementFunctionNameVersion(name: string): string {
217 const [base, count] = name.split(/_(\d+)$/)
218 return (
219 base!
220 .replace(/[^a-zA-Z0-9_$]/g, '_')
221 .replace(/^[0-9]/, '_$&')
222 .replace(/^\$/, '_$')
223 .replace(/_{2,}/g, '_')
224 .replace(/^_|_$/g, '') + `_${Number(count || '0') + 1}`
225 )
226}
227β
228function removeExports(program: Program) {
229 program.body = program.body.flatMap<ProgramStatement>((node) => {
230 if (is.ExportNamedDeclaration(node) || is.ExportDefaultDeclaration(node)) {
231 if (
232 is.FunctionDeclaration(node.declaration) ||
233 is.ClassDeclaration(node.declaration)
234 ) {
235 return node.declaration.id
236 ? [unwrapExport(node, node.declaration)]
237 : [node]
238 }
239 if (is.VariableDeclaration(node.declaration)) {
240 return [unwrapExport(node, node.declaration)]
241 }
242 if (!node.declaration) {
243 return []
244 }
245 }
246 return [node]
247 })
248}