From 1663de672eef4bbcf7c36cbb50b519b4a9823887 Mon Sep 17 00:00:00 2001 From: Tanner Linsley Date: Wed, 11 Dec 2024 13:12:26 -0700 Subject: [PATCH 01/13] checkpoint --- .../server-functions-vite-plugin/README.md | 5 + .../eslint.config.js | 5 + .../server-functions-vite-plugin/package.json | 84 ++ .../server-functions-vite-plugin/src/ast.ts | 44 ++ .../src/compilers.ts | 715 ++++++++++++++++++ .../server-functions-vite-plugin/src/index.ts | 55 ++ .../createIsomorphicFn.test.ts | 90 +++ .../client/createIsomorphicFnDestructured.tsx | 16 + .../createIsomorphicFnDestructuredRename.tsx | 16 + .../client/createIsomorphicFnStarImport.tsx | 16 + .../server/createIsomorphicFnDestructured.tsx | 16 + .../createIsomorphicFnDestructuredRename.tsx | 16 + .../server/createIsomorphicFnStarImport.tsx | 16 + .../createIsomorphicFnDestructured.tsx | 35 + .../createIsomorphicFnDestructuredRename.tsx | 35 + .../createIsomorphicFnStarImport.tsx | 37 + .../createMiddleware/createMiddleware.test.ts | 36 + .../client/createMiddlewareDestructured.tsx | 24 + .../createMiddlewareDestructuredRename.tsx | 24 + .../client/createMiddlewareStarImport.tsx | 24 + .../client/createMiddlewareValidator.tsx | 5 + .../server/createMiddlewareDestructured.tsx | 36 + .../createMiddlewareDestructuredRename.tsx | 36 + .../server/createMiddlewareStarImport.tsx | 38 + .../server/createMiddlewareValidator.tsx | 7 + .../createMiddlewareDestructured.tsx | 51 ++ .../createMiddlewareDestructuredRename.tsx | 51 ++ .../test-files/createMiddlewareStarImport.tsx | 52 ++ .../test-files/createMiddlewareValidator.tsx | 8 + .../createServerFn/createServerFn.test.ts | 62 ++ .../client/createServerFnDestructured.tsx | 61 ++ .../createServerFnDestructuredRename.tsx | 40 + .../client/createServerFnStarImport.tsx | 40 + .../client/createServerFnValidator.tsx | 9 + .../server/createServerFnDestructured.tsx | 77 ++ .../createServerFnDestructuredRename.tsx | 52 ++ .../server/createServerFnStarImport.tsx | 52 ++ .../server/createServerFnValidator.tsx | 11 + .../test-files/createServerFnDestructured.tsx | 67 ++ .../createServerFnDestructuredRename.tsx | 51 ++ .../test-files/createServerFnStarImport.tsx | 52 ++ .../test-files/createServerFnValidator.tsx | 8 + .../tests/envOnly/envOnly.test.ts | 58 ++ .../snapshots/client/envOnlyDestructured.tsx | 5 + .../client/envOnlyDestructuredRename.tsx | 5 + .../snapshots/client/envOnlyStarImport.tsx | 5 + .../snapshots/server/envOnlyDestructured.tsx | 5 + .../server/envOnlyDestructuredRename.tsx | 5 + .../snapshots/server/envOnlyStarImport.tsx | 5 + .../test-files/envOnlyDestructured.tsx | 5 + .../test-files/envOnlyDestructuredRename.tsx | 5 + .../envOnly/test-files/envOnlyStarImport.tsx | 5 + .../tsconfig.json | 8 + .../vite.config.ts | 20 + packages/start/package.json | 11 +- packages/start/src/client-runtime/index.tsx | 22 +- packages/start/src/config/index.ts | 31 +- .../start/src/react-server-runtime/index.tsx | 14 - packages/start/src/server-runtime/index.tsx | 168 +--- packages/start/src/ssr-runtime/index.tsx | 161 ++++ packages/start/tsconfig.json | 2 +- packages/start/tsconfigs/config.tsconfig.json | 1 + .../tsconfigs/router-manifest.tsconfig.json | 1 + .../server-functions-plugin.tsconfig.json | 10 + packages/start/vite.config.ts | 4 +- 65 files changed, 2529 insertions(+), 202 deletions(-) create mode 100644 packages/server-functions-vite-plugin/README.md create mode 100644 packages/server-functions-vite-plugin/eslint.config.js create mode 100644 packages/server-functions-vite-plugin/package.json create mode 100644 packages/server-functions-vite-plugin/src/ast.ts create mode 100644 packages/server-functions-vite-plugin/src/compilers.ts create mode 100644 packages/server-functions-vite-plugin/src/index.ts create mode 100644 packages/server-functions-vite-plugin/tests/createIsomorphicFn/createIsomorphicFn.test.ts create mode 100644 packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnDestructured.tsx create mode 100644 packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnDestructuredRename.tsx create mode 100644 packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnStarImport.tsx create mode 100644 packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnDestructured.tsx create mode 100644 packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnDestructuredRename.tsx create mode 100644 packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnStarImport.tsx create mode 100644 packages/server-functions-vite-plugin/tests/createIsomorphicFn/test-files/createIsomorphicFnDestructured.tsx create mode 100644 packages/server-functions-vite-plugin/tests/createIsomorphicFn/test-files/createIsomorphicFnDestructuredRename.tsx create mode 100644 packages/server-functions-vite-plugin/tests/createIsomorphicFn/test-files/createIsomorphicFnStarImport.tsx create mode 100644 packages/server-functions-vite-plugin/tests/createMiddleware/createMiddleware.test.ts create mode 100644 packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/client/createMiddlewareDestructured.tsx create mode 100644 packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/client/createMiddlewareDestructuredRename.tsx create mode 100644 packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/client/createMiddlewareStarImport.tsx create mode 100644 packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/client/createMiddlewareValidator.tsx create mode 100644 packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/server/createMiddlewareDestructured.tsx create mode 100644 packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/server/createMiddlewareDestructuredRename.tsx create mode 100644 packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/server/createMiddlewareStarImport.tsx create mode 100644 packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/server/createMiddlewareValidator.tsx create mode 100644 packages/server-functions-vite-plugin/tests/createMiddleware/test-files/createMiddlewareDestructured.tsx create mode 100644 packages/server-functions-vite-plugin/tests/createMiddleware/test-files/createMiddlewareDestructuredRename.tsx create mode 100644 packages/server-functions-vite-plugin/tests/createMiddleware/test-files/createMiddlewareStarImport.tsx create mode 100644 packages/server-functions-vite-plugin/tests/createMiddleware/test-files/createMiddlewareValidator.tsx create mode 100644 packages/server-functions-vite-plugin/tests/createServerFn/createServerFn.test.ts create mode 100644 packages/server-functions-vite-plugin/tests/createServerFn/snapshots/client/createServerFnDestructured.tsx create mode 100644 packages/server-functions-vite-plugin/tests/createServerFn/snapshots/client/createServerFnDestructuredRename.tsx create mode 100644 packages/server-functions-vite-plugin/tests/createServerFn/snapshots/client/createServerFnStarImport.tsx create mode 100644 packages/server-functions-vite-plugin/tests/createServerFn/snapshots/client/createServerFnValidator.tsx create mode 100644 packages/server-functions-vite-plugin/tests/createServerFn/snapshots/server/createServerFnDestructured.tsx create mode 100644 packages/server-functions-vite-plugin/tests/createServerFn/snapshots/server/createServerFnDestructuredRename.tsx create mode 100644 packages/server-functions-vite-plugin/tests/createServerFn/snapshots/server/createServerFnStarImport.tsx create mode 100644 packages/server-functions-vite-plugin/tests/createServerFn/snapshots/server/createServerFnValidator.tsx create mode 100644 packages/server-functions-vite-plugin/tests/createServerFn/test-files/createServerFnDestructured.tsx create mode 100644 packages/server-functions-vite-plugin/tests/createServerFn/test-files/createServerFnDestructuredRename.tsx create mode 100644 packages/server-functions-vite-plugin/tests/createServerFn/test-files/createServerFnStarImport.tsx create mode 100644 packages/server-functions-vite-plugin/tests/createServerFn/test-files/createServerFnValidator.tsx create mode 100644 packages/server-functions-vite-plugin/tests/envOnly/envOnly.test.ts create mode 100644 packages/server-functions-vite-plugin/tests/envOnly/snapshots/client/envOnlyDestructured.tsx create mode 100644 packages/server-functions-vite-plugin/tests/envOnly/snapshots/client/envOnlyDestructuredRename.tsx create mode 100644 packages/server-functions-vite-plugin/tests/envOnly/snapshots/client/envOnlyStarImport.tsx create mode 100644 packages/server-functions-vite-plugin/tests/envOnly/snapshots/server/envOnlyDestructured.tsx create mode 100644 packages/server-functions-vite-plugin/tests/envOnly/snapshots/server/envOnlyDestructuredRename.tsx create mode 100644 packages/server-functions-vite-plugin/tests/envOnly/snapshots/server/envOnlyStarImport.tsx create mode 100644 packages/server-functions-vite-plugin/tests/envOnly/test-files/envOnlyDestructured.tsx create mode 100644 packages/server-functions-vite-plugin/tests/envOnly/test-files/envOnlyDestructuredRename.tsx create mode 100644 packages/server-functions-vite-plugin/tests/envOnly/test-files/envOnlyStarImport.tsx create mode 100644 packages/server-functions-vite-plugin/tsconfig.json create mode 100644 packages/server-functions-vite-plugin/vite.config.ts delete mode 100644 packages/start/src/react-server-runtime/index.tsx create mode 100644 packages/start/src/ssr-runtime/index.tsx create mode 100644 packages/start/tsconfigs/server-functions-plugin.tsconfig.json diff --git a/packages/server-functions-vite-plugin/README.md b/packages/server-functions-vite-plugin/README.md new file mode 100644 index 0000000000..798fa094a3 --- /dev/null +++ b/packages/server-functions-vite-plugin/README.md @@ -0,0 +1,5 @@ + + +# TanStack Start Vite Plugin + +See https://tanstack.com/router/latest/docs/framework/react/guide/file-based-routing diff --git a/packages/server-functions-vite-plugin/eslint.config.js b/packages/server-functions-vite-plugin/eslint.config.js new file mode 100644 index 0000000000..8ce6ad05fc --- /dev/null +++ b/packages/server-functions-vite-plugin/eslint.config.js @@ -0,0 +1,5 @@ +// @ts-check + +import rootConfig from '../../eslint.config.js' + +export default [...rootConfig] diff --git a/packages/server-functions-vite-plugin/package.json b/packages/server-functions-vite-plugin/package.json new file mode 100644 index 0000000000..41d0915a16 --- /dev/null +++ b/packages/server-functions-vite-plugin/package.json @@ -0,0 +1,84 @@ +{ + "name": "@tanstack/start-vite-plugin", + "version": "1.87.3", + "description": "Modern and scalable routing for React applications", + "author": "Tanner Linsley", + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/TanStack/router.git", + "directory": "packages/start-vite-plugin" + }, + "homepage": "https://tanstack.com/start", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "keywords": [ + "react", + "location", + "router", + "routing", + "async", + "async router", + "typescript" + ], + "scripts": { + "clean": "rimraf ./dist && rimraf ./coverage", + "test": "pnpm test:eslint && pnpm test:types && pnpm test:build && pnpm test:unit", + "test:unit": "vitest", + "test:eslint": "eslint ./src", + "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", + "test:types:ts52": "node ../../node_modules/typescript52/lib/tsc.js", + "test:types:ts53": "node ../../node_modules/typescript53/lib/tsc.js", + "test:types:ts54": "node ../../node_modules/typescript54/lib/tsc.js", + "test:types:ts55": "node ../../node_modules/typescript55/lib/tsc.js", + "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js", + "test:types:ts57": "tsc", + "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", + "build": "vite build" + }, + "type": "module", + "types": "dist/esm/index.d.ts", + "main": "dist/cjs/index.cjs", + "module": "dist/esm/index.js", + "exports": { + ".": { + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, + "require": { + "types": "./dist/cjs/index.d.cts", + "default": "./dist/cjs/index.cjs" + } + }, + "./package.json": "./package.json" + }, + "sideEffects": false, + "files": [ + "dist", + "src" + ], + "engines": { + "node": ">=12" + }, + "dependencies": { + "@babel/core": "^7.26.0", + "@babel/code-frame": "7.26.2", + "@babel/generator": "^7.26.3", + "@babel/parser": "^7.26.3", + "@babel/plugin-syntax-jsx": "^7.25.9", + "@babel/plugin-syntax-typescript": "^7.25.9", + "@babel/template": "^7.25.9", + "@babel/traverse": "^7.26.4", + "@babel/types": "^7.26.3", + "@types/babel__core": "^7.20.5", + "@types/babel__generator": "^7.6.8", + "@types/babel__code-frame": "^7.0.6", + "@types/babel__template": "^7.4.4", + "@types/babel__traverse": "^7.20.6", + "tiny-invariant": "^1.3.3", + "babel-dead-code-elimination": "^1.0.6" + } +} diff --git a/packages/server-functions-vite-plugin/src/ast.ts b/packages/server-functions-vite-plugin/src/ast.ts new file mode 100644 index 0000000000..6062993cfd --- /dev/null +++ b/packages/server-functions-vite-plugin/src/ast.ts @@ -0,0 +1,44 @@ +import * as babel from '@babel/core' +import '@babel/parser' +// @ts-expect-error +import _babelPluginJsx from '@babel/plugin-syntax-jsx' +// @ts-expect-error +import _babelPluginTypeScript from '@babel/plugin-syntax-typescript' + +let babelPluginJsx = _babelPluginJsx +let babelPluginTypeScript = _babelPluginTypeScript + +if (babelPluginJsx.default) { + babelPluginJsx = babelPluginJsx.default +} + +if (babelPluginTypeScript.default) { + babelPluginTypeScript = babelPluginTypeScript.default +} + +export type ParseAstOptions = { + code: string + filename: string + root: string + env: 'server' | 'client' +} + +export function parseAst(opts: ParseAstOptions) { + const babelPlugins: Array = [ + babelPluginJsx, + [ + babelPluginTypeScript, + { + isTSX: true, + }, + ], + ] + + return babel.parse(opts.code, { + plugins: babelPlugins, + root: opts.root, + filename: opts.filename, + sourceMaps: true, + sourceType: 'module', + }) +} diff --git a/packages/server-functions-vite-plugin/src/compilers.ts b/packages/server-functions-vite-plugin/src/compilers.ts new file mode 100644 index 0000000000..a5d8c49b11 --- /dev/null +++ b/packages/server-functions-vite-plugin/src/compilers.ts @@ -0,0 +1,715 @@ +import * as babel from '@babel/core' +import * as t from '@babel/types' +import _generate from '@babel/generator' +import { codeFrameColumns } from '@babel/code-frame' +import { deadCodeElimination } from 'babel-dead-code-elimination' + +import { parseAst } from './ast' +import type { ParseAstOptions } from './ast' + +// Babel is a CJS package and uses `default` as named binding (`exports.default =`). +// https://github.com/babel/babel/issues/15269. +let generate = (_generate as any)['default'] as typeof _generate + +// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition +if (!generate) { + generate = _generate +} + +export function compileEliminateDeadCode(opts: ParseAstOptions) { + const ast = parseAst(opts) + if (!ast) { + throw new Error( + `Failed to compile ast for compileEliminateDeadCode() for the file: ${opts.filename}`, + ) + } + deadCodeElimination(ast) + + return generate(ast, { + sourceMaps: true, + }) +} + +const debug = process.env.TSR_VITE_DEBUG === 'true' + +// build these once and reuse them +const handleServerOnlyCallExpression = + buildEnvOnlyCallExpressionHandler('server') +const handleClientOnlyCallExpression = + buildEnvOnlyCallExpressionHandler('client') + +type IdentifierConfig = { + name: string + type: 'ImportSpecifier' | 'ImportNamespaceSpecifier' + namespaceId: string + handleCallExpression: ( + path: babel.NodePath, + opts: ParseAstOptions, + ) => void + paths: Array +} + +export function compileStartOutput(opts: ParseAstOptions) { + const ast = parseAst(opts) + + if (!ast) { + throw new Error( + `Failed to compile ast for compileStartOutput() for the file: ${opts.filename}`, + ) + } + + babel.traverse(ast, { + Program: { + enter(programPath) { + const identifiers: { + createServerFn: IdentifierConfig + createMiddleware: IdentifierConfig + serverOnly: IdentifierConfig + clientOnly: IdentifierConfig + createIsomorphicFn: IdentifierConfig + } = { + createServerFn: { + name: 'createServerFn', + type: 'ImportSpecifier', + namespaceId: '', + handleCallExpression: handleCreateServerFnCallExpression, + paths: [], + }, + createMiddleware: { + name: 'createMiddleware', + type: 'ImportSpecifier', + namespaceId: '', + handleCallExpression: handleCreateMiddlewareCallExpression, + paths: [], + }, + serverOnly: { + name: 'serverOnly', + type: 'ImportSpecifier', + namespaceId: '', + handleCallExpression: handleServerOnlyCallExpression, + paths: [], + }, + clientOnly: { + name: 'clientOnly', + type: 'ImportSpecifier', + namespaceId: '', + handleCallExpression: handleClientOnlyCallExpression, + paths: [], + }, + createIsomorphicFn: { + name: 'createIsomorphicFn', + type: 'ImportSpecifier', + namespaceId: '', + handleCallExpression: handleCreateIsomorphicFnCallExpression, + paths: [], + }, + } + + const identifierKeys = Object.keys(identifiers) as Array< + keyof typeof identifiers + > + + programPath.traverse({ + ImportDeclaration: (path) => { + if (path.node.source.value !== '@tanstack/start') { + return + } + + // handle a destructured imports being renamed like "import { createServerFn as myCreateServerFn } from '@tanstack/start';" + path.node.specifiers.forEach((specifier) => { + identifierKeys.forEach((identifierKey) => { + const identifier = identifiers[identifierKey] + + if ( + specifier.type === 'ImportSpecifier' && + specifier.imported.type === 'Identifier' + ) { + if (specifier.imported.name === identifierKey) { + identifier.name = specifier.local.name + identifier.type = 'ImportSpecifier' + } + } + + // handle namespace imports like "import * as TanStackStart from '@tanstack/start';" + if (specifier.type === 'ImportNamespaceSpecifier') { + identifier.type = 'ImportNamespaceSpecifier' + identifier.namespaceId = specifier.local.name + identifier.name = `${identifier.namespaceId}.${identifierKey}` + } + }) + }) + }, + CallExpression: (path) => { + identifierKeys.forEach((identifierKey) => { + // Check to see if the call expression is a call to the + // identifiers[identifierKey].name + if ( + t.isIdentifier(path.node.callee) && + path.node.callee.name === identifiers[identifierKey].name + ) { + // The identifier could be a call to the original function + // in the source code. If this is case, we need to ignore it. + // Check the scope to see if the identifier is a function declaration. + // if it is, then we can ignore it. + + if ( + path.scope.getBinding(identifiers[identifierKey].name)?.path + .node.type === 'FunctionDeclaration' + ) { + return + } + + return identifiers[identifierKey].paths.push(path) + } + + if (t.isMemberExpression(path.node.callee)) { + if ( + t.isIdentifier(path.node.callee.object) && + t.isIdentifier(path.node.callee.property) + ) { + const callname = [ + path.node.callee.object.name, + path.node.callee.property.name, + ].join('.') + + if (callname === identifiers[identifierKey].name) { + identifiers[identifierKey].paths.push(path) + } + } + } + + return + }) + }, + }) + + identifierKeys.forEach((identifierKey) => { + identifiers[identifierKey].paths.forEach((path) => { + identifiers[identifierKey].handleCallExpression( + path as babel.NodePath, + opts, + ) + }) + }) + }, + }, + }) + + return generate(ast, { + sourceMaps: true, + minified: process.env.NODE_ENV === 'production', + }) +} + +function handleCreateServerFnCallExpression( + path: babel.NodePath, + opts: ParseAstOptions, +) { + // The function is the 'fn' property of the object passed to createServerFn + + // const firstArg = path.node.arguments[0] + // if (t.isObjectExpression(firstArg)) { + // // Was called with some options + // } + + // Traverse the member expression and find the call expressions for + // the validator, handler, and middleware methods. Check to make sure they + // are children of the createServerFn call expression. + + const calledOptions = path.node.arguments[0] + ? (path.get('arguments.0') as babel.NodePath) + : null + + const shouldValidateClient = !!calledOptions?.node.properties.find((prop) => { + return ( + t.isObjectProperty(prop) && + t.isIdentifier(prop.key) && + prop.key.name === 'validateClient' && + t.isBooleanLiteral(prop.value) && + prop.value.value === true + ) + }) + + const callExpressionPaths = { + middleware: null as babel.NodePath | null, + validator: null as babel.NodePath | null, + handler: null as babel.NodePath | null, + } + + const validMethods = Object.keys(callExpressionPaths) + + const rootCallExpression = getRootCallExpression(path) + + if (debug) + console.info( + 'Handling createServerFn call expression:', + rootCallExpression.toString(), + ) + + // Check if the call is assigned to a variable + if (!rootCallExpression.parentPath.isVariableDeclarator()) { + throw new Error('createServerFn must be assigned to a variable!') + } + + // Get the identifier name of the variable + const variableDeclarator = rootCallExpression.parentPath.node + const existingVariableName = (variableDeclarator.id as t.Identifier).name + + rootCallExpression.traverse({ + MemberExpression(memberExpressionPath) { + if (t.isIdentifier(memberExpressionPath.node.property)) { + const name = memberExpressionPath.node.property + .name as keyof typeof callExpressionPaths + + if ( + validMethods.includes(name) && + memberExpressionPath.parentPath.isCallExpression() + ) { + callExpressionPaths[name] = memberExpressionPath.parentPath + } + } + }, + }) + + if (callExpressionPaths.validator) { + const innerInputExpression = callExpressionPaths.validator.node.arguments[0] + + if (!innerInputExpression) { + throw new Error( + 'createServerFn().validator() must be called with a validator!', + ) + } + + // If we're on the client, and we're not validating the client, remove the validator call expression + if ( + opts.env === 'client' && + !shouldValidateClient && + t.isMemberExpression(callExpressionPaths.validator.node.callee) + ) { + callExpressionPaths.validator.replaceWith( + callExpressionPaths.validator.node.callee.object, + ) + } + } + + // First, we need to move the handler function to a nested function call + // that is applied to the arguments passed to the server function. + + const handlerFnPath = callExpressionPaths.handler?.get( + 'arguments.0', + ) as babel.NodePath + + if (!callExpressionPaths.handler || !handlerFnPath.node) { + throw codeFrameError( + opts.code, + path.node.callee.loc!, + `createServerFn must be called with a "handler" property!`, + ) + } + + const handlerFn = handlerFnPath.node + + // So, the way we do this is we give the handler function a way + // to access the serverFn ctx on the server via function scope. + // The 'use server' extracted function will be called with the + // payload from the client, then use the scoped serverFn ctx + // to execute the handler function. + // This way, we can do things like data and middleware validation + // in the __execute function without having to AST transform the + // handler function too much itself. + + // .handler((optsOut, ctx) => { + // return ((optsIn) => { + // 'use server' + // ctx.__execute(handlerFn, optsIn) + // })(optsOut) + // }) + + removeUseServerDirective(handlerFnPath) + + handlerFnPath.replaceWith( + t.arrowFunctionExpression( + [t.identifier('opts')], + t.blockStatement( + // Everything in here is server-only, since the client + // will strip out anything in the 'use server' directive. + [ + t.returnStatement( + t.callExpression( + t.identifier(`${existingVariableName}.__executeServer`), + [t.identifier('opts')], + ), + ), + ], + [t.directive(t.directiveLiteral('use server'))], + ), + ), + ) + + if (opts.env === 'server') { + callExpressionPaths.handler.node.arguments.push(handlerFn) + } +} + +function removeUseServerDirective(path: babel.NodePath) { + path.traverse({ + Directive(path) { + if (path.node.value.value === 'use server') { + path.remove() + } + }, + }) +} + +function handleCreateMiddlewareCallExpression( + path: babel.NodePath, + opts: ParseAstOptions, +) { + // const firstArg = path.node.arguments[0] + + // if (!t.isObjectExpression(firstArg)) { + // throw new Error( + // 'createMiddleware must be called with an object of options!', + // ) + // } + + // const idProperty = firstArg.properties.find((prop) => { + // return ( + // t.isObjectProperty(prop) && + // t.isIdentifier(prop.key) && + // prop.key.name === 'id' + // ) + // }) + + // if ( + // !idProperty || + // !t.isObjectProperty(idProperty) || + // !t.isStringLiteral(idProperty.value) + // ) { + // throw new Error( + // 'createMiddleware must be called with an "id" property!', + // ) + // } + + const rootCallExpression = getRootCallExpression(path) + + if (debug) + console.info( + 'Handling createMiddleware call expression:', + rootCallExpression.toString(), + ) + + // Check if the call is assigned to a variable + // if (!rootCallExpression.parentPath.isVariableDeclarator()) { + // TODO: move this logic out to eslint or something like + // the router generator code that can do autofixes on save. + + // // If not assigned to a variable, wrap the call in a variable declaration + // const variableDeclaration = t.variableDeclaration('const', [ + // t.variableDeclarator(t.identifier(middlewareName), path.node), + // ]) + + // // The parent could be an expression statement, if it is, we need to replace + // // it with the variable declaration + // if (path.parentPath.isExpressionStatement()) { + // path.parentPath.replaceWith(variableDeclaration) + // } else { + // // If the parent is not an expression statement, then it is a statement + // // that is not an expression, like a variable declaration or a return statement. + // // In this case, we need to insert the variable declaration before the statement + // path.parentPath.insertBefore(variableDeclaration) + // } + + // // Now we need to export it. Just add an export statement + // // to the program body + // path.findParent((parentPath) => { + // if (parentPath.isProgram()) { + // parentPath.node.body.push( + // t.exportNamedDeclaration(null, [ + // t.exportSpecifier( + // t.identifier(middlewareName), + // t.identifier(middlewareName), + // ), + // ]), + // ) + // } + // return false + // }) + + // throw new Error( + // 'createMiddleware must be assigned to a variable and exported!', + // ) + // } + + // const variableDeclarator = rootCallExpression.parentPath.node + // const existingVariableName = (variableDeclarator.id as t.Identifier).name + + // const program = rootCallExpression.findParent((parentPath) => { + // return parentPath.isProgram() + // }) as babel.NodePath + + // let isExported = false as boolean + + // program.traverse({ + // ExportNamedDeclaration: (path) => { + // if ( + // path.isExportNamedDeclaration() && + // path.node.declaration && + // t.isVariableDeclaration(path.node.declaration) && + // path.node.declaration.declarations.some((decl) => { + // return ( + // t.isVariableDeclarator(decl) && + // t.isIdentifier(decl.id) && + // decl.id.name === existingVariableName + // ) + // }) + // ) { + // isExported = true + // } + // }, + // }) + + // If not exported, export it + // if (!isExported) { + // TODO: move this logic out to eslint or something like + // the router generator code that can do autofixes on save. + + // path.parentPath.parentPath.insertAfter( + // t.exportNamedDeclaration(null, [ + // t.exportSpecifier( + // t.identifier(existingVariableName), + // t.identifier(existingVariableName), + // ), + // ]), + // ) + + // throw new Error( + // 'createMiddleware must be exported as a named export!', + // ) + // } + + // The function is the 'fn' property of the object passed to createMiddleware + + // const firstArg = path.node.arguments[0] + // if (t.isObjectExpression(firstArg)) { + // // Was called with some options + // } + + // Traverse the member expression and find the call expressions for + // the validator, handler, and middleware methods. Check to make sure they + // are children of the createMiddleware call expression. + + const callExpressionPaths = { + middleware: null as babel.NodePath | null, + validator: null as babel.NodePath | null, + client: null as babel.NodePath | null, + server: null as babel.NodePath | null, + } + + const validMethods = Object.keys(callExpressionPaths) + + rootCallExpression.traverse({ + MemberExpression(memberExpressionPath) { + if (t.isIdentifier(memberExpressionPath.node.property)) { + const name = memberExpressionPath.node.property + .name as keyof typeof callExpressionPaths + + if ( + validMethods.includes(name) && + memberExpressionPath.parentPath.isCallExpression() + ) { + callExpressionPaths[name] = memberExpressionPath.parentPath + } + } + }, + }) + + if (callExpressionPaths.validator) { + const innerInputExpression = callExpressionPaths.validator.node.arguments[0] + + if (!innerInputExpression) { + throw new Error( + 'createMiddleware().validator() must be called with a validator!', + ) + } + + // If we're on the client, remove the validator call expression + if (opts.env === 'client') { + if (t.isMemberExpression(callExpressionPaths.validator.node.callee)) { + callExpressionPaths.validator.replaceWith( + callExpressionPaths.validator.node.callee.object, + ) + } + } + } + + const useFnPath = callExpressionPaths.server?.get( + 'arguments.0', + ) as babel.NodePath + + if (!callExpressionPaths.server || !useFnPath.node) { + throw new Error('createMiddleware must be called with a "use" property!') + } + + // If we're on the client, remove the use call expression + + if (opts.env === 'client') { + if (t.isMemberExpression(callExpressionPaths.server.node.callee)) { + callExpressionPaths.server.replaceWith( + callExpressionPaths.server.node.callee.object, + ) + } + } +} + +function buildEnvOnlyCallExpressionHandler(env: 'client' | 'server') { + return function envOnlyCallExpressionHandler( + path: babel.NodePath, + opts: ParseAstOptions, + ) { + if (debug) + console.info(`Handling ${env}Only call expression:`, path.toString()) + + if (opts.env === env) { + // extract the inner function from the call expression + const innerInputExpression = path.node.arguments[0] + + if (!t.isExpression(innerInputExpression)) { + throw new Error( + `${env}Only() functions must be called with a function!`, + ) + } + + path.replaceWith(innerInputExpression) + return + } + + // If we're on the wrong environment, replace the call expression + // with a function that always throws an error. + path.replaceWith( + t.arrowFunctionExpression( + [], + t.blockStatement([ + t.throwStatement( + t.newExpression(t.identifier('Error'), [ + t.stringLiteral( + `${env}Only() functions can only be called on the ${env}!`, + ), + ]), + ), + ]), + ), + ) + } +} + +function handleCreateIsomorphicFnCallExpression( + path: babel.NodePath, + opts: ParseAstOptions, +) { + const rootCallExpression = getRootCallExpression(path) + + if (debug) + console.info( + 'Handling createIsomorphicFn call expression:', + rootCallExpression.toString(), + ) + + const callExpressionPaths = { + client: null as babel.NodePath | null, + server: null as babel.NodePath | null, + } + + const validMethods = Object.keys(callExpressionPaths) + + rootCallExpression.traverse({ + MemberExpression(memberExpressionPath) { + if (t.isIdentifier(memberExpressionPath.node.property)) { + const name = memberExpressionPath.node.property + .name as keyof typeof callExpressionPaths + + if ( + validMethods.includes(name) && + memberExpressionPath.parentPath.isCallExpression() + ) { + callExpressionPaths[name] = memberExpressionPath.parentPath + } + } + }, + }) + + if ( + validMethods.every( + (method) => + !callExpressionPaths[method as keyof typeof callExpressionPaths], + ) + ) { + const variableId = rootCallExpression.parentPath.isVariableDeclarator() + ? rootCallExpression.parentPath.node.id + : null + console.warn( + 'createIsomorphicFn called without a client or server implementation!', + 'This will result in a no-op function.', + 'Variable name:', + t.isIdentifier(variableId) ? variableId.name : 'unknown', + ) + } + + const envCallExpression = callExpressionPaths[opts.env] + + if (!envCallExpression) { + // if we don't have an implementation for this environment, default to a no-op + rootCallExpression.replaceWith( + t.arrowFunctionExpression([], t.blockStatement([])), + ) + return + } + + const innerInputExpression = envCallExpression.node.arguments[0] + + if (!t.isExpression(innerInputExpression)) { + throw new Error( + `createIsomorphicFn().${opts.env}(func) must be called with a function!`, + ) + } + + rootCallExpression.replaceWith(innerInputExpression) +} + +function getRootCallExpression(path: babel.NodePath) { + // Find the highest callExpression parent + let rootCallExpression: babel.NodePath = path + + // Traverse up the chain of CallExpressions + while (rootCallExpression.parentPath.isMemberExpression()) { + const parent = rootCallExpression.parentPath + if (parent.parentPath.isCallExpression()) { + rootCallExpression = parent.parentPath + } + } + + return rootCallExpression +} + +function codeFrameError( + code: string, + loc: { + start: { line: number; column: number } + end: { line: number; column: number } + }, + message: string, +) { + const frame = codeFrameColumns( + code, + { + start: loc.start, + end: loc.end, + }, + { + highlightCode: true, + message, + }, + ) + + return new Error(frame) +} diff --git a/packages/server-functions-vite-plugin/src/index.ts b/packages/server-functions-vite-plugin/src/index.ts new file mode 100644 index 0000000000..6067851fd3 --- /dev/null +++ b/packages/server-functions-vite-plugin/src/index.ts @@ -0,0 +1,55 @@ +import { fileURLToPath, pathToFileURL } from 'node:url' + +import type { Plugin } from 'vite' + +const debug = Boolean(process.env.TSR_VITE_DEBUG) + +export type ServerFunctionsViteOptions = {} + +const useServerRx = /"use server"|'use server'/ + +export function TanStackStartViteServerFn(): Array { + // opts: ServerFunctionsViteOptions, + let ROOT: string = process.cwd() + + return [ + { + name: 'tanstack-start-server-fn-client-vite-plugin', + enforce: 'pre', + configResolved: (config) => { + ROOT = config.root + }, + transform(code, id) { + const url = pathToFileURL(id) + url.searchParams.delete('v') + id = fileURLToPath(url).replace(/\\/g, '/') + + if (!useServerRx.test(code)) { + return null + } + + const { compiledCode, serverFns } = compileServerFnServer({ + code, + root: ROOT, + filename: id, + }) + + if (debug) console.info('') + if (debug) console.info('Compiled createServerFn Output') + if (debug) console.info('') + if (debug) console.info(compiledCode) + if (debug) console.info('') + if (debug) console.info('') + if (debug) console.info('') + + return compiledCode + }, + }, + { + name: 'tanstack-start-server-fn-server-vite-plugin', + transform(code, id) { + return null + }, + }, + ] +} diff --git a/packages/server-functions-vite-plugin/tests/createIsomorphicFn/createIsomorphicFn.test.ts b/packages/server-functions-vite-plugin/tests/createIsomorphicFn/createIsomorphicFn.test.ts new file mode 100644 index 0000000000..28f29510a7 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createIsomorphicFn/createIsomorphicFn.test.ts @@ -0,0 +1,90 @@ +import { readFile, readdir } from 'node:fs/promises' +import path from 'node:path' +import { afterAll, describe, expect, test, vi } from 'vitest' + +import { compileStartOutput } from '../../src/compilers' + +async function getFilenames() { + return await readdir(path.resolve(import.meta.dirname, './test-files')) +} + +describe('createIsomorphicFn compiles correctly', async () => { + const noImplWarning = + 'createIsomorphicFn called without a client or server implementation!' + + const originalConsoleWarn = console.warn + const consoleSpy = vi.spyOn(console, 'warn').mockImplementation((...args) => { + // we want to avoid sending this warning to the console, we know about it + if (args[0] === noImplWarning) { + return + } + originalConsoleWarn(...args) + }) + + afterAll(() => { + consoleSpy.mockRestore() + }) + + const filenames = await getFilenames() + + describe.each(filenames)('should handle "%s"', async (filename) => { + const file = await readFile( + path.resolve(import.meta.dirname, `./test-files/${filename}`), + ) + const code = file.toString() + + test.each(['client', 'server'] as const)( + `should compile for ${filename} %s`, + async (env) => { + const compiledResult = compileStartOutput({ + env, + code, + root: './test-files', + filename, + }) + + await expect(compiledResult.code).toMatchFileSnapshot( + `./snapshots/${env}/${filename}`, + ) + }, + ) + }) + test('should error if implementation not provided', () => { + expect(() => { + compileStartOutput({ + env: 'client', + code: ` + import { createIsomorphicFn } from '@tanstack/start' + const clientOnly = createIsomorphicFn().client()`, + root: './test-files', + filename: 'no-fn.ts', + }) + }).toThrowError() + expect(() => { + compileStartOutput({ + env: 'server', + code: ` + import { createIsomorphicFn } from '@tanstack/start' + const serverOnly = createIsomorphicFn().server()`, + root: './test-files', + filename: 'no-fn.ts', + }) + }).toThrowError() + }) + test('should warn to console if no implementations provided', () => { + compileStartOutput({ + env: 'client', + code: ` + import { createIsomorphicFn } from '@tanstack/start' + const noImpl = createIsomorphicFn()`, + root: './test-files', + filename: 'no-fn.ts', + }) + expect(consoleSpy).toHaveBeenCalledWith( + noImplWarning, + 'This will result in a no-op function.', + 'Variable name:', + 'noImpl', + ) + }) +}) diff --git a/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnDestructured.tsx b/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnDestructured.tsx new file mode 100644 index 0000000000..6fcb30691c --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnDestructured.tsx @@ -0,0 +1,16 @@ +import { createIsomorphicFn } from '@tanstack/start'; +const noImpl = () => {}; +const serverOnlyFn = () => {}; +const clientOnlyFn = () => 'client'; +const serverThenClientFn = () => 'client'; +const clientThenServerFn = () => 'client'; +function abstractedServerFn() { + return 'server'; +} +const serverOnlyFnAbstracted = () => {}; +function abstractedClientFn() { + return 'client'; +} +const clientOnlyFnAbstracted = abstractedClientFn; +const serverThenClientFnAbstracted = abstractedClientFn; +const clientThenServerFnAbstracted = abstractedClientFn; \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnDestructuredRename.tsx b/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnDestructuredRename.tsx new file mode 100644 index 0000000000..d273a49f40 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnDestructuredRename.tsx @@ -0,0 +1,16 @@ +import { createIsomorphicFn as isomorphicFn } from '@tanstack/start'; +const noImpl = () => {}; +const serverOnlyFn = () => {}; +const clientOnlyFn = () => 'client'; +const serverThenClientFn = () => 'client'; +const clientThenServerFn = () => 'client'; +function abstractedServerFn() { + return 'server'; +} +const serverOnlyFnAbstracted = () => {}; +function abstractedClientFn() { + return 'client'; +} +const clientOnlyFnAbstracted = abstractedClientFn; +const serverThenClientFnAbstracted = abstractedClientFn; +const clientThenServerFnAbstracted = abstractedClientFn; \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnStarImport.tsx b/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnStarImport.tsx new file mode 100644 index 0000000000..ffb2ffe79c --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnStarImport.tsx @@ -0,0 +1,16 @@ +import * as TanStackStart from '@tanstack/start'; +const noImpl = () => {}; +const serverOnlyFn = () => {}; +const clientOnlyFn = () => 'client'; +const serverThenClientFn = () => 'client'; +const clientThenServerFn = () => 'client'; +function abstractedServerFn() { + return 'server'; +} +const serverOnlyFnAbstracted = () => {}; +function abstractedClientFn() { + return 'client'; +} +const clientOnlyFnAbstracted = abstractedClientFn; +const serverThenClientFnAbstracted = abstractedClientFn; +const clientThenServerFnAbstracted = abstractedClientFn; \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnDestructured.tsx b/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnDestructured.tsx new file mode 100644 index 0000000000..0e0134e347 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnDestructured.tsx @@ -0,0 +1,16 @@ +import { createIsomorphicFn } from '@tanstack/start'; +const noImpl = () => {}; +const serverOnlyFn = () => 'server'; +const clientOnlyFn = () => {}; +const serverThenClientFn = () => 'server'; +const clientThenServerFn = () => 'server'; +function abstractedServerFn() { + return 'server'; +} +const serverOnlyFnAbstracted = abstractedServerFn; +function abstractedClientFn() { + return 'client'; +} +const clientOnlyFnAbstracted = () => {}; +const serverThenClientFnAbstracted = abstractedServerFn; +const clientThenServerFnAbstracted = abstractedServerFn; \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnDestructuredRename.tsx b/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnDestructuredRename.tsx new file mode 100644 index 0000000000..3ba9d0598f --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnDestructuredRename.tsx @@ -0,0 +1,16 @@ +import { createIsomorphicFn as isomorphicFn } from '@tanstack/start'; +const noImpl = () => {}; +const serverOnlyFn = () => 'server'; +const clientOnlyFn = () => {}; +const serverThenClientFn = () => 'server'; +const clientThenServerFn = () => 'server'; +function abstractedServerFn() { + return 'server'; +} +const serverOnlyFnAbstracted = abstractedServerFn; +function abstractedClientFn() { + return 'client'; +} +const clientOnlyFnAbstracted = () => {}; +const serverThenClientFnAbstracted = abstractedServerFn; +const clientThenServerFnAbstracted = abstractedServerFn; \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnStarImport.tsx b/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnStarImport.tsx new file mode 100644 index 0000000000..c77c6ac839 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnStarImport.tsx @@ -0,0 +1,16 @@ +import * as TanStackStart from '@tanstack/start'; +const noImpl = () => {}; +const serverOnlyFn = () => 'server'; +const clientOnlyFn = () => {}; +const serverThenClientFn = () => 'server'; +const clientThenServerFn = () => 'server'; +function abstractedServerFn() { + return 'server'; +} +const serverOnlyFnAbstracted = abstractedServerFn; +function abstractedClientFn() { + return 'client'; +} +const clientOnlyFnAbstracted = () => {}; +const serverThenClientFnAbstracted = abstractedServerFn; +const clientThenServerFnAbstracted = abstractedServerFn; \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createIsomorphicFn/test-files/createIsomorphicFnDestructured.tsx b/packages/server-functions-vite-plugin/tests/createIsomorphicFn/test-files/createIsomorphicFnDestructured.tsx new file mode 100644 index 0000000000..e6c5c35943 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createIsomorphicFn/test-files/createIsomorphicFnDestructured.tsx @@ -0,0 +1,35 @@ +import { createIsomorphicFn } from '@tanstack/start' + +const noImpl = createIsomorphicFn() + +const serverOnlyFn = createIsomorphicFn().server(() => 'server') + +const clientOnlyFn = createIsomorphicFn().client(() => 'client') + +const serverThenClientFn = createIsomorphicFn() + .server(() => 'server') + .client(() => 'client') + +const clientThenServerFn = createIsomorphicFn() + .client(() => 'client') + .server(() => 'server') + +function abstractedServerFn() { + return 'server' +} + +const serverOnlyFnAbstracted = createIsomorphicFn().server(abstractedServerFn) + +function abstractedClientFn() { + return 'client' +} + +const clientOnlyFnAbstracted = createIsomorphicFn().client(abstractedClientFn) + +const serverThenClientFnAbstracted = createIsomorphicFn() + .server(abstractedServerFn) + .client(abstractedClientFn) + +const clientThenServerFnAbstracted = createIsomorphicFn() + .client(abstractedClientFn) + .server(abstractedServerFn) diff --git a/packages/server-functions-vite-plugin/tests/createIsomorphicFn/test-files/createIsomorphicFnDestructuredRename.tsx b/packages/server-functions-vite-plugin/tests/createIsomorphicFn/test-files/createIsomorphicFnDestructuredRename.tsx new file mode 100644 index 0000000000..9c31330b1b --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createIsomorphicFn/test-files/createIsomorphicFnDestructuredRename.tsx @@ -0,0 +1,35 @@ +import { createIsomorphicFn as isomorphicFn } from '@tanstack/start' + +const noImpl = isomorphicFn() + +const serverOnlyFn = isomorphicFn().server(() => 'server') + +const clientOnlyFn = isomorphicFn().client(() => 'client') + +const serverThenClientFn = isomorphicFn() + .server(() => 'server') + .client(() => 'client') + +const clientThenServerFn = isomorphicFn() + .client(() => 'client') + .server(() => 'server') + +function abstractedServerFn() { + return 'server' +} + +const serverOnlyFnAbstracted = isomorphicFn().server(abstractedServerFn) + +function abstractedClientFn() { + return 'client' +} + +const clientOnlyFnAbstracted = isomorphicFn().client(abstractedClientFn) + +const serverThenClientFnAbstracted = isomorphicFn() + .server(abstractedServerFn) + .client(abstractedClientFn) + +const clientThenServerFnAbstracted = isomorphicFn() + .client(abstractedClientFn) + .server(abstractedServerFn) diff --git a/packages/server-functions-vite-plugin/tests/createIsomorphicFn/test-files/createIsomorphicFnStarImport.tsx b/packages/server-functions-vite-plugin/tests/createIsomorphicFn/test-files/createIsomorphicFnStarImport.tsx new file mode 100644 index 0000000000..4c1bed5741 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createIsomorphicFn/test-files/createIsomorphicFnStarImport.tsx @@ -0,0 +1,37 @@ +import * as TanStackStart from '@tanstack/start' + +const noImpl = TanStackStart.createIsomorphicFn() + +const serverOnlyFn = TanStackStart.createIsomorphicFn().server(() => 'server') + +const clientOnlyFn = TanStackStart.createIsomorphicFn().client(() => 'client') + +const serverThenClientFn = TanStackStart.createIsomorphicFn() + .server(() => 'server') + .client(() => 'client') + +const clientThenServerFn = TanStackStart.createIsomorphicFn() + .client(() => 'client') + .server(() => 'server') + +function abstractedServerFn() { + return 'server' +} + +const serverOnlyFnAbstracted = + TanStackStart.createIsomorphicFn().server(abstractedServerFn) + +function abstractedClientFn() { + return 'client' +} + +const clientOnlyFnAbstracted = + TanStackStart.createIsomorphicFn().client(abstractedClientFn) + +const serverThenClientFnAbstracted = TanStackStart.createIsomorphicFn() + .server(abstractedServerFn) + .client(abstractedClientFn) + +const clientThenServerFnAbstracted = TanStackStart.createIsomorphicFn() + .client(abstractedClientFn) + .server(abstractedServerFn) diff --git a/packages/server-functions-vite-plugin/tests/createMiddleware/createMiddleware.test.ts b/packages/server-functions-vite-plugin/tests/createMiddleware/createMiddleware.test.ts new file mode 100644 index 0000000000..ae4ee2c221 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createMiddleware/createMiddleware.test.ts @@ -0,0 +1,36 @@ +import { readFile, readdir } from 'node:fs/promises' +import path from 'node:path' +import { describe, expect, test } from 'vitest' + +import { compileStartOutput } from '../../src/compilers' + +async function getFilenames() { + return await readdir(path.resolve(import.meta.dirname, './test-files')) +} + +describe('createMiddleware compiles correctly', async () => { + const filenames = await getFilenames() + + describe.each(filenames)('should handle "%s"', async (filename) => { + const file = await readFile( + path.resolve(import.meta.dirname, `./test-files/${filename}`), + ) + const code = file.toString() + + test.each(['client', 'server'] as const)( + `should compile for ${filename} %s`, + async (env) => { + const compiledResult = compileStartOutput({ + env, + code, + root: './test-files', + filename, + }) + + await expect(compiledResult.code).toMatchFileSnapshot( + `./snapshots/${env}/${filename}`, + ) + }, + ) + }) +}) diff --git a/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/client/createMiddlewareDestructured.tsx b/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/client/createMiddlewareDestructured.tsx new file mode 100644 index 0000000000..f0ed6717e4 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/client/createMiddlewareDestructured.tsx @@ -0,0 +1,24 @@ +import { createMiddleware } from '@tanstack/start'; +import { z } from 'zod'; +export const withUseServer = createMiddleware({ + id: 'test' +}); +export const withoutUseServer = createMiddleware({ + id: 'test' +}); +export const withVariable = createMiddleware({ + id: 'test' +}); +async function abstractedFunction() { + console.info('Fetching posts...'); + await new Promise(r => setTimeout(r, 500)); + return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); +} +function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { + return async (input: unknown) => { + return fn(schema.parse(input)); + }; +} +export const withZodValidator = createMiddleware({ + id: 'test' +}); \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/client/createMiddlewareDestructuredRename.tsx b/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/client/createMiddlewareDestructuredRename.tsx new file mode 100644 index 0000000000..c13c45a86c --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/client/createMiddlewareDestructuredRename.tsx @@ -0,0 +1,24 @@ +import { createMiddleware as middlewareFn } from '@tanstack/start'; +import { z } from 'zod'; +export const withUseServer = middlewareFn({ + id: 'test' +}); +export const withoutUseServer = middlewareFn({ + id: 'test' +}); +export const withVariable = middlewareFn({ + id: 'test' +}); +async function abstractedFunction() { + console.info('Fetching posts...'); + await new Promise(r => setTimeout(r, 500)); + return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); +} +function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { + return async (input: unknown) => { + return fn(schema.parse(input)); + }; +} +export const withZodValidator = middlewareFn({ + id: 'test' +}); \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/client/createMiddlewareStarImport.tsx b/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/client/createMiddlewareStarImport.tsx new file mode 100644 index 0000000000..0af363017d --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/client/createMiddlewareStarImport.tsx @@ -0,0 +1,24 @@ +import * as TanStackStart from '@tanstack/start'; +import { z } from 'zod'; +export const withUseServer = TanStackStart.createMiddleware({ + id: 'test' +}); +export const withoutUseServer = TanStackStart.createMiddleware({ + id: 'test' +}); +export const withVariable = TanStackStart.createMiddleware({ + id: 'test' +}); +async function abstractedFunction() { + console.info('Fetching posts...'); + await new Promise(r => setTimeout(r, 500)); + return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); +} +function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { + return async (input: unknown) => { + return fn(schema.parse(input)); + }; +} +export const withZodValidator = TanStackStart.createMiddleware({ + id: 'test' +}); \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/client/createMiddlewareValidator.tsx b/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/client/createMiddlewareValidator.tsx new file mode 100644 index 0000000000..e13946f2d8 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/client/createMiddlewareValidator.tsx @@ -0,0 +1,5 @@ +import { createMiddleware } from '@tanstack/start'; +import { z } from 'zod'; +export const withUseServer = createMiddleware({ + id: 'test' +}); \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/server/createMiddlewareDestructured.tsx b/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/server/createMiddlewareDestructured.tsx new file mode 100644 index 0000000000..a29e1ecb40 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/server/createMiddlewareDestructured.tsx @@ -0,0 +1,36 @@ +import { createMiddleware } from '@tanstack/start'; +import { z } from 'zod'; +export const withUseServer = createMiddleware({ + id: 'test' +}).server(async function () { + console.info('Fetching posts...'); + await new Promise(r => setTimeout(r, 500)); + return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); +}); +export const withoutUseServer = createMiddleware({ + id: 'test' +}).server(async () => { + console.info('Fetching posts...'); + await new Promise(r => setTimeout(r, 500)); + return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); +}); +export const withVariable = createMiddleware({ + id: 'test' +}).server(abstractedFunction); +async function abstractedFunction() { + console.info('Fetching posts...'); + await new Promise(r => setTimeout(r, 500)); + return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); +} +function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { + return async (input: unknown) => { + return fn(schema.parse(input)); + }; +} +export const withZodValidator = createMiddleware({ + id: 'test' +}).server(zodValidator(z.number(), input => { + return { + 'you gave': input + }; +})); \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/server/createMiddlewareDestructuredRename.tsx b/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/server/createMiddlewareDestructuredRename.tsx new file mode 100644 index 0000000000..d529f89fe1 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/server/createMiddlewareDestructuredRename.tsx @@ -0,0 +1,36 @@ +import { createMiddleware as middlewareFn } from '@tanstack/start'; +import { z } from 'zod'; +export const withUseServer = middlewareFn({ + id: 'test' +}).server(async function () { + console.info('Fetching posts...'); + await new Promise(r => setTimeout(r, 500)); + return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); +}); +export const withoutUseServer = middlewareFn({ + id: 'test' +}).server(async () => { + console.info('Fetching posts...'); + await new Promise(r => setTimeout(r, 500)); + return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); +}); +export const withVariable = middlewareFn({ + id: 'test' +}).server(abstractedFunction); +async function abstractedFunction() { + console.info('Fetching posts...'); + await new Promise(r => setTimeout(r, 500)); + return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); +} +function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { + return async (input: unknown) => { + return fn(schema.parse(input)); + }; +} +export const withZodValidator = middlewareFn({ + id: 'test' +}).server(zodValidator(z.number(), input => { + return { + 'you gave': input + }; +})); \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/server/createMiddlewareStarImport.tsx b/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/server/createMiddlewareStarImport.tsx new file mode 100644 index 0000000000..53baf6fa9c --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/server/createMiddlewareStarImport.tsx @@ -0,0 +1,38 @@ +import * as TanStackStart from '@tanstack/start'; +import { z } from 'zod'; +export const withUseServer = TanStackStart.createMiddleware({ + id: 'test' +}).server(async function () { + 'use server'; + + console.info('Fetching posts...'); + await new Promise(r => setTimeout(r, 500)); + return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); +}); +export const withoutUseServer = TanStackStart.createMiddleware({ + id: 'test' +}).server(async () => { + console.info('Fetching posts...'); + await new Promise(r => setTimeout(r, 500)); + return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); +}); +export const withVariable = TanStackStart.createMiddleware({ + id: 'test' +}).server(abstractedFunction); +async function abstractedFunction() { + console.info('Fetching posts...'); + await new Promise(r => setTimeout(r, 500)); + return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); +} +function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { + return async (input: unknown) => { + return fn(schema.parse(input)); + }; +} +export const withZodValidator = TanStackStart.createMiddleware({ + id: 'test' +}).server(zodValidator(z.number(), input => { + return { + 'you gave': input + }; +})); \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/server/createMiddlewareValidator.tsx b/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/server/createMiddlewareValidator.tsx new file mode 100644 index 0000000000..1e41c79866 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/server/createMiddlewareValidator.tsx @@ -0,0 +1,7 @@ +import { createMiddleware } from '@tanstack/start'; +import { z } from 'zod'; +export const withUseServer = createMiddleware({ + id: 'test' +}).validator(z.number()).server(({ + input +}) => input + 1); \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createMiddleware/test-files/createMiddlewareDestructured.tsx b/packages/server-functions-vite-plugin/tests/createMiddleware/test-files/createMiddlewareDestructured.tsx new file mode 100644 index 0000000000..c5ea2aa5b6 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createMiddleware/test-files/createMiddlewareDestructured.tsx @@ -0,0 +1,51 @@ +import { createMiddleware } from '@tanstack/start' +import { z } from 'zod' + +export const withUseServer = createMiddleware({ + id: 'test', +}).server(async function () { + console.info('Fetching posts...') + await new Promise((r) => setTimeout(r, 500)) + return axios + .get>('https://jsonplaceholder.typicode.com/posts') + .then((r) => r.data.slice(0, 10)) +}) + +export const withoutUseServer = createMiddleware({ + id: 'test', +}).server(async () => { + console.info('Fetching posts...') + await new Promise((r) => setTimeout(r, 500)) + return axios + .get>('https://jsonplaceholder.typicode.com/posts') + .then((r) => r.data.slice(0, 10)) +}) + +export const withVariable = createMiddleware({ + id: 'test', +}).server(abstractedFunction) + +async function abstractedFunction() { + console.info('Fetching posts...') + await new Promise((r) => setTimeout(r, 500)) + return axios + .get>('https://jsonplaceholder.typicode.com/posts') + .then((r) => r.data.slice(0, 10)) +} + +function zodValidator( + schema: TSchema, + fn: (input: z.output) => TResult, +) { + return async (input: unknown) => { + return fn(schema.parse(input)) + } +} + +export const withZodValidator = createMiddleware({ + id: 'test', +}).server( + zodValidator(z.number(), (input) => { + return { 'you gave': input } + }), +) diff --git a/packages/server-functions-vite-plugin/tests/createMiddleware/test-files/createMiddlewareDestructuredRename.tsx b/packages/server-functions-vite-plugin/tests/createMiddleware/test-files/createMiddlewareDestructuredRename.tsx new file mode 100644 index 0000000000..2e456131fe --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createMiddleware/test-files/createMiddlewareDestructuredRename.tsx @@ -0,0 +1,51 @@ +import { createMiddleware as middlewareFn } from '@tanstack/start' +import { z } from 'zod' + +export const withUseServer = middlewareFn({ + id: 'test', +}).server(async function () { + console.info('Fetching posts...') + await new Promise((r) => setTimeout(r, 500)) + return axios + .get>('https://jsonplaceholder.typicode.com/posts') + .then((r) => r.data.slice(0, 10)) +}) + +export const withoutUseServer = middlewareFn({ + id: 'test', +}).server(async () => { + console.info('Fetching posts...') + await new Promise((r) => setTimeout(r, 500)) + return axios + .get>('https://jsonplaceholder.typicode.com/posts') + .then((r) => r.data.slice(0, 10)) +}) + +export const withVariable = middlewareFn({ + id: 'test', +}).server(abstractedFunction) + +async function abstractedFunction() { + console.info('Fetching posts...') + await new Promise((r) => setTimeout(r, 500)) + return axios + .get>('https://jsonplaceholder.typicode.com/posts') + .then((r) => r.data.slice(0, 10)) +} + +function zodValidator( + schema: TSchema, + fn: (input: z.output) => TResult, +) { + return async (input: unknown) => { + return fn(schema.parse(input)) + } +} + +export const withZodValidator = middlewareFn({ + id: 'test', +}).server( + zodValidator(z.number(), (input) => { + return { 'you gave': input } + }), +) diff --git a/packages/server-functions-vite-plugin/tests/createMiddleware/test-files/createMiddlewareStarImport.tsx b/packages/server-functions-vite-plugin/tests/createMiddleware/test-files/createMiddlewareStarImport.tsx new file mode 100644 index 0000000000..c1df8e12b3 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createMiddleware/test-files/createMiddlewareStarImport.tsx @@ -0,0 +1,52 @@ +import * as TanStackStart from '@tanstack/start' +import { z } from 'zod' + +export const withUseServer = TanStackStart.createMiddleware({ + id: 'test', +}).server(async function () { + 'use server' + console.info('Fetching posts...') + await new Promise((r) => setTimeout(r, 500)) + return axios + .get>('https://jsonplaceholder.typicode.com/posts') + .then((r) => r.data.slice(0, 10)) +}) + +export const withoutUseServer = TanStackStart.createMiddleware({ + id: 'test', +}).server(async () => { + console.info('Fetching posts...') + await new Promise((r) => setTimeout(r, 500)) + return axios + .get>('https://jsonplaceholder.typicode.com/posts') + .then((r) => r.data.slice(0, 10)) +}) + +export const withVariable = TanStackStart.createMiddleware({ + id: 'test', +}).server(abstractedFunction) + +async function abstractedFunction() { + console.info('Fetching posts...') + await new Promise((r) => setTimeout(r, 500)) + return axios + .get>('https://jsonplaceholder.typicode.com/posts') + .then((r) => r.data.slice(0, 10)) +} + +function zodValidator( + schema: TSchema, + fn: (input: z.output) => TResult, +) { + return async (input: unknown) => { + return fn(schema.parse(input)) + } +} + +export const withZodValidator = TanStackStart.createMiddleware({ + id: 'test', +}).server( + zodValidator(z.number(), (input) => { + return { 'you gave': input } + }), +) diff --git a/packages/server-functions-vite-plugin/tests/createMiddleware/test-files/createMiddlewareValidator.tsx b/packages/server-functions-vite-plugin/tests/createMiddleware/test-files/createMiddlewareValidator.tsx new file mode 100644 index 0000000000..7e0d6ba449 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createMiddleware/test-files/createMiddlewareValidator.tsx @@ -0,0 +1,8 @@ +import { createMiddleware } from '@tanstack/start' +import { z } from 'zod' + +export const withUseServer = createMiddleware({ + id: 'test', +}) + .validator(z.number()) + .server(({ input }) => input + 1) diff --git a/packages/server-functions-vite-plugin/tests/createServerFn/createServerFn.test.ts b/packages/server-functions-vite-plugin/tests/createServerFn/createServerFn.test.ts new file mode 100644 index 0000000000..19b86a0c01 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createServerFn/createServerFn.test.ts @@ -0,0 +1,62 @@ +import { readFile, readdir } from 'node:fs/promises' +import path from 'node:path' +import { describe, expect, test } from 'vitest' + +import { compileStartOutput } from '../../src/compilers' + +async function getFilenames() { + return await readdir(path.resolve(import.meta.dirname, './test-files')) +} + +describe('createServerFn compiles correctly', async () => { + const filenames = await getFilenames() + + describe.each(filenames)('should handle "%s"', async (filename) => { + const file = await readFile( + path.resolve(import.meta.dirname, `./test-files/${filename}`), + ) + const code = file.toString() + + test.each(['client', 'server'] as const)( + `should compile for ${filename} %s`, + async (env) => { + const compiledResult = compileStartOutput({ + env, + code, + root: './test-files', + filename, + }) + + await expect(compiledResult.code).toMatchFileSnapshot( + `./snapshots/${env}/${filename}`, + ) + }, + ) + }) + + test('should error if created without a handler', () => { + expect(() => { + compileStartOutput({ + env: 'client', + code: ` + import { createServerFn } from '@tanstack/start' + createServerFn()`, + root: './test-files', + filename: 'no-fn.ts', + }) + }).toThrowError() + }) + + test('should be assigned to a variable', () => { + expect(() => { + compileStartOutput({ + env: 'client', + code: ` + import { createServerFn } from '@tanstack/start' + createServerFn().handler(async () => {})`, + root: './test-files', + filename: 'no-fn.ts', + }) + }).toThrowError() + }) +}) diff --git a/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/client/createServerFnDestructured.tsx b/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/client/createServerFnDestructured.tsx new file mode 100644 index 0000000000..be1b58b186 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/client/createServerFnDestructured.tsx @@ -0,0 +1,61 @@ +import { createServerFn } from '@tanstack/start'; +import { z } from 'zod'; +export const withUseServer = createServerFn({ + method: 'GET' +}).handler(opts => { + "use server"; + + return withUseServer.__executeServer(opts); +}); +export const withArrowFunction = createServerFn({ + method: 'GET' +}).handler(opts => { + "use server"; + + return withArrowFunction.__executeServer(opts); +}); +export const withArrowFunctionAndFunction = createServerFn({ + method: 'GET' +}).handler(opts => { + "use server"; + + return withArrowFunctionAndFunction.__executeServer(opts); +}); +export const withoutUseServer = createServerFn({ + method: 'GET' +}).handler(opts => { + "use server"; + + return withoutUseServer.__executeServer(opts); +}); +export const withVariable = createServerFn({ + method: 'GET' +}).handler(opts => { + "use server"; + + return withVariable.__executeServer(opts); +}); +async function abstractedFunction() { + console.info('Fetching posts...'); + await new Promise(r => setTimeout(r, 500)); + return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); +} +function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { + return async (input: unknown) => { + return fn(schema.parse(input)); + }; +} +export const withZodValidator = createServerFn({ + method: 'GET' +}).handler(opts => { + "use server"; + + return withZodValidator.__executeServer(opts); +}); +export const withValidatorFn = createServerFn({ + method: 'GET' +}).handler(opts => { + "use server"; + + return withValidatorFn.__executeServer(opts); +}); \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/client/createServerFnDestructuredRename.tsx b/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/client/createServerFnDestructuredRename.tsx new file mode 100644 index 0000000000..f51f0ade21 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/client/createServerFnDestructuredRename.tsx @@ -0,0 +1,40 @@ +import { createServerFn as serverFn } from '@tanstack/start'; +import { z } from 'zod'; +export const withUseServer = serverFn({ + method: 'GET' +}).handler(opts => { + "use server"; + + return withUseServer.__executeServer(opts); +}); +export const withoutUseServer = serverFn({ + method: 'GET' +}).handler(opts => { + "use server"; + + return withoutUseServer.__executeServer(opts); +}); +export const withVariable = serverFn({ + method: 'GET' +}).handler(opts => { + "use server"; + + return withVariable.__executeServer(opts); +}); +async function abstractedFunction() { + console.info('Fetching posts...'); + await new Promise(r => setTimeout(r, 500)); + return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); +} +function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { + return async (input: unknown) => { + return fn(schema.parse(input)); + }; +} +export const withZodValidator = serverFn({ + method: 'GET' +}).handler(opts => { + "use server"; + + return withZodValidator.__executeServer(opts); +}); \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/client/createServerFnStarImport.tsx b/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/client/createServerFnStarImport.tsx new file mode 100644 index 0000000000..750a52532a --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/client/createServerFnStarImport.tsx @@ -0,0 +1,40 @@ +import * as TanStackStart from '@tanstack/start'; +import { z } from 'zod'; +export const withUseServer = TanStackStart.createServerFn({ + method: 'GET' +}).handler(opts => { + "use server"; + + return withUseServer.__executeServer(opts); +}); +export const withoutUseServer = TanStackStart.createServerFn({ + method: 'GET' +}).handler(opts => { + "use server"; + + return withoutUseServer.__executeServer(opts); +}); +export const withVariable = TanStackStart.createServerFn({ + method: 'GET' +}).handler(opts => { + "use server"; + + return withVariable.__executeServer(opts); +}); +async function abstractedFunction() { + console.info('Fetching posts...'); + await new Promise(r => setTimeout(r, 500)); + return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); +} +function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { + return async (input: unknown) => { + return fn(schema.parse(input)); + }; +} +export const withZodValidator = TanStackStart.createServerFn({ + method: 'GET' +}).handler(opts => { + "use server"; + + return withZodValidator.__executeServer(opts); +}); \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/client/createServerFnValidator.tsx b/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/client/createServerFnValidator.tsx new file mode 100644 index 0000000000..4e40b54a24 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/client/createServerFnValidator.tsx @@ -0,0 +1,9 @@ +import { createServerFn } from '@tanstack/start'; +import { z } from 'zod'; +export const withUseServer = createServerFn({ + method: 'GET' +}).handler(opts => { + "use server"; + + return withUseServer.__executeServer(opts); +}); \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/server/createServerFnDestructured.tsx b/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/server/createServerFnDestructured.tsx new file mode 100644 index 0000000000..0176442a89 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/server/createServerFnDestructured.tsx @@ -0,0 +1,77 @@ +import { createServerFn } from '@tanstack/start'; +import { z } from 'zod'; +export const withUseServer = createServerFn({ + method: 'GET' +}).handler(opts => { + "use server"; + + return withUseServer.__executeServer(opts); +}, async function () { + console.info('Fetching posts...'); + await new Promise(r => setTimeout(r, 500)); + return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); +}); +export const withArrowFunction = createServerFn({ + method: 'GET' +}).handler(opts => { + "use server"; + + return withArrowFunction.__executeServer(opts); +}, async () => null); +export const withArrowFunctionAndFunction = createServerFn({ + method: 'GET' +}).handler(opts => { + "use server"; + + return withArrowFunctionAndFunction.__executeServer(opts); +}, async () => test()); +export const withoutUseServer = createServerFn({ + method: 'GET' +}).handler(opts => { + "use server"; + + return withoutUseServer.__executeServer(opts); +}, async () => { + console.info('Fetching posts...'); + await new Promise(r => setTimeout(r, 500)); + return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); +}); +export const withVariable = createServerFn({ + method: 'GET' +}).handler(opts => { + "use server"; + + return withVariable.__executeServer(opts); +}, abstractedFunction); +async function abstractedFunction() { + console.info('Fetching posts...'); + await new Promise(r => setTimeout(r, 500)); + return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); +} +function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { + return async (input: unknown) => { + return fn(schema.parse(input)); + }; +} +export const withZodValidator = createServerFn({ + method: 'GET' +}).handler(opts => { + "use server"; + + return withZodValidator.__executeServer(opts); +}, zodValidator(z.number(), input => { + return { + 'you gave': input + }; +})); +export const withValidatorFn = createServerFn({ + method: 'GET' +}).validator(z.number()).handler(opts => { + "use server"; + + return withValidatorFn.__executeServer(opts); +}, async ({ + input +}) => { + return null; +}); \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/server/createServerFnDestructuredRename.tsx b/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/server/createServerFnDestructuredRename.tsx new file mode 100644 index 0000000000..b391de555f --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/server/createServerFnDestructuredRename.tsx @@ -0,0 +1,52 @@ +import { createServerFn as serverFn } from '@tanstack/start'; +import { z } from 'zod'; +export const withUseServer = serverFn({ + method: 'GET' +}).handler(opts => { + "use server"; + + return withUseServer.__executeServer(opts); +}, async function () { + console.info('Fetching posts...'); + await new Promise(r => setTimeout(r, 500)); + return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); +}); +export const withoutUseServer = serverFn({ + method: 'GET' +}).handler(opts => { + "use server"; + + return withoutUseServer.__executeServer(opts); +}, async () => { + console.info('Fetching posts...'); + await new Promise(r => setTimeout(r, 500)); + return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); +}); +export const withVariable = serverFn({ + method: 'GET' +}).handler(opts => { + "use server"; + + return withVariable.__executeServer(opts); +}, abstractedFunction); +async function abstractedFunction() { + console.info('Fetching posts...'); + await new Promise(r => setTimeout(r, 500)); + return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); +} +function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { + return async (input: unknown) => { + return fn(schema.parse(input)); + }; +} +export const withZodValidator = serverFn({ + method: 'GET' +}).handler(opts => { + "use server"; + + return withZodValidator.__executeServer(opts); +}, zodValidator(z.number(), input => { + return { + 'you gave': input + }; +})); \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/server/createServerFnStarImport.tsx b/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/server/createServerFnStarImport.tsx new file mode 100644 index 0000000000..66088cb181 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/server/createServerFnStarImport.tsx @@ -0,0 +1,52 @@ +import * as TanStackStart from '@tanstack/start'; +import { z } from 'zod'; +export const withUseServer = TanStackStart.createServerFn({ + method: 'GET' +}).handler(opts => { + "use server"; + + return withUseServer.__executeServer(opts); +}, async function () { + console.info('Fetching posts...'); + await new Promise(r => setTimeout(r, 500)); + return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); +}); +export const withoutUseServer = TanStackStart.createServerFn({ + method: 'GET' +}).handler(opts => { + "use server"; + + return withoutUseServer.__executeServer(opts); +}, async () => { + console.info('Fetching posts...'); + await new Promise(r => setTimeout(r, 500)); + return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); +}); +export const withVariable = TanStackStart.createServerFn({ + method: 'GET' +}).handler(opts => { + "use server"; + + return withVariable.__executeServer(opts); +}, abstractedFunction); +async function abstractedFunction() { + console.info('Fetching posts...'); + await new Promise(r => setTimeout(r, 500)); + return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); +} +function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { + return async (input: unknown) => { + return fn(schema.parse(input)); + }; +} +export const withZodValidator = TanStackStart.createServerFn({ + method: 'GET' +}).handler(opts => { + "use server"; + + return withZodValidator.__executeServer(opts); +}, zodValidator(z.number(), input => { + return { + 'you gave': input + }; +})); \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/server/createServerFnValidator.tsx b/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/server/createServerFnValidator.tsx new file mode 100644 index 0000000000..96cd71b9fb --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/server/createServerFnValidator.tsx @@ -0,0 +1,11 @@ +import { createServerFn } from '@tanstack/start'; +import { z } from 'zod'; +export const withUseServer = createServerFn({ + method: 'GET' +}).validator(z.number()).handler(opts => { + "use server"; + + return withUseServer.__executeServer(opts); +}, ({ + input +}) => input + 1); \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createServerFn/test-files/createServerFnDestructured.tsx b/packages/server-functions-vite-plugin/tests/createServerFn/test-files/createServerFnDestructured.tsx new file mode 100644 index 0000000000..780c1e3370 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createServerFn/test-files/createServerFnDestructured.tsx @@ -0,0 +1,67 @@ +import { createServerFn } from '@tanstack/start' +import { z } from 'zod' + +export const withUseServer = createServerFn({ + method: 'GET', +}).handler(async function () { + console.info('Fetching posts...') + await new Promise((r) => setTimeout(r, 500)) + return axios + .get>('https://jsonplaceholder.typicode.com/posts') + .then((r) => r.data.slice(0, 10)) +}) + +export const withArrowFunction = createServerFn({ + method: 'GET', +}).handler(async () => null) + +export const withArrowFunctionAndFunction = createServerFn({ + method: 'GET', +}).handler(async () => test()) + +export const withoutUseServer = createServerFn({ + method: 'GET', +}).handler(async () => { + console.info('Fetching posts...') + await new Promise((r) => setTimeout(r, 500)) + return axios + .get>('https://jsonplaceholder.typicode.com/posts') + .then((r) => r.data.slice(0, 10)) +}) + +export const withVariable = createServerFn({ + method: 'GET', +}).handler(abstractedFunction) + +async function abstractedFunction() { + console.info('Fetching posts...') + await new Promise((r) => setTimeout(r, 500)) + return axios + .get>('https://jsonplaceholder.typicode.com/posts') + .then((r) => r.data.slice(0, 10)) +} + +function zodValidator( + schema: TSchema, + fn: (input: z.output) => TResult, +) { + return async (input: unknown) => { + return fn(schema.parse(input)) + } +} + +export const withZodValidator = createServerFn({ + method: 'GET', +}).handler( + zodValidator(z.number(), (input) => { + return { 'you gave': input } + }), +) + +export const withValidatorFn = createServerFn({ + method: 'GET', +}) + .validator(z.number()) + .handler(async ({ input }) => { + return null + }) diff --git a/packages/server-functions-vite-plugin/tests/createServerFn/test-files/createServerFnDestructuredRename.tsx b/packages/server-functions-vite-plugin/tests/createServerFn/test-files/createServerFnDestructuredRename.tsx new file mode 100644 index 0000000000..aba9859be3 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createServerFn/test-files/createServerFnDestructuredRename.tsx @@ -0,0 +1,51 @@ +import { createServerFn as serverFn } from '@tanstack/start' +import { z } from 'zod' + +export const withUseServer = serverFn({ + method: 'GET', +}).handler(async function () { + console.info('Fetching posts...') + await new Promise((r) => setTimeout(r, 500)) + return axios + .get>('https://jsonplaceholder.typicode.com/posts') + .then((r) => r.data.slice(0, 10)) +}) + +export const withoutUseServer = serverFn({ + method: 'GET', +}).handler(async () => { + console.info('Fetching posts...') + await new Promise((r) => setTimeout(r, 500)) + return axios + .get>('https://jsonplaceholder.typicode.com/posts') + .then((r) => r.data.slice(0, 10)) +}) + +export const withVariable = serverFn({ method: 'GET' }).handler( + abstractedFunction, +) + +async function abstractedFunction() { + console.info('Fetching posts...') + await new Promise((r) => setTimeout(r, 500)) + return axios + .get>('https://jsonplaceholder.typicode.com/posts') + .then((r) => r.data.slice(0, 10)) +} + +function zodValidator( + schema: TSchema, + fn: (input: z.output) => TResult, +) { + return async (input: unknown) => { + return fn(schema.parse(input)) + } +} + +export const withZodValidator = serverFn({ + method: 'GET', +}).handler( + zodValidator(z.number(), (input) => { + return { 'you gave': input } + }), +) diff --git a/packages/server-functions-vite-plugin/tests/createServerFn/test-files/createServerFnStarImport.tsx b/packages/server-functions-vite-plugin/tests/createServerFn/test-files/createServerFnStarImport.tsx new file mode 100644 index 0000000000..6d5ba022bb --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createServerFn/test-files/createServerFnStarImport.tsx @@ -0,0 +1,52 @@ +import * as TanStackStart from '@tanstack/start' +import { z } from 'zod' + +export const withUseServer = TanStackStart.createServerFn({ + method: 'GET', +}).handler(async function () { + 'use server' + console.info('Fetching posts...') + await new Promise((r) => setTimeout(r, 500)) + return axios + .get>('https://jsonplaceholder.typicode.com/posts') + .then((r) => r.data.slice(0, 10)) +}) + +export const withoutUseServer = TanStackStart.createServerFn({ + method: 'GET', +}).handler(async () => { + console.info('Fetching posts...') + await new Promise((r) => setTimeout(r, 500)) + return axios + .get>('https://jsonplaceholder.typicode.com/posts') + .then((r) => r.data.slice(0, 10)) +}) + +export const withVariable = TanStackStart.createServerFn({ + method: 'GET', +}).handler(abstractedFunction) + +async function abstractedFunction() { + console.info('Fetching posts...') + await new Promise((r) => setTimeout(r, 500)) + return axios + .get>('https://jsonplaceholder.typicode.com/posts') + .then((r) => r.data.slice(0, 10)) +} + +function zodValidator( + schema: TSchema, + fn: (input: z.output) => TResult, +) { + return async (input: unknown) => { + return fn(schema.parse(input)) + } +} + +export const withZodValidator = TanStackStart.createServerFn({ + method: 'GET', +}).handler( + zodValidator(z.number(), (input) => { + return { 'you gave': input } + }), +) diff --git a/packages/server-functions-vite-plugin/tests/createServerFn/test-files/createServerFnValidator.tsx b/packages/server-functions-vite-plugin/tests/createServerFn/test-files/createServerFnValidator.tsx new file mode 100644 index 0000000000..b30bcdc731 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/createServerFn/test-files/createServerFnValidator.tsx @@ -0,0 +1,8 @@ +import { createServerFn } from '@tanstack/start' +import { z } from 'zod' + +export const withUseServer = createServerFn({ + method: 'GET', +}) + .validator(z.number()) + .handler(({ input }) => input + 1) diff --git a/packages/server-functions-vite-plugin/tests/envOnly/envOnly.test.ts b/packages/server-functions-vite-plugin/tests/envOnly/envOnly.test.ts new file mode 100644 index 0000000000..67336be35b --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/envOnly/envOnly.test.ts @@ -0,0 +1,58 @@ +import { readFile, readdir } from 'node:fs/promises' +import path from 'node:path' +import { describe, expect, test } from 'vitest' + +import { compileStartOutput } from '../../src/compilers' + +async function getFilenames() { + return await readdir(path.resolve(import.meta.dirname, './test-files')) +} + +describe('envOnly functions compile correctly', async () => { + const filenames = await getFilenames() + + describe.each(filenames)('should handle "%s"', async (filename) => { + const file = await readFile( + path.resolve(import.meta.dirname, `./test-files/${filename}`), + ) + const code = file.toString() + + test.each(['client', 'server'] as const)( + `should compile for ${filename} %s`, + async (env) => { + const compiledResult = compileStartOutput({ + env, + code, + root: './test-files', + filename, + }) + + await expect(compiledResult.code).toMatchFileSnapshot( + `./snapshots/${env}/${filename}`, + ) + }, + ) + }) + test('should error if implementation not provided', () => { + expect(() => { + compileStartOutput({ + env: 'client', + code: ` + import { clientOnly } from '@tanstack/start' + const fn = clientOnly()`, + root: './test-files', + filename: 'no-fn.ts', + }) + }).toThrowError() + expect(() => { + compileStartOutput({ + env: 'server', + code: ` + import { serverOnly } from '@tanstack/start' + const fn = serverOnly()`, + root: './test-files', + filename: 'no-fn.ts', + }) + }).toThrowError() + }) +}) diff --git a/packages/server-functions-vite-plugin/tests/envOnly/snapshots/client/envOnlyDestructured.tsx b/packages/server-functions-vite-plugin/tests/envOnly/snapshots/client/envOnlyDestructured.tsx new file mode 100644 index 0000000000..3dc714f696 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/envOnly/snapshots/client/envOnlyDestructured.tsx @@ -0,0 +1,5 @@ +import { serverOnly, clientOnly } from '@tanstack/start'; +const serverFunc = () => { + throw new Error("serverOnly() functions can only be called on the server!"); +}; +const clientFunc = () => 'client'; \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/envOnly/snapshots/client/envOnlyDestructuredRename.tsx b/packages/server-functions-vite-plugin/tests/envOnly/snapshots/client/envOnlyDestructuredRename.tsx new file mode 100644 index 0000000000..3dd661c865 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/envOnly/snapshots/client/envOnlyDestructuredRename.tsx @@ -0,0 +1,5 @@ +import { serverOnly as serverFn, clientOnly as clientFn } from '@tanstack/start'; +const serverFunc = () => { + throw new Error("serverOnly() functions can only be called on the server!"); +}; +const clientFunc = () => 'client'; \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/envOnly/snapshots/client/envOnlyStarImport.tsx b/packages/server-functions-vite-plugin/tests/envOnly/snapshots/client/envOnlyStarImport.tsx new file mode 100644 index 0000000000..61f0677953 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/envOnly/snapshots/client/envOnlyStarImport.tsx @@ -0,0 +1,5 @@ +import * as TanstackStart from '@tanstack/start'; +const serverFunc = () => { + throw new Error("serverOnly() functions can only be called on the server!"); +}; +const clientFunc = () => 'client'; \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/envOnly/snapshots/server/envOnlyDestructured.tsx b/packages/server-functions-vite-plugin/tests/envOnly/snapshots/server/envOnlyDestructured.tsx new file mode 100644 index 0000000000..24f736eac2 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/envOnly/snapshots/server/envOnlyDestructured.tsx @@ -0,0 +1,5 @@ +import { serverOnly, clientOnly } from '@tanstack/start'; +const serverFunc = () => 'server'; +const clientFunc = () => { + throw new Error("clientOnly() functions can only be called on the client!"); +}; \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/envOnly/snapshots/server/envOnlyDestructuredRename.tsx b/packages/server-functions-vite-plugin/tests/envOnly/snapshots/server/envOnlyDestructuredRename.tsx new file mode 100644 index 0000000000..790e1328d7 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/envOnly/snapshots/server/envOnlyDestructuredRename.tsx @@ -0,0 +1,5 @@ +import { serverOnly as serverFn, clientOnly as clientFn } from '@tanstack/start'; +const serverFunc = () => 'server'; +const clientFunc = () => { + throw new Error("clientOnly() functions can only be called on the client!"); +}; \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/envOnly/snapshots/server/envOnlyStarImport.tsx b/packages/server-functions-vite-plugin/tests/envOnly/snapshots/server/envOnlyStarImport.tsx new file mode 100644 index 0000000000..51e320d4a2 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/envOnly/snapshots/server/envOnlyStarImport.tsx @@ -0,0 +1,5 @@ +import * as TanstackStart from '@tanstack/start'; +const serverFunc = () => 'server'; +const clientFunc = () => { + throw new Error("clientOnly() functions can only be called on the client!"); +}; \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/envOnly/test-files/envOnlyDestructured.tsx b/packages/server-functions-vite-plugin/tests/envOnly/test-files/envOnlyDestructured.tsx new file mode 100644 index 0000000000..1389624d34 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/envOnly/test-files/envOnlyDestructured.tsx @@ -0,0 +1,5 @@ +import { serverOnly, clientOnly } from '@tanstack/start' + +const serverFunc = serverOnly(() => 'server') + +const clientFunc = clientOnly(() => 'client') diff --git a/packages/server-functions-vite-plugin/tests/envOnly/test-files/envOnlyDestructuredRename.tsx b/packages/server-functions-vite-plugin/tests/envOnly/test-files/envOnlyDestructuredRename.tsx new file mode 100644 index 0000000000..ac34f06134 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/envOnly/test-files/envOnlyDestructuredRename.tsx @@ -0,0 +1,5 @@ +import { serverOnly as serverFn, clientOnly as clientFn } from '@tanstack/start' + +const serverFunc = serverFn(() => 'server') + +const clientFunc = clientFn(() => 'client') diff --git a/packages/server-functions-vite-plugin/tests/envOnly/test-files/envOnlyStarImport.tsx b/packages/server-functions-vite-plugin/tests/envOnly/test-files/envOnlyStarImport.tsx new file mode 100644 index 0000000000..cd262b54a0 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/envOnly/test-files/envOnlyStarImport.tsx @@ -0,0 +1,5 @@ +import * as TanstackStart from '@tanstack/start' + +const serverFunc = TanstackStart.serverOnly(() => 'server') + +const clientFunc = TanstackStart.clientOnly(() => 'client') diff --git a/packages/server-functions-vite-plugin/tsconfig.json b/packages/server-functions-vite-plugin/tsconfig.json new file mode 100644 index 0000000000..37d21ef6ca --- /dev/null +++ b/packages/server-functions-vite-plugin/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.json", + "include": ["src", "vite.config.ts", "tests"], + "exclude": ["tests/**/test-files/**", "tests/**/snapshots/**"], + "compilerOptions": { + "jsx": "react-jsx" + } +} diff --git a/packages/server-functions-vite-plugin/vite.config.ts b/packages/server-functions-vite-plugin/vite.config.ts new file mode 100644 index 0000000000..5389f0f739 --- /dev/null +++ b/packages/server-functions-vite-plugin/vite.config.ts @@ -0,0 +1,20 @@ +import { defineConfig, mergeConfig } from 'vitest/config' +import { tanstackViteConfig } from '@tanstack/config/vite' +import packageJson from './package.json' + +const config = defineConfig({ + test: { + name: packageJson.name, + dir: './tests', + watch: false, + typecheck: { enabled: true }, + }, +}) + +export default mergeConfig( + config, + tanstackViteConfig({ + entry: './src/index.ts', + srcDir: './src', + }), +) diff --git a/packages/start/package.json b/packages/start/package.json index afde4bd213..549da390f1 100644 --- a/packages/start/package.json +++ b/packages/start/package.json @@ -36,9 +36,10 @@ "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js", "test:types:ts57": "tsc", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", - "build": "vite build && pnpm build:config && pnpm build:router-manifest", + "build": "pnpm build:config && pnpm build:router-manifest && pnpm build:vite", "build:config": "tsc --project tsconfigs/config.tsconfig.json", - "build:router-manifest": "tsc --project tsconfigs/router-manifest.tsconfig.json" + "build:router-manifest": "tsc --project tsconfigs/router-manifest.tsconfig.json", + "build:vite": "vite build" }, "type": "module", "exports": { @@ -110,10 +111,10 @@ "default": "./dist/esm/server-runtime/index.js" } }, - "./react-server-runtime": { + "./ssr-runtime": { "import": { - "types": "./dist/esm/react-server-runtime/index.d.ts", - "default": "./dist/esm/react-server-runtime/index.js" + "types": "./dist/esm/ssr-runtime/index.d.ts", + "default": "./dist/esm/ssr-runtime/index.js" } }, "./server-handler": { diff --git a/packages/start/src/client-runtime/index.tsx b/packages/start/src/client-runtime/index.tsx index 9e4f2b67f6..2c02f6b9c7 100644 --- a/packages/start/src/client-runtime/index.tsx +++ b/packages/start/src/client-runtime/index.tsx @@ -1,21 +1,19 @@ import { fetcher } from './fetcher' import { getBaseUrl } from './getBaseUrl' -import type { ServerFn } from '../client/createServerFn' +import type { CreateRpcFn } from '@tanstack/start/server-functions-plugin' -export function createServerReference( - _fn: ServerFn, - id: string, - name: string, -) { - // let base = getBaseUrl(import.meta.env.SERVER_BASE_URL, id, name) - const base = getBaseUrl(window.location.origin, id, name) +export const createClientRpc: CreateRpcFn = ( + filename: string, + functionId: string, +) => { + const base = getBaseUrl(window.location.origin, filename, functionId) - const proxyFn = (...args: Array) => fetcher(base, args, fetch) + const fn = (...args: Array) => fetcher(base, args, fetch) - return Object.assign(proxyFn, { + return Object.assign(fn, { url: base, - filename: id, - functionId: name, + filename, + functionId, }) } diff --git a/packages/start/src/config/index.ts b/packages/start/src/config/index.ts index f371997c8e..8e0d5dbdc2 100644 --- a/packages/start/src/config/index.ts +++ b/packages/start/src/config/index.ts @@ -14,10 +14,7 @@ import { createApp } from 'vinxi' import { config } from 'vinxi/plugins/config' // // @ts-expect-error // import { serverComponents } from '@vinxi/server-components/plugin' -// @ts-expect-error -import { serverFunctions } from '@vinxi/server-functions/plugin' -// @ts-expect-error -import { serverTransform } from '@vinxi/server-functions/server' +import { createServerFunctionsPlugin } from '@tanstack/start/server-functions-plugin' import { tanstackStartVinxiFileRouter } from './vinxi-file-router.js' import { checkDeploymentPresetInput, @@ -123,6 +120,8 @@ export function defineConfig( const apiEntryExists = existsSync(apiEntry) + const serverFunctionsPlugin = createServerFunctionsPlugin() + let vinxiApp = createApp({ server: { ...serverOptions, @@ -170,8 +169,10 @@ export function defineConfig( }), ...(viteConfig.plugins || []), ...(clientViteConfig.plugins || []), - serverFunctions.client({ - runtime: '@tanstack/start/client-runtime', + serverFunctionsPlugin.client({ + runtimeCode: `import { createClientRpc } from '@tanstack/start/client-runtime'`, + replacer: (opts) => + `createClientRpc('${opts.filename}', '${opts.functionId}')`, }), viteReact(opts.react), // TODO: RSCS - enable this @@ -211,8 +212,10 @@ export function defineConfig( }), ...(getUserViteConfig(opts.vite).plugins || []), ...(getUserViteConfig(opts.routers?.ssr?.vite).plugins || []), - serverTransform({ - runtime: '@tanstack/start/server-runtime', + serverFunctionsPlugin.server({ + runtimeCode: `import { createServerRpc } from '@tanstack/start/ssr-runtime'`, + replacer: (opts) => + `createSsrRpc('${opts.filename}', '${opts.functionId}')`, }), config('start-ssr', { ssr: { @@ -254,12 +257,14 @@ export function defineConfig( ...injectDefineEnv('TSS_API_BASE', apiBase), }, }), - serverFunctions.server({ - runtime: '@tanstack/start/react-server-runtime', + serverFunctionsPlugin.server({ + runtimeCode: `import { createServerRpc } from '@tanstack/start/server-runtime'`, + replacer: (opts) => + `createServerRpc('${opts.filename}', '${opts.functionId}')`, // TODO: RSCS - remove this - resolve: { - conditions: [], - }, + // resolve: { + // conditions: [], + // }, }), // TODO: RSCs - add this // serverComponents.serverActions({ diff --git a/packages/start/src/react-server-runtime/index.tsx b/packages/start/src/react-server-runtime/index.tsx deleted file mode 100644 index d7fbea3fe7..0000000000 --- a/packages/start/src/react-server-runtime/index.tsx +++ /dev/null @@ -1,14 +0,0 @@ -// import { getBaseUrl } from '../client-runtime/getBaseUrl' - -export function createServerReference( - fn: any, - id: string, - name: string, -) { - // const functionUrl = getBaseUrl('http://localhost:3000', id, name) - const functionUrl = 'https://localhost:3000' - - return Object.assign(fn, { - url: functionUrl, - }) -} diff --git a/packages/start/src/server-runtime/index.tsx b/packages/start/src/server-runtime/index.tsx index eda1e96e91..5d1a68cb87 100644 --- a/packages/start/src/server-runtime/index.tsx +++ b/packages/start/src/server-runtime/index.tsx @@ -1,159 +1,17 @@ -import { Readable } from 'node:stream' -import { getEvent, getRequestHeaders } from 'vinxi/http' -import invariant from 'tiny-invariant' -import { fetcher } from '../client-runtime/fetcher' -import { getBaseUrl } from '../client-runtime/getBaseUrl' -import { handleServerRequest } from '../server-handler/index' -/** - * - * @returns {import('node:http').IncomingMessage} - */ -export function createIncomingMessage( - url: string, - method: string, - headers: HeadersInit, -): Readable { - const readable = new Readable({ objectMode: true }) as any - readable._read = () => {} +// import { getBaseUrl } from '../client-runtime/getBaseUrl' +import type { CreateRpcFn } from '@tanstack/start/server-functions-plugin' - readable.url = url - readable.method = method - readable.headers = headers - readable.connection = {} - readable.getHeaders = () => { - return headers - } - return readable -} +export const createServerRpc: CreateRpcFn = ( + fn: any, + filename: string, + functionId: string, +) => { + // const functionUrl = getBaseUrl('http://localhost:3000', id, name) + const functionUrl = 'https://localhost:3000' -// function createAsyncStream(options?: WritableOptions) { -// let firstActivity = false -// let resolveActivity: () => void -// let finishActivity: () => void - -// const initialPromise = new Promise((resolve) => { -// resolveActivity = resolve -// }) - -// const finishPromise = new Promise((resolve) => { -// finishActivity = resolve -// }) - -// const readable = new Readable({ -// objectMode: true, -// }) - -// readable._read = () => {} - -// const writable = new Writable({ -// ...options, -// write(chunk, encoding, callback) { -// if (!firstActivity) { -// firstActivity = true -// resolveActivity() -// } -// readable.push(chunk, encoding) -// callback() -// }, -// }) as any - -// const headers = new Headers() - -// writable.setHeader = (key: string, value: string) => { -// headers.set(key, value) -// } - -// writable.on('finish', () => { -// readable.push(null) -// readable.destroy() -// finishActivity() -// }) - -// return { -// readable, -// writable, -// headers, -// initialPromise, -// finishPromise, -// } as const -// } - -const fakeHost = 'http://localhost:3000' - -export function createServerReference(_fn: any, id: string, name: string) { - const functionUrl = getBaseUrl(fakeHost, id, name) - - const proxyFn = (...args: Array) => { - invariant( - args.length === 1, - 'Server functions can only accept a single argument', - ) - - return fetcher(functionUrl, args, async (request) => { - const event = getEvent() - - const ogRequestHeaders = getRequestHeaders(event) - - Object.entries(ogRequestHeaders).forEach(([key, value]) => { - if (!request.headers.has(key)) { - request.headers.append(key, value!) - } - }) - - // // For RSC, we need to proxy this request back to the server under - // // the /_server path and let the RSC/Server-fn router handle it - // if (RSC) { - - // const incomingMessage = createIncomingMessage( - // new URL(request.url).pathname + new URL(request.url).search, - // request.method, - // Object.fromEntries(request.headers.entries()), - // ) - - // const asyncStream = createAsyncStream() - - // const result = await handleHTTPEvent( - // new H3Event(incomingMessage as any, asyncStream.writable), - // ) - - // console.info('awaiting initial promise', result, asyncStream) - - // await asyncStream.initialPromise - - // // Only augment the headers of the underlying document request - // // if the response headers have not been sent yet - // if (!(event as any).__tsrHeadersSent) { - // const ogResponseHeaders = getResponseHeaders(event) - - // asyncStream.headers.forEach((value, key) => { - // if (!Object.hasOwn(ogResponseHeaders, key)) { - // ogResponseHeaders[key] = value - // } - // }) - - // setResponseHeaders(event, ogResponseHeaders as any) - // } - - // console.info(asyncStream.readable) - - // // if (asyncStream.headers.get('content-type') === 'application/json') { - // // await asyncStream.finishPromise - // // } - - // return new Response(Readable.toWeb(asyncStream.readable) as any, { - // headers: asyncStream.headers, - // }) - // } - - // For now, we're not doing RSC, so we just handle the request - // in the current non-worker scope - return handleServerRequest(request, event) - }) - } - - return Object.assign(proxyFn, { - url: functionUrl.replace(fakeHost, ''), - filename: id, - functionId: name, + return Object.assign(fn, { + url: functionUrl, + filename, + functionId, }) } diff --git a/packages/start/src/ssr-runtime/index.tsx b/packages/start/src/ssr-runtime/index.tsx new file mode 100644 index 0000000000..f2c3582da6 --- /dev/null +++ b/packages/start/src/ssr-runtime/index.tsx @@ -0,0 +1,161 @@ +import { Readable } from 'node:stream' +import { getEvent, getRequestHeaders } from 'vinxi/http' +import invariant from 'tiny-invariant' +import { fetcher } from '../client-runtime/fetcher' +import { getBaseUrl } from '../client-runtime/getBaseUrl' +import { handleServerRequest } from '../server-handler/index' +import type { CreateRpcFn } from '@tanstack/start/server-functions-plugin' + +export function createIncomingMessage( + url: string, + method: string, + headers: HeadersInit, +): Readable { + const readable = new Readable({ objectMode: true }) as any + readable._read = () => {} + + readable.url = url + readable.method = method + readable.headers = headers + readable.connection = {} + readable.getHeaders = () => { + return headers + } + return readable +} + +// function createAsyncStream(options?: WritableOptions) { +// let firstActivity = false +// let resolveActivity: () => void +// let finishActivity: () => void + +// const initialPromise = new Promise((resolve) => { +// resolveActivity = resolve +// }) + +// const finishPromise = new Promise((resolve) => { +// finishActivity = resolve +// }) + +// const readable = new Readable({ +// objectMode: true, +// }) + +// readable._read = () => {} + +// const writable = new Writable({ +// ...options, +// write(chunk, encoding, callback) { +// if (!firstActivity) { +// firstActivity = true +// resolveActivity() +// } +// readable.push(chunk, encoding) +// callback() +// }, +// }) as any + +// const headers = new Headers() + +// writable.setHeader = (key: string, value: string) => { +// headers.set(key, value) +// } + +// writable.on('finish', () => { +// readable.push(null) +// readable.destroy() +// finishActivity() +// }) + +// return { +// readable, +// writable, +// headers, +// initialPromise, +// finishPromise, +// } as const +// } + +const fakeHost = 'http://localhost:3000' + +export const createSsrRpc: CreateRpcFn = ( + _fn: any, + filename: string, + functionId: string, +) => { + const functionUrl = getBaseUrl(fakeHost, filename, functionId) + + const proxyFn = (...args: Array) => { + invariant( + args.length === 1, + 'Server functions can only accept a single argument', + ) + + return fetcher(functionUrl, args, async (request) => { + const event = getEvent() + + const ogRequestHeaders = getRequestHeaders(event) + + Object.entries(ogRequestHeaders).forEach(([key, value]) => { + if (!request.headers.has(key)) { + request.headers.append(key, value!) + } + }) + + // // For RSC, we need to proxy this request back to the server under + // // the /_server path and let the RSC/Server-fn router handle it + // if (RSC) { + + // const incomingMessage = createIncomingMessage( + // new URL(request.url).pathname + new URL(request.url).search, + // request.method, + // Object.fromEntries(request.headers.entries()), + // ) + + // const asyncStream = createAsyncStream() + + // const result = await handleHTTPEvent( + // new H3Event(incomingMessage as any, asyncStream.writable), + // ) + + // console.info('awaiting initial promise', result, asyncStream) + + // await asyncStream.initialPromise + + // // Only augment the headers of the underlying document request + // // if the response headers have not been sent yet + // if (!(event as any).__tsrHeadersSent) { + // const ogResponseHeaders = getResponseHeaders(event) + + // asyncStream.headers.forEach((value, key) => { + // if (!Object.hasOwn(ogResponseHeaders, key)) { + // ogResponseHeaders[key] = value + // } + // }) + + // setResponseHeaders(event, ogResponseHeaders as any) + // } + + // console.info(asyncStream.readable) + + // // if (asyncStream.headers.get('content-type') === 'application/json') { + // // await asyncStream.finishPromise + // // } + + // return new Response(Readable.toWeb(asyncStream.readable) as any, { + // headers: asyncStream.headers, + // }) + // } + + // For now, we're not doing RSC, so we just handle the request + // in the current non-worker scope + return handleServerRequest(request, event) + }) + } + + return Object.assign(proxyFn, { + url: functionUrl.replace(fakeHost, ''), + filename, + functionId, + }) +} diff --git a/packages/start/tsconfig.json b/packages/start/tsconfig.json index fe3fb37c9e..51dda9abf2 100644 --- a/packages/start/tsconfig.json +++ b/packages/start/tsconfig.json @@ -4,5 +4,5 @@ "jsx": "react-jsx", "module": "esnext" }, - "include": ["src", "vite.config.ts", "src/client/DehydrateRouter.tsx"] + "include": ["src", "vite.config.ts"] } diff --git a/packages/start/tsconfigs/config.tsconfig.json b/packages/start/tsconfigs/config.tsconfig.json index 948b455bbc..58fc33fb0a 100644 --- a/packages/start/tsconfigs/config.tsconfig.json +++ b/packages/start/tsconfigs/config.tsconfig.json @@ -2,6 +2,7 @@ "extends": "../../../tsconfig.json", "include": ["../src/config/index.ts"], "compilerOptions": { + "rootDir": "../src/config", "outDir": "../dist/esm/config", "target": "esnext", "noEmit": false diff --git a/packages/start/tsconfigs/router-manifest.tsconfig.json b/packages/start/tsconfigs/router-manifest.tsconfig.json index 4849ec7e6a..cc108d2494 100644 --- a/packages/start/tsconfigs/router-manifest.tsconfig.json +++ b/packages/start/tsconfigs/router-manifest.tsconfig.json @@ -2,6 +2,7 @@ "extends": "../../../tsconfig.json", "include": ["../src/router-manifest/index.ts"], "compilerOptions": { + "rootDir": "../src/router-manifest", "outDir": "../dist/esm/router-manifest", "target": "esnext", "noEmit": false diff --git a/packages/start/tsconfigs/server-functions-plugin.tsconfig.json b/packages/start/tsconfigs/server-functions-plugin.tsconfig.json new file mode 100644 index 0000000000..440bc758da --- /dev/null +++ b/packages/start/tsconfigs/server-functions-plugin.tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../../tsconfig.json", + "include": ["../src/server-functions-plugin/index.ts"], + "compilerOptions": { + "rootDir": "../src/server-functions-plugin", + "outDir": "../dist/esm/server-functions-plugin", + "target": "esnext", + "noEmit": false + } +} diff --git a/packages/start/vite.config.ts b/packages/start/vite.config.ts index 82a14ae09b..7f3b092680 100644 --- a/packages/start/vite.config.ts +++ b/packages/start/vite.config.ts @@ -20,10 +20,10 @@ export default mergeConfig( entry: [ './src/client/index.tsx', './src/server/index.tsx', - './src/client-runtime/index.tsx', './src/api/index.ts', + './src/client-runtime/index.tsx', './src/server-runtime/index.tsx', - './src/react-server-runtime/index.tsx', + './src/ssr-runtime/index.tsx', './src/server-handler/index.tsx', ], srcDir: './src', From 83e7a78b236088488a6fc400d99b5b6095b76839 Mon Sep 17 00:00:00 2001 From: Tanner Linsley Date: Thu, 12 Dec 2024 00:44:43 -0700 Subject: [PATCH 02/13] checkpoint --- .prettierignore | 3 +- .../server-functions-vite-plugin/package.json | 4 +- .../server-functions-vite-plugin/src/ast.ts | 44 +- .../src/compilers.ts | 728 ++---------------- .../server-functions-vite-plugin/src/index.ts | 33 +- packages/start/package.json | 1 + packages/start/src/client-runtime/index.tsx | 17 +- packages/start/src/config/index.ts | 13 +- packages/start/src/server-runtime/index.tsx | 14 +- packages/start/src/ssr-runtime/index.tsx | 14 +- pnpm-lock.yaml | 54 ++ 11 files changed, 206 insertions(+), 719 deletions(-) diff --git a/.prettierignore b/.prettierignore index 210d68c1b1..a234ee7bd1 100644 --- a/.prettierignore +++ b/.prettierignore @@ -13,4 +13,5 @@ pnpm-lock.yaml node_modules **/test-results -**/tests/generator/file-modification/routes/(test)/* \ No newline at end of file +**/tests/generator/file-modification/routes/(test)/* +/.nx/workspace-data \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/package.json b/packages/server-functions-vite-plugin/package.json index 41d0915a16..2dbf643a41 100644 --- a/packages/server-functions-vite-plugin/package.json +++ b/packages/server-functions-vite-plugin/package.json @@ -1,5 +1,5 @@ { - "name": "@tanstack/start-vite-plugin", + "name": "@tanstack/server-functions-plugin", "version": "1.87.3", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", @@ -7,7 +7,7 @@ "repository": { "type": "git", "url": "https://github.com/TanStack/router.git", - "directory": "packages/start-vite-plugin" + "directory": "packages/server-functions-plugin" }, "homepage": "https://tanstack.com/start", "funding": { diff --git a/packages/server-functions-vite-plugin/src/ast.ts b/packages/server-functions-vite-plugin/src/ast.ts index 6062993cfd..c353b97abc 100644 --- a/packages/server-functions-vite-plugin/src/ast.ts +++ b/packages/server-functions-vite-plugin/src/ast.ts @@ -1,44 +1,20 @@ -import * as babel from '@babel/core' -import '@babel/parser' -// @ts-expect-error -import _babelPluginJsx from '@babel/plugin-syntax-jsx' -// @ts-expect-error -import _babelPluginTypeScript from '@babel/plugin-syntax-typescript' - -let babelPluginJsx = _babelPluginJsx -let babelPluginTypeScript = _babelPluginTypeScript - -if (babelPluginJsx.default) { - babelPluginJsx = babelPluginJsx.default -} - -if (babelPluginTypeScript.default) { - babelPluginTypeScript = babelPluginTypeScript.default -} +import { parse } from '@babel/parser' +import type { ParseResult } from '@babel/parser' export type ParseAstOptions = { code: string filename: string root: string - env: 'server' | 'client' } -export function parseAst(opts: ParseAstOptions) { - const babelPlugins: Array = [ - babelPluginJsx, - [ - babelPluginTypeScript, - { - isTSX: true, - }, - ], - ] - - return babel.parse(opts.code, { - plugins: babelPlugins, - root: opts.root, - filename: opts.filename, - sourceMaps: true, +export function parseAst(opts: ParseAstOptions): ParseResult { + return parse(opts.code, { + plugins: ['jsx', 'typescript'], sourceType: 'module', + ...{ + root: opts.root, + filename: opts.filename, + sourceMaps: true, + }, }) } diff --git a/packages/server-functions-vite-plugin/src/compilers.ts b/packages/server-functions-vite-plugin/src/compilers.ts index a5d8c49b11..1103bba03b 100644 --- a/packages/server-functions-vite-plugin/src/compilers.ts +++ b/packages/server-functions-vite-plugin/src/compilers.ts @@ -1,28 +1,13 @@ import * as babel from '@babel/core' -import * as t from '@babel/types' -import _generate from '@babel/generator' +import generate from '@babel/generator' import { codeFrameColumns } from '@babel/code-frame' import { deadCodeElimination } from 'babel-dead-code-elimination' import { parseAst } from './ast' import type { ParseAstOptions } from './ast' -// Babel is a CJS package and uses `default` as named binding (`exports.default =`). -// https://github.com/babel/babel/issues/15269. -let generate = (_generate as any)['default'] as typeof _generate - -// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -if (!generate) { - generate = _generate -} - export function compileEliminateDeadCode(opts: ParseAstOptions) { const ast = parseAst(opts) - if (!ast) { - throw new Error( - `Failed to compile ast for compileEliminateDeadCode() for the file: ${opts.filename}`, - ) - } deadCodeElimination(ast) return generate(ast, { @@ -32,665 +17,114 @@ export function compileEliminateDeadCode(opts: ParseAstOptions) { const debug = process.env.TSR_VITE_DEBUG === 'true' -// build these once and reuse them -const handleServerOnlyCallExpression = - buildEnvOnlyCallExpressionHandler('server') -const handleClientOnlyCallExpression = - buildEnvOnlyCallExpressionHandler('client') - -type IdentifierConfig = { - name: string - type: 'ImportSpecifier' | 'ImportNamespaceSpecifier' - namespaceId: string - handleCallExpression: ( - path: babel.NodePath, - opts: ParseAstOptions, - ) => void - paths: Array -} - -export function compileStartOutput(opts: ParseAstOptions) { +export function compileServerFnClient(opts: ParseAstOptions) { const ast = parseAst(opts) - if (!ast) { - throw new Error( - `Failed to compile ast for compileStartOutput() for the file: ${opts.filename}`, - ) - } + const serverFnPaths: Array = [] babel.traverse(ast, { Program: { enter(programPath) { - const identifiers: { - createServerFn: IdentifierConfig - createMiddleware: IdentifierConfig - serverOnly: IdentifierConfig - clientOnly: IdentifierConfig - createIsomorphicFn: IdentifierConfig - } = { - createServerFn: { - name: 'createServerFn', - type: 'ImportSpecifier', - namespaceId: '', - handleCallExpression: handleCreateServerFnCallExpression, - paths: [], - }, - createMiddleware: { - name: 'createMiddleware', - type: 'ImportSpecifier', - namespaceId: '', - handleCallExpression: handleCreateMiddlewareCallExpression, - paths: [], - }, - serverOnly: { - name: 'serverOnly', - type: 'ImportSpecifier', - namespaceId: '', - handleCallExpression: handleServerOnlyCallExpression, - paths: [], - }, - clientOnly: { - name: 'clientOnly', - type: 'ImportSpecifier', - namespaceId: '', - handleCallExpression: handleClientOnlyCallExpression, - paths: [], - }, - createIsomorphicFn: { - name: 'createIsomorphicFn', - type: 'ImportSpecifier', - namespaceId: '', - handleCallExpression: handleCreateIsomorphicFnCallExpression, - paths: [], - }, - } - - const identifierKeys = Object.keys(identifiers) as Array< - keyof typeof identifiers - > - programPath.traverse({ - ImportDeclaration: (path) => { - if (path.node.source.value !== '@tanstack/start') { - return + enter(path) { + // Check for 'use server' directive in function declarations (named functions) + if (path.isFunctionDeclaration()) { + const directives = path.node.body.directives + for (const directive of directives) { + if (directive.value.value === 'use server') { + serverFnPaths.push(path) + } + } } - // handle a destructured imports being renamed like "import { createServerFn as myCreateServerFn } from '@tanstack/start';" - path.node.specifiers.forEach((specifier) => { - identifierKeys.forEach((identifierKey) => { - const identifier = identifiers[identifierKey] - - if ( - specifier.type === 'ImportSpecifier' && - specifier.imported.type === 'Identifier' - ) { - if (specifier.imported.name === identifierKey) { - identifier.name = specifier.local.name - identifier.type = 'ImportSpecifier' - } + // Check for 'use server' directive in function expressions (anonymous functions) + if (path.isFunctionExpression()) { + const directives = path.node.body.directives + for (const directive of directives) { + if (directive.value.value === 'use server') { + serverFnPaths.push(path) } - - // handle namespace imports like "import * as TanStackStart from '@tanstack/start';" - if (specifier.type === 'ImportNamespaceSpecifier') { - identifier.type = 'ImportNamespaceSpecifier' - identifier.namespaceId = specifier.local.name - identifier.name = `${identifier.namespaceId}.${identifierKey}` - } - }) - }) - }, - CallExpression: (path) => { - identifierKeys.forEach((identifierKey) => { - // Check to see if the call expression is a call to the - // identifiers[identifierKey].name - if ( - t.isIdentifier(path.node.callee) && - path.node.callee.name === identifiers[identifierKey].name - ) { - // The identifier could be a call to the original function - // in the source code. If this is case, we need to ignore it. - // Check the scope to see if the identifier is a function declaration. - // if it is, then we can ignore it. - - if ( - path.scope.getBinding(identifiers[identifierKey].name)?.path - .node.type === 'FunctionDeclaration' - ) { - return - } - - return identifiers[identifierKey].paths.push(path) } + } - if (t.isMemberExpression(path.node.callee)) { - if ( - t.isIdentifier(path.node.callee.object) && - t.isIdentifier(path.node.callee.property) - ) { - const callname = [ - path.node.callee.object.name, - path.node.callee.property.name, - ].join('.') - - if (callname === identifiers[identifierKey].name) { - identifiers[identifierKey].paths.push(path) + // Check for 'use server' directive in arrow functions + if (path.isArrowFunctionExpression()) { + if (babel.types.isBlockStatement(path.node.body)) { + const directives = path.node.body.directives + for (const directive of directives) { + if (directive.value.value === 'use server') { + serverFnPaths.push(path) } } } + } - return - }) + // Check for 'use server' directive in class methods + if (path.isClassMethod()) { + const directives = path.node.body.directives + for (const directive of directives) { + if (directive.value.value === 'use server') { + serverFnPaths.push(path) + } + } + } + + // Check for 'use server' directive in object methods + if (path.isObjectMethod()) { + const directives = path.node.body.directives + for (const directive of directives) { + if (directive.value.value === 'use server') { + serverFnPaths.push(path) + } + } + } + + // Check for 'use server' directive in variable declarations with function expressions + if ( + path.isVariableDeclarator() && + (babel.types.isFunctionExpression(path.node.init) || + babel.types.isArrowFunctionExpression(path.node.init)) + ) { + const init = path.node.init + if (babel.types.isBlockStatement(init.body)) { + const directives = init.body.directives + for (const directive of directives) { + if (directive.value.value === 'use server') { + serverFnPaths.push(path.get('init') as babel.NodePath) + } + } + } + } + + return serverFnPaths }, }) - - identifierKeys.forEach((identifierKey) => { - identifiers[identifierKey].paths.forEach((path) => { - identifiers[identifierKey].handleCallExpression( - path as babel.NodePath, - opts, - ) - }) - }) }, }, }) + const compiledCode = generate(ast, { + sourceMaps: true, + minified: process.env.NODE_ENV === 'production', + }) + + console.log(serverFnPaths) + + return { + compiledCode, + serverFns: serverFnPaths, + } +} + +export function compileServerFnServer(opts: ParseAstOptions) { + const ast = parseAst(opts) + return generate(ast, { sourceMaps: true, minified: process.env.NODE_ENV === 'production', }) } -function handleCreateServerFnCallExpression( - path: babel.NodePath, - opts: ParseAstOptions, -) { - // The function is the 'fn' property of the object passed to createServerFn - - // const firstArg = path.node.arguments[0] - // if (t.isObjectExpression(firstArg)) { - // // Was called with some options - // } - - // Traverse the member expression and find the call expressions for - // the validator, handler, and middleware methods. Check to make sure they - // are children of the createServerFn call expression. - - const calledOptions = path.node.arguments[0] - ? (path.get('arguments.0') as babel.NodePath) - : null - - const shouldValidateClient = !!calledOptions?.node.properties.find((prop) => { - return ( - t.isObjectProperty(prop) && - t.isIdentifier(prop.key) && - prop.key.name === 'validateClient' && - t.isBooleanLiteral(prop.value) && - prop.value.value === true - ) - }) - - const callExpressionPaths = { - middleware: null as babel.NodePath | null, - validator: null as babel.NodePath | null, - handler: null as babel.NodePath | null, - } - - const validMethods = Object.keys(callExpressionPaths) - - const rootCallExpression = getRootCallExpression(path) - - if (debug) - console.info( - 'Handling createServerFn call expression:', - rootCallExpression.toString(), - ) - - // Check if the call is assigned to a variable - if (!rootCallExpression.parentPath.isVariableDeclarator()) { - throw new Error('createServerFn must be assigned to a variable!') - } - - // Get the identifier name of the variable - const variableDeclarator = rootCallExpression.parentPath.node - const existingVariableName = (variableDeclarator.id as t.Identifier).name - - rootCallExpression.traverse({ - MemberExpression(memberExpressionPath) { - if (t.isIdentifier(memberExpressionPath.node.property)) { - const name = memberExpressionPath.node.property - .name as keyof typeof callExpressionPaths - - if ( - validMethods.includes(name) && - memberExpressionPath.parentPath.isCallExpression() - ) { - callExpressionPaths[name] = memberExpressionPath.parentPath - } - } - }, - }) - - if (callExpressionPaths.validator) { - const innerInputExpression = callExpressionPaths.validator.node.arguments[0] - - if (!innerInputExpression) { - throw new Error( - 'createServerFn().validator() must be called with a validator!', - ) - } - - // If we're on the client, and we're not validating the client, remove the validator call expression - if ( - opts.env === 'client' && - !shouldValidateClient && - t.isMemberExpression(callExpressionPaths.validator.node.callee) - ) { - callExpressionPaths.validator.replaceWith( - callExpressionPaths.validator.node.callee.object, - ) - } - } - - // First, we need to move the handler function to a nested function call - // that is applied to the arguments passed to the server function. - - const handlerFnPath = callExpressionPaths.handler?.get( - 'arguments.0', - ) as babel.NodePath - - if (!callExpressionPaths.handler || !handlerFnPath.node) { - throw codeFrameError( - opts.code, - path.node.callee.loc!, - `createServerFn must be called with a "handler" property!`, - ) - } - - const handlerFn = handlerFnPath.node - - // So, the way we do this is we give the handler function a way - // to access the serverFn ctx on the server via function scope. - // The 'use server' extracted function will be called with the - // payload from the client, then use the scoped serverFn ctx - // to execute the handler function. - // This way, we can do things like data and middleware validation - // in the __execute function without having to AST transform the - // handler function too much itself. - - // .handler((optsOut, ctx) => { - // return ((optsIn) => { - // 'use server' - // ctx.__execute(handlerFn, optsIn) - // })(optsOut) - // }) - - removeUseServerDirective(handlerFnPath) - - handlerFnPath.replaceWith( - t.arrowFunctionExpression( - [t.identifier('opts')], - t.blockStatement( - // Everything in here is server-only, since the client - // will strip out anything in the 'use server' directive. - [ - t.returnStatement( - t.callExpression( - t.identifier(`${existingVariableName}.__executeServer`), - [t.identifier('opts')], - ), - ), - ], - [t.directive(t.directiveLiteral('use server'))], - ), - ), - ) - - if (opts.env === 'server') { - callExpressionPaths.handler.node.arguments.push(handlerFn) - } -} - -function removeUseServerDirective(path: babel.NodePath) { - path.traverse({ - Directive(path) { - if (path.node.value.value === 'use server') { - path.remove() - } - }, - }) -} - -function handleCreateMiddlewareCallExpression( - path: babel.NodePath, - opts: ParseAstOptions, -) { - // const firstArg = path.node.arguments[0] - - // if (!t.isObjectExpression(firstArg)) { - // throw new Error( - // 'createMiddleware must be called with an object of options!', - // ) - // } - - // const idProperty = firstArg.properties.find((prop) => { - // return ( - // t.isObjectProperty(prop) && - // t.isIdentifier(prop.key) && - // prop.key.name === 'id' - // ) - // }) - - // if ( - // !idProperty || - // !t.isObjectProperty(idProperty) || - // !t.isStringLiteral(idProperty.value) - // ) { - // throw new Error( - // 'createMiddleware must be called with an "id" property!', - // ) - // } - - const rootCallExpression = getRootCallExpression(path) - - if (debug) - console.info( - 'Handling createMiddleware call expression:', - rootCallExpression.toString(), - ) - - // Check if the call is assigned to a variable - // if (!rootCallExpression.parentPath.isVariableDeclarator()) { - // TODO: move this logic out to eslint or something like - // the router generator code that can do autofixes on save. - - // // If not assigned to a variable, wrap the call in a variable declaration - // const variableDeclaration = t.variableDeclaration('const', [ - // t.variableDeclarator(t.identifier(middlewareName), path.node), - // ]) - - // // The parent could be an expression statement, if it is, we need to replace - // // it with the variable declaration - // if (path.parentPath.isExpressionStatement()) { - // path.parentPath.replaceWith(variableDeclaration) - // } else { - // // If the parent is not an expression statement, then it is a statement - // // that is not an expression, like a variable declaration or a return statement. - // // In this case, we need to insert the variable declaration before the statement - // path.parentPath.insertBefore(variableDeclaration) - // } - - // // Now we need to export it. Just add an export statement - // // to the program body - // path.findParent((parentPath) => { - // if (parentPath.isProgram()) { - // parentPath.node.body.push( - // t.exportNamedDeclaration(null, [ - // t.exportSpecifier( - // t.identifier(middlewareName), - // t.identifier(middlewareName), - // ), - // ]), - // ) - // } - // return false - // }) - - // throw new Error( - // 'createMiddleware must be assigned to a variable and exported!', - // ) - // } - - // const variableDeclarator = rootCallExpression.parentPath.node - // const existingVariableName = (variableDeclarator.id as t.Identifier).name - - // const program = rootCallExpression.findParent((parentPath) => { - // return parentPath.isProgram() - // }) as babel.NodePath - - // let isExported = false as boolean - - // program.traverse({ - // ExportNamedDeclaration: (path) => { - // if ( - // path.isExportNamedDeclaration() && - // path.node.declaration && - // t.isVariableDeclaration(path.node.declaration) && - // path.node.declaration.declarations.some((decl) => { - // return ( - // t.isVariableDeclarator(decl) && - // t.isIdentifier(decl.id) && - // decl.id.name === existingVariableName - // ) - // }) - // ) { - // isExported = true - // } - // }, - // }) - - // If not exported, export it - // if (!isExported) { - // TODO: move this logic out to eslint or something like - // the router generator code that can do autofixes on save. - - // path.parentPath.parentPath.insertAfter( - // t.exportNamedDeclaration(null, [ - // t.exportSpecifier( - // t.identifier(existingVariableName), - // t.identifier(existingVariableName), - // ), - // ]), - // ) - - // throw new Error( - // 'createMiddleware must be exported as a named export!', - // ) - // } - - // The function is the 'fn' property of the object passed to createMiddleware - - // const firstArg = path.node.arguments[0] - // if (t.isObjectExpression(firstArg)) { - // // Was called with some options - // } - - // Traverse the member expression and find the call expressions for - // the validator, handler, and middleware methods. Check to make sure they - // are children of the createMiddleware call expression. - - const callExpressionPaths = { - middleware: null as babel.NodePath | null, - validator: null as babel.NodePath | null, - client: null as babel.NodePath | null, - server: null as babel.NodePath | null, - } - - const validMethods = Object.keys(callExpressionPaths) - - rootCallExpression.traverse({ - MemberExpression(memberExpressionPath) { - if (t.isIdentifier(memberExpressionPath.node.property)) { - const name = memberExpressionPath.node.property - .name as keyof typeof callExpressionPaths - - if ( - validMethods.includes(name) && - memberExpressionPath.parentPath.isCallExpression() - ) { - callExpressionPaths[name] = memberExpressionPath.parentPath - } - } - }, - }) - - if (callExpressionPaths.validator) { - const innerInputExpression = callExpressionPaths.validator.node.arguments[0] - - if (!innerInputExpression) { - throw new Error( - 'createMiddleware().validator() must be called with a validator!', - ) - } - - // If we're on the client, remove the validator call expression - if (opts.env === 'client') { - if (t.isMemberExpression(callExpressionPaths.validator.node.callee)) { - callExpressionPaths.validator.replaceWith( - callExpressionPaths.validator.node.callee.object, - ) - } - } - } - - const useFnPath = callExpressionPaths.server?.get( - 'arguments.0', - ) as babel.NodePath - - if (!callExpressionPaths.server || !useFnPath.node) { - throw new Error('createMiddleware must be called with a "use" property!') - } - - // If we're on the client, remove the use call expression - - if (opts.env === 'client') { - if (t.isMemberExpression(callExpressionPaths.server.node.callee)) { - callExpressionPaths.server.replaceWith( - callExpressionPaths.server.node.callee.object, - ) - } - } -} - -function buildEnvOnlyCallExpressionHandler(env: 'client' | 'server') { - return function envOnlyCallExpressionHandler( - path: babel.NodePath, - opts: ParseAstOptions, - ) { - if (debug) - console.info(`Handling ${env}Only call expression:`, path.toString()) - - if (opts.env === env) { - // extract the inner function from the call expression - const innerInputExpression = path.node.arguments[0] - - if (!t.isExpression(innerInputExpression)) { - throw new Error( - `${env}Only() functions must be called with a function!`, - ) - } - - path.replaceWith(innerInputExpression) - return - } - - // If we're on the wrong environment, replace the call expression - // with a function that always throws an error. - path.replaceWith( - t.arrowFunctionExpression( - [], - t.blockStatement([ - t.throwStatement( - t.newExpression(t.identifier('Error'), [ - t.stringLiteral( - `${env}Only() functions can only be called on the ${env}!`, - ), - ]), - ), - ]), - ), - ) - } -} - -function handleCreateIsomorphicFnCallExpression( - path: babel.NodePath, - opts: ParseAstOptions, -) { - const rootCallExpression = getRootCallExpression(path) - - if (debug) - console.info( - 'Handling createIsomorphicFn call expression:', - rootCallExpression.toString(), - ) - - const callExpressionPaths = { - client: null as babel.NodePath | null, - server: null as babel.NodePath | null, - } - - const validMethods = Object.keys(callExpressionPaths) - - rootCallExpression.traverse({ - MemberExpression(memberExpressionPath) { - if (t.isIdentifier(memberExpressionPath.node.property)) { - const name = memberExpressionPath.node.property - .name as keyof typeof callExpressionPaths - - if ( - validMethods.includes(name) && - memberExpressionPath.parentPath.isCallExpression() - ) { - callExpressionPaths[name] = memberExpressionPath.parentPath - } - } - }, - }) - - if ( - validMethods.every( - (method) => - !callExpressionPaths[method as keyof typeof callExpressionPaths], - ) - ) { - const variableId = rootCallExpression.parentPath.isVariableDeclarator() - ? rootCallExpression.parentPath.node.id - : null - console.warn( - 'createIsomorphicFn called without a client or server implementation!', - 'This will result in a no-op function.', - 'Variable name:', - t.isIdentifier(variableId) ? variableId.name : 'unknown', - ) - } - - const envCallExpression = callExpressionPaths[opts.env] - - if (!envCallExpression) { - // if we don't have an implementation for this environment, default to a no-op - rootCallExpression.replaceWith( - t.arrowFunctionExpression([], t.blockStatement([])), - ) - return - } - - const innerInputExpression = envCallExpression.node.arguments[0] - - if (!t.isExpression(innerInputExpression)) { - throw new Error( - `createIsomorphicFn().${opts.env}(func) must be called with a function!`, - ) - } - - rootCallExpression.replaceWith(innerInputExpression) -} - -function getRootCallExpression(path: babel.NodePath) { - // Find the highest callExpression parent - let rootCallExpression: babel.NodePath = path - - // Traverse up the chain of CallExpressions - while (rootCallExpression.parentPath.isMemberExpression()) { - const parent = rootCallExpression.parentPath - if (parent.parentPath.isCallExpression()) { - rootCallExpression = parent.parentPath - } - } - - return rootCallExpression -} - function codeFrameError( code: string, loc: { diff --git a/packages/server-functions-vite-plugin/src/index.ts b/packages/server-functions-vite-plugin/src/index.ts index 6067851fd3..709c86a4f4 100644 --- a/packages/server-functions-vite-plugin/src/index.ts +++ b/packages/server-functions-vite-plugin/src/index.ts @@ -1,14 +1,26 @@ import { fileURLToPath, pathToFileURL } from 'node:url' +import { compileServerFnClient } from './compilers' import type { Plugin } from 'vite' const debug = Boolean(process.env.TSR_VITE_DEBUG) -export type ServerFunctionsViteOptions = {} +export type ServerFunctionsViteOptions = { + runtimeCode: string + replacer: (opts: { filename: string; functionId: string }) => string +} const useServerRx = /"use server"|'use server'/ -export function TanStackStartViteServerFn(): Array { +export type CreateRpcFn = (opts: { + fn: (...args: Array) => any + filename: string + functionId: string +}) => (...args: Array) => any + +export function TanStackServerFnPluginClient( + opts: ServerFunctionsViteOptions, +): Array { // opts: ServerFunctionsViteOptions, let ROOT: string = process.cwd() @@ -28,7 +40,15 @@ export function TanStackStartViteServerFn(): Array { return null } - const { compiledCode, serverFns } = compileServerFnServer({ + if (debug) console.info('') + if (debug) console.info('Compiled createServerFn Input') + if (debug) console.info('') + if (debug) console.info(code) + if (debug) console.info('') + if (debug) console.info('') + if (debug) console.info('') + + const { compiledCode, serverFns } = compileServerFnClient({ code, root: ROOT, filename: id, @@ -45,6 +65,13 @@ export function TanStackStartViteServerFn(): Array { return compiledCode }, }, + ] +} + +export function TanStackServerFnPluginServer( + opts: ServerFunctionsViteOptions, +): Array { + return [ { name: 'tanstack-start-server-fn-server-vite-plugin', transform(code, id) { diff --git a/packages/start/package.json b/packages/start/package.json index 549da390f1..1f3f1fe2fa 100644 --- a/packages/start/package.json +++ b/packages/start/package.json @@ -139,6 +139,7 @@ "@tanstack/router-generator": "workspace:^", "@tanstack/router-plugin": "workspace:^", "@tanstack/start-vite-plugin": "workspace:^", + "@tanstack/server-functions-plugin": "workspace:^", "@vinxi/react": "0.2.5", "@vinxi/react-server-dom": "^0.0.3", "@vinxi/server-components": "0.5.0", diff --git a/packages/start/src/client-runtime/index.tsx b/packages/start/src/client-runtime/index.tsx index 2c02f6b9c7..9321438a70 100644 --- a/packages/start/src/client-runtime/index.tsx +++ b/packages/start/src/client-runtime/index.tsx @@ -1,19 +1,20 @@ import { fetcher } from './fetcher' import { getBaseUrl } from './getBaseUrl' -import type { CreateRpcFn } from '@tanstack/start/server-functions-plugin' +import type { CreateRpcFn } from '@tanstack/server-functions-plugin' -export const createClientRpc: CreateRpcFn = ( - filename: string, - functionId: string, -) => { - const base = getBaseUrl(window.location.origin, filename, functionId) +export const createClientRpc: CreateRpcFn = (opts) => { + const base = getBaseUrl( + window.location.origin, + opts.filename, + opts.functionId, + ) const fn = (...args: Array) => fetcher(base, args, fetch) return Object.assign(fn, { url: base, - filename, - functionId, + filename: opts.filename, + functionId: opts.functionId, }) } diff --git a/packages/start/src/config/index.ts b/packages/start/src/config/index.ts index 8e0d5dbdc2..093c4f875e 100644 --- a/packages/start/src/config/index.ts +++ b/packages/start/src/config/index.ts @@ -14,7 +14,10 @@ import { createApp } from 'vinxi' import { config } from 'vinxi/plugins/config' // // @ts-expect-error // import { serverComponents } from '@vinxi/server-components/plugin' -import { createServerFunctionsPlugin } from '@tanstack/start/server-functions-plugin' +import { + TanStackServerFnPluginClient, + TanStackServerFnPluginServer, +} from '@tanstack/server-functions-plugin' import { tanstackStartVinxiFileRouter } from './vinxi-file-router.js' import { checkDeploymentPresetInput, @@ -120,8 +123,6 @@ export function defineConfig( const apiEntryExists = existsSync(apiEntry) - const serverFunctionsPlugin = createServerFunctionsPlugin() - let vinxiApp = createApp({ server: { ...serverOptions, @@ -169,7 +170,7 @@ export function defineConfig( }), ...(viteConfig.plugins || []), ...(clientViteConfig.plugins || []), - serverFunctionsPlugin.client({ + TanStackServerFnPluginClient({ runtimeCode: `import { createClientRpc } from '@tanstack/start/client-runtime'`, replacer: (opts) => `createClientRpc('${opts.filename}', '${opts.functionId}')`, @@ -212,7 +213,7 @@ export function defineConfig( }), ...(getUserViteConfig(opts.vite).plugins || []), ...(getUserViteConfig(opts.routers?.ssr?.vite).plugins || []), - serverFunctionsPlugin.server({ + TanStackServerFnPluginServer({ runtimeCode: `import { createServerRpc } from '@tanstack/start/ssr-runtime'`, replacer: (opts) => `createSsrRpc('${opts.filename}', '${opts.functionId}')`, @@ -257,7 +258,7 @@ export function defineConfig( ...injectDefineEnv('TSS_API_BASE', apiBase), }, }), - serverFunctionsPlugin.server({ + TanStackServerFnPluginServer({ runtimeCode: `import { createServerRpc } from '@tanstack/start/server-runtime'`, replacer: (opts) => `createServerRpc('${opts.filename}', '${opts.functionId}')`, diff --git a/packages/start/src/server-runtime/index.tsx b/packages/start/src/server-runtime/index.tsx index 5d1a68cb87..6c68ed7866 100644 --- a/packages/start/src/server-runtime/index.tsx +++ b/packages/start/src/server-runtime/index.tsx @@ -1,17 +1,13 @@ // import { getBaseUrl } from '../client-runtime/getBaseUrl' -import type { CreateRpcFn } from '@tanstack/start/server-functions-plugin' +import type { CreateRpcFn } from '@tanstack/server-functions-plugin' -export const createServerRpc: CreateRpcFn = ( - fn: any, - filename: string, - functionId: string, -) => { +export const createServerRpc: CreateRpcFn = (opts) => { // const functionUrl = getBaseUrl('http://localhost:3000', id, name) const functionUrl = 'https://localhost:3000' - return Object.assign(fn, { + return Object.assign(opts.fn, { url: functionUrl, - filename, - functionId, + filename: opts.filename, + functionId: opts.functionId, }) } diff --git a/packages/start/src/ssr-runtime/index.tsx b/packages/start/src/ssr-runtime/index.tsx index f2c3582da6..f4dadc87f7 100644 --- a/packages/start/src/ssr-runtime/index.tsx +++ b/packages/start/src/ssr-runtime/index.tsx @@ -4,7 +4,7 @@ import invariant from 'tiny-invariant' import { fetcher } from '../client-runtime/fetcher' import { getBaseUrl } from '../client-runtime/getBaseUrl' import { handleServerRequest } from '../server-handler/index' -import type { CreateRpcFn } from '@tanstack/start/server-functions-plugin' +import type { CreateRpcFn } from '@tanstack/server-functions-plugin' export function createIncomingMessage( url: string, @@ -78,12 +78,8 @@ export function createIncomingMessage( const fakeHost = 'http://localhost:3000' -export const createSsrRpc: CreateRpcFn = ( - _fn: any, - filename: string, - functionId: string, -) => { - const functionUrl = getBaseUrl(fakeHost, filename, functionId) +export const createSsrRpc: CreateRpcFn = (opts) => { + const functionUrl = getBaseUrl(fakeHost, opts.filename, opts.functionId) const proxyFn = (...args: Array) => { invariant( @@ -155,7 +151,7 @@ export const createSsrRpc: CreateRpcFn = ( return Object.assign(proxyFn, { url: functionUrl.replace(fakeHost, ''), - filename, - functionId, + filename: opts.filename, + functionId: opts.functionId, }) } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index af6cc1cdad..727e356e75 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -3501,6 +3501,57 @@ importers: specifier: workspace:* version: link:../router-plugin + packages/server-functions-vite-plugin: + dependencies: + '@babel/code-frame': + specifier: 7.26.2 + version: 7.26.2 + '@babel/core': + specifier: ^7.26.0 + version: 7.26.0 + '@babel/generator': + specifier: ^7.26.3 + version: 7.26.3 + '@babel/parser': + specifier: ^7.26.3 + version: 7.26.3 + '@babel/plugin-syntax-jsx': + specifier: ^7.25.9 + version: 7.25.9(@babel/core@7.26.0) + '@babel/plugin-syntax-typescript': + specifier: ^7.25.9 + version: 7.25.9(@babel/core@7.26.0) + '@babel/template': + specifier: ^7.25.9 + version: 7.25.9 + '@babel/traverse': + specifier: ^7.26.4 + version: 7.26.4 + '@babel/types': + specifier: ^7.26.3 + version: 7.26.3 + '@types/babel__code-frame': + specifier: ^7.0.6 + version: 7.0.6 + '@types/babel__core': + specifier: ^7.20.5 + version: 7.20.5 + '@types/babel__generator': + specifier: ^7.6.8 + version: 7.6.8 + '@types/babel__template': + specifier: ^7.4.4 + version: 7.4.4 + '@types/babel__traverse': + specifier: ^7.20.6 + version: 7.20.6 + babel-dead-code-elimination: + specifier: ^1.0.6 + version: 1.0.6 + tiny-invariant: + specifier: ^1.3.3 + version: 1.3.3 + packages/start: dependencies: '@tanstack/react-cross-context': @@ -3515,6 +3566,9 @@ importers: '@tanstack/router-plugin': specifier: workspace:* version: link:../router-plugin + '@tanstack/server-functions-plugin': + specifier: workspace:^ + version: link:../server-functions-vite-plugin '@tanstack/start-vite-plugin': specifier: workspace:* version: link:../start-vite-plugin From 9ac11e8bcf28927134c740933972b20bce494f48 Mon Sep 17 00:00:00 2001 From: Tanner Linsley Date: Thu, 12 Dec 2024 10:16:36 -0700 Subject: [PATCH 03/13] cleanup --- package.json | 4 +--- packages/start/package.json | 6 +++--- .../tsconfigs/server-functions-plugin.tsconfig.json | 10 ---------- pnpm-lock.yaml | 2 -- 4 files changed, 4 insertions(+), 18 deletions(-) delete mode 100644 packages/start/tsconfigs/server-functions-plugin.tsconfig.json diff --git a/package.json b/package.json index 1c40996f6d..4007d6ba70 100644 --- a/package.json +++ b/package.json @@ -81,9 +81,7 @@ "@tanstack/arktype-adapter": "workspace:*", "@tanstack/start": "workspace:*", "@tanstack/start-vite-plugin": "workspace:*", - "@tanstack/eslint-plugin-router": "workspace:*", - "temp-react": "0.0.0-experimental-035a41c4e-20230704", - "temp-react-dom": "0.0.0-experimental-035a41c4e-20230704" + "@tanstack/eslint-plugin-router": "workspace:*" } } } diff --git a/packages/start/package.json b/packages/start/package.json index 1f3f1fe2fa..70f1fcc9e8 100644 --- a/packages/start/package.json +++ b/packages/start/package.json @@ -36,10 +36,10 @@ "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js", "test:types:ts57": "tsc", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", - "build": "pnpm build:config && pnpm build:router-manifest && pnpm build:vite", + "build": "pnpm build:vite && pnpm build:config && pnpm build:router-manifest", + "build:vite": "vite build", "build:config": "tsc --project tsconfigs/config.tsconfig.json", - "build:router-manifest": "tsc --project tsconfigs/router-manifest.tsconfig.json", - "build:vite": "vite build" + "build:router-manifest": "tsc --project tsconfigs/router-manifest.tsconfig.json" }, "type": "module", "exports": { diff --git a/packages/start/tsconfigs/server-functions-plugin.tsconfig.json b/packages/start/tsconfigs/server-functions-plugin.tsconfig.json deleted file mode 100644 index 440bc758da..0000000000 --- a/packages/start/tsconfigs/server-functions-plugin.tsconfig.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "extends": "../../../tsconfig.json", - "include": ["../src/server-functions-plugin/index.ts"], - "compilerOptions": { - "rootDir": "../src/server-functions-plugin", - "outDir": "../dist/esm/server-functions-plugin", - "target": "esnext", - "noEmit": false - } -} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 727e356e75..e97a5cd541 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -23,8 +23,6 @@ overrides: '@tanstack/start': workspace:* '@tanstack/start-vite-plugin': workspace:* '@tanstack/eslint-plugin-router': workspace:* - temp-react: 0.0.0-experimental-035a41c4e-20230704 - temp-react-dom: 0.0.0-experimental-035a41c4e-20230704 importers: From 35823231c30ed64fad0da457e124bfa8af5cd894 Mon Sep 17 00:00:00 2001 From: Tanner Linsley Date: Thu, 12 Dec 2024 12:11:14 -0700 Subject: [PATCH 04/13] checkpoint --- .../react/start-basic/app/routes/deferred.tsx | 4 +- .../react/start-basic/app/utils/posts.tsx | 2 +- .../start-supabase-basic/app/utils/posts.ts | 2 +- .../src/compilers.ts | 223 ++++++++++++++---- .../server-functions-vite-plugin/src/index.ts | 2 + 5 files changed, 186 insertions(+), 47 deletions(-) diff --git a/examples/react/start-basic/app/routes/deferred.tsx b/examples/react/start-basic/app/routes/deferred.tsx index 7cc7f8b9b5..606ab69b80 100644 --- a/examples/react/start-basic/app/routes/deferred.tsx +++ b/examples/react/start-basic/app/routes/deferred.tsx @@ -3,13 +3,13 @@ import { createServerFn } from '@tanstack/start' import { Suspense, useState } from 'react' const personServerFn = createServerFn({ method: 'GET' }) - .validator((d) => d as string) + .validator((d: string) => d) .handler(({ data: name }) => { return { name, randomNumber: Math.floor(Math.random() * 100) } }) const slowServerFn = createServerFn({ method: 'GET' }) - .validator((d) => d as string) + .validator((d: string) => d) .handler(async ({ data: name }) => { await new Promise((r) => setTimeout(r, 1000)) return { name, randomNumber: Math.floor(Math.random() * 100) } diff --git a/examples/react/start-basic/app/utils/posts.tsx b/examples/react/start-basic/app/utils/posts.tsx index 196498f8c9..99e43f5197 100644 --- a/examples/react/start-basic/app/utils/posts.tsx +++ b/examples/react/start-basic/app/utils/posts.tsx @@ -11,7 +11,7 @@ export type PostType = { export const fetchPost = createServerFn({ method: 'GET' }) .middleware([logMiddleware]) - .validator((d) => d as string) + .validator((d: string) => d) .handler(async ({ data }) => { console.info(`Fetching post with id ${data}...`) const post = await axios diff --git a/examples/react/start-supabase-basic/app/utils/posts.ts b/examples/react/start-supabase-basic/app/utils/posts.ts index 3c8b8d2434..6eb213af1f 100644 --- a/examples/react/start-supabase-basic/app/utils/posts.ts +++ b/examples/react/start-supabase-basic/app/utils/posts.ts @@ -9,7 +9,7 @@ export type PostType = { } export const fetchPost = createServerFn({ method: 'GET' }) - .validator((d) => d as string) + .validator((d: string) => d) .handler(async ({ data: postId }) => { console.info(`Fetching post with id ${postId}...`) const post = await axios diff --git a/packages/server-functions-vite-plugin/src/compilers.ts b/packages/server-functions-vite-plugin/src/compilers.ts index 1103bba03b..b08101463d 100644 --- a/packages/server-functions-vite-plugin/src/compilers.ts +++ b/packages/server-functions-vite-plugin/src/compilers.ts @@ -1,11 +1,18 @@ +import path from 'node:path' import * as babel from '@babel/core' -import generate from '@babel/generator' -import { codeFrameColumns } from '@babel/code-frame' +import _generate from '@babel/generator' import { deadCodeElimination } from 'babel-dead-code-elimination' +import { isIdentifier, isVariableDeclarator } from '@babel/types' import { parseAst } from './ast' import type { ParseAstOptions } from './ast' +let generate = _generate + +if ('default' in generate) { + generate = generate.default as typeof generate +} + export function compileEliminateDeadCode(opts: ParseAstOptions) { const ast = parseAst(opts) deadCodeElimination(ast) @@ -15,71 +22,203 @@ export function compileEliminateDeadCode(opts: ParseAstOptions) { }) } -const debug = process.env.TSR_VITE_DEBUG === 'true' +// const debug = process.env.TSR_VITE_DEBUG === 'true' -export function compileServerFnClient(opts: ParseAstOptions) { +function findNearestVariableName(path: babel.NodePath): 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) + ) { + if (babel.types.isIdentifier(currentPath.node.key)) { + return currentPath.node.key.name + } + if (babel.types.isStringLiteral(currentPath.node.key)) { + return currentPath.node.key.value + } + } + + return null + })() + + if (name) { + nameParts.unshift(name) + } + + currentPath = currentPath.parentPath + } + + return nameParts.length > 0 ? nameParts.join('_') : 'anonymous' +} + +function makeFileLocationUrlSafe(location: string): string { + return location + .replace(/[^a-zA-Z0-9-_]/g, '_') // Replace unsafe chars with underscore + .replace(/_{2,}/g, '_') // Collapse multiple underscores + .replace(/^_|_$/g, '') // Trim leading/trailing underscores +} + +export function compileServerFnClient( + opts: ParseAstOptions & { + runtimeCode: string + replacer: (opts: { filename: string; functionId: string }) => string + }, +) { const ast = parseAst(opts) - - const serverFnPaths: Array = [] + const serverFnPathsByLabel: Record< + string, + { + nodePath: babel.NodePath + functionName: string + functionId: string + } + > = {} + const counts: Record = {} babel.traverse(ast, { Program: { enter(programPath) { + const recordServerFunction = (nodePath: babel.NodePath) => { + const fnName = findNearestVariableName(nodePath) + + const baseLabel = makeFileLocationUrlSafe( + `${opts.filename.replace( + path.extname(opts.filename), + '', + )}--${fnName}`.replace(opts.root, ''), + ) + + counts[baseLabel] = (counts[baseLabel] || 0) + 1 + + const label = + counts[baseLabel] > 1 + ? `${baseLabel}_${counts[baseLabel] - 1}` + : baseLabel + + serverFnPathsByLabel[label] = { + nodePath, + functionName: fnName || '', + functionId: label, + } + } + programPath.traverse({ enter(path) { - // Check for 'use server' directive in function declarations (named functions) + // Function declarations if (path.isFunctionDeclaration()) { const directives = path.node.body.directives for (const directive of directives) { if (directive.value.value === 'use server') { - serverFnPaths.push(path) + recordServerFunction(path) } } } - // Check for 'use server' directive in function expressions (anonymous functions) + // Function expressions if (path.isFunctionExpression()) { const directives = path.node.body.directives for (const directive of directives) { if (directive.value.value === 'use server') { - serverFnPaths.push(path) + recordServerFunction(path) } } } - // Check for 'use server' directive in arrow functions + // Arrow functions if (path.isArrowFunctionExpression()) { if (babel.types.isBlockStatement(path.node.body)) { const directives = path.node.body.directives for (const directive of directives) { if (directive.value.value === 'use server') { - serverFnPaths.push(path) + recordServerFunction(path) } } } } - // Check for 'use server' directive in class methods + // Class methods if (path.isClassMethod()) { const directives = path.node.body.directives for (const directive of directives) { if (directive.value.value === 'use server') { - serverFnPaths.push(path) + recordServerFunction(path) } } } - // Check for 'use server' directive in object methods + // Object methods if (path.isObjectMethod()) { const directives = path.node.body.directives for (const directive of directives) { if (directive.value.value === 'use server') { - serverFnPaths.push(path) + recordServerFunction(path) } } } - // Check for 'use server' directive in variable declarations with function expressions + // Variable declarations with function expressions if ( path.isVariableDeclarator() && (babel.types.isFunctionExpression(path.node.init) || @@ -90,13 +229,11 @@ export function compileServerFnClient(opts: ParseAstOptions) { const directives = init.body.directives for (const directive of directives) { if (directive.value.value === 'use server') { - serverFnPaths.push(path.get('init') as babel.NodePath) + recordServerFunction(path.get('init') as babel.NodePath) } } } } - - return serverFnPaths }, }) }, @@ -108,11 +245,11 @@ export function compileServerFnClient(opts: ParseAstOptions) { minified: process.env.NODE_ENV === 'production', }) - console.log(serverFnPaths) + console.log(serverFnPathsByLabel) return { compiledCode, - serverFns: serverFnPaths, + serverFns: serverFnPathsByLabel, } } @@ -125,25 +262,25 @@ export function compileServerFnServer(opts: ParseAstOptions) { }) } -function codeFrameError( - code: string, - loc: { - start: { line: number; column: number } - end: { line: number; column: number } - }, - message: string, -) { - const frame = codeFrameColumns( - code, - { - start: loc.start, - end: loc.end, - }, - { - highlightCode: true, - message, - }, - ) +// function codeFrameError( +// code: string, +// loc: { +// start: { line: number; column: number } +// end: { line: number; column: number } +// }, +// message: string, +// ) { +// const frame = codeFrameColumns( +// code, +// { +// start: loc.start, +// end: loc.end, +// }, +// { +// highlightCode: true, +// message, +// }, +// ) - return new Error(frame) -} +// return new Error(frame) +// } diff --git a/packages/server-functions-vite-plugin/src/index.ts b/packages/server-functions-vite-plugin/src/index.ts index 709c86a4f4..d6fe2101a5 100644 --- a/packages/server-functions-vite-plugin/src/index.ts +++ b/packages/server-functions-vite-plugin/src/index.ts @@ -52,6 +52,8 @@ export function TanStackServerFnPluginClient( code, root: ROOT, filename: id, + runtimeCode: opts.runtimeCode, + replacer: opts.replacer, }) if (debug) console.info('') From fa7c03592aedfa9630d880f75f393ebb26b743fc Mon Sep 17 00:00:00 2001 From: Tanner Linsley Date: Thu, 12 Dec 2024 14:48:08 -0700 Subject: [PATCH 05/13] client babel now works, runtime and rpc injection --- .../server-functions-vite-plugin/package.json | 12 +- .../src/compilers.ts | 68 ++- .../server-functions-vite-plugin/src/index.ts | 33 +- .../src/logger.ts | 59 +++ .../tests/compiler.test.ts | 478 ++++++++++++++++++ .../createIsomorphicFn.test.ts | 90 ---- .../client/createIsomorphicFnDestructured.tsx | 16 - .../createIsomorphicFnDestructuredRename.tsx | 16 - .../client/createIsomorphicFnStarImport.tsx | 16 - .../server/createIsomorphicFnDestructured.tsx | 16 - .../createIsomorphicFnDestructuredRename.tsx | 16 - .../server/createIsomorphicFnStarImport.tsx | 16 - .../createIsomorphicFnDestructured.tsx | 35 -- .../createIsomorphicFnDestructuredRename.tsx | 35 -- .../createIsomorphicFnStarImport.tsx | 37 -- .../createMiddleware/createMiddleware.test.ts | 36 -- .../client/createMiddlewareDestructured.tsx | 24 - .../createMiddlewareDestructuredRename.tsx | 24 - .../client/createMiddlewareStarImport.tsx | 24 - .../client/createMiddlewareValidator.tsx | 5 - .../server/createMiddlewareDestructured.tsx | 36 -- .../createMiddlewareDestructuredRename.tsx | 36 -- .../server/createMiddlewareStarImport.tsx | 38 -- .../server/createMiddlewareValidator.tsx | 7 - .../createMiddlewareDestructured.tsx | 51 -- .../createMiddlewareDestructuredRename.tsx | 51 -- .../test-files/createMiddlewareStarImport.tsx | 52 -- .../test-files/createMiddlewareValidator.tsx | 8 - .../createServerFn/createServerFn.test.ts | 62 --- .../client/createServerFnDestructured.tsx | 61 --- .../createServerFnDestructuredRename.tsx | 40 -- .../client/createServerFnStarImport.tsx | 40 -- .../client/createServerFnValidator.tsx | 9 - .../server/createServerFnDestructured.tsx | 77 --- .../createServerFnDestructuredRename.tsx | 52 -- .../server/createServerFnStarImport.tsx | 52 -- .../server/createServerFnValidator.tsx | 11 - .../test-files/createServerFnDestructured.tsx | 67 --- .../createServerFnDestructuredRename.tsx | 51 -- .../test-files/createServerFnStarImport.tsx | 52 -- .../test-files/createServerFnValidator.tsx | 8 - .../tests/envOnly/envOnly.test.ts | 58 --- .../snapshots/client/envOnlyDestructured.tsx | 5 - .../client/envOnlyDestructuredRename.tsx | 5 - .../snapshots/client/envOnlyStarImport.tsx | 5 - .../snapshots/server/envOnlyDestructured.tsx | 5 - .../server/envOnlyDestructuredRename.tsx | 5 - .../snapshots/server/envOnlyStarImport.tsx | 5 - .../test-files/envOnlyDestructured.tsx | 5 - .../test-files/envOnlyDestructuredRename.tsx | 5 - .../envOnly/test-files/envOnlyStarImport.tsx | 5 - packages/start/src/config/index.ts | 9 +- pnpm-lock.yaml | 20 + 53 files changed, 645 insertions(+), 1404 deletions(-) create mode 100644 packages/server-functions-vite-plugin/src/logger.ts create mode 100644 packages/server-functions-vite-plugin/tests/compiler.test.ts delete mode 100644 packages/server-functions-vite-plugin/tests/createIsomorphicFn/createIsomorphicFn.test.ts delete mode 100644 packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnDestructured.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnDestructuredRename.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnStarImport.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnDestructured.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnDestructuredRename.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnStarImport.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/createIsomorphicFn/test-files/createIsomorphicFnDestructured.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/createIsomorphicFn/test-files/createIsomorphicFnDestructuredRename.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/createIsomorphicFn/test-files/createIsomorphicFnStarImport.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/createMiddleware/createMiddleware.test.ts delete mode 100644 packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/client/createMiddlewareDestructured.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/client/createMiddlewareDestructuredRename.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/client/createMiddlewareStarImport.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/client/createMiddlewareValidator.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/server/createMiddlewareDestructured.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/server/createMiddlewareDestructuredRename.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/server/createMiddlewareStarImport.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/server/createMiddlewareValidator.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/createMiddleware/test-files/createMiddlewareDestructured.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/createMiddleware/test-files/createMiddlewareDestructuredRename.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/createMiddleware/test-files/createMiddlewareStarImport.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/createMiddleware/test-files/createMiddlewareValidator.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/createServerFn/createServerFn.test.ts delete mode 100644 packages/server-functions-vite-plugin/tests/createServerFn/snapshots/client/createServerFnDestructured.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/createServerFn/snapshots/client/createServerFnDestructuredRename.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/createServerFn/snapshots/client/createServerFnStarImport.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/createServerFn/snapshots/client/createServerFnValidator.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/createServerFn/snapshots/server/createServerFnDestructured.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/createServerFn/snapshots/server/createServerFnDestructuredRename.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/createServerFn/snapshots/server/createServerFnStarImport.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/createServerFn/snapshots/server/createServerFnValidator.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/createServerFn/test-files/createServerFnDestructured.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/createServerFn/test-files/createServerFnDestructuredRename.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/createServerFn/test-files/createServerFnStarImport.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/createServerFn/test-files/createServerFnValidator.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/envOnly/envOnly.test.ts delete mode 100644 packages/server-functions-vite-plugin/tests/envOnly/snapshots/client/envOnlyDestructured.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/envOnly/snapshots/client/envOnlyDestructuredRename.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/envOnly/snapshots/client/envOnlyStarImport.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/envOnly/snapshots/server/envOnlyDestructured.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/envOnly/snapshots/server/envOnlyDestructuredRename.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/envOnly/snapshots/server/envOnlyStarImport.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/envOnly/test-files/envOnlyDestructured.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/envOnly/test-files/envOnlyDestructuredRename.tsx delete mode 100644 packages/server-functions-vite-plugin/tests/envOnly/test-files/envOnlyStarImport.tsx diff --git a/packages/server-functions-vite-plugin/package.json b/packages/server-functions-vite-plugin/package.json index 2dbf643a41..2dd6e26e72 100644 --- a/packages/server-functions-vite-plugin/package.json +++ b/packages/server-functions-vite-plugin/package.json @@ -27,6 +27,7 @@ "clean": "rimraf ./dist && rimraf ./coverage", "test": "pnpm test:eslint && pnpm test:types && pnpm test:build && pnpm test:unit", "test:unit": "vitest", + "test:unit:dev": "vitest --watch", "test:eslint": "eslint ./src", "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", "test:types:ts52": "node ../../node_modules/typescript52/lib/tsc.js", @@ -64,8 +65,8 @@ "node": ">=12" }, "dependencies": { - "@babel/core": "^7.26.0", "@babel/code-frame": "7.26.2", + "@babel/core": "^7.26.0", "@babel/generator": "^7.26.3", "@babel/parser": "^7.26.3", "@babel/plugin-syntax-jsx": "^7.25.9", @@ -73,12 +74,15 @@ "@babel/template": "^7.25.9", "@babel/traverse": "^7.26.4", "@babel/types": "^7.26.3", + "@types/babel__code-frame": "^7.0.6", "@types/babel__core": "^7.20.5", "@types/babel__generator": "^7.6.8", - "@types/babel__code-frame": "^7.0.6", "@types/babel__template": "^7.4.4", "@types/babel__traverse": "^7.20.6", - "tiny-invariant": "^1.3.3", - "babel-dead-code-elimination": "^1.0.6" + "@types/diff": "^6.0.0", + "babel-dead-code-elimination": "^1.0.6", + "chalk": "^5.3.0", + "diff": "^7.0.0", + "tiny-invariant": "^1.3.3" } } diff --git a/packages/server-functions-vite-plugin/src/compilers.ts b/packages/server-functions-vite-plugin/src/compilers.ts index b08101463d..b9679e9c6e 100644 --- a/packages/server-functions-vite-plugin/src/compilers.ts +++ b/packages/server-functions-vite-plugin/src/compilers.ts @@ -122,12 +122,17 @@ function makeFileLocationUrlSafe(location: string): string { export function compileServerFnClient( opts: ParseAstOptions & { - runtimeCode: string + getRuntimeCode: (opts: { + serverFnPathsByFunctionId: Record< + string, + { nodePath: babel.NodePath; functionName: string; functionId: string } + > + }) => string replacer: (opts: { filename: string; functionId: string }) => string }, ) { const ast = parseAst(opts) - const serverFnPathsByLabel: Record< + const serverFnPathsByFunctionId: Record< string, { nodePath: babel.NodePath @@ -152,15 +157,15 @@ export function compileServerFnClient( counts[baseLabel] = (counts[baseLabel] || 0) + 1 - const label = + const functionId = counts[baseLabel] > 1 ? `${baseLabel}_${counts[baseLabel] - 1}` : baseLabel - serverFnPathsByLabel[label] = { + serverFnPathsByFunctionId[functionId] = { nodePath, functionName: fnName || '', - functionId: label, + functionId: functionId, } } @@ -236,6 +241,49 @@ export function compileServerFnClient( } }, }) + + if (Object.keys(serverFnPathsByFunctionId).length > 0) { + const runtimeImport = babel.template.statement( + opts.getRuntimeCode({ serverFnPathsByFunctionId }), + )() + ast.program.body.unshift(runtimeImport) + } + + // Replace server functions with client-side stubs + for (const [functionId, fnPath] of Object.entries( + serverFnPathsByFunctionId, + )) { + const replacementCode = opts.replacer({ + filename: opts.filename, + functionId: functionId, + }) + const replacement = babel.template.expression(replacementCode)() + + // For variable declarations, replace the init + if (fnPath.nodePath.isVariableDeclarator()) { + fnPath.nodePath.get('init').replaceWith(replacement) + } + // For class/object methods, replace the whole method + else if ( + fnPath.nodePath.isClassMethod() || + fnPath.nodePath.isObjectMethod() + ) { + fnPath.nodePath.replaceWith( + babel.types.classMethod( + fnPath.nodePath.node.kind, + fnPath.nodePath.node.key, + fnPath.nodePath.node.params, + babel.types.blockStatement([ + babel.types.returnStatement(replacement), + ]), + ), + ) + } + // For function expressions, replace the whole path + else { + fnPath.nodePath.replaceWith(replacement) + } + } }, }, }) @@ -245,21 +293,23 @@ export function compileServerFnClient( minified: process.env.NODE_ENV === 'production', }) - console.log(serverFnPathsByLabel) - return { compiledCode, - serverFns: serverFnPathsByLabel, + serverFns: serverFnPathsByFunctionId, } } export function compileServerFnServer(opts: ParseAstOptions) { const ast = parseAst(opts) - return generate(ast, { + const compiledCode = generate(ast, { sourceMaps: true, minified: process.env.NODE_ENV === 'production', }) + + return { + compiledCode, + } } // function codeFrameError( diff --git a/packages/server-functions-vite-plugin/src/index.ts b/packages/server-functions-vite-plugin/src/index.ts index d6fe2101a5..8ee6b4cda8 100644 --- a/packages/server-functions-vite-plugin/src/index.ts +++ b/packages/server-functions-vite-plugin/src/index.ts @@ -1,12 +1,22 @@ import { fileURLToPath, pathToFileURL } from 'node:url' import { compileServerFnClient } from './compilers' +import { logDiff } from './logger' import type { Plugin } from 'vite' -const debug = Boolean(process.env.TSR_VITE_DEBUG) +const debug = Boolean(process.env.TSR_VITE_DEBUG) || (true as boolean) export type ServerFunctionsViteOptions = { - runtimeCode: string + getRuntimeCode: (opts: { + serverFnPathsByFunctionId: Record< + string, + { + nodePath: babel.NodePath + functionName: string + functionId: string + } + > + }) => string replacer: (opts: { filename: string; functionId: string }) => string } @@ -40,29 +50,16 @@ export function TanStackServerFnPluginClient( return null } - if (debug) console.info('') - if (debug) console.info('Compiled createServerFn Input') - if (debug) console.info('') - if (debug) console.info(code) - if (debug) console.info('') - if (debug) console.info('') - if (debug) console.info('') - const { compiledCode, serverFns } = compileServerFnClient({ code, root: ROOT, filename: id, - runtimeCode: opts.runtimeCode, + getRuntimeCode: opts.getRuntimeCode, replacer: opts.replacer, }) - if (debug) console.info('') - if (debug) console.info('Compiled createServerFn Output') - if (debug) console.info('') - if (debug) console.info(compiledCode) - if (debug) console.info('') - if (debug) console.info('') - if (debug) console.info('') + if (debug) console.info('createServerFn Input/Output') + if (debug) logDiff(code, compiledCode.code.replace(/ctx/g, 'blah')) return compiledCode }, diff --git a/packages/server-functions-vite-plugin/src/logger.ts b/packages/server-functions-vite-plugin/src/logger.ts new file mode 100644 index 0000000000..e1a3c37eea --- /dev/null +++ b/packages/server-functions-vite-plugin/src/logger.ts @@ -0,0 +1,59 @@ +import chalk from 'chalk' +import { diffChars } from 'diff' + +export function logDiff(oldStr: string, newStr: string) { + const differences = diffChars(oldStr, newStr) + + let output = '' + let unchangedLines = '' + + function processUnchangedLines(lines: string): string { + const lineArray = lines.split('\n') + if (lineArray.length > 4) { + return [ + chalk.dim(lineArray[0]), + chalk.dim(lineArray[1]), + '', + chalk.dim.bold(`... (${lineArray.length - 4} lines) ...`), + '', + chalk.dim(lineArray[lineArray.length - 2]), + chalk.dim(lineArray[lineArray.length - 1]), + ].join('\n') + } + return chalk.dim(lines) + } + + differences.forEach((part, index) => { + const nextPart = differences[index + 1] + + if (part.added) { + if (unchangedLines) { + output += processUnchangedLines(unchangedLines) + unchangedLines = '' + } + output += chalk.green.bold(part.value) + if (nextPart?.removed) output += ' ' + } else if (part.removed) { + if (unchangedLines) { + output += processUnchangedLines(unchangedLines) + unchangedLines = '' + } + output += chalk.red.bold(part.value) + if (nextPart?.added) output += ' ' + } else { + unchangedLines += part.value + } + }) + + // Process any remaining unchanged lines at the end + if (unchangedLines) { + output += processUnchangedLines(unchangedLines) + } + + if (output) { + console.log('\nDiff:') + console.log(output) + } else { + console.log('No changes') + } +} diff --git a/packages/server-functions-vite-plugin/tests/compiler.test.ts b/packages/server-functions-vite-plugin/tests/compiler.test.ts new file mode 100644 index 0000000000..6c287b2f18 --- /dev/null +++ b/packages/server-functions-vite-plugin/tests/compiler.test.ts @@ -0,0 +1,478 @@ +import { describe, expect, test } from 'vitest' + +import { compileServerFnClient, compileServerFnServer } from '../src/compilers' + +const clientConfig = { + root: './test-files', + filename: 'test.ts', + getRuntimeCode: () => 'import { createClientRpc } from "my-rpc-lib"', + replacer: (opts: { filename: string; functionId: string }) => + `createClientRpc({ + filename: ${JSON.stringify(opts.filename)}, + functionId: ${JSON.stringify(opts.functionId)}, + })`, +} + +const serverConfig = { + root: './test-files', + filename: 'test.ts', +} + +describe('server function compilation', () => { + test('basic function declaration', async () => { + const code = ` + function useServer() { + 'use server' + return 'hello' + } + ` + + const client = compileServerFnClient({ ...clientConfig, code }) + await expect(client.compiledCode.code).toMatchInlineSnapshot(` + "import { createClientRpc } from "my-rpc-lib"; + createClientRpc({ + filename: "test.ts", + functionId: "test--useServer" + });" + `) + + const server = compileServerFnServer({ ...serverConfig, code }) + await expect(server.compiledCode.code).toMatchInlineSnapshot(` + "function useServer() { + 'use server'; + + return 'hello'; + }" + `) + }) + + test('arrow function', () => { + const code = ` + const fn = () => { + 'use server' + return 'hello' + } + ` + + const client = compileServerFnClient({ ...clientConfig, code }) + expect(client.compiledCode.code).toMatchInlineSnapshot(` + "import { createClientRpc } from "my-rpc-lib"; + const fn = createClientRpc({ + filename: "test.ts", + functionId: "test--fn_1" + });" + `) + + const server = compileServerFnServer({ ...serverConfig, code }) + expect(server.compiledCode.code).toMatchInlineSnapshot(` + "const fn = () => { + 'use server'; + + return 'hello'; + };" + `) + }) + + test('anonymous function', () => { + const code = ` + const anonymousFn = function () { + 'use server' + } + ` + + const client = compileServerFnClient({ ...clientConfig, code }) + expect(client.compiledCode.code).toMatchInlineSnapshot(` + "import { createClientRpc } from "my-rpc-lib"; + const anonymousFn = createClientRpc({ + filename: "test.ts", + functionId: "test--anonymousFn_1" + });" + `) + + const server = compileServerFnServer({ ...serverConfig, code }) + expect(server.compiledCode.code).toMatchInlineSnapshot(` + "const anonymousFn = function () { + 'use server'; + };" + `) + }) + + test('class methods', () => { + const code = ` + class TestClass { + method() { + 'use server' + return 'hello' + } + + static staticMethod() { + 'use server' + return 'hello' + } + } + ` + + const client = compileServerFnClient({ ...clientConfig, code }) + expect(client.compiledCode.code).toMatchInlineSnapshot(` + "import { createClientRpc } from "my-rpc-lib"; + class TestClass { + method() { + return createClientRpc({ + filename: "test.ts", + functionId: "test--method" + }); + } + staticMethod() { + return createClientRpc({ + filename: "test.ts", + functionId: "test--staticMethod" + }); + } + }" + `) + + const server = compileServerFnServer({ ...serverConfig, code }) + expect(server.compiledCode.code).toMatchInlineSnapshot(` + "class TestClass { + method() { + 'use server'; + + return 'hello'; + } + static staticMethod() { + 'use server'; + + return 'hello'; + } + }" + `) + }) + + test('object methods', () => { + const code = ` + const obj = { + method() { + 'use server' + return 'hello' + }, + } + ` + + const client = compileServerFnClient({ ...clientConfig, code }) + expect(client.compiledCode.code).toMatchInlineSnapshot(` + "import { createClientRpc } from "my-rpc-lib"; + const obj = { + method() { + return createClientRpc({ + filename: "test.ts", + functionId: "test--obj_method" + }); + } + };" + `) + + const server = compileServerFnServer({ ...serverConfig, code }) + expect(server.compiledCode.code).toMatchInlineSnapshot(` + "const obj = { + method() { + 'use server'; + + return 'hello'; + } + };" + `) + }) + + test('async functions', () => { + const code = ` + async function asyncServer() { + 'use server' + return 'hello' + } + + const asyncArrow = async () => { + 'use server' + return 'hello' + } + ` + + const client = compileServerFnClient({ ...clientConfig, code }) + expect(client.compiledCode.code).toMatchInlineSnapshot(` + "import { createClientRpc } from "my-rpc-lib"; + createClientRpc({ + filename: "test.ts", + functionId: "test--asyncServer" + }); + const asyncArrow = createClientRpc({ + filename: "test.ts", + functionId: "test--asyncArrow_1" + });" + `) + + const server = compileServerFnServer({ ...serverConfig, code }) + expect(server.compiledCode.code).toMatchInlineSnapshot(` + "async function asyncServer() { + 'use server'; + + return 'hello'; + } + const asyncArrow = async () => { + 'use server'; + + return 'hello'; + };" + `) + }) + + test('generator functions', () => { + const code = ` + function* generatorServer() { + 'use server' + yield 'hello' + } + + async function* asyncGeneratorServer() { + 'use server' + yield 'hello' + } + ` + + const client = compileServerFnClient({ ...clientConfig, code }) + expect(client.compiledCode.code).toMatchInlineSnapshot(` + "import { createClientRpc } from "my-rpc-lib"; + createClientRpc({ + filename: "test.ts", + functionId: "test--generatorServer" + }); + createClientRpc({ + filename: "test.ts", + functionId: "test--asyncGeneratorServer" + });" + `) + + const server = compileServerFnServer({ ...serverConfig, code }) + expect(server.compiledCode.code).toMatchInlineSnapshot(` + "function* generatorServer() { + 'use server'; + + yield 'hello'; + } + async function* asyncGeneratorServer() { + 'use server'; + + yield 'hello'; + }" + `) + }) + + test('nested functions', () => { + const code = ` + function outer() { + function inner() { + 'use server' + return 'hello' + } + return inner + } + ` + + const client = compileServerFnClient({ ...clientConfig, code }) + expect(client.compiledCode.code).toMatchInlineSnapshot(` + "import { createClientRpc } from "my-rpc-lib"; + function outer() { + createClientRpc({ + filename: "test.ts", + functionId: "test--outer_inner" + }); + return inner; + }" + `) + + const server = compileServerFnServer({ ...serverConfig, code }) + expect(server.compiledCode.code).toMatchInlineSnapshot(` + "function outer() { + function inner() { + 'use server'; + + return 'hello'; + } + return inner; + }" + `) + }) + + test('multiple directives', () => { + const code = ` + function multiDirective() { + 'use strict' + 'use server' + return 'hello' + } + ` + + const client = compileServerFnClient({ ...clientConfig, code }) + expect(client.compiledCode.code).toMatchInlineSnapshot(` + "import { createClientRpc } from "my-rpc-lib"; + createClientRpc({ + filename: "test.ts", + functionId: "test--multiDirective" + });" + `) + + const server = compileServerFnServer({ ...serverConfig, code }) + expect(server.compiledCode.code).toMatchInlineSnapshot(` + "function multiDirective() { + 'use strict'; + 'use server'; + + return 'hello'; + }" + `) + }) + + test('function with parameters', () => { + const code = ` + function withParams(a: string, b: number) { + 'use server' + return \`\${a} \${b}\` + } + ` + + const client = compileServerFnClient({ ...clientConfig, code }) + expect(client.compiledCode.code).toMatchInlineSnapshot(` + "import { createClientRpc } from "my-rpc-lib"; + createClientRpc({ + filename: "test.ts", + functionId: "test--withParams" + });" + `) + + const server = compileServerFnServer({ ...serverConfig, code }) + expect(server.compiledCode.code).toMatchInlineSnapshot(` + "function withParams(a: string, b: number) { + 'use server'; + + return \`\${a} \${b}\`; + }" + `) + }) + + test('IIFE', () => { + const code = ` + const iife = (function () { + 'use server' + return 'hello' + })() + ` + + const client = compileServerFnClient({ ...clientConfig, code }) + expect(client.compiledCode.code).toMatchInlineSnapshot(` + "import { createClientRpc } from "my-rpc-lib"; + const iife = createClientRpc({ + filename: "test.ts", + functionId: "test--iife" + })();" + `) + + const server = compileServerFnServer({ ...serverConfig, code }) + expect(server.compiledCode.code).toMatchInlineSnapshot(` + "const iife = function () { + 'use server'; + + return 'hello'; + }();" + `) + }) + + test('higher order functions', () => { + const code = ` + function higherOrder() { + return function () { + 'use server' + return 'hello' + } + } + ` + + const client = compileServerFnClient({ ...clientConfig, code }) + expect(client.compiledCode.code).toMatchInlineSnapshot(` + "import { createClientRpc } from "my-rpc-lib"; + function higherOrder() { + return createClientRpc({ + filename: "test.ts", + functionId: "test--higherOrder" + }); + }" + `) + + const server = compileServerFnServer({ ...serverConfig, code }) + expect(server.compiledCode.code).toMatchInlineSnapshot(` + "function higherOrder() { + return function () { + 'use server'; + + return 'hello'; + }; + }" + `) + }) + + test('functions that might have the same functionId', () => { + const code = ` + function main() { + function middle() { + const useServer = function () { + 'use server' + return 'hello' + } + return useServer + } + return middle + } + + main().middle(function useServer() { + 'use server' + return 'hello' + }) + ` + + const client = compileServerFnClient({ ...clientConfig, code }) + expect(client.compiledCode.code).toMatchInlineSnapshot(` + "import { createClientRpc } from "my-rpc-lib"; + function main() { + function middle() { + const useServer = createClientRpc({ + filename: "test.ts", + functionId: "test--main_middle_useServer_1" + }); + return useServer; + } + return middle; + } + main().middle(createClientRpc({ + filename: "test.ts", + functionId: "test--main_middle_useServer_2" + }));" + `) + + const server = compileServerFnServer({ ...serverConfig, code }) + expect(server.compiledCode.code).toMatchInlineSnapshot(` + "function main() { + function middle() { + const useServer = function () { + 'use server'; + + return 'hello'; + }; + return useServer; + } + return middle; + } + main().middle(function useServer() { + 'use server'; + + return 'hello'; + });" + `) + }) +}) diff --git a/packages/server-functions-vite-plugin/tests/createIsomorphicFn/createIsomorphicFn.test.ts b/packages/server-functions-vite-plugin/tests/createIsomorphicFn/createIsomorphicFn.test.ts deleted file mode 100644 index 28f29510a7..0000000000 --- a/packages/server-functions-vite-plugin/tests/createIsomorphicFn/createIsomorphicFn.test.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { readFile, readdir } from 'node:fs/promises' -import path from 'node:path' -import { afterAll, describe, expect, test, vi } from 'vitest' - -import { compileStartOutput } from '../../src/compilers' - -async function getFilenames() { - return await readdir(path.resolve(import.meta.dirname, './test-files')) -} - -describe('createIsomorphicFn compiles correctly', async () => { - const noImplWarning = - 'createIsomorphicFn called without a client or server implementation!' - - const originalConsoleWarn = console.warn - const consoleSpy = vi.spyOn(console, 'warn').mockImplementation((...args) => { - // we want to avoid sending this warning to the console, we know about it - if (args[0] === noImplWarning) { - return - } - originalConsoleWarn(...args) - }) - - afterAll(() => { - consoleSpy.mockRestore() - }) - - const filenames = await getFilenames() - - describe.each(filenames)('should handle "%s"', async (filename) => { - const file = await readFile( - path.resolve(import.meta.dirname, `./test-files/${filename}`), - ) - const code = file.toString() - - test.each(['client', 'server'] as const)( - `should compile for ${filename} %s`, - async (env) => { - const compiledResult = compileStartOutput({ - env, - code, - root: './test-files', - filename, - }) - - await expect(compiledResult.code).toMatchFileSnapshot( - `./snapshots/${env}/${filename}`, - ) - }, - ) - }) - test('should error if implementation not provided', () => { - expect(() => { - compileStartOutput({ - env: 'client', - code: ` - import { createIsomorphicFn } from '@tanstack/start' - const clientOnly = createIsomorphicFn().client()`, - root: './test-files', - filename: 'no-fn.ts', - }) - }).toThrowError() - expect(() => { - compileStartOutput({ - env: 'server', - code: ` - import { createIsomorphicFn } from '@tanstack/start' - const serverOnly = createIsomorphicFn().server()`, - root: './test-files', - filename: 'no-fn.ts', - }) - }).toThrowError() - }) - test('should warn to console if no implementations provided', () => { - compileStartOutput({ - env: 'client', - code: ` - import { createIsomorphicFn } from '@tanstack/start' - const noImpl = createIsomorphicFn()`, - root: './test-files', - filename: 'no-fn.ts', - }) - expect(consoleSpy).toHaveBeenCalledWith( - noImplWarning, - 'This will result in a no-op function.', - 'Variable name:', - 'noImpl', - ) - }) -}) diff --git a/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnDestructured.tsx b/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnDestructured.tsx deleted file mode 100644 index 6fcb30691c..0000000000 --- a/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnDestructured.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createIsomorphicFn } from '@tanstack/start'; -const noImpl = () => {}; -const serverOnlyFn = () => {}; -const clientOnlyFn = () => 'client'; -const serverThenClientFn = () => 'client'; -const clientThenServerFn = () => 'client'; -function abstractedServerFn() { - return 'server'; -} -const serverOnlyFnAbstracted = () => {}; -function abstractedClientFn() { - return 'client'; -} -const clientOnlyFnAbstracted = abstractedClientFn; -const serverThenClientFnAbstracted = abstractedClientFn; -const clientThenServerFnAbstracted = abstractedClientFn; \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnDestructuredRename.tsx b/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnDestructuredRename.tsx deleted file mode 100644 index d273a49f40..0000000000 --- a/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnDestructuredRename.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createIsomorphicFn as isomorphicFn } from '@tanstack/start'; -const noImpl = () => {}; -const serverOnlyFn = () => {}; -const clientOnlyFn = () => 'client'; -const serverThenClientFn = () => 'client'; -const clientThenServerFn = () => 'client'; -function abstractedServerFn() { - return 'server'; -} -const serverOnlyFnAbstracted = () => {}; -function abstractedClientFn() { - return 'client'; -} -const clientOnlyFnAbstracted = abstractedClientFn; -const serverThenClientFnAbstracted = abstractedClientFn; -const clientThenServerFnAbstracted = abstractedClientFn; \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnStarImport.tsx b/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnStarImport.tsx deleted file mode 100644 index ffb2ffe79c..0000000000 --- a/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnStarImport.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import * as TanStackStart from '@tanstack/start'; -const noImpl = () => {}; -const serverOnlyFn = () => {}; -const clientOnlyFn = () => 'client'; -const serverThenClientFn = () => 'client'; -const clientThenServerFn = () => 'client'; -function abstractedServerFn() { - return 'server'; -} -const serverOnlyFnAbstracted = () => {}; -function abstractedClientFn() { - return 'client'; -} -const clientOnlyFnAbstracted = abstractedClientFn; -const serverThenClientFnAbstracted = abstractedClientFn; -const clientThenServerFnAbstracted = abstractedClientFn; \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnDestructured.tsx b/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnDestructured.tsx deleted file mode 100644 index 0e0134e347..0000000000 --- a/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnDestructured.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createIsomorphicFn } from '@tanstack/start'; -const noImpl = () => {}; -const serverOnlyFn = () => 'server'; -const clientOnlyFn = () => {}; -const serverThenClientFn = () => 'server'; -const clientThenServerFn = () => 'server'; -function abstractedServerFn() { - return 'server'; -} -const serverOnlyFnAbstracted = abstractedServerFn; -function abstractedClientFn() { - return 'client'; -} -const clientOnlyFnAbstracted = () => {}; -const serverThenClientFnAbstracted = abstractedServerFn; -const clientThenServerFnAbstracted = abstractedServerFn; \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnDestructuredRename.tsx b/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnDestructuredRename.tsx deleted file mode 100644 index 3ba9d0598f..0000000000 --- a/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnDestructuredRename.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createIsomorphicFn as isomorphicFn } from '@tanstack/start'; -const noImpl = () => {}; -const serverOnlyFn = () => 'server'; -const clientOnlyFn = () => {}; -const serverThenClientFn = () => 'server'; -const clientThenServerFn = () => 'server'; -function abstractedServerFn() { - return 'server'; -} -const serverOnlyFnAbstracted = abstractedServerFn; -function abstractedClientFn() { - return 'client'; -} -const clientOnlyFnAbstracted = () => {}; -const serverThenClientFnAbstracted = abstractedServerFn; -const clientThenServerFnAbstracted = abstractedServerFn; \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnStarImport.tsx b/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnStarImport.tsx deleted file mode 100644 index c77c6ac839..0000000000 --- a/packages/server-functions-vite-plugin/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnStarImport.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import * as TanStackStart from '@tanstack/start'; -const noImpl = () => {}; -const serverOnlyFn = () => 'server'; -const clientOnlyFn = () => {}; -const serverThenClientFn = () => 'server'; -const clientThenServerFn = () => 'server'; -function abstractedServerFn() { - return 'server'; -} -const serverOnlyFnAbstracted = abstractedServerFn; -function abstractedClientFn() { - return 'client'; -} -const clientOnlyFnAbstracted = () => {}; -const serverThenClientFnAbstracted = abstractedServerFn; -const clientThenServerFnAbstracted = abstractedServerFn; \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createIsomorphicFn/test-files/createIsomorphicFnDestructured.tsx b/packages/server-functions-vite-plugin/tests/createIsomorphicFn/test-files/createIsomorphicFnDestructured.tsx deleted file mode 100644 index e6c5c35943..0000000000 --- a/packages/server-functions-vite-plugin/tests/createIsomorphicFn/test-files/createIsomorphicFnDestructured.tsx +++ /dev/null @@ -1,35 +0,0 @@ -import { createIsomorphicFn } from '@tanstack/start' - -const noImpl = createIsomorphicFn() - -const serverOnlyFn = createIsomorphicFn().server(() => 'server') - -const clientOnlyFn = createIsomorphicFn().client(() => 'client') - -const serverThenClientFn = createIsomorphicFn() - .server(() => 'server') - .client(() => 'client') - -const clientThenServerFn = createIsomorphicFn() - .client(() => 'client') - .server(() => 'server') - -function abstractedServerFn() { - return 'server' -} - -const serverOnlyFnAbstracted = createIsomorphicFn().server(abstractedServerFn) - -function abstractedClientFn() { - return 'client' -} - -const clientOnlyFnAbstracted = createIsomorphicFn().client(abstractedClientFn) - -const serverThenClientFnAbstracted = createIsomorphicFn() - .server(abstractedServerFn) - .client(abstractedClientFn) - -const clientThenServerFnAbstracted = createIsomorphicFn() - .client(abstractedClientFn) - .server(abstractedServerFn) diff --git a/packages/server-functions-vite-plugin/tests/createIsomorphicFn/test-files/createIsomorphicFnDestructuredRename.tsx b/packages/server-functions-vite-plugin/tests/createIsomorphicFn/test-files/createIsomorphicFnDestructuredRename.tsx deleted file mode 100644 index 9c31330b1b..0000000000 --- a/packages/server-functions-vite-plugin/tests/createIsomorphicFn/test-files/createIsomorphicFnDestructuredRename.tsx +++ /dev/null @@ -1,35 +0,0 @@ -import { createIsomorphicFn as isomorphicFn } from '@tanstack/start' - -const noImpl = isomorphicFn() - -const serverOnlyFn = isomorphicFn().server(() => 'server') - -const clientOnlyFn = isomorphicFn().client(() => 'client') - -const serverThenClientFn = isomorphicFn() - .server(() => 'server') - .client(() => 'client') - -const clientThenServerFn = isomorphicFn() - .client(() => 'client') - .server(() => 'server') - -function abstractedServerFn() { - return 'server' -} - -const serverOnlyFnAbstracted = isomorphicFn().server(abstractedServerFn) - -function abstractedClientFn() { - return 'client' -} - -const clientOnlyFnAbstracted = isomorphicFn().client(abstractedClientFn) - -const serverThenClientFnAbstracted = isomorphicFn() - .server(abstractedServerFn) - .client(abstractedClientFn) - -const clientThenServerFnAbstracted = isomorphicFn() - .client(abstractedClientFn) - .server(abstractedServerFn) diff --git a/packages/server-functions-vite-plugin/tests/createIsomorphicFn/test-files/createIsomorphicFnStarImport.tsx b/packages/server-functions-vite-plugin/tests/createIsomorphicFn/test-files/createIsomorphicFnStarImport.tsx deleted file mode 100644 index 4c1bed5741..0000000000 --- a/packages/server-functions-vite-plugin/tests/createIsomorphicFn/test-files/createIsomorphicFnStarImport.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import * as TanStackStart from '@tanstack/start' - -const noImpl = TanStackStart.createIsomorphicFn() - -const serverOnlyFn = TanStackStart.createIsomorphicFn().server(() => 'server') - -const clientOnlyFn = TanStackStart.createIsomorphicFn().client(() => 'client') - -const serverThenClientFn = TanStackStart.createIsomorphicFn() - .server(() => 'server') - .client(() => 'client') - -const clientThenServerFn = TanStackStart.createIsomorphicFn() - .client(() => 'client') - .server(() => 'server') - -function abstractedServerFn() { - return 'server' -} - -const serverOnlyFnAbstracted = - TanStackStart.createIsomorphicFn().server(abstractedServerFn) - -function abstractedClientFn() { - return 'client' -} - -const clientOnlyFnAbstracted = - TanStackStart.createIsomorphicFn().client(abstractedClientFn) - -const serverThenClientFnAbstracted = TanStackStart.createIsomorphicFn() - .server(abstractedServerFn) - .client(abstractedClientFn) - -const clientThenServerFnAbstracted = TanStackStart.createIsomorphicFn() - .client(abstractedClientFn) - .server(abstractedServerFn) diff --git a/packages/server-functions-vite-plugin/tests/createMiddleware/createMiddleware.test.ts b/packages/server-functions-vite-plugin/tests/createMiddleware/createMiddleware.test.ts deleted file mode 100644 index ae4ee2c221..0000000000 --- a/packages/server-functions-vite-plugin/tests/createMiddleware/createMiddleware.test.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { readFile, readdir } from 'node:fs/promises' -import path from 'node:path' -import { describe, expect, test } from 'vitest' - -import { compileStartOutput } from '../../src/compilers' - -async function getFilenames() { - return await readdir(path.resolve(import.meta.dirname, './test-files')) -} - -describe('createMiddleware compiles correctly', async () => { - const filenames = await getFilenames() - - describe.each(filenames)('should handle "%s"', async (filename) => { - const file = await readFile( - path.resolve(import.meta.dirname, `./test-files/${filename}`), - ) - const code = file.toString() - - test.each(['client', 'server'] as const)( - `should compile for ${filename} %s`, - async (env) => { - const compiledResult = compileStartOutput({ - env, - code, - root: './test-files', - filename, - }) - - await expect(compiledResult.code).toMatchFileSnapshot( - `./snapshots/${env}/${filename}`, - ) - }, - ) - }) -}) diff --git a/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/client/createMiddlewareDestructured.tsx b/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/client/createMiddlewareDestructured.tsx deleted file mode 100644 index f0ed6717e4..0000000000 --- a/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/client/createMiddlewareDestructured.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import { createMiddleware } from '@tanstack/start'; -import { z } from 'zod'; -export const withUseServer = createMiddleware({ - id: 'test' -}); -export const withoutUseServer = createMiddleware({ - id: 'test' -}); -export const withVariable = createMiddleware({ - id: 'test' -}); -async function abstractedFunction() { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -} -function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { - return async (input: unknown) => { - return fn(schema.parse(input)); - }; -} -export const withZodValidator = createMiddleware({ - id: 'test' -}); \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/client/createMiddlewareDestructuredRename.tsx b/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/client/createMiddlewareDestructuredRename.tsx deleted file mode 100644 index c13c45a86c..0000000000 --- a/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/client/createMiddlewareDestructuredRename.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import { createMiddleware as middlewareFn } from '@tanstack/start'; -import { z } from 'zod'; -export const withUseServer = middlewareFn({ - id: 'test' -}); -export const withoutUseServer = middlewareFn({ - id: 'test' -}); -export const withVariable = middlewareFn({ - id: 'test' -}); -async function abstractedFunction() { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -} -function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { - return async (input: unknown) => { - return fn(schema.parse(input)); - }; -} -export const withZodValidator = middlewareFn({ - id: 'test' -}); \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/client/createMiddlewareStarImport.tsx b/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/client/createMiddlewareStarImport.tsx deleted file mode 100644 index 0af363017d..0000000000 --- a/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/client/createMiddlewareStarImport.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import * as TanStackStart from '@tanstack/start'; -import { z } from 'zod'; -export const withUseServer = TanStackStart.createMiddleware({ - id: 'test' -}); -export const withoutUseServer = TanStackStart.createMiddleware({ - id: 'test' -}); -export const withVariable = TanStackStart.createMiddleware({ - id: 'test' -}); -async function abstractedFunction() { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -} -function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { - return async (input: unknown) => { - return fn(schema.parse(input)); - }; -} -export const withZodValidator = TanStackStart.createMiddleware({ - id: 'test' -}); \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/client/createMiddlewareValidator.tsx b/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/client/createMiddlewareValidator.tsx deleted file mode 100644 index e13946f2d8..0000000000 --- a/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/client/createMiddlewareValidator.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createMiddleware } from '@tanstack/start'; -import { z } from 'zod'; -export const withUseServer = createMiddleware({ - id: 'test' -}); \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/server/createMiddlewareDestructured.tsx b/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/server/createMiddlewareDestructured.tsx deleted file mode 100644 index a29e1ecb40..0000000000 --- a/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/server/createMiddlewareDestructured.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import { createMiddleware } from '@tanstack/start'; -import { z } from 'zod'; -export const withUseServer = createMiddleware({ - id: 'test' -}).server(async function () { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -}); -export const withoutUseServer = createMiddleware({ - id: 'test' -}).server(async () => { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -}); -export const withVariable = createMiddleware({ - id: 'test' -}).server(abstractedFunction); -async function abstractedFunction() { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -} -function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { - return async (input: unknown) => { - return fn(schema.parse(input)); - }; -} -export const withZodValidator = createMiddleware({ - id: 'test' -}).server(zodValidator(z.number(), input => { - return { - 'you gave': input - }; -})); \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/server/createMiddlewareDestructuredRename.tsx b/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/server/createMiddlewareDestructuredRename.tsx deleted file mode 100644 index d529f89fe1..0000000000 --- a/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/server/createMiddlewareDestructuredRename.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import { createMiddleware as middlewareFn } from '@tanstack/start'; -import { z } from 'zod'; -export const withUseServer = middlewareFn({ - id: 'test' -}).server(async function () { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -}); -export const withoutUseServer = middlewareFn({ - id: 'test' -}).server(async () => { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -}); -export const withVariable = middlewareFn({ - id: 'test' -}).server(abstractedFunction); -async function abstractedFunction() { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -} -function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { - return async (input: unknown) => { - return fn(schema.parse(input)); - }; -} -export const withZodValidator = middlewareFn({ - id: 'test' -}).server(zodValidator(z.number(), input => { - return { - 'you gave': input - }; -})); \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/server/createMiddlewareStarImport.tsx b/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/server/createMiddlewareStarImport.tsx deleted file mode 100644 index 53baf6fa9c..0000000000 --- a/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/server/createMiddlewareStarImport.tsx +++ /dev/null @@ -1,38 +0,0 @@ -import * as TanStackStart from '@tanstack/start'; -import { z } from 'zod'; -export const withUseServer = TanStackStart.createMiddleware({ - id: 'test' -}).server(async function () { - 'use server'; - - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -}); -export const withoutUseServer = TanStackStart.createMiddleware({ - id: 'test' -}).server(async () => { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -}); -export const withVariable = TanStackStart.createMiddleware({ - id: 'test' -}).server(abstractedFunction); -async function abstractedFunction() { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -} -function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { - return async (input: unknown) => { - return fn(schema.parse(input)); - }; -} -export const withZodValidator = TanStackStart.createMiddleware({ - id: 'test' -}).server(zodValidator(z.number(), input => { - return { - 'you gave': input - }; -})); \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/server/createMiddlewareValidator.tsx b/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/server/createMiddlewareValidator.tsx deleted file mode 100644 index 1e41c79866..0000000000 --- a/packages/server-functions-vite-plugin/tests/createMiddleware/snapshots/server/createMiddlewareValidator.tsx +++ /dev/null @@ -1,7 +0,0 @@ -import { createMiddleware } from '@tanstack/start'; -import { z } from 'zod'; -export const withUseServer = createMiddleware({ - id: 'test' -}).validator(z.number()).server(({ - input -}) => input + 1); \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createMiddleware/test-files/createMiddlewareDestructured.tsx b/packages/server-functions-vite-plugin/tests/createMiddleware/test-files/createMiddlewareDestructured.tsx deleted file mode 100644 index c5ea2aa5b6..0000000000 --- a/packages/server-functions-vite-plugin/tests/createMiddleware/test-files/createMiddlewareDestructured.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import { createMiddleware } from '@tanstack/start' -import { z } from 'zod' - -export const withUseServer = createMiddleware({ - id: 'test', -}).server(async function () { - console.info('Fetching posts...') - await new Promise((r) => setTimeout(r, 500)) - return axios - .get>('https://jsonplaceholder.typicode.com/posts') - .then((r) => r.data.slice(0, 10)) -}) - -export const withoutUseServer = createMiddleware({ - id: 'test', -}).server(async () => { - console.info('Fetching posts...') - await new Promise((r) => setTimeout(r, 500)) - return axios - .get>('https://jsonplaceholder.typicode.com/posts') - .then((r) => r.data.slice(0, 10)) -}) - -export const withVariable = createMiddleware({ - id: 'test', -}).server(abstractedFunction) - -async function abstractedFunction() { - console.info('Fetching posts...') - await new Promise((r) => setTimeout(r, 500)) - return axios - .get>('https://jsonplaceholder.typicode.com/posts') - .then((r) => r.data.slice(0, 10)) -} - -function zodValidator( - schema: TSchema, - fn: (input: z.output) => TResult, -) { - return async (input: unknown) => { - return fn(schema.parse(input)) - } -} - -export const withZodValidator = createMiddleware({ - id: 'test', -}).server( - zodValidator(z.number(), (input) => { - return { 'you gave': input } - }), -) diff --git a/packages/server-functions-vite-plugin/tests/createMiddleware/test-files/createMiddlewareDestructuredRename.tsx b/packages/server-functions-vite-plugin/tests/createMiddleware/test-files/createMiddlewareDestructuredRename.tsx deleted file mode 100644 index 2e456131fe..0000000000 --- a/packages/server-functions-vite-plugin/tests/createMiddleware/test-files/createMiddlewareDestructuredRename.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import { createMiddleware as middlewareFn } from '@tanstack/start' -import { z } from 'zod' - -export const withUseServer = middlewareFn({ - id: 'test', -}).server(async function () { - console.info('Fetching posts...') - await new Promise((r) => setTimeout(r, 500)) - return axios - .get>('https://jsonplaceholder.typicode.com/posts') - .then((r) => r.data.slice(0, 10)) -}) - -export const withoutUseServer = middlewareFn({ - id: 'test', -}).server(async () => { - console.info('Fetching posts...') - await new Promise((r) => setTimeout(r, 500)) - return axios - .get>('https://jsonplaceholder.typicode.com/posts') - .then((r) => r.data.slice(0, 10)) -}) - -export const withVariable = middlewareFn({ - id: 'test', -}).server(abstractedFunction) - -async function abstractedFunction() { - console.info('Fetching posts...') - await new Promise((r) => setTimeout(r, 500)) - return axios - .get>('https://jsonplaceholder.typicode.com/posts') - .then((r) => r.data.slice(0, 10)) -} - -function zodValidator( - schema: TSchema, - fn: (input: z.output) => TResult, -) { - return async (input: unknown) => { - return fn(schema.parse(input)) - } -} - -export const withZodValidator = middlewareFn({ - id: 'test', -}).server( - zodValidator(z.number(), (input) => { - return { 'you gave': input } - }), -) diff --git a/packages/server-functions-vite-plugin/tests/createMiddleware/test-files/createMiddlewareStarImport.tsx b/packages/server-functions-vite-plugin/tests/createMiddleware/test-files/createMiddlewareStarImport.tsx deleted file mode 100644 index c1df8e12b3..0000000000 --- a/packages/server-functions-vite-plugin/tests/createMiddleware/test-files/createMiddlewareStarImport.tsx +++ /dev/null @@ -1,52 +0,0 @@ -import * as TanStackStart from '@tanstack/start' -import { z } from 'zod' - -export const withUseServer = TanStackStart.createMiddleware({ - id: 'test', -}).server(async function () { - 'use server' - console.info('Fetching posts...') - await new Promise((r) => setTimeout(r, 500)) - return axios - .get>('https://jsonplaceholder.typicode.com/posts') - .then((r) => r.data.slice(0, 10)) -}) - -export const withoutUseServer = TanStackStart.createMiddleware({ - id: 'test', -}).server(async () => { - console.info('Fetching posts...') - await new Promise((r) => setTimeout(r, 500)) - return axios - .get>('https://jsonplaceholder.typicode.com/posts') - .then((r) => r.data.slice(0, 10)) -}) - -export const withVariable = TanStackStart.createMiddleware({ - id: 'test', -}).server(abstractedFunction) - -async function abstractedFunction() { - console.info('Fetching posts...') - await new Promise((r) => setTimeout(r, 500)) - return axios - .get>('https://jsonplaceholder.typicode.com/posts') - .then((r) => r.data.slice(0, 10)) -} - -function zodValidator( - schema: TSchema, - fn: (input: z.output) => TResult, -) { - return async (input: unknown) => { - return fn(schema.parse(input)) - } -} - -export const withZodValidator = TanStackStart.createMiddleware({ - id: 'test', -}).server( - zodValidator(z.number(), (input) => { - return { 'you gave': input } - }), -) diff --git a/packages/server-functions-vite-plugin/tests/createMiddleware/test-files/createMiddlewareValidator.tsx b/packages/server-functions-vite-plugin/tests/createMiddleware/test-files/createMiddlewareValidator.tsx deleted file mode 100644 index 7e0d6ba449..0000000000 --- a/packages/server-functions-vite-plugin/tests/createMiddleware/test-files/createMiddlewareValidator.tsx +++ /dev/null @@ -1,8 +0,0 @@ -import { createMiddleware } from '@tanstack/start' -import { z } from 'zod' - -export const withUseServer = createMiddleware({ - id: 'test', -}) - .validator(z.number()) - .server(({ input }) => input + 1) diff --git a/packages/server-functions-vite-plugin/tests/createServerFn/createServerFn.test.ts b/packages/server-functions-vite-plugin/tests/createServerFn/createServerFn.test.ts deleted file mode 100644 index 19b86a0c01..0000000000 --- a/packages/server-functions-vite-plugin/tests/createServerFn/createServerFn.test.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { readFile, readdir } from 'node:fs/promises' -import path from 'node:path' -import { describe, expect, test } from 'vitest' - -import { compileStartOutput } from '../../src/compilers' - -async function getFilenames() { - return await readdir(path.resolve(import.meta.dirname, './test-files')) -} - -describe('createServerFn compiles correctly', async () => { - const filenames = await getFilenames() - - describe.each(filenames)('should handle "%s"', async (filename) => { - const file = await readFile( - path.resolve(import.meta.dirname, `./test-files/${filename}`), - ) - const code = file.toString() - - test.each(['client', 'server'] as const)( - `should compile for ${filename} %s`, - async (env) => { - const compiledResult = compileStartOutput({ - env, - code, - root: './test-files', - filename, - }) - - await expect(compiledResult.code).toMatchFileSnapshot( - `./snapshots/${env}/${filename}`, - ) - }, - ) - }) - - test('should error if created without a handler', () => { - expect(() => { - compileStartOutput({ - env: 'client', - code: ` - import { createServerFn } from '@tanstack/start' - createServerFn()`, - root: './test-files', - filename: 'no-fn.ts', - }) - }).toThrowError() - }) - - test('should be assigned to a variable', () => { - expect(() => { - compileStartOutput({ - env: 'client', - code: ` - import { createServerFn } from '@tanstack/start' - createServerFn().handler(async () => {})`, - root: './test-files', - filename: 'no-fn.ts', - }) - }).toThrowError() - }) -}) diff --git a/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/client/createServerFnDestructured.tsx b/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/client/createServerFnDestructured.tsx deleted file mode 100644 index be1b58b186..0000000000 --- a/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/client/createServerFnDestructured.tsx +++ /dev/null @@ -1,61 +0,0 @@ -import { createServerFn } from '@tanstack/start'; -import { z } from 'zod'; -export const withUseServer = createServerFn({ - method: 'GET' -}).handler(opts => { - "use server"; - - return withUseServer.__executeServer(opts); -}); -export const withArrowFunction = createServerFn({ - method: 'GET' -}).handler(opts => { - "use server"; - - return withArrowFunction.__executeServer(opts); -}); -export const withArrowFunctionAndFunction = createServerFn({ - method: 'GET' -}).handler(opts => { - "use server"; - - return withArrowFunctionAndFunction.__executeServer(opts); -}); -export const withoutUseServer = createServerFn({ - method: 'GET' -}).handler(opts => { - "use server"; - - return withoutUseServer.__executeServer(opts); -}); -export const withVariable = createServerFn({ - method: 'GET' -}).handler(opts => { - "use server"; - - return withVariable.__executeServer(opts); -}); -async function abstractedFunction() { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -} -function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { - return async (input: unknown) => { - return fn(schema.parse(input)); - }; -} -export const withZodValidator = createServerFn({ - method: 'GET' -}).handler(opts => { - "use server"; - - return withZodValidator.__executeServer(opts); -}); -export const withValidatorFn = createServerFn({ - method: 'GET' -}).handler(opts => { - "use server"; - - return withValidatorFn.__executeServer(opts); -}); \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/client/createServerFnDestructuredRename.tsx b/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/client/createServerFnDestructuredRename.tsx deleted file mode 100644 index f51f0ade21..0000000000 --- a/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/client/createServerFnDestructuredRename.tsx +++ /dev/null @@ -1,40 +0,0 @@ -import { createServerFn as serverFn } from '@tanstack/start'; -import { z } from 'zod'; -export const withUseServer = serverFn({ - method: 'GET' -}).handler(opts => { - "use server"; - - return withUseServer.__executeServer(opts); -}); -export const withoutUseServer = serverFn({ - method: 'GET' -}).handler(opts => { - "use server"; - - return withoutUseServer.__executeServer(opts); -}); -export const withVariable = serverFn({ - method: 'GET' -}).handler(opts => { - "use server"; - - return withVariable.__executeServer(opts); -}); -async function abstractedFunction() { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -} -function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { - return async (input: unknown) => { - return fn(schema.parse(input)); - }; -} -export const withZodValidator = serverFn({ - method: 'GET' -}).handler(opts => { - "use server"; - - return withZodValidator.__executeServer(opts); -}); \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/client/createServerFnStarImport.tsx b/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/client/createServerFnStarImport.tsx deleted file mode 100644 index 750a52532a..0000000000 --- a/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/client/createServerFnStarImport.tsx +++ /dev/null @@ -1,40 +0,0 @@ -import * as TanStackStart from '@tanstack/start'; -import { z } from 'zod'; -export const withUseServer = TanStackStart.createServerFn({ - method: 'GET' -}).handler(opts => { - "use server"; - - return withUseServer.__executeServer(opts); -}); -export const withoutUseServer = TanStackStart.createServerFn({ - method: 'GET' -}).handler(opts => { - "use server"; - - return withoutUseServer.__executeServer(opts); -}); -export const withVariable = TanStackStart.createServerFn({ - method: 'GET' -}).handler(opts => { - "use server"; - - return withVariable.__executeServer(opts); -}); -async function abstractedFunction() { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -} -function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { - return async (input: unknown) => { - return fn(schema.parse(input)); - }; -} -export const withZodValidator = TanStackStart.createServerFn({ - method: 'GET' -}).handler(opts => { - "use server"; - - return withZodValidator.__executeServer(opts); -}); \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/client/createServerFnValidator.tsx b/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/client/createServerFnValidator.tsx deleted file mode 100644 index 4e40b54a24..0000000000 --- a/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/client/createServerFnValidator.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createServerFn } from '@tanstack/start'; -import { z } from 'zod'; -export const withUseServer = createServerFn({ - method: 'GET' -}).handler(opts => { - "use server"; - - return withUseServer.__executeServer(opts); -}); \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/server/createServerFnDestructured.tsx b/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/server/createServerFnDestructured.tsx deleted file mode 100644 index 0176442a89..0000000000 --- a/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/server/createServerFnDestructured.tsx +++ /dev/null @@ -1,77 +0,0 @@ -import { createServerFn } from '@tanstack/start'; -import { z } from 'zod'; -export const withUseServer = createServerFn({ - method: 'GET' -}).handler(opts => { - "use server"; - - return withUseServer.__executeServer(opts); -}, async function () { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -}); -export const withArrowFunction = createServerFn({ - method: 'GET' -}).handler(opts => { - "use server"; - - return withArrowFunction.__executeServer(opts); -}, async () => null); -export const withArrowFunctionAndFunction = createServerFn({ - method: 'GET' -}).handler(opts => { - "use server"; - - return withArrowFunctionAndFunction.__executeServer(opts); -}, async () => test()); -export const withoutUseServer = createServerFn({ - method: 'GET' -}).handler(opts => { - "use server"; - - return withoutUseServer.__executeServer(opts); -}, async () => { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -}); -export const withVariable = createServerFn({ - method: 'GET' -}).handler(opts => { - "use server"; - - return withVariable.__executeServer(opts); -}, abstractedFunction); -async function abstractedFunction() { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -} -function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { - return async (input: unknown) => { - return fn(schema.parse(input)); - }; -} -export const withZodValidator = createServerFn({ - method: 'GET' -}).handler(opts => { - "use server"; - - return withZodValidator.__executeServer(opts); -}, zodValidator(z.number(), input => { - return { - 'you gave': input - }; -})); -export const withValidatorFn = createServerFn({ - method: 'GET' -}).validator(z.number()).handler(opts => { - "use server"; - - return withValidatorFn.__executeServer(opts); -}, async ({ - input -}) => { - return null; -}); \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/server/createServerFnDestructuredRename.tsx b/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/server/createServerFnDestructuredRename.tsx deleted file mode 100644 index b391de555f..0000000000 --- a/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/server/createServerFnDestructuredRename.tsx +++ /dev/null @@ -1,52 +0,0 @@ -import { createServerFn as serverFn } from '@tanstack/start'; -import { z } from 'zod'; -export const withUseServer = serverFn({ - method: 'GET' -}).handler(opts => { - "use server"; - - return withUseServer.__executeServer(opts); -}, async function () { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -}); -export const withoutUseServer = serverFn({ - method: 'GET' -}).handler(opts => { - "use server"; - - return withoutUseServer.__executeServer(opts); -}, async () => { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -}); -export const withVariable = serverFn({ - method: 'GET' -}).handler(opts => { - "use server"; - - return withVariable.__executeServer(opts); -}, abstractedFunction); -async function abstractedFunction() { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -} -function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { - return async (input: unknown) => { - return fn(schema.parse(input)); - }; -} -export const withZodValidator = serverFn({ - method: 'GET' -}).handler(opts => { - "use server"; - - return withZodValidator.__executeServer(opts); -}, zodValidator(z.number(), input => { - return { - 'you gave': input - }; -})); \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/server/createServerFnStarImport.tsx b/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/server/createServerFnStarImport.tsx deleted file mode 100644 index 66088cb181..0000000000 --- a/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/server/createServerFnStarImport.tsx +++ /dev/null @@ -1,52 +0,0 @@ -import * as TanStackStart from '@tanstack/start'; -import { z } from 'zod'; -export const withUseServer = TanStackStart.createServerFn({ - method: 'GET' -}).handler(opts => { - "use server"; - - return withUseServer.__executeServer(opts); -}, async function () { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -}); -export const withoutUseServer = TanStackStart.createServerFn({ - method: 'GET' -}).handler(opts => { - "use server"; - - return withoutUseServer.__executeServer(opts); -}, async () => { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -}); -export const withVariable = TanStackStart.createServerFn({ - method: 'GET' -}).handler(opts => { - "use server"; - - return withVariable.__executeServer(opts); -}, abstractedFunction); -async function abstractedFunction() { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -} -function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { - return async (input: unknown) => { - return fn(schema.parse(input)); - }; -} -export const withZodValidator = TanStackStart.createServerFn({ - method: 'GET' -}).handler(opts => { - "use server"; - - return withZodValidator.__executeServer(opts); -}, zodValidator(z.number(), input => { - return { - 'you gave': input - }; -})); \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/server/createServerFnValidator.tsx b/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/server/createServerFnValidator.tsx deleted file mode 100644 index 96cd71b9fb..0000000000 --- a/packages/server-functions-vite-plugin/tests/createServerFn/snapshots/server/createServerFnValidator.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { createServerFn } from '@tanstack/start'; -import { z } from 'zod'; -export const withUseServer = createServerFn({ - method: 'GET' -}).validator(z.number()).handler(opts => { - "use server"; - - return withUseServer.__executeServer(opts); -}, ({ - input -}) => input + 1); \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/createServerFn/test-files/createServerFnDestructured.tsx b/packages/server-functions-vite-plugin/tests/createServerFn/test-files/createServerFnDestructured.tsx deleted file mode 100644 index 780c1e3370..0000000000 --- a/packages/server-functions-vite-plugin/tests/createServerFn/test-files/createServerFnDestructured.tsx +++ /dev/null @@ -1,67 +0,0 @@ -import { createServerFn } from '@tanstack/start' -import { z } from 'zod' - -export const withUseServer = createServerFn({ - method: 'GET', -}).handler(async function () { - console.info('Fetching posts...') - await new Promise((r) => setTimeout(r, 500)) - return axios - .get>('https://jsonplaceholder.typicode.com/posts') - .then((r) => r.data.slice(0, 10)) -}) - -export const withArrowFunction = createServerFn({ - method: 'GET', -}).handler(async () => null) - -export const withArrowFunctionAndFunction = createServerFn({ - method: 'GET', -}).handler(async () => test()) - -export const withoutUseServer = createServerFn({ - method: 'GET', -}).handler(async () => { - console.info('Fetching posts...') - await new Promise((r) => setTimeout(r, 500)) - return axios - .get>('https://jsonplaceholder.typicode.com/posts') - .then((r) => r.data.slice(0, 10)) -}) - -export const withVariable = createServerFn({ - method: 'GET', -}).handler(abstractedFunction) - -async function abstractedFunction() { - console.info('Fetching posts...') - await new Promise((r) => setTimeout(r, 500)) - return axios - .get>('https://jsonplaceholder.typicode.com/posts') - .then((r) => r.data.slice(0, 10)) -} - -function zodValidator( - schema: TSchema, - fn: (input: z.output) => TResult, -) { - return async (input: unknown) => { - return fn(schema.parse(input)) - } -} - -export const withZodValidator = createServerFn({ - method: 'GET', -}).handler( - zodValidator(z.number(), (input) => { - return { 'you gave': input } - }), -) - -export const withValidatorFn = createServerFn({ - method: 'GET', -}) - .validator(z.number()) - .handler(async ({ input }) => { - return null - }) diff --git a/packages/server-functions-vite-plugin/tests/createServerFn/test-files/createServerFnDestructuredRename.tsx b/packages/server-functions-vite-plugin/tests/createServerFn/test-files/createServerFnDestructuredRename.tsx deleted file mode 100644 index aba9859be3..0000000000 --- a/packages/server-functions-vite-plugin/tests/createServerFn/test-files/createServerFnDestructuredRename.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import { createServerFn as serverFn } from '@tanstack/start' -import { z } from 'zod' - -export const withUseServer = serverFn({ - method: 'GET', -}).handler(async function () { - console.info('Fetching posts...') - await new Promise((r) => setTimeout(r, 500)) - return axios - .get>('https://jsonplaceholder.typicode.com/posts') - .then((r) => r.data.slice(0, 10)) -}) - -export const withoutUseServer = serverFn({ - method: 'GET', -}).handler(async () => { - console.info('Fetching posts...') - await new Promise((r) => setTimeout(r, 500)) - return axios - .get>('https://jsonplaceholder.typicode.com/posts') - .then((r) => r.data.slice(0, 10)) -}) - -export const withVariable = serverFn({ method: 'GET' }).handler( - abstractedFunction, -) - -async function abstractedFunction() { - console.info('Fetching posts...') - await new Promise((r) => setTimeout(r, 500)) - return axios - .get>('https://jsonplaceholder.typicode.com/posts') - .then((r) => r.data.slice(0, 10)) -} - -function zodValidator( - schema: TSchema, - fn: (input: z.output) => TResult, -) { - return async (input: unknown) => { - return fn(schema.parse(input)) - } -} - -export const withZodValidator = serverFn({ - method: 'GET', -}).handler( - zodValidator(z.number(), (input) => { - return { 'you gave': input } - }), -) diff --git a/packages/server-functions-vite-plugin/tests/createServerFn/test-files/createServerFnStarImport.tsx b/packages/server-functions-vite-plugin/tests/createServerFn/test-files/createServerFnStarImport.tsx deleted file mode 100644 index 6d5ba022bb..0000000000 --- a/packages/server-functions-vite-plugin/tests/createServerFn/test-files/createServerFnStarImport.tsx +++ /dev/null @@ -1,52 +0,0 @@ -import * as TanStackStart from '@tanstack/start' -import { z } from 'zod' - -export const withUseServer = TanStackStart.createServerFn({ - method: 'GET', -}).handler(async function () { - 'use server' - console.info('Fetching posts...') - await new Promise((r) => setTimeout(r, 500)) - return axios - .get>('https://jsonplaceholder.typicode.com/posts') - .then((r) => r.data.slice(0, 10)) -}) - -export const withoutUseServer = TanStackStart.createServerFn({ - method: 'GET', -}).handler(async () => { - console.info('Fetching posts...') - await new Promise((r) => setTimeout(r, 500)) - return axios - .get>('https://jsonplaceholder.typicode.com/posts') - .then((r) => r.data.slice(0, 10)) -}) - -export const withVariable = TanStackStart.createServerFn({ - method: 'GET', -}).handler(abstractedFunction) - -async function abstractedFunction() { - console.info('Fetching posts...') - await new Promise((r) => setTimeout(r, 500)) - return axios - .get>('https://jsonplaceholder.typicode.com/posts') - .then((r) => r.data.slice(0, 10)) -} - -function zodValidator( - schema: TSchema, - fn: (input: z.output) => TResult, -) { - return async (input: unknown) => { - return fn(schema.parse(input)) - } -} - -export const withZodValidator = TanStackStart.createServerFn({ - method: 'GET', -}).handler( - zodValidator(z.number(), (input) => { - return { 'you gave': input } - }), -) diff --git a/packages/server-functions-vite-plugin/tests/createServerFn/test-files/createServerFnValidator.tsx b/packages/server-functions-vite-plugin/tests/createServerFn/test-files/createServerFnValidator.tsx deleted file mode 100644 index b30bcdc731..0000000000 --- a/packages/server-functions-vite-plugin/tests/createServerFn/test-files/createServerFnValidator.tsx +++ /dev/null @@ -1,8 +0,0 @@ -import { createServerFn } from '@tanstack/start' -import { z } from 'zod' - -export const withUseServer = createServerFn({ - method: 'GET', -}) - .validator(z.number()) - .handler(({ input }) => input + 1) diff --git a/packages/server-functions-vite-plugin/tests/envOnly/envOnly.test.ts b/packages/server-functions-vite-plugin/tests/envOnly/envOnly.test.ts deleted file mode 100644 index 67336be35b..0000000000 --- a/packages/server-functions-vite-plugin/tests/envOnly/envOnly.test.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { readFile, readdir } from 'node:fs/promises' -import path from 'node:path' -import { describe, expect, test } from 'vitest' - -import { compileStartOutput } from '../../src/compilers' - -async function getFilenames() { - return await readdir(path.resolve(import.meta.dirname, './test-files')) -} - -describe('envOnly functions compile correctly', async () => { - const filenames = await getFilenames() - - describe.each(filenames)('should handle "%s"', async (filename) => { - const file = await readFile( - path.resolve(import.meta.dirname, `./test-files/${filename}`), - ) - const code = file.toString() - - test.each(['client', 'server'] as const)( - `should compile for ${filename} %s`, - async (env) => { - const compiledResult = compileStartOutput({ - env, - code, - root: './test-files', - filename, - }) - - await expect(compiledResult.code).toMatchFileSnapshot( - `./snapshots/${env}/${filename}`, - ) - }, - ) - }) - test('should error if implementation not provided', () => { - expect(() => { - compileStartOutput({ - env: 'client', - code: ` - import { clientOnly } from '@tanstack/start' - const fn = clientOnly()`, - root: './test-files', - filename: 'no-fn.ts', - }) - }).toThrowError() - expect(() => { - compileStartOutput({ - env: 'server', - code: ` - import { serverOnly } from '@tanstack/start' - const fn = serverOnly()`, - root: './test-files', - filename: 'no-fn.ts', - }) - }).toThrowError() - }) -}) diff --git a/packages/server-functions-vite-plugin/tests/envOnly/snapshots/client/envOnlyDestructured.tsx b/packages/server-functions-vite-plugin/tests/envOnly/snapshots/client/envOnlyDestructured.tsx deleted file mode 100644 index 3dc714f696..0000000000 --- a/packages/server-functions-vite-plugin/tests/envOnly/snapshots/client/envOnlyDestructured.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { serverOnly, clientOnly } from '@tanstack/start'; -const serverFunc = () => { - throw new Error("serverOnly() functions can only be called on the server!"); -}; -const clientFunc = () => 'client'; \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/envOnly/snapshots/client/envOnlyDestructuredRename.tsx b/packages/server-functions-vite-plugin/tests/envOnly/snapshots/client/envOnlyDestructuredRename.tsx deleted file mode 100644 index 3dd661c865..0000000000 --- a/packages/server-functions-vite-plugin/tests/envOnly/snapshots/client/envOnlyDestructuredRename.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { serverOnly as serverFn, clientOnly as clientFn } from '@tanstack/start'; -const serverFunc = () => { - throw new Error("serverOnly() functions can only be called on the server!"); -}; -const clientFunc = () => 'client'; \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/envOnly/snapshots/client/envOnlyStarImport.tsx b/packages/server-functions-vite-plugin/tests/envOnly/snapshots/client/envOnlyStarImport.tsx deleted file mode 100644 index 61f0677953..0000000000 --- a/packages/server-functions-vite-plugin/tests/envOnly/snapshots/client/envOnlyStarImport.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import * as TanstackStart from '@tanstack/start'; -const serverFunc = () => { - throw new Error("serverOnly() functions can only be called on the server!"); -}; -const clientFunc = () => 'client'; \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/envOnly/snapshots/server/envOnlyDestructured.tsx b/packages/server-functions-vite-plugin/tests/envOnly/snapshots/server/envOnlyDestructured.tsx deleted file mode 100644 index 24f736eac2..0000000000 --- a/packages/server-functions-vite-plugin/tests/envOnly/snapshots/server/envOnlyDestructured.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { serverOnly, clientOnly } from '@tanstack/start'; -const serverFunc = () => 'server'; -const clientFunc = () => { - throw new Error("clientOnly() functions can only be called on the client!"); -}; \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/envOnly/snapshots/server/envOnlyDestructuredRename.tsx b/packages/server-functions-vite-plugin/tests/envOnly/snapshots/server/envOnlyDestructuredRename.tsx deleted file mode 100644 index 790e1328d7..0000000000 --- a/packages/server-functions-vite-plugin/tests/envOnly/snapshots/server/envOnlyDestructuredRename.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { serverOnly as serverFn, clientOnly as clientFn } from '@tanstack/start'; -const serverFunc = () => 'server'; -const clientFunc = () => { - throw new Error("clientOnly() functions can only be called on the client!"); -}; \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/envOnly/snapshots/server/envOnlyStarImport.tsx b/packages/server-functions-vite-plugin/tests/envOnly/snapshots/server/envOnlyStarImport.tsx deleted file mode 100644 index 51e320d4a2..0000000000 --- a/packages/server-functions-vite-plugin/tests/envOnly/snapshots/server/envOnlyStarImport.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import * as TanstackStart from '@tanstack/start'; -const serverFunc = () => 'server'; -const clientFunc = () => { - throw new Error("clientOnly() functions can only be called on the client!"); -}; \ No newline at end of file diff --git a/packages/server-functions-vite-plugin/tests/envOnly/test-files/envOnlyDestructured.tsx b/packages/server-functions-vite-plugin/tests/envOnly/test-files/envOnlyDestructured.tsx deleted file mode 100644 index 1389624d34..0000000000 --- a/packages/server-functions-vite-plugin/tests/envOnly/test-files/envOnlyDestructured.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { serverOnly, clientOnly } from '@tanstack/start' - -const serverFunc = serverOnly(() => 'server') - -const clientFunc = clientOnly(() => 'client') diff --git a/packages/server-functions-vite-plugin/tests/envOnly/test-files/envOnlyDestructuredRename.tsx b/packages/server-functions-vite-plugin/tests/envOnly/test-files/envOnlyDestructuredRename.tsx deleted file mode 100644 index ac34f06134..0000000000 --- a/packages/server-functions-vite-plugin/tests/envOnly/test-files/envOnlyDestructuredRename.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { serverOnly as serverFn, clientOnly as clientFn } from '@tanstack/start' - -const serverFunc = serverFn(() => 'server') - -const clientFunc = clientFn(() => 'client') diff --git a/packages/server-functions-vite-plugin/tests/envOnly/test-files/envOnlyStarImport.tsx b/packages/server-functions-vite-plugin/tests/envOnly/test-files/envOnlyStarImport.tsx deleted file mode 100644 index cd262b54a0..0000000000 --- a/packages/server-functions-vite-plugin/tests/envOnly/test-files/envOnlyStarImport.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import * as TanstackStart from '@tanstack/start' - -const serverFunc = TanstackStart.serverOnly(() => 'server') - -const clientFunc = TanstackStart.clientOnly(() => 'client') diff --git a/packages/start/src/config/index.ts b/packages/start/src/config/index.ts index 093c4f875e..f8c14fee4f 100644 --- a/packages/start/src/config/index.ts +++ b/packages/start/src/config/index.ts @@ -171,7 +171,8 @@ export function defineConfig( ...(viteConfig.plugins || []), ...(clientViteConfig.plugins || []), TanStackServerFnPluginClient({ - runtimeCode: `import { createClientRpc } from '@tanstack/start/client-runtime'`, + getRuntimeCode: (opts) => + `import { createClientRpc } from '@tanstack/start/client-runtime'`, replacer: (opts) => `createClientRpc('${opts.filename}', '${opts.functionId}')`, }), @@ -214,7 +215,8 @@ export function defineConfig( ...(getUserViteConfig(opts.vite).plugins || []), ...(getUserViteConfig(opts.routers?.ssr?.vite).plugins || []), TanStackServerFnPluginServer({ - runtimeCode: `import { createServerRpc } from '@tanstack/start/ssr-runtime'`, + getRuntimeCode: (opts) => + `import { createServerRpc } from '@tanstack/start/ssr-runtime'`, replacer: (opts) => `createSsrRpc('${opts.filename}', '${opts.functionId}')`, }), @@ -259,7 +261,8 @@ export function defineConfig( }, }), TanStackServerFnPluginServer({ - runtimeCode: `import { createServerRpc } from '@tanstack/start/server-runtime'`, + getRuntimeCode: (opts) => + `import { createServerRpc } from '@tanstack/start/server-runtime'`, replacer: (opts) => `createServerRpc('${opts.filename}', '${opts.functionId}')`, // TODO: RSCS - remove this diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e97a5cd541..2269a73f44 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -3543,9 +3543,18 @@ importers: '@types/babel__traverse': specifier: ^7.20.6 version: 7.20.6 + '@types/diff': + specifier: ^6.0.0 + version: 6.0.0 babel-dead-code-elimination: specifier: ^1.0.6 version: 1.0.6 + chalk: + specifier: ^5.3.0 + version: 5.3.0 + diff: + specifier: ^7.0.0 + version: 7.0.0 tiny-invariant: specifier: ^1.3.3 version: 1.3.3 @@ -6018,6 +6027,9 @@ packages: '@types/cross-spawn@6.0.6': resolution: {integrity: sha512-fXRhhUkG4H3TQk5dBhQ7m/JDdSNHKwR2BBia62lhwEIq9xGiQKLxd6LymNhn47SjXhsUEPmxi+PKw2OkW4LLjA==} + '@types/diff@6.0.0': + resolution: {integrity: sha512-dhVCYGv3ZSbzmQaBSagrv1WJ6rXCdkyTcDyoNu1MD8JohI7pR7k8wdZEm+mvdxRKXyHVwckFzWU1vJc+Z29MlA==} + '@types/eslint-scope@3.7.7': resolution: {integrity: sha512-MzMFlSLBqNF2gcHWO0G1vP/YQyfvrxZ0bF+u7mzUdZ1/xK4A4sru+nraZz5i3iEIk1l1uyicaDVTB4QbbEkAYg==} @@ -7290,6 +7302,10 @@ packages: resolution: {integrity: sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==} engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + diff@7.0.0: + resolution: {integrity: sha512-PJWHUb1RFevKCwaFA9RlG5tCd+FO5iRh9A8HEtkmBH2Li03iJriB6m6JIN4rGz3K3JLawI7/veA1xzRKP6ISBw==} + engines: {node: '>=0.3.1'} + dir-glob@3.0.1: resolution: {integrity: sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==} engines: {node: '>=8'} @@ -13009,6 +13025,8 @@ snapshots: dependencies: '@types/node': 22.10.1 + '@types/diff@6.0.0': {} + '@types/eslint-scope@3.7.7': dependencies: '@types/eslint': 9.6.1 @@ -14420,6 +14438,8 @@ snapshots: diff-sequences@29.6.3: {} + diff@7.0.0: {} + dir-glob@3.0.1: dependencies: path-type: 4.0.0 From e0d8a313d23e4748d41cde3a7c3975f0fb46826e Mon Sep 17 00:00:00 2001 From: Tanner Linsley Date: Thu, 12 Dec 2024 15:40:39 -0700 Subject: [PATCH 06/13] fix: dont touch anything outside of the function --- .../src/compilers.ts | 238 ++++++++++-------- .../tests/compiler.test.ts | 154 +++++++----- 2 files changed, 222 insertions(+), 170 deletions(-) diff --git a/packages/server-functions-vite-plugin/src/compilers.ts b/packages/server-functions-vite-plugin/src/compilers.ts index b9679e9c6e..5bad33d8ee 100644 --- a/packages/server-functions-vite-plugin/src/compilers.ts +++ b/packages/server-functions-vite-plugin/src/compilers.ts @@ -1,7 +1,6 @@ import path from 'node:path' import * as babel from '@babel/core' import _generate from '@babel/generator' -import { deadCodeElimination } from 'babel-dead-code-elimination' import { isIdentifier, isVariableDeclarator } from '@babel/types' import { parseAst } from './ast' @@ -13,15 +12,21 @@ if ('default' in generate) { generate = generate.default as typeof generate } -export function compileEliminateDeadCode(opts: ParseAstOptions) { - const ast = parseAst(opts) - deadCodeElimination(ast) - - return generate(ast, { - sourceMaps: true, - }) +interface ServerFunctionInfo { + nodePath: babel.NodePath + functionName: string + functionId: string } +// export function compileEliminateDeadCode(opts: ParseAstOptions) { +// const ast = parseAst(opts) +// deadCodeElimination(ast) + +// return generate(ast, { +// sourceMaps: true, +// }) +// } + // const debug = process.env.TSR_VITE_DEBUG === 'true' function findNearestVariableName(path: babel.NodePath): string { @@ -123,52 +128,133 @@ function makeFileLocationUrlSafe(location: string): string { export function compileServerFnClient( opts: ParseAstOptions & { getRuntimeCode: (opts: { - serverFnPathsByFunctionId: Record< - string, - { nodePath: babel.NodePath; functionName: string; functionId: string } - > + serverFnPathsByFunctionId: Record }) => string replacer: (opts: { filename: string; functionId: string }) => string }, ) { const ast = parseAst(opts) - const serverFnPathsByFunctionId: Record< - string, - { - nodePath: babel.NodePath - functionName: string - functionId: string + const serverFnPathsByFunctionId = findServerFunctions(ast, opts) + + // Add runtime code if there are server functions + if (Object.keys(serverFnPathsByFunctionId).length > 0) { + const runtimeImport = babel.template.statement( + opts.getRuntimeCode({ serverFnPathsByFunctionId }), + )() + ast.program.body.unshift(runtimeImport) + } + + // Replace server functions with client-side stubs + for (const [functionId, { nodePath }] of Object.entries( + serverFnPathsByFunctionId, + )) { + const replacementCode = opts.replacer({ + filename: opts.filename, + functionId: functionId, + }) + + // Check to see if we can do this: + if ( + babel.types.isArrowFunctionExpression(nodePath.node) || + babel.types.isFunctionExpression(nodePath.node) || + babel.types.isFunctionDeclaration(nodePath.node) || + babel.types.isObjectMethod(nodePath.node) || + babel.types.isClassMethod(nodePath.node) + ) { + nodePath.node.params = [ + babel.types.restElement(babel.types.identifier('args')), + ] } - > = {} + + // Get the function body statements + const bodyStatements: Array = [] + + // Remove 'use server' directive + if (babel.types.isBlockStatement(nodePath.node.body)) { + nodePath.node.body.directives = nodePath.node.body.directives.filter( + (directive) => directive.value.value !== 'use server', + ) + } + + const replacement = babel.template.expression( + `(${replacementCode})(...args)`, + )() + + if (babel.types.isArrowFunctionExpression(nodePath.node)) { + if (babel.types.isBlockStatement(nodePath.node.body)) { + nodePath.node.body.body = [babel.types.returnStatement(replacement)] + } else { + nodePath.node.body = babel.types.blockStatement([ + babel.types.returnStatement(replacement), + ]) + } + } else if ( + babel.types.isFunctionExpression(nodePath.node) || + babel.types.isFunctionDeclaration(nodePath.node) || + babel.types.isObjectMethod(nodePath.node) || + babel.types.isClassMethod(nodePath.node) + ) { + nodePath.node.body.body = [babel.types.returnStatement(replacement)] + } + } + + const compiledCode = generate(ast, { + sourceMaps: true, + minified: process.env.NODE_ENV === 'production', + }) + + return { + compiledCode, + serverFns: serverFnPathsByFunctionId, + } +} + +export function compileServerFnServer(opts: ParseAstOptions) { + const ast = parseAst(opts) + const serverFnPathsByFunctionId = findServerFunctions(ast, opts) + + const compiledCode = generate(ast, { + sourceMaps: true, + minified: process.env.NODE_ENV === 'production', + }) + + return { + compiledCode, + serverFns: serverFnPathsByFunctionId, + } +} + +function findServerFunctions(ast: babel.types.File, opts: ParseAstOptions) { + const serverFnPathsByFunctionId: Record = {} const counts: Record = {} + const recordServerFunction = (nodePath: babel.NodePath) => { + const fnName = findNearestVariableName(nodePath) + + const baseLabel = makeFileLocationUrlSafe( + `${opts.filename.replace( + path.extname(opts.filename), + '', + )}--${fnName}`.replace(opts.root, ''), + ) + + counts[baseLabel] = (counts[baseLabel] || 0) + 1 + + const functionId = + counts[baseLabel] > 1 + ? `${baseLabel}_${counts[baseLabel] - 1}` + : baseLabel + + serverFnPathsByFunctionId[functionId] = { + nodePath, + functionName: fnName || '', + functionId: functionId, + } + } + babel.traverse(ast, { Program: { enter(programPath) { - const recordServerFunction = (nodePath: babel.NodePath) => { - const fnName = findNearestVariableName(nodePath) - - const baseLabel = makeFileLocationUrlSafe( - `${opts.filename.replace( - path.extname(opts.filename), - '', - )}--${fnName}`.replace(opts.root, ''), - ) - - counts[baseLabel] = (counts[baseLabel] || 0) + 1 - - const functionId = - counts[baseLabel] > 1 - ? `${baseLabel}_${counts[baseLabel] - 1}` - : baseLabel - - serverFnPathsByFunctionId[functionId] = { - nodePath, - functionName: fnName || '', - functionId: functionId, - } - } - programPath.traverse({ enter(path) { // Function declarations @@ -241,75 +327,11 @@ export function compileServerFnClient( } }, }) - - if (Object.keys(serverFnPathsByFunctionId).length > 0) { - const runtimeImport = babel.template.statement( - opts.getRuntimeCode({ serverFnPathsByFunctionId }), - )() - ast.program.body.unshift(runtimeImport) - } - - // Replace server functions with client-side stubs - for (const [functionId, fnPath] of Object.entries( - serverFnPathsByFunctionId, - )) { - const replacementCode = opts.replacer({ - filename: opts.filename, - functionId: functionId, - }) - const replacement = babel.template.expression(replacementCode)() - - // For variable declarations, replace the init - if (fnPath.nodePath.isVariableDeclarator()) { - fnPath.nodePath.get('init').replaceWith(replacement) - } - // For class/object methods, replace the whole method - else if ( - fnPath.nodePath.isClassMethod() || - fnPath.nodePath.isObjectMethod() - ) { - fnPath.nodePath.replaceWith( - babel.types.classMethod( - fnPath.nodePath.node.kind, - fnPath.nodePath.node.key, - fnPath.nodePath.node.params, - babel.types.blockStatement([ - babel.types.returnStatement(replacement), - ]), - ), - ) - } - // For function expressions, replace the whole path - else { - fnPath.nodePath.replaceWith(replacement) - } - } }, }, }) - const compiledCode = generate(ast, { - sourceMaps: true, - minified: process.env.NODE_ENV === 'production', - }) - - return { - compiledCode, - serverFns: serverFnPathsByFunctionId, - } -} - -export function compileServerFnServer(opts: ParseAstOptions) { - const ast = parseAst(opts) - - const compiledCode = generate(ast, { - sourceMaps: true, - minified: process.env.NODE_ENV === 'production', - }) - - return { - compiledCode, - } + return serverFnPathsByFunctionId } // function codeFrameError( diff --git a/packages/server-functions-vite-plugin/tests/compiler.test.ts b/packages/server-functions-vite-plugin/tests/compiler.test.ts index 6c287b2f18..e34a8d7de7 100644 --- a/packages/server-functions-vite-plugin/tests/compiler.test.ts +++ b/packages/server-functions-vite-plugin/tests/compiler.test.ts @@ -30,10 +30,12 @@ describe('server function compilation', () => { const client = compileServerFnClient({ ...clientConfig, code }) await expect(client.compiledCode.code).toMatchInlineSnapshot(` "import { createClientRpc } from "my-rpc-lib"; - createClientRpc({ - filename: "test.ts", - functionId: "test--useServer" - });" + function useServer(...args) { + return createClientRpc({ + filename: "test.ts", + functionId: "test--useServer" + })(...args); + }" `) const server = compileServerFnServer({ ...serverConfig, code }) @@ -57,10 +59,12 @@ describe('server function compilation', () => { const client = compileServerFnClient({ ...clientConfig, code }) expect(client.compiledCode.code).toMatchInlineSnapshot(` "import { createClientRpc } from "my-rpc-lib"; - const fn = createClientRpc({ - filename: "test.ts", - functionId: "test--fn_1" - });" + const fn = (...args) => { + return createClientRpc({ + filename: "test.ts", + functionId: "test--fn_1" + })(...args); + };" `) const server = compileServerFnServer({ ...serverConfig, code }) @@ -83,10 +87,12 @@ describe('server function compilation', () => { const client = compileServerFnClient({ ...clientConfig, code }) expect(client.compiledCode.code).toMatchInlineSnapshot(` "import { createClientRpc } from "my-rpc-lib"; - const anonymousFn = createClientRpc({ - filename: "test.ts", - functionId: "test--anonymousFn_1" - });" + const anonymousFn = function (...args) { + return createClientRpc({ + filename: "test.ts", + functionId: "test--anonymousFn_1" + })(...args); + };" `) const server = compileServerFnServer({ ...serverConfig, code }) @@ -116,17 +122,17 @@ describe('server function compilation', () => { expect(client.compiledCode.code).toMatchInlineSnapshot(` "import { createClientRpc } from "my-rpc-lib"; class TestClass { - method() { + method(...args) { return createClientRpc({ filename: "test.ts", functionId: "test--method" - }); + })(...args); } - staticMethod() { + static staticMethod(...args) { return createClientRpc({ filename: "test.ts", functionId: "test--staticMethod" - }); + })(...args); } }" `) @@ -162,11 +168,11 @@ describe('server function compilation', () => { expect(client.compiledCode.code).toMatchInlineSnapshot(` "import { createClientRpc } from "my-rpc-lib"; const obj = { - method() { + method(...args) { return createClientRpc({ filename: "test.ts", functionId: "test--obj_method" - }); + })(...args); } };" `) @@ -199,14 +205,18 @@ describe('server function compilation', () => { const client = compileServerFnClient({ ...clientConfig, code }) expect(client.compiledCode.code).toMatchInlineSnapshot(` "import { createClientRpc } from "my-rpc-lib"; - createClientRpc({ - filename: "test.ts", - functionId: "test--asyncServer" - }); - const asyncArrow = createClientRpc({ - filename: "test.ts", - functionId: "test--asyncArrow_1" - });" + async function asyncServer(...args) { + return createClientRpc({ + filename: "test.ts", + functionId: "test--asyncServer" + })(...args); + } + const asyncArrow = async (...args) => { + return createClientRpc({ + filename: "test.ts", + functionId: "test--asyncArrow_1" + })(...args); + };" `) const server = compileServerFnServer({ ...serverConfig, code }) @@ -240,14 +250,18 @@ describe('server function compilation', () => { const client = compileServerFnClient({ ...clientConfig, code }) expect(client.compiledCode.code).toMatchInlineSnapshot(` "import { createClientRpc } from "my-rpc-lib"; - createClientRpc({ - filename: "test.ts", - functionId: "test--generatorServer" - }); - createClientRpc({ - filename: "test.ts", - functionId: "test--asyncGeneratorServer" - });" + function* generatorServer(...args) { + return createClientRpc({ + filename: "test.ts", + functionId: "test--generatorServer" + })(...args); + } + async function* asyncGeneratorServer(...args) { + return createClientRpc({ + filename: "test.ts", + functionId: "test--asyncGeneratorServer" + })(...args); + }" `) const server = compileServerFnServer({ ...serverConfig, code }) @@ -280,10 +294,12 @@ describe('server function compilation', () => { expect(client.compiledCode.code).toMatchInlineSnapshot(` "import { createClientRpc } from "my-rpc-lib"; function outer() { - createClientRpc({ - filename: "test.ts", - functionId: "test--outer_inner" - }); + function inner(...args) { + return createClientRpc({ + filename: "test.ts", + functionId: "test--outer_inner" + })(...args); + } return inner; }" `) @@ -313,10 +329,14 @@ describe('server function compilation', () => { const client = compileServerFnClient({ ...clientConfig, code }) expect(client.compiledCode.code).toMatchInlineSnapshot(` "import { createClientRpc } from "my-rpc-lib"; - createClientRpc({ - filename: "test.ts", - functionId: "test--multiDirective" - });" + function multiDirective(...args) { + 'use strict'; + + return createClientRpc({ + filename: "test.ts", + functionId: "test--multiDirective" + })(...args); + }" `) const server = compileServerFnServer({ ...serverConfig, code }) @@ -341,10 +361,12 @@ describe('server function compilation', () => { const client = compileServerFnClient({ ...clientConfig, code }) expect(client.compiledCode.code).toMatchInlineSnapshot(` "import { createClientRpc } from "my-rpc-lib"; - createClientRpc({ - filename: "test.ts", - functionId: "test--withParams" - });" + function withParams(...args) { + return createClientRpc({ + filename: "test.ts", + functionId: "test--withParams" + })(...args); + }" `) const server = compileServerFnServer({ ...serverConfig, code }) @@ -368,10 +390,12 @@ describe('server function compilation', () => { const client = compileServerFnClient({ ...clientConfig, code }) expect(client.compiledCode.code).toMatchInlineSnapshot(` "import { createClientRpc } from "my-rpc-lib"; - const iife = createClientRpc({ - filename: "test.ts", - functionId: "test--iife" - })();" + const iife = function (...args) { + return createClientRpc({ + filename: "test.ts", + functionId: "test--iife" + })(...args); + }();" `) const server = compileServerFnServer({ ...serverConfig, code }) @@ -398,10 +422,12 @@ describe('server function compilation', () => { expect(client.compiledCode.code).toMatchInlineSnapshot(` "import { createClientRpc } from "my-rpc-lib"; function higherOrder() { - return createClientRpc({ - filename: "test.ts", - functionId: "test--higherOrder" - }); + return function (...args) { + return createClientRpc({ + filename: "test.ts", + functionId: "test--higherOrder" + })(...args); + }; }" `) @@ -441,18 +467,22 @@ describe('server function compilation', () => { "import { createClientRpc } from "my-rpc-lib"; function main() { function middle() { - const useServer = createClientRpc({ - filename: "test.ts", - functionId: "test--main_middle_useServer_1" - }); + const useServer = function (...args) { + return createClientRpc({ + filename: "test.ts", + functionId: "test--main_middle_useServer_1" + })(...args); + }; return useServer; } return middle; } - main().middle(createClientRpc({ - filename: "test.ts", - functionId: "test--main_middle_useServer_2" - }));" + main().middle(function useServer(...args) { + return createClientRpc({ + filename: "test.ts", + functionId: "test--main_middle_useServer_2" + })(...args); + });" `) const server = compileServerFnServer({ ...serverConfig, code }) From 44dac10664c2c1140fd229c109ab1e84d9b97986 Mon Sep 17 00:00:00 2001 From: Tanner Linsley Date: Thu, 12 Dec 2024 16:15:54 -0700 Subject: [PATCH 07/13] server functions now import a tsr-serverfn-split file version --- .../src/core/code-splitter/compilers.ts | 2 + .../src/compilers.ts | 117 +++++++++++++++--- .../tests/compiler.test.ts | 99 +++++---------- packages/start-vite-plugin/src/compilers.ts | 3 + 4 files changed, 136 insertions(+), 85 deletions(-) diff --git a/packages/router-plugin/src/core/code-splitter/compilers.ts b/packages/router-plugin/src/core/code-splitter/compilers.ts index 84f082e1cc..ba2485b7d8 100644 --- a/packages/router-plugin/src/core/code-splitter/compilers.ts +++ b/packages/router-plugin/src/core/code-splitter/compilers.ts @@ -270,6 +270,7 @@ export function compileCodeSplitReferenceRoute(opts: ParseAstOptions) { return generate(ast, { sourceMaps: true, sourceFileName: opts.filename, + minified: process.env.NODE_ENV === 'production', }) } @@ -543,6 +544,7 @@ export function compileCodeSplitVirtualRoute(opts: ParseAstOptions) { return generate(ast, { sourceMaps: true, sourceFileName: opts.filename, + minified: process.env.NODE_ENV === 'production', }) } diff --git a/packages/server-functions-vite-plugin/src/compilers.ts b/packages/server-functions-vite-plugin/src/compilers.ts index 5bad33d8ee..f08b6eb408 100644 --- a/packages/server-functions-vite-plugin/src/compilers.ts +++ b/packages/server-functions-vite-plugin/src/compilers.ts @@ -24,6 +24,8 @@ interface ServerFunctionInfo { // return generate(ast, { // sourceMaps: true, +// sourceFileName: opts.filename, +// minified: process.env.NODE_ENV === 'production', // }) // } @@ -118,6 +120,23 @@ function findNearestVariableName(path: babel.NodePath): string { return nameParts.length > 0 ? nameParts.join('_') : 'anonymous' } +function isFunctionDeclaration( + node: babel.types.Node, +): node is + | babel.types.FunctionDeclaration + | babel.types.FunctionExpression + | babel.types.ArrowFunctionExpression + | babel.types.ClassMethod + | babel.types.ObjectMethod { + return ( + babel.types.isFunctionDeclaration(node) || + babel.types.isFunctionExpression(node) || + babel.types.isArrowFunctionExpression(node) || + babel.types.isClassMethod(node) || + babel.types.isObjectMethod(node) + ) +} + function makeFileLocationUrlSafe(location: string): string { return location .replace(/[^a-zA-Z0-9-_]/g, '_') // Replace unsafe chars with underscore @@ -153,29 +172,30 @@ export function compileServerFnClient( functionId: functionId, }) - // Check to see if we can do this: - if ( - babel.types.isArrowFunctionExpression(nodePath.node) || - babel.types.isFunctionExpression(nodePath.node) || - babel.types.isFunctionDeclaration(nodePath.node) || - babel.types.isObjectMethod(nodePath.node) || - babel.types.isClassMethod(nodePath.node) - ) { - nodePath.node.params = [ - babel.types.restElement(babel.types.identifier('args')), - ] - } - - // Get the function body statements - const bodyStatements: Array = [] - - // Remove 'use server' directive - if (babel.types.isBlockStatement(nodePath.node.body)) { - nodePath.node.body.directives = nodePath.node.body.directives.filter( - (directive) => directive.value.value !== 'use server', + // Check to see if the function is a valid function declaration + if (!isFunctionDeclaration(nodePath.node)) { + throw new Error( + `Server function is not a function declaration: ${nodePath.node}`, ) } + nodePath.node.params = [ + babel.types.restElement(babel.types.identifier('args')), + ] + + // Remove 'use server' directive + // Check if the node body is a block statement + if (!babel.types.isBlockStatement(nodePath.node.body)) { + throw new Error( + `Server function body is not a block statement: ${nodePath.node.body}`, + ) + } + + const nodeBody = nodePath.node.body + nodeBody.directives = nodeBody.directives.filter( + (directive) => directive.value.value !== 'use server', + ) + const replacement = babel.template.expression( `(${replacementCode})(...args)`, )() @@ -200,6 +220,7 @@ export function compileServerFnClient( const compiledCode = generate(ast, { sourceMaps: true, + sourceFileName: opts.filename, minified: process.env.NODE_ENV === 'production', }) @@ -213,8 +234,64 @@ export function compileServerFnServer(opts: ParseAstOptions) { const ast = parseAst(opts) const serverFnPathsByFunctionId = findServerFunctions(ast, opts) + // Replace server function bodies with dynamic imports + Object.entries(serverFnPathsByFunctionId).forEach( + ([functionId, { nodePath }]) => { + // Check if the node is a function declaration + if (!isFunctionDeclaration(nodePath.node)) { + throw new Error( + `Server function is not a function declaration: ${nodePath.node}`, + ) + } + + nodePath.node.params = [ + babel.types.restElement(babel.types.identifier('args')), + ] + + // Check if the node body is a block statement + if (!babel.types.isBlockStatement(nodePath.node.body)) { + throw new Error( + `Server function body is not a block statement: ${nodePath.node.body}`, + ) + } + + const nodeBody = nodePath.node.body + nodeBody.directives = nodeBody.directives.filter( + (directive) => directive.value.value !== 'use server', + ) + + // Create the dynamic import expression + const importExpression = babel.template.expression(` + import(${JSON.stringify(`${opts.filename}?tsr-serverfn-split=${functionId}`)}) + .then(mod => mod.serverFn(...args)) + `)() + + if (babel.types.isArrowFunctionExpression(nodePath.node)) { + if (babel.types.isBlockStatement(nodePath.node.body)) { + nodePath.node.body.body = [ + babel.types.returnStatement(importExpression), + ] + } else { + nodePath.node.body = babel.types.blockStatement([ + babel.types.returnStatement(importExpression), + ]) + } + } else if ( + babel.types.isFunctionExpression(nodePath.node) || + babel.types.isFunctionDeclaration(nodePath.node) || + babel.types.isObjectMethod(nodePath.node) || + babel.types.isClassMethod(nodePath.node) + ) { + nodePath.node.body.body = [ + babel.types.returnStatement(importExpression), + ] + } + }, + ) + const compiledCode = generate(ast, { sourceMaps: true, + sourceFileName: opts.filename, minified: process.env.NODE_ENV === 'production', }) diff --git a/packages/server-functions-vite-plugin/tests/compiler.test.ts b/packages/server-functions-vite-plugin/tests/compiler.test.ts index e34a8d7de7..ee958f0084 100644 --- a/packages/server-functions-vite-plugin/tests/compiler.test.ts +++ b/packages/server-functions-vite-plugin/tests/compiler.test.ts @@ -40,10 +40,8 @@ describe('server function compilation', () => { const server = compileServerFnServer({ ...serverConfig, code }) await expect(server.compiledCode.code).toMatchInlineSnapshot(` - "function useServer() { - 'use server'; - - return 'hello'; + "function useServer(...args) { + return import("test.ts?tsr-serverfn-split=test--useServer").then(mod => mod.serverFn(...args)); }" `) }) @@ -69,10 +67,8 @@ describe('server function compilation', () => { const server = compileServerFnServer({ ...serverConfig, code }) expect(server.compiledCode.code).toMatchInlineSnapshot(` - "const fn = () => { - 'use server'; - - return 'hello'; + "const fn = (...args) => { + return import("test.ts?tsr-serverfn-split=test--fn_1").then(mod => mod.serverFn(...args)); };" `) }) @@ -97,8 +93,8 @@ describe('server function compilation', () => { const server = compileServerFnServer({ ...serverConfig, code }) expect(server.compiledCode.code).toMatchInlineSnapshot(` - "const anonymousFn = function () { - 'use server'; + "const anonymousFn = function (...args) { + return import("test.ts?tsr-serverfn-split=test--anonymousFn_1").then(mod => mod.serverFn(...args)); };" `) }) @@ -140,15 +136,11 @@ describe('server function compilation', () => { const server = compileServerFnServer({ ...serverConfig, code }) expect(server.compiledCode.code).toMatchInlineSnapshot(` "class TestClass { - method() { - 'use server'; - - return 'hello'; + method(...args) { + return import("test.ts?tsr-serverfn-split=test--method").then(mod => mod.serverFn(...args)); } - static staticMethod() { - 'use server'; - - return 'hello'; + static staticMethod(...args) { + return import("test.ts?tsr-serverfn-split=test--staticMethod").then(mod => mod.serverFn(...args)); } }" `) @@ -180,10 +172,8 @@ describe('server function compilation', () => { const server = compileServerFnServer({ ...serverConfig, code }) expect(server.compiledCode.code).toMatchInlineSnapshot(` "const obj = { - method() { - 'use server'; - - return 'hello'; + method(...args) { + return import("test.ts?tsr-serverfn-split=test--obj_method").then(mod => mod.serverFn(...args)); } };" `) @@ -221,15 +211,11 @@ describe('server function compilation', () => { const server = compileServerFnServer({ ...serverConfig, code }) expect(server.compiledCode.code).toMatchInlineSnapshot(` - "async function asyncServer() { - 'use server'; - - return 'hello'; + "async function asyncServer(...args) { + return import("test.ts?tsr-serverfn-split=test--asyncServer").then(mod => mod.serverFn(...args)); } - const asyncArrow = async () => { - 'use server'; - - return 'hello'; + const asyncArrow = async (...args) => { + return import("test.ts?tsr-serverfn-split=test--asyncArrow_1").then(mod => mod.serverFn(...args)); };" `) }) @@ -266,15 +252,11 @@ describe('server function compilation', () => { const server = compileServerFnServer({ ...serverConfig, code }) expect(server.compiledCode.code).toMatchInlineSnapshot(` - "function* generatorServer() { - 'use server'; - - yield 'hello'; + "function* generatorServer(...args) { + return import("test.ts?tsr-serverfn-split=test--generatorServer").then(mod => mod.serverFn(...args)); } - async function* asyncGeneratorServer() { - 'use server'; - - yield 'hello'; + async function* asyncGeneratorServer(...args) { + return import("test.ts?tsr-serverfn-split=test--asyncGeneratorServer").then(mod => mod.serverFn(...args)); }" `) }) @@ -307,10 +289,8 @@ describe('server function compilation', () => { const server = compileServerFnServer({ ...serverConfig, code }) expect(server.compiledCode.code).toMatchInlineSnapshot(` "function outer() { - function inner() { - 'use server'; - - return 'hello'; + function inner(...args) { + return import("test.ts?tsr-serverfn-split=test--outer_inner").then(mod => mod.serverFn(...args)); } return inner; }" @@ -341,11 +321,10 @@ describe('server function compilation', () => { const server = compileServerFnServer({ ...serverConfig, code }) expect(server.compiledCode.code).toMatchInlineSnapshot(` - "function multiDirective() { + "function multiDirective(...args) { 'use strict'; - 'use server'; - return 'hello'; + return import("test.ts?tsr-serverfn-split=test--multiDirective").then(mod => mod.serverFn(...args)); }" `) }) @@ -371,10 +350,8 @@ describe('server function compilation', () => { const server = compileServerFnServer({ ...serverConfig, code }) expect(server.compiledCode.code).toMatchInlineSnapshot(` - "function withParams(a: string, b: number) { - 'use server'; - - return \`\${a} \${b}\`; + "function withParams(...args) { + return import("test.ts?tsr-serverfn-split=test--withParams").then(mod => mod.serverFn(...args)); }" `) }) @@ -400,10 +377,8 @@ describe('server function compilation', () => { const server = compileServerFnServer({ ...serverConfig, code }) expect(server.compiledCode.code).toMatchInlineSnapshot(` - "const iife = function () { - 'use server'; - - return 'hello'; + "const iife = function (...args) { + return import("test.ts?tsr-serverfn-split=test--iife").then(mod => mod.serverFn(...args)); }();" `) }) @@ -434,10 +409,8 @@ describe('server function compilation', () => { const server = compileServerFnServer({ ...serverConfig, code }) expect(server.compiledCode.code).toMatchInlineSnapshot(` "function higherOrder() { - return function () { - 'use server'; - - return 'hello'; + return function (...args) { + return import("test.ts?tsr-serverfn-split=test--higherOrder").then(mod => mod.serverFn(...args)); }; }" `) @@ -489,19 +462,15 @@ describe('server function compilation', () => { expect(server.compiledCode.code).toMatchInlineSnapshot(` "function main() { function middle() { - const useServer = function () { - 'use server'; - - return 'hello'; + const useServer = function (...args) { + return import("test.ts?tsr-serverfn-split=test--main_middle_useServer_1").then(mod => mod.serverFn(...args)); }; return useServer; } return middle; } - main().middle(function useServer() { - 'use server'; - - return 'hello'; + main().middle(function useServer(...args) { + return import("test.ts?tsr-serverfn-split=test--main_middle_useServer_2").then(mod => mod.serverFn(...args)); });" `) }) diff --git a/packages/start-vite-plugin/src/compilers.ts b/packages/start-vite-plugin/src/compilers.ts index 365a38609d..41b54b8ac2 100644 --- a/packages/start-vite-plugin/src/compilers.ts +++ b/packages/start-vite-plugin/src/compilers.ts @@ -21,6 +21,8 @@ export function compileEliminateDeadCode(opts: ParseAstOptions) { deadCodeElimination(ast) return generate(ast, { sourceMaps: true, + sourceFileName: opts.filename, + minified: process.env.NODE_ENV === 'production', filename: opts.filename, }) } @@ -186,6 +188,7 @@ export function compileStartOutput(opts: ParseAstOptions) { return generate(ast, { sourceMaps: true, + sourceFileName: opts.filename, filename: opts.filename, minified: process.env.NODE_ENV === 'production', }) From b1335a3be2ec512f13608c3261b9dfb63efc6f7e Mon Sep 17 00:00:00 2001 From: Tanner Linsley Date: Wed, 18 Dec 2024 09:34:31 -0700 Subject: [PATCH 08/13] checkpoint --- .../server-functions-vite-plugin/package.json | 1 + .../src/compilers.ts | 683 ++++++------ .../server-functions-vite-plugin/src/index.ts | 17 +- .../tests/compiler.test.ts | 992 +++++++++++------- pnpm-lock.yaml | 13 + 5 files changed, 1044 insertions(+), 662 deletions(-) diff --git a/packages/server-functions-vite-plugin/package.json b/packages/server-functions-vite-plugin/package.json index 2dd6e26e72..dd6f839ff9 100644 --- a/packages/server-functions-vite-plugin/package.json +++ b/packages/server-functions-vite-plugin/package.json @@ -82,6 +82,7 @@ "@types/diff": "^6.0.0", "babel-dead-code-elimination": "^1.0.6", "chalk": "^5.3.0", + "dedent": "^1.5.3", "diff": "^7.0.0", "tiny-invariant": "^1.3.3" } diff --git a/packages/server-functions-vite-plugin/src/compilers.ts b/packages/server-functions-vite-plugin/src/compilers.ts index f08b6eb408..70ecafcb73 100644 --- a/packages/server-functions-vite-plugin/src/compilers.ts +++ b/packages/server-functions-vite-plugin/src/compilers.ts @@ -3,6 +3,8 @@ import * as babel from '@babel/core' import _generate from '@babel/generator' import { isIdentifier, isVariableDeclarator } from '@babel/types' +import { codeFrameColumns } from '@babel/code-frame' +import { deadCodeElimination } from 'babel-dead-code-elimination' import { parseAst } from './ast' import type { ParseAstOptions } from './ast' @@ -12,25 +14,97 @@ if ('default' in generate) { generate = generate.default as typeof generate } -interface ServerFunctionInfo { - nodePath: babel.NodePath +export interface ServerFunctionInfo { + nodePath: SupportedFunctionPath functionName: string functionId: string + referenceName: string + splitFileId: string } -// export function compileEliminateDeadCode(opts: ParseAstOptions) { -// const ast = parseAst(opts) -// deadCodeElimination(ast) +export type SupportedFunctionPath = + | babel.NodePath + | babel.NodePath + | babel.NodePath -// return generate(ast, { -// sourceMaps: true, -// sourceFileName: opts.filename, -// minified: process.env.NODE_ENV === 'production', -// }) -// } +export type ReplacerFn = (opts: { + fn: string + splitImportFn: string + filename: string + functionId: string +}) => string // const debug = process.env.TSR_VITE_DEBUG === 'true' +export type CompileDirectivesOpts = ParseAstOptions & { + directive: string + getRuntimeCode?: (opts: { + serverFnPathsByFunctionId: Record + }) => string + replacer: ReplacerFn +} + +const tsrServerFnSplitParam = 'tsr-serverfn-split' + +export function compileDirectives(opts: CompileDirectivesOpts) { + const [_, searchParamsStr] = opts.filename.split('?') + const searchParams = new URLSearchParams(searchParamsStr) + const functionId = searchParams.get(tsrServerFnSplitParam) + + const ast = parseAst(opts) + const serverFnPathsByFunctionId = findServerFunctions(ast, { + ...opts, + splitFunctionId: functionId, + }) + + // Add runtime code if there are server functions + // Add runtime code if there are server functions + if ( + Object.keys(serverFnPathsByFunctionId).length > 0 && + opts.getRuntimeCode + ) { + const runtimeImport = babel.template.statement( + opts.getRuntimeCode({ serverFnPathsByFunctionId }), + )() + ast.program.body.unshift(runtimeImport) + } + + // If there is a functionId, we need to remove all exports + // then make sure that our function is exported under the + // "serverFn" name + if (functionId) { + const serverFn = serverFnPathsByFunctionId[functionId] + + if (!serverFn) { + throw new Error(`Server function ${functionId} not found`) + } + + console.log('functionId', functionId) + safeRemoveExports(ast) + + ast.program.body.push( + babel.types.exportDefaultDeclaration( + babel.types.identifier(serverFn.referenceName), + ), + ) + + // If we have a functionId, we're also going to DCE the file + // so that the functionId is not exported + deadCodeElimination(ast) + } + + const compiledResult = generate(ast, { + sourceMaps: true, + sourceFileName: opts.filename, + minified: process.env.NODE_ENV === 'production', + }) + + return { + compiledResult, + serverFns: serverFnPathsByFunctionId, + } +} + function findNearestVariableName(path: babel.NodePath): string { let currentPath: babel.NodePath | null = path const nameParts: Array = [] @@ -99,15 +173,12 @@ function findNearestVariableName(path: babel.NodePath): string { babel.types.isClassMethod(currentPath.node) || babel.types.isObjectMethod(currentPath.node) ) { - if (babel.types.isIdentifier(currentPath.node.key)) { - return currentPath.node.key.name - } - if (babel.types.isStringLiteral(currentPath.node.key)) { - return currentPath.node.key.value - } + throw new Error( + 'use server in ClassMethod or ObjectMethod not supported', + ) } - return null + return '' })() if (name) { @@ -120,23 +191,6 @@ function findNearestVariableName(path: babel.NodePath): string { return nameParts.length > 0 ? nameParts.join('_') : 'anonymous' } -function isFunctionDeclaration( - node: babel.types.Node, -): node is - | babel.types.FunctionDeclaration - | babel.types.FunctionExpression - | babel.types.ArrowFunctionExpression - | babel.types.ClassMethod - | babel.types.ObjectMethod { - return ( - babel.types.isFunctionDeclaration(node) || - babel.types.isFunctionExpression(node) || - babel.types.isArrowFunctionExpression(node) || - babel.types.isClassMethod(node) || - babel.types.isObjectMethod(node) - ) -} - function makeFileLocationUrlSafe(location: string): string { return location .replace(/[^a-zA-Z0-9-_]/g, '_') // Replace unsafe chars with underscore @@ -144,292 +198,317 @@ function makeFileLocationUrlSafe(location: string): string { .replace(/^_|_$/g, '') // Trim leading/trailing underscores } -export function compileServerFnClient( +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 findServerFunctions( + ast: babel.types.File, opts: ParseAstOptions & { - getRuntimeCode: (opts: { - serverFnPathsByFunctionId: Record - }) => string - replacer: (opts: { filename: string; functionId: string }) => string + replacer?: ReplacerFn + splitFunctionId?: string | null }, ) { - const ast = parseAst(opts) - const serverFnPathsByFunctionId = findServerFunctions(ast, opts) - - // Add runtime code if there are server functions - if (Object.keys(serverFnPathsByFunctionId).length > 0) { - const runtimeImport = babel.template.statement( - opts.getRuntimeCode({ serverFnPathsByFunctionId }), - )() - ast.program.body.unshift(runtimeImport) - } - - // Replace server functions with client-side stubs - for (const [functionId, { nodePath }] of Object.entries( - serverFnPathsByFunctionId, - )) { - const replacementCode = opts.replacer({ - filename: opts.filename, - functionId: functionId, - }) - - // Check to see if the function is a valid function declaration - if (!isFunctionDeclaration(nodePath.node)) { - throw new Error( - `Server function is not a function declaration: ${nodePath.node}`, - ) - } - - nodePath.node.params = [ - babel.types.restElement(babel.types.identifier('args')), - ] - - // Remove 'use server' directive - // Check if the node body is a block statement - if (!babel.types.isBlockStatement(nodePath.node.body)) { - throw new Error( - `Server function body is not a block statement: ${nodePath.node.body}`, - ) - } - - const nodeBody = nodePath.node.body - nodeBody.directives = nodeBody.directives.filter( - (directive) => directive.value.value !== 'use server', - ) - - const replacement = babel.template.expression( - `(${replacementCode})(...args)`, - )() - - if (babel.types.isArrowFunctionExpression(nodePath.node)) { - if (babel.types.isBlockStatement(nodePath.node.body)) { - nodePath.node.body.body = [babel.types.returnStatement(replacement)] - } else { - nodePath.node.body = babel.types.blockStatement([ - babel.types.returnStatement(replacement), - ]) - } - } else if ( - babel.types.isFunctionExpression(nodePath.node) || - babel.types.isFunctionDeclaration(nodePath.node) || - babel.types.isObjectMethod(nodePath.node) || - babel.types.isClassMethod(nodePath.node) - ) { - nodePath.node.body.body = [babel.types.returnStatement(replacement)] - } - } - - const compiledCode = generate(ast, { - sourceMaps: true, - sourceFileName: opts.filename, - minified: process.env.NODE_ENV === 'production', - }) - - return { - compiledCode, - serverFns: serverFnPathsByFunctionId, - } -} - -export function compileServerFnServer(opts: ParseAstOptions) { - const ast = parseAst(opts) - const serverFnPathsByFunctionId = findServerFunctions(ast, opts) - - // Replace server function bodies with dynamic imports - Object.entries(serverFnPathsByFunctionId).forEach( - ([functionId, { nodePath }]) => { - // Check if the node is a function declaration - if (!isFunctionDeclaration(nodePath.node)) { - throw new Error( - `Server function is not a function declaration: ${nodePath.node}`, - ) - } - - nodePath.node.params = [ - babel.types.restElement(babel.types.identifier('args')), - ] - - // Check if the node body is a block statement - if (!babel.types.isBlockStatement(nodePath.node.body)) { - throw new Error( - `Server function body is not a block statement: ${nodePath.node.body}`, - ) - } - - const nodeBody = nodePath.node.body - nodeBody.directives = nodeBody.directives.filter( - (directive) => directive.value.value !== 'use server', - ) - - // Create the dynamic import expression - const importExpression = babel.template.expression(` - import(${JSON.stringify(`${opts.filename}?tsr-serverfn-split=${functionId}`)}) - .then(mod => mod.serverFn(...args)) - `)() - - if (babel.types.isArrowFunctionExpression(nodePath.node)) { - if (babel.types.isBlockStatement(nodePath.node.body)) { - nodePath.node.body.body = [ - babel.types.returnStatement(importExpression), - ] - } else { - nodePath.node.body = babel.types.blockStatement([ - babel.types.returnStatement(importExpression), - ]) - } - } else if ( - babel.types.isFunctionExpression(nodePath.node) || - babel.types.isFunctionDeclaration(nodePath.node) || - babel.types.isObjectMethod(nodePath.node) || - babel.types.isClassMethod(nodePath.node) - ) { - nodePath.node.body.body = [ - babel.types.returnStatement(importExpression), - ] - } - }, - ) - - const compiledCode = generate(ast, { - sourceMaps: true, - sourceFileName: opts.filename, - minified: process.env.NODE_ENV === 'production', - }) - - return { - compiledCode, - serverFns: serverFnPathsByFunctionId, - } -} - -function findServerFunctions(ast: babel.types.File, opts: ParseAstOptions) { const serverFnPathsByFunctionId: Record = {} - const counts: Record = {} + const functionIdCounts: Record = {} + const referenceCounts: Map = new Map() - const recordServerFunction = (nodePath: babel.NodePath) => { - const fnName = findNearestVariableName(nodePath) - - const baseLabel = makeFileLocationUrlSafe( - `${opts.filename.replace( - path.extname(opts.filename), - '', - )}--${fnName}`.replace(opts.root, ''), - ) - - counts[baseLabel] = (counts[baseLabel] || 0) + 1 - - const functionId = - counts[baseLabel] > 1 - ? `${baseLabel}_${counts[baseLabel] - 1}` - : baseLabel - - serverFnPathsByFunctionId[functionId] = { - nodePath, - functionName: fnName || '', - functionId: functionId, - } - } + let programPath: babel.NodePath babel.traverse(ast, { - Program: { - enter(programPath) { - programPath.traverse({ - enter(path) { - // Function declarations - if (path.isFunctionDeclaration()) { - const directives = path.node.body.directives - for (const directive of directives) { - if (directive.value.value === 'use server') { - recordServerFunction(path) - } - } - } + Program(path) { + programPath = path + }, + }) - // Function expressions - if (path.isFunctionExpression()) { - const directives = path.node.body.directives - for (const directive of directives) { - if (directive.value.value === 'use server') { - recordServerFunction(path) - } - } - } + // Find all server functions + babel.traverse(ast, { + DirectiveLiteral(nodePath) { + if (nodePath.node.value === 'use server') { + let directiveFn = nodePath.findParent((p) => p.isFunction()) as + | SupportedFunctionPath + | undefined - // Arrow functions - if (path.isArrowFunctionExpression()) { - if (babel.types.isBlockStatement(path.node.body)) { - const directives = path.node.body.directives - for (const directive of directives) { - if (directive.value.value === 'use server') { - recordServerFunction(path) - } - } - } - } + if (!directiveFn) return - // Class methods - if (path.isClassMethod()) { - const directives = path.node.body.directives - for (const directive of directives) { - if (directive.value.value === 'use server') { - recordServerFunction(path) - } - } - } + // Handle class and object methods which are not supported + const isGenerator = + directiveFn.isFunction() && directiveFn.node.generator - // Object methods - if (path.isObjectMethod()) { - const directives = path.node.body.directives - for (const directive of directives) { - if (directive.value.value === 'use server') { - recordServerFunction(path) - } - } - } + const isClassMethod = directiveFn.isClassMethod() + const isObjectMethod = directiveFn.isObjectMethod() - // Variable declarations with function expressions + if (isClassMethod || isObjectMethod || isGenerator) { + throw codeFrameError( + opts.code, + directiveFn.node.loc, + `use server in ${isClassMethod ? 'class' : isObjectMethod ? 'object method' : 'generator function'} 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, + 'Server functions cannot be nested in other blocks or functions', + ) + } + + // Handle supported function types + if ( + directiveFn.isFunctionDeclaration() || + directiveFn.isFunctionExpression() || + (directiveFn.isArrowFunctionExpression() && + babel.types.isBlockStatement(directiveFn.node.body)) + ) { + // Remove the 'use server' 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 !== 'use server', + ) + } + + // Find the nearest variable name + const fnName = findNearestVariableName(directiveFn) + + // Make the functionId safe for use in a URL + const baseLabel = makeFileLocationUrlSafe( + `${opts.filename.replace( + path.extname(opts.filename), + '', + )}--${fnName}`.replace(opts.root, ''), + ) + + // Count the number of functions with the same baseLabel + functionIdCounts[baseLabel] = (functionIdCounts[baseLabel] || 0) + 1 + + // If there are multiple functions with the same baseLabel, + // append a unique identifier to the functionId + const functionId = + functionIdCounts[baseLabel] > 1 + ? `${baseLabel}_${functionIdCounts[baseLabel] - 1}` + : baseLabel + + // Move the function to program level while preserving its position + // in the program body + const programBody = programPath.node.body + + const topParent = + directiveFn.findParent((p) => !!p.parentPath?.isProgram()) || + directiveFn + + const topParentIndex = programBody.indexOf(topParent.node as any) + + // Determine the reference name for the function + let referenceName = makeIdentifierSafe(fnName) + + // If we find this referece in the scope, we need to make it unique + while (programPath.scope.hasBinding(referenceName)) { + referenceCounts.set( + referenceName, + (referenceCounts.get(referenceName) || 0) + 1, + ) + referenceName += `_${referenceCounts.get(referenceName) || 0}` + } + + // if (referenceCounts.get(referenceName) === 0) { + + // referenceName += `_${(referenceCounts.get(referenceName) || 0) + 1}` + + // If the reference name came from the function declaration, + // // We need to update the function name to match the reference name + // if (babel.types.isFunctionDeclaration(directiveFn.node)) { + // console.log('updating function name', directiveFn.node.id!.name) + // directiveFn.node.id!.name = referenceName + // } + + // 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()) { + // Then place the function at the top level + programBody.splice( + topParentIndex, + 0, + babel.types.variableDeclaration('const', [ + babel.types.variableDeclarator( + babel.types.identifier(referenceName), + babel.types.toExpression(directiveFn.node as any), + ), + ]), + ) + + // If it's an exported named function, we need to swap it with an + // export const originalFunctionName = referenceName if ( - path.isVariableDeclarator() && - (babel.types.isFunctionExpression(path.node.init) || - babel.types.isArrowFunctionExpression(path.node.init)) + babel.types.isExportNamedDeclaration( + directiveFn.parentPath.node, + ) && + (babel.types.isFunctionDeclaration(directiveFn.node) || + babel.types.isFunctionExpression(directiveFn.node)) && + babel.types.isIdentifier(directiveFn.node.id) ) { - const init = path.node.init - if (babel.types.isBlockStatement(init.body)) { - const directives = init.body.directives - for (const directive of directives) { - if (directive.value.value === 'use server') { - recordServerFunction(path.get('init') as babel.NodePath) - } - } - } + 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(referenceName), + ), + ]), + ), + ) + + directiveFn.remove() + } else { + directiveFn.replaceWith(babel.types.identifier(referenceName)) } - }, - }) - }, + + directiveFn = programPath.get( + `body.${topParentIndex}.declarations.0.init`, + ) as SupportedFunctionPath + } + + const [filename, searchParamsStr] = opts.filename.split('?') + + const searchParams = new URLSearchParams(searchParamsStr) + searchParams.set('tsr-serverfn-split', functionId) + const splitFileId = `${filename}?${searchParams.toString()}` + + // If a replacer is provided, replace the function with the replacer + if (functionId !== opts.splitFunctionId && opts.replacer) { + const replacer = opts.replacer({ + fn: '$$fn$$', + splitImportFn: '$$splitImportFn$$', + // splitFileId, + filename: filename!, + functionId: functionId, + }) + + const replacement = babel.template.expression(replacer, { + placeholderPattern: false, + placeholderWhitelist: new Set(['$$fn$$', '$$splitImportFn$$']), + })({ + ...(replacer.includes('$$fn$$') + ? { $$fn$$: babel.types.toExpression(directiveFn.node) } + : {}), + ...(replacer.includes('$$splitImportFn$$') + ? { + $$splitImportFn$$: `(...args) => import(${JSON.stringify(splitFileId)}).then(module => module.default(...args))`, + } + : {}), + }) + + directiveFn.replaceWith(replacement) + } + + // Finally register the server function to + // our map of server functions + serverFnPathsByFunctionId[functionId] = { + nodePath: directiveFn, + referenceName, + functionName: fnName || '', + functionId: functionId, + splitFileId, + } + } + } }, }) return serverFnPathsByFunctionId } -// function codeFrameError( -// code: string, -// loc: { -// start: { line: number; column: number } -// end: { line: number; column: number } -// }, -// message: string, -// ) { -// const frame = codeFrameColumns( -// code, -// { -// start: loc.start, -// end: loc.end, -// }, -// { -// highlightCode: true, -// message, -// }, -// ) +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`) + } -// return new Error(frame) -// } + const frame = codeFrameColumns( + code, + { + start: loc.start, + end: loc.end, + }, + { + highlightCode: true, + message, + }, + ) + + return new Error(frame) +} + +const safeRemoveExports = (ast: babel.types.File) => { + const programBody = ast.program.body + + const removeExport = ( + path: + | babel.NodePath + | babel.NodePath, + ) => { + // If the value is a function declaration, class declaration, or variable declaration, + // That means it has a name and can remain in the file, just unexported. + if ( + babel.types.isFunctionDeclaration(path.node.declaration) || + babel.types.isClassDeclaration(path.node.declaration) || + babel.types.isVariableDeclaration(path.node.declaration) + ) { + // If the value is a function declaration, class declaration, or variable declaration, + // That means it has a name and can remain in the file, just unexported. + if ( + babel.types.isFunctionDeclaration(path.node.declaration) || + babel.types.isClassDeclaration(path.node.declaration) || + babel.types.isVariableDeclaration(path.node.declaration) + ) { + // Move the declaration to the top level at the same index + const insertIndex = programBody.findIndex( + (node) => node === path.node.declaration, + ) + programBody.splice(insertIndex, 0, path.node.declaration as any) + } + } + + // Otherwise, remove the export declaration + path.remove() + } + + // Before we add our export, remove any other exports. + // Don't remove the thing they export, just the export declaration + babel.traverse(ast, { + ExportDefaultDeclaration(path) { + removeExport(path) + }, + ExportNamedDeclaration(path) { + removeExport(path) + }, + }) +} diff --git a/packages/server-functions-vite-plugin/src/index.ts b/packages/server-functions-vite-plugin/src/index.ts index 8ee6b4cda8..12a710f138 100644 --- a/packages/server-functions-vite-plugin/src/index.ts +++ b/packages/server-functions-vite-plugin/src/index.ts @@ -1,7 +1,8 @@ import { fileURLToPath, pathToFileURL } from 'node:url' -import { compileServerFnClient } from './compilers' +import { compileDirectives } from './compilers' import { logDiff } from './logger' +import type { ReplacerFn } from './compilers' import type { Plugin } from 'vite' const debug = Boolean(process.env.TSR_VITE_DEBUG) || (true as boolean) @@ -17,7 +18,7 @@ export type ServerFunctionsViteOptions = { } > }) => string - replacer: (opts: { filename: string; functionId: string }) => string + replacer: ReplacerFn } const useServerRx = /"use server"|'use server'/ @@ -28,10 +29,9 @@ export type CreateRpcFn = (opts: { functionId: string }) => (...args: Array) => any -export function TanStackServerFnPluginClient( +export function TanStackServerFnPluginRuntime( opts: ServerFunctionsViteOptions, ): Array { - // opts: ServerFunctionsViteOptions, let ROOT: string = process.cwd() return [ @@ -50,7 +50,8 @@ export function TanStackServerFnPluginClient( return null } - const { compiledCode, serverFns } = compileServerFnClient({ + const { compiledResult, serverFns } = compileDirectives({ + directive: 'use server', code, root: ROOT, filename: id, @@ -59,15 +60,15 @@ export function TanStackServerFnPluginClient( }) if (debug) console.info('createServerFn Input/Output') - if (debug) logDiff(code, compiledCode.code.replace(/ctx/g, 'blah')) + if (debug) logDiff(code, compiledResult.code.replace(/ctx/g, 'blah')) - return compiledCode + return compiledResult }, }, ] } -export function TanStackServerFnPluginServer( +export function TanStackServerFnPluginSplitFn( opts: ServerFunctionsViteOptions, ): Array { return [ diff --git a/packages/server-functions-vite-plugin/tests/compiler.test.ts b/packages/server-functions-vite-plugin/tests/compiler.test.ts index ee958f0084..dc62daee66 100644 --- a/packages/server-functions-vite-plugin/tests/compiler.test.ts +++ b/packages/server-functions-vite-plugin/tests/compiler.test.ts @@ -1,105 +1,384 @@ import { describe, expect, test } from 'vitest' -import { compileServerFnClient, compileServerFnServer } from '../src/compilers' +import { compileDirectives } from '../src/compilers' +import type { CompileDirectivesOpts } from '../src/compilers' -const clientConfig = { +const clientConfig: Omit = { + directive: 'use server', root: './test-files', filename: 'test.ts', - getRuntimeCode: () => 'import { createClientRpc } from "my-rpc-lib"', - replacer: (opts: { filename: string; functionId: string }) => + getRuntimeCode: () => 'import { createClientRpc } from "my-rpc-lib-client"', + replacer: (opts) => `createClientRpc({ filename: ${JSON.stringify(opts.filename)}, functionId: ${JSON.stringify(opts.functionId)}, })`, } -const serverConfig = { +const serverConfig: Omit = { + directive: 'use server', root: './test-files', filename: 'test.ts', + getRuntimeCode: () => 'import { createServerRpc } from "my-rpc-lib-server"', + replacer: (opts) => + `createServerRpc({ + fn: ${opts.splitImportFn}, + filename: ${JSON.stringify(opts.filename)}, + functionId: ${JSON.stringify(opts.functionId)}, + })`, } describe('server function compilation', () => { - test('basic function declaration', async () => { - const code = ` - function useServer() { + const code = ` + const namedFunction = wrapper(function namedFunction() { + 'use server' + return 'hello' + }) + + const arrowFunction = wrapper(() => { + 'use server' + return 'hello' + }) + + const anonymousFunction = wrapper(function () { + 'use server' + return 'hello' + }) + + const multipleDirectives = function multipleDirectives() { + 'use server' + 'use strict' + return 'hello' + } + + const iife = (function () { + 'use server' + return 'hello' + })() + + export default function defaultExportFn() { 'use server' return 'hello' } - ` - const client = compileServerFnClient({ ...clientConfig, code }) - await expect(client.compiledCode.code).toMatchInlineSnapshot(` - "import { createClientRpc } from "my-rpc-lib"; - function useServer(...args) { - return createClientRpc({ - filename: "test.ts", - functionId: "test--useServer" - })(...args); - }" - `) - - const server = compileServerFnServer({ ...serverConfig, code }) - await expect(server.compiledCode.code).toMatchInlineSnapshot(` - "function useServer(...args) { - return import("test.ts?tsr-serverfn-split=test--useServer").then(mod => mod.serverFn(...args)); - }" - `) - }) - - test('arrow function', () => { - const code = ` - const fn = () => { + export function namedExportFn() { 'use server' return 'hello' } - ` - const client = compileServerFnClient({ ...clientConfig, code }) - expect(client.compiledCode.code).toMatchInlineSnapshot(` - "import { createClientRpc } from "my-rpc-lib"; - const fn = (...args) => { - return createClientRpc({ - filename: "test.ts", - functionId: "test--fn_1" - })(...args); - };" - `) - - const server = compileServerFnServer({ ...serverConfig, code }) - expect(server.compiledCode.code).toMatchInlineSnapshot(` - "const fn = (...args) => { - return import("test.ts?tsr-serverfn-split=test--fn_1").then(mod => mod.serverFn(...args)); - };" - `) - }) - - test('anonymous function', () => { - const code = ` - const anonymousFn = function () { + export const exportedArrowFunction = wrapper(() => { 'use server' + return 'hello' + }) + + export const namedExportConst = () => { + 'use server' + return 'hello' } + + const namedDefaultExport = 'namedDefaultExport' + export default namedDefaultExport + + export const usedButNotExported = 'usedButNotExported' + + const namedExport = 'namedExport' + + export { + namedExport + } + ` - const client = compileServerFnClient({ ...clientConfig, code }) - expect(client.compiledCode.code).toMatchInlineSnapshot(` - "import { createClientRpc } from "my-rpc-lib"; - const anonymousFn = function (...args) { - return createClientRpc({ - filename: "test.ts", - functionId: "test--anonymousFn_1" - })(...args); - };" + test('basic function declaration nested in other variable', () => { + const client = compileDirectives({ + ...clientConfig, + code, + }) + const ssr = compileDirectives({ ...serverConfig, code }) + const splitFiles = Object.entries(ssr.serverFns) + .map(([_fnId, serverFn]) => { + return `// ${serverFn.functionName}\n\n${ + compileDirectives({ + ...serverConfig, + code, + filename: serverFn.splitFileId, + }).compiledResult.code + }` + }) + .join('\n\n\n') + + expect(client.compiledResult.code).toMatchInlineSnapshot(` + "import { createClientRpc } from "my-rpc-lib-client"; + const namedFunction_wrapper_namedFunction = createClientRpc({ + filename: "test.ts", + functionId: "test--namedFunction_wrapper_namedFunction" + }); + const namedFunction = wrapper(namedFunction_wrapper_namedFunction); + const arrowFunction_wrapper = createClientRpc({ + filename: "test.ts", + functionId: "test--arrowFunction_wrapper" + }); + const arrowFunction = wrapper(arrowFunction_wrapper); + const anonymousFunction_wrapper = createClientRpc({ + filename: "test.ts", + functionId: "test--anonymousFunction_wrapper" + }); + const anonymousFunction = wrapper(anonymousFunction_wrapper); + const multipleDirectives_multipleDirectives = createClientRpc({ + filename: "test.ts", + functionId: "test--multipleDirectives_multipleDirectives" + }); + const multipleDirectives = multipleDirectives_multipleDirectives; + const iife_1 = createClientRpc({ + filename: "test.ts", + functionId: "test--iife" + }); + const iife = iife_1(); + const defaultExportFn_1 = createClientRpc({ + filename: "test.ts", + functionId: "test--defaultExportFn" + }); + export default defaultExportFn_1; + const namedExportFn_1 = createClientRpc({ + filename: "test.ts", + functionId: "test--namedExportFn" + }); + export const namedExportFn = namedExportFn_1; + const exportedArrowFunction_wrapper = createClientRpc({ + filename: "test.ts", + functionId: "test--exportedArrowFunction_wrapper" + }); + export const exportedArrowFunction = wrapper(exportedArrowFunction_wrapper); + const namedExportConst_1 = createClientRpc({ + filename: "test.ts", + functionId: "test--namedExportConst" + }); + export const namedExportConst = namedExportConst_1; + const namedDefaultExport = 'namedDefaultExport'; + export default namedDefaultExport; + export const usedButNotExported = 'usedButNotExported'; + const namedExport = 'namedExport'; + export { namedExport };" `) - const server = compileServerFnServer({ ...serverConfig, code }) - expect(server.compiledCode.code).toMatchInlineSnapshot(` - "const anonymousFn = function (...args) { - return import("test.ts?tsr-serverfn-split=test--anonymousFn_1").then(mod => mod.serverFn(...args)); - };" + expect(ssr.compiledResult.code).toMatchInlineSnapshot(` + "import { createServerRpc } from "my-rpc-lib-server"; + const namedFunction_wrapper_namedFunction = createServerRpc({ + fn: (...args) => import("test.ts?tsr-serverfn-split=test--namedFunction_wrapper_namedFunction").then(module => module.default(...args)), + filename: "test.ts", + functionId: "test--namedFunction_wrapper_namedFunction" + }); + const namedFunction = wrapper(namedFunction_wrapper_namedFunction); + const arrowFunction_wrapper = createServerRpc({ + fn: (...args) => import("test.ts?tsr-serverfn-split=test--arrowFunction_wrapper").then(module => module.default(...args)), + filename: "test.ts", + functionId: "test--arrowFunction_wrapper" + }); + const arrowFunction = wrapper(arrowFunction_wrapper); + const anonymousFunction_wrapper = createServerRpc({ + fn: (...args) => import("test.ts?tsr-serverfn-split=test--anonymousFunction_wrapper").then(module => module.default(...args)), + filename: "test.ts", + functionId: "test--anonymousFunction_wrapper" + }); + const anonymousFunction = wrapper(anonymousFunction_wrapper); + const multipleDirectives_multipleDirectives = createServerRpc({ + fn: (...args) => import("test.ts?tsr-serverfn-split=test--multipleDirectives_multipleDirectives").then(module => module.default(...args)), + filename: "test.ts", + functionId: "test--multipleDirectives_multipleDirectives" + }); + const multipleDirectives = multipleDirectives_multipleDirectives; + const iife_1 = createServerRpc({ + fn: (...args) => import("test.ts?tsr-serverfn-split=test--iife").then(module => module.default(...args)), + filename: "test.ts", + functionId: "test--iife" + }); + const iife = iife_1(); + const defaultExportFn_1 = createServerRpc({ + fn: (...args) => import("test.ts?tsr-serverfn-split=test--defaultExportFn").then(module => module.default(...args)), + filename: "test.ts", + functionId: "test--defaultExportFn" + }); + export default defaultExportFn_1; + const namedExportFn_1 = createServerRpc({ + fn: (...args) => import("test.ts?tsr-serverfn-split=test--namedExportFn").then(module => module.default(...args)), + filename: "test.ts", + functionId: "test--namedExportFn" + }); + export const namedExportFn = namedExportFn_1; + const exportedArrowFunction_wrapper = createServerRpc({ + fn: (...args) => import("test.ts?tsr-serverfn-split=test--exportedArrowFunction_wrapper").then(module => module.default(...args)), + filename: "test.ts", + functionId: "test--exportedArrowFunction_wrapper" + }); + export const exportedArrowFunction = wrapper(exportedArrowFunction_wrapper); + const namedExportConst_1 = createServerRpc({ + fn: (...args) => import("test.ts?tsr-serverfn-split=test--namedExportConst").then(module => module.default(...args)), + filename: "test.ts", + functionId: "test--namedExportConst" + }); + export const namedExportConst = namedExportConst_1; + const namedDefaultExport = 'namedDefaultExport'; + export default namedDefaultExport; + export const usedButNotExported = 'usedButNotExported'; + const namedExport = 'namedExport'; + export { namedExport };" `) + + expect(splitFiles).toMatchInlineSnapshot( + ` + "// namedFunction_wrapper_namedFunction + + const namedFunction_wrapper_namedFunction = function namedFunction() { + return 'hello'; + }; + export default namedFunction_wrapper_namedFunction; + + + // arrowFunction_wrapper + + const arrowFunction_wrapper = () => { + return 'hello'; + }; + export default arrowFunction_wrapper; + + + // anonymousFunction_wrapper + + const anonymousFunction_wrapper = function () { + return 'hello'; + }; + export default anonymousFunction_wrapper; + + + // multipleDirectives_multipleDirectives + + const multipleDirectives_multipleDirectives = function multipleDirectives() { + 'use strict'; + + return 'hello'; + }; + export default multipleDirectives_multipleDirectives; + + + // iife + + const iife_1 = function () { + return 'hello'; + }; + export default iife_1; + + + // defaultExportFn + + const defaultExportFn_1 = function defaultExportFn() { + return 'hello'; + }; + export default defaultExportFn_1; + + + // namedExportFn + + const namedExportFn_1 = function namedExportFn() { + return 'hello'; + }; + export default namedExportFn_1; + + + // exportedArrowFunction_wrapper + + const exportedArrowFunction_wrapper = () => { + return 'hello'; + }; + export default exportedArrowFunction_wrapper; + + + // namedExportConst + + const namedExportConst_1 = () => { + return 'hello'; + }; + export default namedExportConst_1;" + `, + ) }) - test('class methods', () => { + test('Does not support function declarations nested in other blocks', () => { + const code = ` + outer(() => { + function useServer() { + 'use server' + return 'hello' + } + }) + ` + + expect(() => + compileDirectives({ ...clientConfig, code }), + ).toThrowErrorMatchingInlineSnapshot( + ` + [Error: 1 | + > 2 | outer(() => { + | ^^ + > 3 | function useServer() { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + > 4 | 'use server' + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + > 5 | return 'hello' + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + > 6 | } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + > 7 | }) + | ^^^^^^^ Server functions cannot be nested in other blocks or functions + 8 | ] + `, + ) + expect(() => + compileDirectives({ ...serverConfig, code }), + ).toThrowErrorMatchingInlineSnapshot( + ` + [Error: 1 | + > 2 | outer(() => { + | ^^ + > 3 | function useServer() { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + > 4 | 'use server' + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + > 5 | return 'hello' + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + > 6 | } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + > 7 | }) + | ^^^^^^^ Server functions cannot be nested in other blocks or functions + 8 | ] + `, + ) + expect(() => + compileDirectives({ + ...serverConfig, + code, + filename: serverConfig.filename + `?tsr-serverfn-split=temp`, + }), + ).toThrowErrorMatchingInlineSnapshot( + ` + [Error: 1 | + > 2 | outer(() => { + | ^^ + > 3 | function useServer() { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + > 4 | 'use server' + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + > 5 | return 'hello' + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + > 6 | } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + > 7 | }) + | ^^^^^^^ Server functions cannot be nested in other blocks or functions + 8 | ] + `, + ) + }) + + test('does not support class methods', () => { const code = ` class TestClass { method() { @@ -114,39 +393,62 @@ describe('server function compilation', () => { } ` - const client = compileServerFnClient({ ...clientConfig, code }) - expect(client.compiledCode.code).toMatchInlineSnapshot(` - "import { createClientRpc } from "my-rpc-lib"; - class TestClass { - method(...args) { - return createClientRpc({ - filename: "test.ts", - functionId: "test--method" - })(...args); - } - static staticMethod(...args) { - return createClientRpc({ - filename: "test.ts", - functionId: "test--staticMethod" - })(...args); - } - }" + expect(() => compileDirectives({ ...clientConfig, code })) + .toThrowErrorMatchingInlineSnapshot(` + [Error: 1 | + 2 | class TestClass { + > 3 | method() { + | ^^^^^^^^^^^ + > 4 | 'use server' + | ^^^^^^^^^^^^^^^^^^^^^^ + > 5 | return 'hello' + | ^^^^^^^^^^^^^^^^^^^^^^ + > 6 | } + | ^^^^^^^^^ use server in class not supported + 7 | + 8 | static staticMethod() { + 9 | 'use server'] `) - - const server = compileServerFnServer({ ...serverConfig, code }) - expect(server.compiledCode.code).toMatchInlineSnapshot(` - "class TestClass { - method(...args) { - return import("test.ts?tsr-serverfn-split=test--method").then(mod => mod.serverFn(...args)); - } - static staticMethod(...args) { - return import("test.ts?tsr-serverfn-split=test--staticMethod").then(mod => mod.serverFn(...args)); - } - }" + expect(() => compileDirectives({ ...serverConfig, code })) + .toThrowErrorMatchingInlineSnapshot(` + [Error: 1 | + 2 | class TestClass { + > 3 | method() { + | ^^^^^^^^^^^ + > 4 | 'use server' + | ^^^^^^^^^^^^^^^^^^^^^^ + > 5 | return 'hello' + | ^^^^^^^^^^^^^^^^^^^^^^ + > 6 | } + | ^^^^^^^^^ use server in class not supported + 7 | + 8 | static staticMethod() { + 9 | 'use server'] + `) + expect(() => + compileDirectives({ + ...serverConfig, + code, + filename: serverConfig.filename + `?tsr-serverfn-split=temp`, + }), + ).toThrowErrorMatchingInlineSnapshot(` + [Error: 1 | + 2 | class TestClass { + > 3 | method() { + | ^^^^^^^^^^^ + > 4 | 'use server' + | ^^^^^^^^^^^^^^^^^^^^^^ + > 5 | return 'hello' + | ^^^^^^^^^^^^^^^^^^^^^^ + > 6 | } + | ^^^^^^^^^ use server in class not supported + 7 | + 8 | static staticMethod() { + 9 | 'use server'] `) }) - test('object methods', () => { + test('does not support object methods', () => { const code = ` const obj = { method() { @@ -156,71 +458,59 @@ describe('server function compilation', () => { } ` - const client = compileServerFnClient({ ...clientConfig, code }) - expect(client.compiledCode.code).toMatchInlineSnapshot(` - "import { createClientRpc } from "my-rpc-lib"; - const obj = { - method(...args) { - return createClientRpc({ - filename: "test.ts", - functionId: "test--obj_method" - })(...args); - } - };" + expect(() => compileDirectives({ ...clientConfig, code })) + .toThrowErrorMatchingInlineSnapshot(` + [Error: 1 | + 2 | const obj = { + > 3 | method() { + | ^^^^^^^^^^^ + > 4 | 'use server' + | ^^^^^^^^^^^^^^^^^^^^^^ + > 5 | return 'hello' + | ^^^^^^^^^^^^^^^^^^^^^^ + > 6 | }, + | ^^^^^^^^^ use server in object method not supported + 7 | } + 8 | ] `) - - const server = compileServerFnServer({ ...serverConfig, code }) - expect(server.compiledCode.code).toMatchInlineSnapshot(` - "const obj = { - method(...args) { - return import("test.ts?tsr-serverfn-split=test--obj_method").then(mod => mod.serverFn(...args)); - } - };" + expect(() => compileDirectives({ ...serverConfig, code })) + .toThrowErrorMatchingInlineSnapshot(` + [Error: 1 | + 2 | const obj = { + > 3 | method() { + | ^^^^^^^^^^^ + > 4 | 'use server' + | ^^^^^^^^^^^^^^^^^^^^^^ + > 5 | return 'hello' + | ^^^^^^^^^^^^^^^^^^^^^^ + > 6 | }, + | ^^^^^^^^^ use server in object method not supported + 7 | } + 8 | ] + `) + expect(() => + compileDirectives({ + ...serverConfig, + code, + filename: serverConfig.filename + `?tsr-serverfn-split=temp`, + }), + ).toThrowErrorMatchingInlineSnapshot(` + [Error: 1 | + 2 | const obj = { + > 3 | method() { + | ^^^^^^^^^^^ + > 4 | 'use server' + | ^^^^^^^^^^^^^^^^^^^^^^ + > 5 | return 'hello' + | ^^^^^^^^^^^^^^^^^^^^^^ + > 6 | }, + | ^^^^^^^^^ use server in object method not supported + 7 | } + 8 | ] `) }) - test('async functions', () => { - const code = ` - async function asyncServer() { - 'use server' - return 'hello' - } - - const asyncArrow = async () => { - 'use server' - return 'hello' - } - ` - - const client = compileServerFnClient({ ...clientConfig, code }) - expect(client.compiledCode.code).toMatchInlineSnapshot(` - "import { createClientRpc } from "my-rpc-lib"; - async function asyncServer(...args) { - return createClientRpc({ - filename: "test.ts", - functionId: "test--asyncServer" - })(...args); - } - const asyncArrow = async (...args) => { - return createClientRpc({ - filename: "test.ts", - functionId: "test--asyncArrow_1" - })(...args); - };" - `) - - const server = compileServerFnServer({ ...serverConfig, code }) - expect(server.compiledCode.code).toMatchInlineSnapshot(` - "async function asyncServer(...args) { - return import("test.ts?tsr-serverfn-split=test--asyncServer").then(mod => mod.serverFn(...args)); - } - const asyncArrow = async (...args) => { - return import("test.ts?tsr-serverfn-split=test--asyncArrow_1").then(mod => mod.serverFn(...args)); - };" - `) - }) - - test('generator functions', () => { + test('does not support generator functions', () => { const code = ` function* generatorServer() { 'use server' @@ -233,67 +523,55 @@ describe('server function compilation', () => { } ` - const client = compileServerFnClient({ ...clientConfig, code }) - expect(client.compiledCode.code).toMatchInlineSnapshot(` - "import { createClientRpc } from "my-rpc-lib"; - function* generatorServer(...args) { - return createClientRpc({ - filename: "test.ts", - functionId: "test--generatorServer" - })(...args); - } - async function* asyncGeneratorServer(...args) { - return createClientRpc({ - filename: "test.ts", - functionId: "test--asyncGeneratorServer" - })(...args); - }" + expect(() => compileDirectives({ ...clientConfig, code })) + .toThrowErrorMatchingInlineSnapshot(` + [Error: 1 | + > 2 | function* generatorServer() { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + > 3 | 'use server' + | ^^^^^^^^^^^^^^^^^^^^ + > 4 | yield 'hello' + | ^^^^^^^^^^^^^^^^^^^^ + > 5 | } + | ^^^^^^^ use server in generator function not supported + 6 | + 7 | async function* asyncGeneratorServer() { + 8 | 'use server'] `) - - const server = compileServerFnServer({ ...serverConfig, code }) - expect(server.compiledCode.code).toMatchInlineSnapshot(` - "function* generatorServer(...args) { - return import("test.ts?tsr-serverfn-split=test--generatorServer").then(mod => mod.serverFn(...args)); - } - async function* asyncGeneratorServer(...args) { - return import("test.ts?tsr-serverfn-split=test--asyncGeneratorServer").then(mod => mod.serverFn(...args)); - }" + expect(() => compileDirectives({ ...serverConfig, code })) + .toThrowErrorMatchingInlineSnapshot(` + [Error: 1 | + > 2 | function* generatorServer() { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + > 3 | 'use server' + | ^^^^^^^^^^^^^^^^^^^^ + > 4 | yield 'hello' + | ^^^^^^^^^^^^^^^^^^^^ + > 5 | } + | ^^^^^^^ use server in generator function not supported + 6 | + 7 | async function* asyncGeneratorServer() { + 8 | 'use server'] `) - }) - - test('nested functions', () => { - const code = ` - function outer() { - function inner() { - 'use server' - return 'hello' - } - return inner - } - ` - - const client = compileServerFnClient({ ...clientConfig, code }) - expect(client.compiledCode.code).toMatchInlineSnapshot(` - "import { createClientRpc } from "my-rpc-lib"; - function outer() { - function inner(...args) { - return createClientRpc({ - filename: "test.ts", - functionId: "test--outer_inner" - })(...args); - } - return inner; - }" - `) - - const server = compileServerFnServer({ ...serverConfig, code }) - expect(server.compiledCode.code).toMatchInlineSnapshot(` - "function outer() { - function inner(...args) { - return import("test.ts?tsr-serverfn-split=test--outer_inner").then(mod => mod.serverFn(...args)); - } - return inner; - }" + expect(() => + compileDirectives({ + ...serverConfig, + code, + filename: serverConfig.filename + `?tsr-serverfn-split=temp`, + }), + ).toThrowErrorMatchingInlineSnapshot(` + [Error: 1 | + > 2 | function* generatorServer() { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + > 3 | 'use server' + | ^^^^^^^^^^^^^^^^^^^^ + > 4 | yield 'hello' + | ^^^^^^^^^^^^^^^^^^^^ + > 5 | } + | ^^^^^^^ use server in generator function not supported + 6 | + 7 | async function* asyncGeneratorServer() { + 8 | 'use server'] `) }) @@ -306,53 +584,39 @@ describe('server function compilation', () => { } ` - const client = compileServerFnClient({ ...clientConfig, code }) - expect(client.compiledCode.code).toMatchInlineSnapshot(` - "import { createClientRpc } from "my-rpc-lib"; - function multiDirective(...args) { - 'use strict'; + const client = compileDirectives({ ...clientConfig, code }) + const ssr = compileDirectives({ ...serverConfig, code }) + const splitFiles = Object.entries(ssr.serverFns) + .map(([_fnId, serverFn]) => { + return `// ${serverFn.functionName}\n\n${ + compileDirectives({ + ...serverConfig, + code, + filename: serverFn.splitFileId, + }).compiledResult.code + }` + }) + .join('\n\n\n') - return createClientRpc({ - filename: "test.ts", - functionId: "test--multiDirective" - })(...args); - }" + expect(client.compiledResult.code).toMatchInlineSnapshot(` + "import { createClientRpc } from "my-rpc-lib-client"; + createClientRpc({ + filename: "test.ts", + functionId: "test--multiDirective" + });" `) - - const server = compileServerFnServer({ ...serverConfig, code }) - expect(server.compiledCode.code).toMatchInlineSnapshot(` - "function multiDirective(...args) { - 'use strict'; - - return import("test.ts?tsr-serverfn-split=test--multiDirective").then(mod => mod.serverFn(...args)); - }" + expect(ssr.compiledResult.code).toMatchInlineSnapshot(` + "import { createServerRpc } from "my-rpc-lib-server"; + createServerRpc({ + fn: (...args) => import("test.ts?tsr-serverfn-split=test--multiDirective").then(module => module.default(...args)), + filename: "test.ts", + functionId: "test--multiDirective" + });" `) - }) + expect(splitFiles).toMatchInlineSnapshot(` + "// multiDirective - test('function with parameters', () => { - const code = ` - function withParams(a: string, b: number) { - 'use server' - return \`\${a} \${b}\` - } - ` - - const client = compileServerFnClient({ ...clientConfig, code }) - expect(client.compiledCode.code).toMatchInlineSnapshot(` - "import { createClientRpc } from "my-rpc-lib"; - function withParams(...args) { - return createClientRpc({ - filename: "test.ts", - functionId: "test--withParams" - })(...args); - }" - `) - - const server = compileServerFnServer({ ...serverConfig, code }) - expect(server.compiledCode.code).toMatchInlineSnapshot(` - "function withParams(...args) { - return import("test.ts?tsr-serverfn-split=test--withParams").then(mod => mod.serverFn(...args)); - }" + export default multiDirective_1;" `) }) @@ -364,114 +628,138 @@ describe('server function compilation', () => { })() ` - const client = compileServerFnClient({ ...clientConfig, code }) - expect(client.compiledCode.code).toMatchInlineSnapshot(` - "import { createClientRpc } from "my-rpc-lib"; - const iife = function (...args) { - return createClientRpc({ - filename: "test.ts", - functionId: "test--iife" - })(...args); - }();" + const client = compileDirectives({ ...clientConfig, code }) + const ssr = compileDirectives({ ...serverConfig, code }) + const splitFiles = Object.entries(ssr.serverFns) + .map(([_fnId, serverFn]) => { + return `// ${serverFn.functionName}\n\n${ + compileDirectives({ + ...serverConfig, + code, + filename: serverFn.splitFileId, + }).compiledResult.code + }` + }) + .join('\n\n\n') + + expect(client.compiledResult.code).toMatchInlineSnapshot(` + "import { createClientRpc } from "my-rpc-lib-client"; + const iife_1 = createClientRpc({ + filename: "test.ts", + functionId: "test--iife" + }); + const iife = iife_1();" `) - const server = compileServerFnServer({ ...serverConfig, code }) - expect(server.compiledCode.code).toMatchInlineSnapshot(` - "const iife = function (...args) { - return import("test.ts?tsr-serverfn-split=test--iife").then(mod => mod.serverFn(...args)); - }();" - `) - }) - - test('higher order functions', () => { - const code = ` - function higherOrder() { - return function () { - 'use server' - return 'hello' - } - } - ` - - const client = compileServerFnClient({ ...clientConfig, code }) - expect(client.compiledCode.code).toMatchInlineSnapshot(` - "import { createClientRpc } from "my-rpc-lib"; - function higherOrder() { - return function (...args) { - return createClientRpc({ - filename: "test.ts", - functionId: "test--higherOrder" - })(...args); - }; - }" + expect(ssr.compiledResult.code).toMatchInlineSnapshot(` + "import { createServerRpc } from "my-rpc-lib-server"; + const iife_1 = createServerRpc({ + fn: (...args) => import("test.ts?tsr-serverfn-split=test--iife").then(module => module.default(...args)), + filename: "test.ts", + functionId: "test--iife" + }); + const iife = iife_1();" `) - const server = compileServerFnServer({ ...serverConfig, code }) - expect(server.compiledCode.code).toMatchInlineSnapshot(` - "function higherOrder() { - return function (...args) { - return import("test.ts?tsr-serverfn-split=test--higherOrder").then(mod => mod.serverFn(...args)); - }; - }" + expect(splitFiles).toMatchInlineSnapshot(` + "// iife + + const iife_1 = function () { + return 'hello'; + }; + export default iife_1;" `) }) test('functions that might have the same functionId', () => { const code = ` - function main() { - function middle() { - const useServer = function () { - 'use server' - return 'hello' - } - return useServer - } - return middle - } + outer(function useServer() { + 'use server' + return 'hello' + }) - main().middle(function useServer() { + outer(function useServer() { 'use server' return 'hello' }) ` - const client = compileServerFnClient({ ...clientConfig, code }) - expect(client.compiledCode.code).toMatchInlineSnapshot(` - "import { createClientRpc } from "my-rpc-lib"; - function main() { - function middle() { - const useServer = function (...args) { - return createClientRpc({ - filename: "test.ts", - functionId: "test--main_middle_useServer_1" - })(...args); - }; - return useServer; - } - return middle; - } - main().middle(function useServer(...args) { - return createClientRpc({ - filename: "test.ts", - functionId: "test--main_middle_useServer_2" - })(...args); - });" + const client = compileDirectives({ ...clientConfig, code }) + const ssr = compileDirectives({ ...serverConfig, code }) + console.log('serverFns', ssr.serverFns) + const splitFiles = Object.entries(ssr.serverFns) + .map(([_fnId, serverFn]) => { + return `// ${serverFn.functionName}\n\n${ + compileDirectives({ + ...serverConfig, + code, + filename: serverFn.splitFileId, + }).compiledResult.code + }` + }) + .join('\n\n\n') + + expect(client.compiledResult.code).toMatchInlineSnapshot(` + "import { createClientRpc } from "my-rpc-lib-client"; + const outer_useServer_2 = createClientRpc({ + filename: "test.ts", + functionId: "test--outer_useServer" + }); + outer(outer_useServer_2); + const outer_useServer_3 = createClientRpc({ + filename: "test.ts", + functionId: "test--outer_useServer_1" + }); + outer(outer_useServer_3);" `) - const server = compileServerFnServer({ ...serverConfig, code }) - expect(server.compiledCode.code).toMatchInlineSnapshot(` - "function main() { - function middle() { - const useServer = function (...args) { - return import("test.ts?tsr-serverfn-split=test--main_middle_useServer_1").then(mod => mod.serverFn(...args)); - }; - return useServer; - } - return middle; - } - main().middle(function useServer(...args) { - return import("test.ts?tsr-serverfn-split=test--main_middle_useServer_2").then(mod => mod.serverFn(...args)); - });" + expect(ssr.compiledResult.code).toMatchInlineSnapshot(` + "import { createServerRpc } from "my-rpc-lib-server"; + const outer_useServer_2 = createServerRpc({ + fn: (...args) => import("test.ts?tsr-serverfn-split=test--outer_useServer").then(module => module.default(...args)), + filename: "test.ts", + functionId: "test--outer_useServer" + }); + outer(outer_useServer_2); + const outer_useServer_3 = createServerRpc({ + fn: (...args) => import("test.ts?tsr-serverfn-split=test--outer_useServer_1").then(module => module.default(...args)), + filename: "test.ts", + functionId: "test--outer_useServer_1" + }); + outer(outer_useServer_3);" + `) + + expect(splitFiles).toMatchInlineSnapshot(` + "// outer_useServer + + import { createServerRpc } from "my-rpc-lib-server"; + const outer_useServer_2 = function useServer() { + return 'hello'; + }; + outer(outer_useServer_2); + const outer_useServer_3 = createServerRpc({ + fn: (...args) => import("test.ts?tsr-serverfn-split=test--outer_useServer_1").then(module => module.default(...args)), + filename: "test.ts", + functionId: "test--outer_useServer_1" + }); + outer(outer_useServer_3); + export default outer_useServer_2; + + + // outer_useServer + + import { createServerRpc } from "my-rpc-lib-server"; + const outer_useServer_2 = createServerRpc({ + fn: (...args) => import("test.ts?tsr-serverfn-split=test--outer_useServer").then(module => module.default(...args)), + filename: "test.ts", + functionId: "test--outer_useServer" + }); + outer(outer_useServer_2); + const outer_useServer_3 = function useServer() { + return 'hello'; + }; + outer(outer_useServer_3); + export default outer_useServer_3;" `) }) }) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2269a73f44..f7c941e7cf 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -3552,6 +3552,9 @@ importers: chalk: specifier: ^5.3.0 version: 5.3.0 + dedent: + specifier: ^1.5.3 + version: 1.5.3 diff: specifier: ^7.0.0 version: 7.0.0 @@ -7209,6 +7212,14 @@ packages: decimal.js@10.4.3: resolution: {integrity: sha512-VBBaLc1MgL5XpzgIP7ny5Z6Nx3UrRkIViUkPUdtl9aya5amy3De1gsUUSB1g3+3sExYNjCAsAznmukyxCb1GRA==} + dedent@1.5.3: + resolution: {integrity: sha512-NHQtfOOW68WD8lgypbLA5oT+Bt0xXJhiYvoR6SmmNXZfpzOGXwdKWmcwG8N7PwVVWV3eF/68nmD9BaJSsTBhyQ==} + peerDependencies: + babel-plugin-macros: ^3.1.0 + peerDependenciesMeta: + babel-plugin-macros: + optional: true + deep-eql@5.0.2: resolution: {integrity: sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==} engines: {node: '>=6'} @@ -14379,6 +14390,8 @@ snapshots: decimal.js@10.4.3: {} + dedent@1.5.3: {} + deep-eql@5.0.2: {} deep-is@0.1.4: {} From 9e2d9cc4a7d44c5738197234b5a985d4d18b38ec Mon Sep 17 00:00:00 2001 From: Tanner Linsley Date: Thu, 19 Dec 2024 17:16:59 -0700 Subject: [PATCH 09/13] checkpoint --- .../server-functions-vite-plugin/package.json | 4 +- .../src/compilers.ts | 494 ++++++++++-------- .../server-functions-vite-plugin/src/index.ts | 193 ++++--- .../tests/compiler.test.ts | 413 +++++++++------ packages/start/package.json | 2 +- packages/start/src/client-runtime/index.tsx | 2 +- packages/start/src/config/index.ts | 6 +- packages/start/src/server-runtime/index.tsx | 2 +- .../start/src/server/defaultStreamHandler.tsx | 4 +- packages/start/src/ssr-runtime/index.tsx | 2 +- pnpm-lock.yaml | 8 +- 11 files changed, 664 insertions(+), 466 deletions(-) diff --git a/packages/server-functions-vite-plugin/package.json b/packages/server-functions-vite-plugin/package.json index dd6f839ff9..831a76d956 100644 --- a/packages/server-functions-vite-plugin/package.json +++ b/packages/server-functions-vite-plugin/package.json @@ -1,5 +1,5 @@ { - "name": "@tanstack/server-functions-plugin", + "name": "@tanstack/directive-functions-plugin", "version": "1.87.3", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", @@ -7,7 +7,7 @@ "repository": { "type": "git", "url": "https://github.com/TanStack/router.git", - "directory": "packages/server-functions-plugin" + "directory": "packages/directive-functions-plugin" }, "homepage": "https://tanstack.com/start", "funding": { diff --git a/packages/server-functions-vite-plugin/src/compilers.ts b/packages/server-functions-vite-plugin/src/compilers.ts index 70ecafcb73..120f30c0fb 100644 --- a/packages/server-functions-vite-plugin/src/compilers.ts +++ b/packages/server-functions-vite-plugin/src/compilers.ts @@ -14,7 +14,7 @@ if ('default' in generate) { generate = generate.default as typeof generate } -export interface ServerFunctionInfo { +export interface DirectiveFn { nodePath: SupportedFunctionPath functionName: string functionId: string @@ -38,61 +38,56 @@ export type ReplacerFn = (opts: { export type CompileDirectivesOpts = ParseAstOptions & { directive: string + directiveLabel: string getRuntimeCode?: (opts: { - serverFnPathsByFunctionId: Record + directiveFnsById: Record }) => string replacer: ReplacerFn } -const tsrServerFnSplitParam = 'tsr-serverfn-split' - export function compileDirectives(opts: CompileDirectivesOpts) { const [_, searchParamsStr] = opts.filename.split('?') const searchParams = new URLSearchParams(searchParamsStr) - const functionId = searchParams.get(tsrServerFnSplitParam) + const directiveSplitParam = `tsr-directive-${opts.directive.replace(/[^a-zA-Z0-9]/g, '-')}-split` + const functionId = searchParams.get(directiveSplitParam) const ast = parseAst(opts) - const serverFnPathsByFunctionId = findServerFunctions(ast, { + const directiveFnsById = findDirectives(ast, { ...opts, splitFunctionId: functionId, + directiveSplitParam, }) - // Add runtime code if there are server functions - // Add runtime code if there are server functions - if ( - Object.keys(serverFnPathsByFunctionId).length > 0 && - opts.getRuntimeCode - ) { + // Add runtime code if there are directives + // Add runtime code if there are directives + if (Object.keys(directiveFnsById).length > 0 && opts.getRuntimeCode) { const runtimeImport = babel.template.statement( - opts.getRuntimeCode({ serverFnPathsByFunctionId }), + opts.getRuntimeCode({ directiveFnsById }), )() ast.program.body.unshift(runtimeImport) } // If there is a functionId, we need to remove all exports // then make sure that our function is exported under the - // "serverFn" name + // directive name if (functionId) { - const serverFn = serverFnPathsByFunctionId[functionId] + const directiveFn = directiveFnsById[functionId] - if (!serverFn) { - throw new Error(`Server function ${functionId} not found`) + if (!directiveFn) { + throw new Error(`${opts.directiveLabel} ${functionId} not found`) } - console.log('functionId', functionId) safeRemoveExports(ast) ast.program.body.push( babel.types.exportDefaultDeclaration( - babel.types.identifier(serverFn.referenceName), + babel.types.identifier(directiveFn.referenceName), ), ) - - // If we have a functionId, we're also going to DCE the file - // so that the functionId is not exported - deadCodeElimination(ast) } + deadCodeElimination(ast) + const compiledResult = generate(ast, { sourceMaps: true, sourceFileName: opts.filename, @@ -101,11 +96,14 @@ export function compileDirectives(opts: CompileDirectivesOpts) { return { compiledResult, - serverFns: serverFnPathsByFunctionId, + directiveFnsById, } } -function findNearestVariableName(path: babel.NodePath): string { +function findNearestVariableName( + path: babel.NodePath, + directiveLabel: string, +): string { let currentPath: babel.NodePath | null = path const nameParts: Array = [] @@ -174,7 +172,7 @@ function findNearestVariableName(path: babel.NodePath): string { babel.types.isObjectMethod(currentPath.node) ) { throw new Error( - 'use server in ClassMethod or ObjectMethod not supported', + `${directiveLabel} in ClassMethod or ObjectMethod not supported`, ) } @@ -207,16 +205,18 @@ function makeIdentifierSafe(identifier: string): string { .replace(/^_|_$/g, '') // Trim leading/trailing underscores } -export function findServerFunctions( +export function findDirectives( ast: babel.types.File, opts: ParseAstOptions & { + directive: string + directiveLabel: string replacer?: ReplacerFn splitFunctionId?: string | null + directiveSplitParam: string }, ) { - const serverFnPathsByFunctionId: Record = {} + const directiveFnsById: Record = {} const functionIdCounts: Record = {} - const referenceCounts: Map = new Map() let programPath: babel.NodePath @@ -226,215 +226,247 @@ export function findServerFunctions( }, }) - // Find all server functions - babel.traverse(ast, { - DirectiveLiteral(nodePath) { - if (nodePath.node.value === 'use server') { - let directiveFn = nodePath.findParent((p) => p.isFunction()) as - | SupportedFunctionPath - | undefined + // Does the file have the directive in the program body? + const hasFileDirective = ast.program.directives.some( + (directive) => directive.value.value === opts.directive, + ) - if (!directiveFn) return - - // Handle class and object methods which are not supported - const isGenerator = - directiveFn.isFunction() && directiveFn.node.generator - - const isClassMethod = directiveFn.isClassMethod() - const isObjectMethod = directiveFn.isObjectMethod() - - if (isClassMethod || isObjectMethod || isGenerator) { - throw codeFrameError( - opts.code, - directiveFn.node.loc, - `use server in ${isClassMethod ? 'class' : isObjectMethod ? 'object method' : 'generator function'} not supported`, - ) + // 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) } + }, + ExportNamedDeclaration(path) { + if (babel.types.isFunctionDeclaration(path.node.declaration)) { + compileDirective(path.get('declaration') as SupportedFunctionPath) + } + }, + }) + } else { + // Find all directives + babel.traverse(ast, { + DirectiveLiteral(nodePath) { + if (nodePath.node.value === opts.directive) { + const directiveFn = nodePath.findParent((p) => p.isFunction()) as + | SupportedFunctionPath + | undefined - // 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 (!directiveFn) return + + // Handle class and object methods which are not supported + const isGenerator = + directiveFn.isFunction() && directiveFn.node.generator + + const isClassMethod = directiveFn.isClassMethod() + const isObjectMethod = directiveFn.isObjectMethod() + + if (isClassMethod || isObjectMethod || isGenerator) { + throw codeFrameError( + opts.code, + directiveFn.node.loc, + `"${opts.directive}" in ${isClassMethod ? 'class' : isObjectMethod ? 'object method' : 'generator function'} 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.directiveLabel}s 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.directiveLabel}s must be function declarations or function expressions`, + ) + } + + compileDirective(directiveFn) + } + }, + }) + } + + return directiveFnsById + + function compileDirective(directiveFn: SupportedFunctionPath) { + // 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, + ) + } + + // Find the nearest variable name + const fnName = findNearestVariableName(directiveFn, opts.directiveLabel) + + // Make the functionId safe for use in a URL + const baseLabel = makeFileLocationUrlSafe( + `${opts.filename.replace( + path.extname(opts.filename), + '', + )}--${fnName}`.replace(opts.root, ''), + ) + + // Count the number of functions with the same baseLabel + functionIdCounts[baseLabel] = (functionIdCounts[baseLabel] || 0) + 1 + + // If there are multiple functions with the same baseLabel, + // append a unique identifier to the functionId + const functionId = + functionIdCounts[baseLabel] > 1 + ? `${baseLabel}_${functionIdCounts[baseLabel] - 1}` + : baseLabel + + // Move the function to program level while preserving its position + // in the program body + const programBody = programPath.node.body + + const topParent = + directiveFn.findParent((p) => !!p.parentPath?.isProgram()) || directiveFn + + const topParentIndex = programBody.indexOf(topParent.node as any) + + // Determine the reference name for the function + let referenceName = makeIdentifierSafe(fnName) + + // Crawl the scope to refresh all the bindings + programPath.scope.crawl() + + // If we find this referece in the scope, we need to make it unique + while (programPath.scope.hasBinding(referenceName)) { + const [realReferenceName, count] = referenceName.split(/_(\d+)$/) + referenceName = realReferenceName + `_${Number(count || '0') + 1}` + } + + // if (referenceCounts.get(referenceName) === 0) { + + // referenceName += `_${(referenceCounts.get(referenceName) || 0) + 1}` + + // If the reference name came from the function declaration, + // // We need to update the function name to match the reference name + // if (babel.types.isFunctionDeclaration(directiveFn.node)) { + // console.log('updating function name', directiveFn.node.id!.name) + // directiveFn.node.id!.name = referenceName + // } + + // 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()) { + // Then place the function at the top level + programBody.splice( + topParentIndex, + 0, + babel.types.variableDeclaration('const', [ + babel.types.variableDeclarator( + babel.types.identifier(referenceName), + babel.types.toExpression(directiveFn.node as any), + ), + ]), + ) + + // If it's an exported named function, we need to swap it with an + // export const originalFunctionName = referenceName + if ( + babel.types.isExportNamedDeclaration(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(referenceName), + ), + ]), + ), ) - if (nearestBlock) { - throw codeFrameError( - opts.code, - nearestBlock.node.loc, - 'Server functions cannot be nested in other blocks or functions', - ) - } - - // Handle supported function types - if ( - directiveFn.isFunctionDeclaration() || - directiveFn.isFunctionExpression() || - (directiveFn.isArrowFunctionExpression() && - babel.types.isBlockStatement(directiveFn.node.body)) - ) { - // Remove the 'use server' 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 !== 'use server', - ) - } - - // Find the nearest variable name - const fnName = findNearestVariableName(directiveFn) - - // Make the functionId safe for use in a URL - const baseLabel = makeFileLocationUrlSafe( - `${opts.filename.replace( - path.extname(opts.filename), - '', - )}--${fnName}`.replace(opts.root, ''), - ) - - // Count the number of functions with the same baseLabel - functionIdCounts[baseLabel] = (functionIdCounts[baseLabel] || 0) + 1 - - // If there are multiple functions with the same baseLabel, - // append a unique identifier to the functionId - const functionId = - functionIdCounts[baseLabel] > 1 - ? `${baseLabel}_${functionIdCounts[baseLabel] - 1}` - : baseLabel - - // Move the function to program level while preserving its position - // in the program body - const programBody = programPath.node.body - - const topParent = - directiveFn.findParent((p) => !!p.parentPath?.isProgram()) || - directiveFn - - const topParentIndex = programBody.indexOf(topParent.node as any) - - // Determine the reference name for the function - let referenceName = makeIdentifierSafe(fnName) - - // If we find this referece in the scope, we need to make it unique - while (programPath.scope.hasBinding(referenceName)) { - referenceCounts.set( - referenceName, - (referenceCounts.get(referenceName) || 0) + 1, - ) - referenceName += `_${referenceCounts.get(referenceName) || 0}` - } - - // if (referenceCounts.get(referenceName) === 0) { - - // referenceName += `_${(referenceCounts.get(referenceName) || 0) + 1}` - - // If the reference name came from the function declaration, - // // We need to update the function name to match the reference name - // if (babel.types.isFunctionDeclaration(directiveFn.node)) { - // console.log('updating function name', directiveFn.node.id!.name) - // directiveFn.node.id!.name = referenceName - // } - - // 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()) { - // Then place the function at the top level - programBody.splice( - topParentIndex, - 0, - babel.types.variableDeclaration('const', [ - babel.types.variableDeclarator( - babel.types.identifier(referenceName), - babel.types.toExpression(directiveFn.node as any), - ), - ]), - ) - - // If it's an exported named function, we need to swap it with an - // export const originalFunctionName = referenceName - if ( - babel.types.isExportNamedDeclaration( - 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(referenceName), - ), - ]), - ), - ) - - directiveFn.remove() - } else { - directiveFn.replaceWith(babel.types.identifier(referenceName)) - } - - directiveFn = programPath.get( - `body.${topParentIndex}.declarations.0.init`, - ) as SupportedFunctionPath - } - - const [filename, searchParamsStr] = opts.filename.split('?') - - const searchParams = new URLSearchParams(searchParamsStr) - searchParams.set('tsr-serverfn-split', functionId) - const splitFileId = `${filename}?${searchParams.toString()}` - - // If a replacer is provided, replace the function with the replacer - if (functionId !== opts.splitFunctionId && opts.replacer) { - const replacer = opts.replacer({ - fn: '$$fn$$', - splitImportFn: '$$splitImportFn$$', - // splitFileId, - filename: filename!, - functionId: functionId, - }) - - const replacement = babel.template.expression(replacer, { - placeholderPattern: false, - placeholderWhitelist: new Set(['$$fn$$', '$$splitImportFn$$']), - })({ - ...(replacer.includes('$$fn$$') - ? { $$fn$$: babel.types.toExpression(directiveFn.node) } - : {}), - ...(replacer.includes('$$splitImportFn$$') - ? { - $$splitImportFn$$: `(...args) => import(${JSON.stringify(splitFileId)}).then(module => module.default(...args))`, - } - : {}), - }) - - directiveFn.replaceWith(replacement) - } - - // Finally register the server function to - // our map of server functions - serverFnPathsByFunctionId[functionId] = { - nodePath: directiveFn, - referenceName, - functionName: fnName || '', - functionId: functionId, - splitFileId, - } - } + directiveFn.remove() + } else { + directiveFn.replaceWith(babel.types.identifier(referenceName)) } - }, - }) - return serverFnPathsByFunctionId + directiveFn = programPath.get( + `body.${topParentIndex}.declarations.0.init`, + ) as SupportedFunctionPath + } + + const [filename, searchParamsStr] = opts.filename.split('?') + + const searchParams = new URLSearchParams(searchParamsStr) + searchParams.set(opts.directiveSplitParam, functionId) + const splitFileId = `${filename}?${searchParams.toString()}` + + // If a replacer is provided, replace the function with the replacer + if (functionId !== opts.splitFunctionId && opts.replacer) { + const replacer = opts.replacer({ + fn: '$$fn$$', + splitImportFn: '$$splitImportFn$$', + // splitFileId, + filename: filename!, + functionId: functionId, + }) + + const replacement = babel.template.expression(replacer, { + placeholderPattern: false, + placeholderWhitelist: new Set(['$$fn$$', '$$splitImportFn$$']), + })({ + ...(replacer.includes('$$fn$$') + ? { $$fn$$: babel.types.toExpression(directiveFn.node) } + : {}), + ...(replacer.includes('$$splitImportFn$$') + ? { + $$splitImportFn$$: `(...args) => import(${JSON.stringify(splitFileId)}).then(module => module.default(...args))`, + } + : {}), + }) + + directiveFn.replaceWith(replacement) + } + + // Finally register the directive to + // our map of directives + directiveFnsById[functionId] = { + nodePath: directiveFn, + referenceName, + functionName: fnName || '', + functionId: functionId, + splitFileId, + } + } } function codeFrameError( diff --git a/packages/server-functions-vite-plugin/src/index.ts b/packages/server-functions-vite-plugin/src/index.ts index 12a710f138..8a96c502e9 100644 --- a/packages/server-functions-vite-plugin/src/index.ts +++ b/packages/server-functions-vite-plugin/src/index.ts @@ -2,81 +2,148 @@ import { fileURLToPath, pathToFileURL } from 'node:url' import { compileDirectives } from './compilers' import { logDiff } from './logger' -import type { ReplacerFn } from './compilers' +import type { CompileDirectivesOpts, DirectiveFn } from './compilers' import type { Plugin } from 'vite' const debug = Boolean(process.env.TSR_VITE_DEBUG) || (true as boolean) -export type ServerFunctionsViteOptions = { - getRuntimeCode: (opts: { - serverFnPathsByFunctionId: Record< - string, +export type ServerFunctionsViteOptions = Pick< + CompileDirectivesOpts, + 'directive' | 'directiveLabel' | 'getRuntimeCode' | 'replacer' +> + +export type CreateClientRpcFn = (functionId: string) => any +export type CreateSsrRpcFn = (functionId: string) => any +export type CreateServerRpcFn = ( + functionId: string, + splitImportFn: string, +) => any + +const createDirectiveRx = (directive: string) => + new RegExp(`"${directive}"|'${directive}'`, 'g') + +export function createTanStackServerFnPlugin( + opts: ServerFunctionsViteOptions, +): { + client: Array + ssr: Array + server: Array +} { + let directiveFnsById: Record = {} + + return { + client: [ + // The client plugin is used to compile the client directives + // and save them so we can create a manifest + TanStackDirectiveFunctionsPlugin({ + directive: 'use server', + directiveLabel: 'Server Function', + getRuntimeCode: () => + `import { createClientRpc } from '@tanstack/start/client-runtime'`, + replacer: (opts) => + // On the client, all we need is the function ID + `createClientRpc(${JSON.stringify(opts.functionId)})`, + onDirectiveFnsById: (d) => { + // When the client directives are compiled, save them so we + // can create a manifest + directiveFnsById = d + }, + }), + // Now that we have the directiveFnsById, we need to create a new + // virtual module that can be used to import that manifest { - nodePath: babel.NodePath - functionName: string - functionId: string - } - > - }) => string - replacer: ReplacerFn + name: 'tanstack-start-server-fn-vite-plugin-manifest', + resolveId: (id) => { + if (id === 'virtual:tanstack-start-server-fn-manifest') { + return JSON.stringify( + Object.fromEntries( + Object.entries(directiveFnsById).map(([id, fn]) => [ + id, + { + functionName: fn.functionName, + referenceName: fn.referenceName, + splitFileId: fn.splitFileId, + }, + ]), + ), + ) + } + + return null + }, + }, + ], + ssr: [ + // The SSR plugin is used to compile the server directives + TanStackDirectiveFunctionsPlugin({ + directive: 'use server', + directiveLabel: 'Server Function', + getRuntimeCode: () => + `import { createSsrRpc } from '@tanstack/start/ssr-runtime'`, + replacer: (opts) => + // During SSR, we just need the function ID since our server environment + // is split into a worker. Similar to the client, we'll use the ID + // to call into the worker using a local http event. + `createSsrRpc(${JSON.stringify(opts.functionId)})`, + }), + ], + server: [ + // On the server, we need to compile the server functions + // so they can be called by other server functions. + // This is also where we split the server function into a separate file + // so we can load them on demand in the worker. + TanStackDirectiveFunctionsPlugin({ + directive: 'use server', + directiveLabel: 'Server Function', + getRuntimeCode: () => + `import { createServerRpc } from '@tanstack/start/ssr-runtime'`, + replacer: (opts) => + // By using the provided splitImportFn, we can both trigger vite + // to create a new chunk/entry for the server function and also + // replace other function references to it with the import statement + `createServerRpc(${JSON.stringify(opts.functionId)}, ${JSON.stringify(opts.splitImportFn)})`, + }), + ], + } } -const useServerRx = /"use server"|'use server'/ - -export type CreateRpcFn = (opts: { - fn: (...args: Array) => any - filename: string - functionId: string -}) => (...args: Array) => any - -export function TanStackServerFnPluginRuntime( - opts: ServerFunctionsViteOptions, -): Array { +export function TanStackDirectiveFunctionsPlugin( + opts: ServerFunctionsViteOptions & { + onDirectiveFnsById?: (directiveFnsById: Record) => void + }, +): Plugin { let ROOT: string = process.cwd() - return [ - { - name: 'tanstack-start-server-fn-client-vite-plugin', - enforce: 'pre', - configResolved: (config) => { - ROOT = config.root - }, - transform(code, id) { - const url = pathToFileURL(id) - url.searchParams.delete('v') - id = fileURLToPath(url).replace(/\\/g, '/') + const directiveRx = createDirectiveRx(opts.directive) - if (!useServerRx.test(code)) { - return null - } - - const { compiledResult, serverFns } = compileDirectives({ - directive: 'use server', - code, - root: ROOT, - filename: id, - getRuntimeCode: opts.getRuntimeCode, - replacer: opts.replacer, - }) - - if (debug) console.info('createServerFn Input/Output') - if (debug) logDiff(code, compiledResult.code.replace(/ctx/g, 'blah')) - - return compiledResult - }, + return { + name: 'tanstack-start-directive-vite-plugin', + enforce: 'pre', + configResolved: (config) => { + ROOT = config.root }, - ] -} + transform(code, id) { + const url = pathToFileURL(id) + url.searchParams.delete('v') + id = fileURLToPath(url).replace(/\\/g, '/') -export function TanStackServerFnPluginSplitFn( - opts: ServerFunctionsViteOptions, -): Array { - return [ - { - name: 'tanstack-start-server-fn-server-vite-plugin', - transform(code, id) { + if (!directiveRx.test(code)) { return null - }, + } + + const { compiledResult, directiveFnsById } = compileDirectives({ + ...opts, + code, + root: ROOT, + filename: id, + }) + + opts.onDirectiveFnsById?.(directiveFnsById) + + if (debug) console.info('Directive Input/Output') + if (debug) logDiff(code, compiledResult.code.replace(/ctx/g, 'blah')) + + return compiledResult }, - ] + } } diff --git a/packages/server-functions-vite-plugin/tests/compiler.test.ts b/packages/server-functions-vite-plugin/tests/compiler.test.ts index dc62daee66..3fc16a059c 100644 --- a/packages/server-functions-vite-plugin/tests/compiler.test.ts +++ b/packages/server-functions-vite-plugin/tests/compiler.test.ts @@ -5,6 +5,7 @@ import type { CompileDirectivesOpts } from '../src/compilers' const clientConfig: Omit = { directive: 'use server', + directiveLabel: 'Server function', root: './test-files', filename: 'test.ts', getRuntimeCode: () => 'import { createClientRpc } from "my-rpc-lib-client"', @@ -17,6 +18,7 @@ const clientConfig: Omit = { const serverConfig: Omit = { directive: 'use server', + directiveLabel: 'Server function', root: './test-files', filename: 'test.ts', getRuntimeCode: () => 'import { createServerRpc } from "my-rpc-lib-server"', @@ -30,28 +32,28 @@ const serverConfig: Omit = { describe('server function compilation', () => { const code = ` - const namedFunction = wrapper(function namedFunction() { + export const namedFunction = wrapper(function namedFunction() { 'use server' return 'hello' }) - const arrowFunction = wrapper(() => { + export const arrowFunction = wrapper(() => { 'use server' return 'hello' }) - const anonymousFunction = wrapper(function () { + export const anonymousFunction = wrapper(function () { 'use server' return 'hello' }) - const multipleDirectives = function multipleDirectives() { + export const multipleDirectives = function multipleDirectives() { 'use server' 'use strict' return 'hello' } - const iife = (function () { + export const iife = (function () { 'use server' return 'hello' })() @@ -73,13 +75,21 @@ describe('server function compilation', () => { export const namedExportConst = () => { 'use server' + return usedFn() + } + + function usedFn() { + return 'hello' + } + + function unusedFn() { return 'hello' } const namedDefaultExport = 'namedDefaultExport' export default namedDefaultExport - export const usedButNotExported = 'usedButNotExported' + const usedButNotExported = 'usedButNotExported' const namedExport = 'namedExport' @@ -95,13 +105,13 @@ describe('server function compilation', () => { code, }) const ssr = compileDirectives({ ...serverConfig, code }) - const splitFiles = Object.entries(ssr.serverFns) - .map(([_fnId, serverFn]) => { - return `// ${serverFn.functionName}\n\n${ + const splitFiles = Object.entries(ssr.directives) + .map(([_fnId, directiveFn]) => { + return `// ${directiveFn.functionName}\n\n${ compileDirectives({ ...serverConfig, code, - filename: serverFn.splitFileId, + filename: directiveFn.splitFileId, }).compiledResult.code }` }) @@ -113,27 +123,27 @@ describe('server function compilation', () => { filename: "test.ts", functionId: "test--namedFunction_wrapper_namedFunction" }); - const namedFunction = wrapper(namedFunction_wrapper_namedFunction); + export const namedFunction = wrapper(namedFunction_wrapper_namedFunction); const arrowFunction_wrapper = createClientRpc({ filename: "test.ts", functionId: "test--arrowFunction_wrapper" }); - const arrowFunction = wrapper(arrowFunction_wrapper); + export const arrowFunction = wrapper(arrowFunction_wrapper); const anonymousFunction_wrapper = createClientRpc({ filename: "test.ts", functionId: "test--anonymousFunction_wrapper" }); - const anonymousFunction = wrapper(anonymousFunction_wrapper); + export const anonymousFunction = wrapper(anonymousFunction_wrapper); const multipleDirectives_multipleDirectives = createClientRpc({ filename: "test.ts", functionId: "test--multipleDirectives_multipleDirectives" }); - const multipleDirectives = multipleDirectives_multipleDirectives; + export const multipleDirectives = multipleDirectives_multipleDirectives; const iife_1 = createClientRpc({ filename: "test.ts", functionId: "test--iife" }); - const iife = iife_1(); + export const iife = iife_1(); const defaultExportFn_1 = createClientRpc({ filename: "test.ts", functionId: "test--defaultExportFn" @@ -156,7 +166,6 @@ describe('server function compilation', () => { export const namedExportConst = namedExportConst_1; const namedDefaultExport = 'namedDefaultExport'; export default namedDefaultExport; - export const usedButNotExported = 'usedButNotExported'; const namedExport = 'namedExport'; export { namedExport };" `) @@ -164,62 +173,61 @@ describe('server function compilation', () => { expect(ssr.compiledResult.code).toMatchInlineSnapshot(` "import { createServerRpc } from "my-rpc-lib-server"; const namedFunction_wrapper_namedFunction = createServerRpc({ - fn: (...args) => import("test.ts?tsr-serverfn-split=test--namedFunction_wrapper_namedFunction").then(module => module.default(...args)), + fn: (...args) => import("test.ts?tsr-directive-use-server-split=test--namedFunction_wrapper_namedFunction").then(module => module.default(...args)), filename: "test.ts", functionId: "test--namedFunction_wrapper_namedFunction" }); - const namedFunction = wrapper(namedFunction_wrapper_namedFunction); + export const namedFunction = wrapper(namedFunction_wrapper_namedFunction); const arrowFunction_wrapper = createServerRpc({ - fn: (...args) => import("test.ts?tsr-serverfn-split=test--arrowFunction_wrapper").then(module => module.default(...args)), + fn: (...args) => import("test.ts?tsr-directive-use-server-split=test--arrowFunction_wrapper").then(module => module.default(...args)), filename: "test.ts", functionId: "test--arrowFunction_wrapper" }); - const arrowFunction = wrapper(arrowFunction_wrapper); + export const arrowFunction = wrapper(arrowFunction_wrapper); const anonymousFunction_wrapper = createServerRpc({ - fn: (...args) => import("test.ts?tsr-serverfn-split=test--anonymousFunction_wrapper").then(module => module.default(...args)), + fn: (...args) => import("test.ts?tsr-directive-use-server-split=test--anonymousFunction_wrapper").then(module => module.default(...args)), filename: "test.ts", functionId: "test--anonymousFunction_wrapper" }); - const anonymousFunction = wrapper(anonymousFunction_wrapper); + export const anonymousFunction = wrapper(anonymousFunction_wrapper); const multipleDirectives_multipleDirectives = createServerRpc({ - fn: (...args) => import("test.ts?tsr-serverfn-split=test--multipleDirectives_multipleDirectives").then(module => module.default(...args)), + fn: (...args) => import("test.ts?tsr-directive-use-server-split=test--multipleDirectives_multipleDirectives").then(module => module.default(...args)), filename: "test.ts", functionId: "test--multipleDirectives_multipleDirectives" }); - const multipleDirectives = multipleDirectives_multipleDirectives; + export const multipleDirectives = multipleDirectives_multipleDirectives; const iife_1 = createServerRpc({ - fn: (...args) => import("test.ts?tsr-serverfn-split=test--iife").then(module => module.default(...args)), + fn: (...args) => import("test.ts?tsr-directive-use-server-split=test--iife").then(module => module.default(...args)), filename: "test.ts", functionId: "test--iife" }); - const iife = iife_1(); + export const iife = iife_1(); const defaultExportFn_1 = createServerRpc({ - fn: (...args) => import("test.ts?tsr-serverfn-split=test--defaultExportFn").then(module => module.default(...args)), + fn: (...args) => import("test.ts?tsr-directive-use-server-split=test--defaultExportFn").then(module => module.default(...args)), filename: "test.ts", functionId: "test--defaultExportFn" }); export default defaultExportFn_1; const namedExportFn_1 = createServerRpc({ - fn: (...args) => import("test.ts?tsr-serverfn-split=test--namedExportFn").then(module => module.default(...args)), + fn: (...args) => import("test.ts?tsr-directive-use-server-split=test--namedExportFn").then(module => module.default(...args)), filename: "test.ts", functionId: "test--namedExportFn" }); export const namedExportFn = namedExportFn_1; const exportedArrowFunction_wrapper = createServerRpc({ - fn: (...args) => import("test.ts?tsr-serverfn-split=test--exportedArrowFunction_wrapper").then(module => module.default(...args)), + fn: (...args) => import("test.ts?tsr-directive-use-server-split=test--exportedArrowFunction_wrapper").then(module => module.default(...args)), filename: "test.ts", functionId: "test--exportedArrowFunction_wrapper" }); export const exportedArrowFunction = wrapper(exportedArrowFunction_wrapper); const namedExportConst_1 = createServerRpc({ - fn: (...args) => import("test.ts?tsr-serverfn-split=test--namedExportConst").then(module => module.default(...args)), + fn: (...args) => import("test.ts?tsr-directive-use-server-split=test--namedExportConst").then(module => module.default(...args)), filename: "test.ts", functionId: "test--namedExportConst" }); export const namedExportConst = namedExportConst_1; const namedDefaultExport = 'namedDefaultExport'; export default namedDefaultExport; - export const usedButNotExported = 'usedButNotExported'; const namedExport = 'namedExport'; export { namedExport };" `) @@ -295,8 +303,11 @@ describe('server function compilation', () => { // namedExportConst const namedExportConst_1 = () => { - return 'hello'; + return usedFn(); }; + function usedFn() { + return 'hello'; + } export default namedExportConst_1;" `, ) @@ -395,36 +406,36 @@ describe('server function compilation', () => { expect(() => compileDirectives({ ...clientConfig, code })) .toThrowErrorMatchingInlineSnapshot(` - [Error: 1 | - 2 | class TestClass { - > 3 | method() { - | ^^^^^^^^^^^ - > 4 | 'use server' - | ^^^^^^^^^^^^^^^^^^^^^^ - > 5 | return 'hello' - | ^^^^^^^^^^^^^^^^^^^^^^ - > 6 | } - | ^^^^^^^^^ use server in class not supported - 7 | - 8 | static staticMethod() { - 9 | 'use server'] - `) + [Error: 1 | + 2 | class TestClass { + > 3 | method() { + | ^^^^^^^^^^^ + > 4 | 'use server' + | ^^^^^^^^^^^^^^^^^^^^^^ + > 5 | return 'hello' + | ^^^^^^^^^^^^^^^^^^^^^^ + > 6 | } + | ^^^^^^^^^ "use server" in class not supported + 7 | + 8 | static staticMethod() { + 9 | 'use server'] + `) expect(() => compileDirectives({ ...serverConfig, code })) .toThrowErrorMatchingInlineSnapshot(` - [Error: 1 | - 2 | class TestClass { - > 3 | method() { - | ^^^^^^^^^^^ - > 4 | 'use server' - | ^^^^^^^^^^^^^^^^^^^^^^ - > 5 | return 'hello' - | ^^^^^^^^^^^^^^^^^^^^^^ - > 6 | } - | ^^^^^^^^^ use server in class not supported - 7 | - 8 | static staticMethod() { - 9 | 'use server'] - `) + [Error: 1 | + 2 | class TestClass { + > 3 | method() { + | ^^^^^^^^^^^ + > 4 | 'use server' + | ^^^^^^^^^^^^^^^^^^^^^^ + > 5 | return 'hello' + | ^^^^^^^^^^^^^^^^^^^^^^ + > 6 | } + | ^^^^^^^^^ "use server" in class not supported + 7 | + 8 | static staticMethod() { + 9 | 'use server'] + `) expect(() => compileDirectives({ ...serverConfig, @@ -441,7 +452,7 @@ describe('server function compilation', () => { > 5 | return 'hello' | ^^^^^^^^^^^^^^^^^^^^^^ > 6 | } - | ^^^^^^^^^ use server in class not supported + | ^^^^^^^^^ "use server" in class not supported 7 | 8 | static staticMethod() { 9 | 'use server'] @@ -460,34 +471,34 @@ describe('server function compilation', () => { expect(() => compileDirectives({ ...clientConfig, code })) .toThrowErrorMatchingInlineSnapshot(` - [Error: 1 | - 2 | const obj = { - > 3 | method() { - | ^^^^^^^^^^^ - > 4 | 'use server' - | ^^^^^^^^^^^^^^^^^^^^^^ - > 5 | return 'hello' - | ^^^^^^^^^^^^^^^^^^^^^^ - > 6 | }, - | ^^^^^^^^^ use server in object method not supported - 7 | } - 8 | ] - `) + [Error: 1 | + 2 | const obj = { + > 3 | method() { + | ^^^^^^^^^^^ + > 4 | 'use server' + | ^^^^^^^^^^^^^^^^^^^^^^ + > 5 | return 'hello' + | ^^^^^^^^^^^^^^^^^^^^^^ + > 6 | }, + | ^^^^^^^^^ "use server" in object method not supported + 7 | } + 8 | ] + `) expect(() => compileDirectives({ ...serverConfig, code })) .toThrowErrorMatchingInlineSnapshot(` - [Error: 1 | - 2 | const obj = { - > 3 | method() { - | ^^^^^^^^^^^ - > 4 | 'use server' - | ^^^^^^^^^^^^^^^^^^^^^^ - > 5 | return 'hello' - | ^^^^^^^^^^^^^^^^^^^^^^ - > 6 | }, - | ^^^^^^^^^ use server in object method not supported - 7 | } - 8 | ] - `) + [Error: 1 | + 2 | const obj = { + > 3 | method() { + | ^^^^^^^^^^^ + > 4 | 'use server' + | ^^^^^^^^^^^^^^^^^^^^^^ + > 5 | return 'hello' + | ^^^^^^^^^^^^^^^^^^^^^^ + > 6 | }, + | ^^^^^^^^^ "use server" in object method not supported + 7 | } + 8 | ] + `) expect(() => compileDirectives({ ...serverConfig, @@ -504,7 +515,7 @@ describe('server function compilation', () => { > 5 | return 'hello' | ^^^^^^^^^^^^^^^^^^^^^^ > 6 | }, - | ^^^^^^^^^ use server in object method not supported + | ^^^^^^^^^ "use server" in object method not supported 7 | } 8 | ] `) @@ -525,34 +536,34 @@ describe('server function compilation', () => { expect(() => compileDirectives({ ...clientConfig, code })) .toThrowErrorMatchingInlineSnapshot(` - [Error: 1 | - > 2 | function* generatorServer() { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - > 3 | 'use server' - | ^^^^^^^^^^^^^^^^^^^^ - > 4 | yield 'hello' - | ^^^^^^^^^^^^^^^^^^^^ - > 5 | } - | ^^^^^^^ use server in generator function not supported - 6 | - 7 | async function* asyncGeneratorServer() { - 8 | 'use server'] - `) + [Error: 1 | + > 2 | function* generatorServer() { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + > 3 | 'use server' + | ^^^^^^^^^^^^^^^^^^^^ + > 4 | yield 'hello' + | ^^^^^^^^^^^^^^^^^^^^ + > 5 | } + | ^^^^^^^ "use server" in generator function not supported + 6 | + 7 | async function* asyncGeneratorServer() { + 8 | 'use server'] + `) expect(() => compileDirectives({ ...serverConfig, code })) .toThrowErrorMatchingInlineSnapshot(` - [Error: 1 | - > 2 | function* generatorServer() { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - > 3 | 'use server' - | ^^^^^^^^^^^^^^^^^^^^ - > 4 | yield 'hello' - | ^^^^^^^^^^^^^^^^^^^^ - > 5 | } - | ^^^^^^^ use server in generator function not supported - 6 | - 7 | async function* asyncGeneratorServer() { - 8 | 'use server'] - `) + [Error: 1 | + > 2 | function* generatorServer() { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + > 3 | 'use server' + | ^^^^^^^^^^^^^^^^^^^^ + > 4 | yield 'hello' + | ^^^^^^^^^^^^^^^^^^^^ + > 5 | } + | ^^^^^^^ "use server" in generator function not supported + 6 | + 7 | async function* asyncGeneratorServer() { + 8 | 'use server'] + `) expect(() => compileDirectives({ ...serverConfig, @@ -568,7 +579,7 @@ describe('server function compilation', () => { > 4 | yield 'hello' | ^^^^^^^^^^^^^^^^^^^^ > 5 | } - | ^^^^^^^ use server in generator function not supported + | ^^^^^^^ "use server" in generator function not supported 6 | 7 | async function* asyncGeneratorServer() { 8 | 'use server'] @@ -586,13 +597,13 @@ describe('server function compilation', () => { const client = compileDirectives({ ...clientConfig, code }) const ssr = compileDirectives({ ...serverConfig, code }) - const splitFiles = Object.entries(ssr.serverFns) - .map(([_fnId, serverFn]) => { - return `// ${serverFn.functionName}\n\n${ + const splitFiles = Object.entries(ssr.directives) + .map(([_fnId, directiveFn]) => { + return `// ${directiveFn.functionName}\n\n${ compileDirectives({ ...serverConfig, code, - filename: serverFn.splitFileId, + filename: directiveFn.splitFileId, }).compiledResult.code }` }) @@ -608,7 +619,7 @@ describe('server function compilation', () => { expect(ssr.compiledResult.code).toMatchInlineSnapshot(` "import { createServerRpc } from "my-rpc-lib-server"; createServerRpc({ - fn: (...args) => import("test.ts?tsr-serverfn-split=test--multiDirective").then(module => module.default(...args)), + fn: (...args) => import("test.ts?tsr-directive-use-server-split=test--multiDirective").then(module => module.default(...args)), filename: "test.ts", functionId: "test--multiDirective" });" @@ -622,7 +633,7 @@ describe('server function compilation', () => { test('IIFE', () => { const code = ` - const iife = (function () { + export const iife = (function () { 'use server' return 'hello' })() @@ -630,13 +641,13 @@ describe('server function compilation', () => { const client = compileDirectives({ ...clientConfig, code }) const ssr = compileDirectives({ ...serverConfig, code }) - const splitFiles = Object.entries(ssr.serverFns) - .map(([_fnId, serverFn]) => { - return `// ${serverFn.functionName}\n\n${ + const splitFiles = Object.entries(ssr.directives) + .map(([_fnId, directiveFn]) => { + return `// ${directiveFn.functionName}\n\n${ compileDirectives({ ...serverConfig, code, - filename: serverFn.splitFileId, + filename: directiveFn.splitFileId, }).compiledResult.code }` }) @@ -648,17 +659,17 @@ describe('server function compilation', () => { filename: "test.ts", functionId: "test--iife" }); - const iife = iife_1();" + export const iife = iife_1();" `) expect(ssr.compiledResult.code).toMatchInlineSnapshot(` "import { createServerRpc } from "my-rpc-lib-server"; const iife_1 = createServerRpc({ - fn: (...args) => import("test.ts?tsr-serverfn-split=test--iife").then(module => module.default(...args)), + fn: (...args) => import("test.ts?tsr-directive-use-server-split=test--iife").then(module => module.default(...args)), filename: "test.ts", functionId: "test--iife" }); - const iife = iife_1();" + export const iife = iife_1();" `) expect(splitFiles).toMatchInlineSnapshot(` @@ -686,14 +697,14 @@ describe('server function compilation', () => { const client = compileDirectives({ ...clientConfig, code }) const ssr = compileDirectives({ ...serverConfig, code }) - console.log('serverFns', ssr.serverFns) - const splitFiles = Object.entries(ssr.serverFns) - .map(([_fnId, serverFn]) => { - return `// ${serverFn.functionName}\n\n${ + + const splitFiles = Object.entries(ssr.directives) + .map(([_fnId, directiveFn]) => { + return `// ${directiveFn.functionName}\n\n${ compileDirectives({ ...serverConfig, code, - filename: serverFn.splitFileId, + filename: directiveFn.splitFileId, }).compiledResult.code }` }) @@ -701,65 +712,157 @@ describe('server function compilation', () => { expect(client.compiledResult.code).toMatchInlineSnapshot(` "import { createClientRpc } from "my-rpc-lib-client"; - const outer_useServer_2 = createClientRpc({ + const outer_useServer = createClientRpc({ filename: "test.ts", functionId: "test--outer_useServer" }); - outer(outer_useServer_2); - const outer_useServer_3 = createClientRpc({ + outer(outer_useServer); + const outer_useServer_1 = createClientRpc({ filename: "test.ts", functionId: "test--outer_useServer_1" }); - outer(outer_useServer_3);" + outer(outer_useServer_1);" `) expect(ssr.compiledResult.code).toMatchInlineSnapshot(` "import { createServerRpc } from "my-rpc-lib-server"; - const outer_useServer_2 = createServerRpc({ - fn: (...args) => import("test.ts?tsr-serverfn-split=test--outer_useServer").then(module => module.default(...args)), + const outer_useServer = createServerRpc({ + fn: (...args) => import("test.ts?tsr-directive-use-server-split=test--outer_useServer").then(module => module.default(...args)), filename: "test.ts", functionId: "test--outer_useServer" }); - outer(outer_useServer_2); - const outer_useServer_3 = createServerRpc({ - fn: (...args) => import("test.ts?tsr-serverfn-split=test--outer_useServer_1").then(module => module.default(...args)), + outer(outer_useServer); + const outer_useServer_1 = createServerRpc({ + fn: (...args) => import("test.ts?tsr-directive-use-server-split=test--outer_useServer_1").then(module => module.default(...args)), filename: "test.ts", functionId: "test--outer_useServer_1" }); - outer(outer_useServer_3);" + outer(outer_useServer_1);" `) expect(splitFiles).toMatchInlineSnapshot(` "// outer_useServer import { createServerRpc } from "my-rpc-lib-server"; - const outer_useServer_2 = function useServer() { + const outer_useServer = function useServer() { return 'hello'; }; - outer(outer_useServer_2); - const outer_useServer_3 = createServerRpc({ - fn: (...args) => import("test.ts?tsr-serverfn-split=test--outer_useServer_1").then(module => module.default(...args)), + outer(outer_useServer); + const outer_useServer_1 = createServerRpc({ + fn: (...args) => import("test.ts?tsr-directive-use-server-split=test--outer_useServer_1").then(module => module.default(...args)), filename: "test.ts", functionId: "test--outer_useServer_1" }); - outer(outer_useServer_3); - export default outer_useServer_2; + outer(outer_useServer_1); + export default outer_useServer; // outer_useServer import { createServerRpc } from "my-rpc-lib-server"; - const outer_useServer_2 = createServerRpc({ - fn: (...args) => import("test.ts?tsr-serverfn-split=test--outer_useServer").then(module => module.default(...args)), + const outer_useServer = createServerRpc({ + fn: (...args) => import("test.ts?tsr-directive-use-server-split=test--outer_useServer").then(module => module.default(...args)), filename: "test.ts", functionId: "test--outer_useServer" }); - outer(outer_useServer_2); - const outer_useServer_3 = function useServer() { + outer(outer_useServer); + const outer_useServer_1 = function useServer() { return 'hello'; }; - outer(outer_useServer_3); - export default outer_useServer_3;" + outer(outer_useServer_1); + export default outer_useServer_1;" + `) + }) + + test('use server directive in program body', () => { + const code = ` + 'use server' + + export function useServer() { + return usedInUseServer() + } + + function notExported() { + return 'hello' + } + + function usedInUseServer() { + return 'hello' + } + + export default function defaultExport() { + return 'hello' + } + ` + + const client = compileDirectives({ ...clientConfig, code }) + const ssr = compileDirectives({ ...serverConfig, code }) + const splitFiles = Object.entries(ssr.directives) + .map(([_fnId, directive]) => { + return `// ${directive.functionName}\n\n${ + compileDirectives({ + ...serverConfig, + code, + filename: directive.splitFileId, + }).compiledResult.code + }` + }) + .join('\n\n\n') + + expect(client.compiledResult.code).toMatchInlineSnapshot(` + "'use server'; + + import { createClientRpc } from "my-rpc-lib-client"; + const useServer_1 = createClientRpc({ + filename: "test.ts", + functionId: "test--useServer" + }); + export const useServer = useServer_1; + const defaultExport_1 = createClientRpc({ + filename: "test.ts", + functionId: "test--defaultExport" + }); + export default defaultExport_1;" + `) + expect(ssr.compiledResult.code).toMatchInlineSnapshot(` + "'use server'; + + import { createServerRpc } from "my-rpc-lib-server"; + const useServer_1 = createServerRpc({ + fn: (...args) => import("test.ts?tsr-directive-use-server-split=test--useServer").then(module => module.default(...args)), + filename: "test.ts", + functionId: "test--useServer" + }); + export const useServer = useServer_1; + const defaultExport_1 = createServerRpc({ + fn: (...args) => import("test.ts?tsr-directive-use-server-split=test--defaultExport").then(module => module.default(...args)), + filename: "test.ts", + functionId: "test--defaultExport" + }); + export default defaultExport_1;" + `) + expect(splitFiles).toMatchInlineSnapshot(` + "// useServer + + 'use server'; + + const useServer_1 = function useServer() { + return usedInUseServer(); + }; + function usedInUseServer() { + return 'hello'; + } + export default useServer_1; + + + // defaultExport + + 'use server'; + + const defaultExport_1 = function defaultExport() { + return 'hello'; + }; + export default defaultExport_1;" `) }) }) diff --git a/packages/start/package.json b/packages/start/package.json index 70f1fcc9e8..c03e27a0ca 100644 --- a/packages/start/package.json +++ b/packages/start/package.json @@ -139,7 +139,7 @@ "@tanstack/router-generator": "workspace:^", "@tanstack/router-plugin": "workspace:^", "@tanstack/start-vite-plugin": "workspace:^", - "@tanstack/server-functions-plugin": "workspace:^", + "@tanstack/directive-functions-plugin": "workspace:^", "@vinxi/react": "0.2.5", "@vinxi/react-server-dom": "^0.0.3", "@vinxi/server-components": "0.5.0", diff --git a/packages/start/src/client-runtime/index.tsx b/packages/start/src/client-runtime/index.tsx index 9321438a70..59b4434d4d 100644 --- a/packages/start/src/client-runtime/index.tsx +++ b/packages/start/src/client-runtime/index.tsx @@ -1,6 +1,6 @@ import { fetcher } from './fetcher' import { getBaseUrl } from './getBaseUrl' -import type { CreateRpcFn } from '@tanstack/server-functions-plugin' +import type { CreateRpcFn } from '@tanstack/directive-functions-plugin' export const createClientRpc: CreateRpcFn = (opts) => { const base = getBaseUrl( diff --git a/packages/start/src/config/index.ts b/packages/start/src/config/index.ts index f8c14fee4f..c6e9c80d0d 100644 --- a/packages/start/src/config/index.ts +++ b/packages/start/src/config/index.ts @@ -14,10 +14,6 @@ import { createApp } from 'vinxi' import { config } from 'vinxi/plugins/config' // // @ts-expect-error // import { serverComponents } from '@vinxi/server-components/plugin' -import { - TanStackServerFnPluginClient, - TanStackServerFnPluginServer, -} from '@tanstack/server-functions-plugin' import { tanstackStartVinxiFileRouter } from './vinxi-file-router.js' import { checkDeploymentPresetInput, @@ -170,7 +166,7 @@ export function defineConfig( }), ...(viteConfig.plugins || []), ...(clientViteConfig.plugins || []), - TanStackServerFnPluginClient({ + Directive({ getRuntimeCode: (opts) => `import { createClientRpc } from '@tanstack/start/client-runtime'`, replacer: (opts) => diff --git a/packages/start/src/server-runtime/index.tsx b/packages/start/src/server-runtime/index.tsx index 6c68ed7866..1b222d6ec9 100644 --- a/packages/start/src/server-runtime/index.tsx +++ b/packages/start/src/server-runtime/index.tsx @@ -1,5 +1,5 @@ // import { getBaseUrl } from '../client-runtime/getBaseUrl' -import type { CreateRpcFn } from '@tanstack/server-functions-plugin' +import type { CreateRpcFn } from '@tanstack/directive-functions-plugin' export const createServerRpc: CreateRpcFn = (opts) => { // const functionUrl = getBaseUrl('http://localhost:3000', id, name) diff --git a/packages/start/src/server/defaultStreamHandler.tsx b/packages/start/src/server/defaultStreamHandler.tsx index af86e4fc85..3a8707017a 100644 --- a/packages/start/src/server/defaultStreamHandler.tsx +++ b/packages/start/src/server/defaultStreamHandler.tsx @@ -63,12 +63,12 @@ export const defaultStreamHandler: HandlerCallback = async ({ }, }), onError: (error, info) => { - console.log('Error in renderToPipeableStream:', error, info) + console.error('Error in renderToPipeableStream:', error, info) }, }, ) } catch (e) { - console.log('Error in renderToPipeableStream:', e) + console.error('Error in renderToPipeableStream:', e) } const transforms = [transformStreamWithRouter(router)] diff --git a/packages/start/src/ssr-runtime/index.tsx b/packages/start/src/ssr-runtime/index.tsx index f4dadc87f7..4a148fdda2 100644 --- a/packages/start/src/ssr-runtime/index.tsx +++ b/packages/start/src/ssr-runtime/index.tsx @@ -4,7 +4,7 @@ import invariant from 'tiny-invariant' import { fetcher } from '../client-runtime/fetcher' import { getBaseUrl } from '../client-runtime/getBaseUrl' import { handleServerRequest } from '../server-handler/index' -import type { CreateRpcFn } from '@tanstack/server-functions-plugin' +import type { CreateRpcFn } from '@tanstack/directive-functions-plugin' export function createIncomingMessage( url: string, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f7c941e7cf..b4adb9bbf2 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -3548,7 +3548,7 @@ importers: version: 6.0.0 babel-dead-code-elimination: specifier: ^1.0.6 - version: 1.0.6 + version: 1.0.8 chalk: specifier: ^5.3.0 version: 5.3.0 @@ -3564,6 +3564,9 @@ importers: packages/start: dependencies: + '@tanstack/directive-functions-plugin': + specifier: workspace:^ + version: link:../server-functions-vite-plugin '@tanstack/react-cross-context': specifier: workspace:* version: link:../react-cross-context @@ -3576,9 +3579,6 @@ importers: '@tanstack/router-plugin': specifier: workspace:* version: link:../router-plugin - '@tanstack/server-functions-plugin': - specifier: workspace:^ - version: link:../server-functions-vite-plugin '@tanstack/start-vite-plugin': specifier: workspace:* version: link:../start-vite-plugin From ce2ab1082de979e94e483c2e5544a5dcb88edf63 Mon Sep 17 00:00:00 2001 From: Tanner Linsley Date: Thu, 19 Dec 2024 17:27:28 -0700 Subject: [PATCH 10/13] fis tests --- .../tests/compiler.test.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/packages/server-functions-vite-plugin/tests/compiler.test.ts b/packages/server-functions-vite-plugin/tests/compiler.test.ts index 3fc16a059c..4aeb219618 100644 --- a/packages/server-functions-vite-plugin/tests/compiler.test.ts +++ b/packages/server-functions-vite-plugin/tests/compiler.test.ts @@ -105,7 +105,7 @@ describe('server function compilation', () => { code, }) const ssr = compileDirectives({ ...serverConfig, code }) - const splitFiles = Object.entries(ssr.directives) + const splitFiles = Object.entries(ssr.directiveFnsById) .map(([_fnId, directiveFn]) => { return `// ${directiveFn.functionName}\n\n${ compileDirectives({ @@ -586,7 +586,7 @@ describe('server function compilation', () => { `) }) - test('multiple directives', () => { + test('multiple directiveFnsById', () => { const code = ` function multiDirective() { 'use strict' @@ -597,7 +597,7 @@ describe('server function compilation', () => { const client = compileDirectives({ ...clientConfig, code }) const ssr = compileDirectives({ ...serverConfig, code }) - const splitFiles = Object.entries(ssr.directives) + const splitFiles = Object.entries(ssr.directiveFnsById) .map(([_fnId, directiveFn]) => { return `// ${directiveFn.functionName}\n\n${ compileDirectives({ @@ -641,7 +641,7 @@ describe('server function compilation', () => { const client = compileDirectives({ ...clientConfig, code }) const ssr = compileDirectives({ ...serverConfig, code }) - const splitFiles = Object.entries(ssr.directives) + const splitFiles = Object.entries(ssr.directiveFnsById) .map(([_fnId, directiveFn]) => { return `// ${directiveFn.functionName}\n\n${ compileDirectives({ @@ -698,7 +698,7 @@ describe('server function compilation', () => { const client = compileDirectives({ ...clientConfig, code }) const ssr = compileDirectives({ ...serverConfig, code }) - const splitFiles = Object.entries(ssr.directives) + const splitFiles = Object.entries(ssr.directiveFnsById) .map(([_fnId, directiveFn]) => { return `// ${directiveFn.functionName}\n\n${ compileDirectives({ @@ -797,7 +797,7 @@ describe('server function compilation', () => { const client = compileDirectives({ ...clientConfig, code }) const ssr = compileDirectives({ ...serverConfig, code }) - const splitFiles = Object.entries(ssr.directives) + const splitFiles = Object.entries(ssr.directiveFnsById) .map(([_fnId, directive]) => { return `// ${directive.functionName}\n\n${ compileDirectives({ From bc985743c33beecb6536d98987039c328cd436f2 Mon Sep 17 00:00:00 2001 From: Tanner Linsley Date: Fri, 20 Dec 2024 17:22:30 -0700 Subject: [PATCH 11/13] It's working!!! --- .../src/compilers.ts | 105 +++-- .../server-functions-vite-plugin/src/index.ts | 153 +++++-- .../src/logger.ts | 4 +- .../tests/compiler.test.ts | 431 +++++++++++++----- packages/start-vite-plugin/src/ast.ts | 2 +- packages/start-vite-plugin/src/compilers.ts | 174 ++----- packages/start-vite-plugin/src/index.ts | 4 +- .../createServerFn/createServerFn.test.ts | 44 ++ .../client/createServerFnDestructured.tsx | 5 - .../createServerFnDestructuredRename.tsx | 5 - .../client/createServerFnStarImport.tsx | 5 - .../server/createServerFnStarImport.tsx | 2 + packages/start/src/client-runtime/fetcher.tsx | 8 +- .../start/src/client-runtime/getBaseUrl.tsx | 4 +- packages/start/src/client-runtime/index.tsx | 13 +- packages/start/src/client/createServerFn.ts | 2 +- packages/start/src/config/index.ts | 38 +- packages/start/src/server-handler/index.tsx | 51 ++- packages/start/src/server-runtime/index.tsx | 21 +- packages/start/src/ssr-runtime/index.tsx | 13 +- packages/start/vite.config.ts | 2 +- 21 files changed, 677 insertions(+), 409 deletions(-) diff --git a/packages/server-functions-vite-plugin/src/compilers.ts b/packages/server-functions-vite-plugin/src/compilers.ts index 120f30c0fb..eb16b459bc 100644 --- a/packages/server-functions-vite-plugin/src/compilers.ts +++ b/packages/server-functions-vite-plugin/src/compilers.ts @@ -19,7 +19,9 @@ export interface DirectiveFn { functionName: string functionId: string referenceName: string - splitFileId: string + splitFilename: string + filename: string + chunkName: string } export type SupportedFunctionPath = @@ -32,6 +34,7 @@ export type ReplacerFn = (opts: { splitImportFn: string filename: string functionId: string + isSplitFn: boolean }) => string // const debug = process.env.TSR_VITE_DEBUG === 'true' @@ -43,38 +46,53 @@ export type CompileDirectivesOpts = ParseAstOptions & { directiveFnsById: Record }) => string replacer: ReplacerFn + devSplitImporter: string } export function compileDirectives(opts: CompileDirectivesOpts) { const [_, searchParamsStr] = opts.filename.split('?') const searchParams = new URLSearchParams(searchParamsStr) const directiveSplitParam = `tsr-directive-${opts.directive.replace(/[^a-zA-Z0-9]/g, '-')}-split` - const functionId = searchParams.get(directiveSplitParam) + const functionName = searchParams.get(directiveSplitParam) const ast = parseAst(opts) const directiveFnsById = findDirectives(ast, { ...opts, - splitFunctionId: functionId, + splitFunctionName: functionName, directiveSplitParam, }) + const directiveFnsByFunctionName = Object.fromEntries( + Object.entries(directiveFnsById).map(([id, fn]) => [fn.functionName, fn]), + ) + // Add runtime code if there are directives // Add runtime code if there are directives - if (Object.keys(directiveFnsById).length > 0 && opts.getRuntimeCode) { - const runtimeImport = babel.template.statement( - opts.getRuntimeCode({ directiveFnsById }), - )() - ast.program.body.unshift(runtimeImport) + if (Object.keys(directiveFnsById).length > 0) { + // Add a vite import to the top of the file + ast.program.body.unshift( + babel.types.importDeclaration( + [babel.types.importDefaultSpecifier(babel.types.identifier('vite'))], + babel.types.stringLiteral('vite'), + ), + ) + + if (opts.getRuntimeCode) { + const runtimeImport = babel.template.statement( + opts.getRuntimeCode({ directiveFnsById }), + )() + ast.program.body.unshift(runtimeImport) + } } - // If there is a functionId, we need to remove all exports + // If there is a functionName, we need to remove all exports // then make sure that our function is exported under the // directive name - if (functionId) { - const directiveFn = directiveFnsById[functionId] + if (functionName) { + const directiveFn = directiveFnsByFunctionName[functionName] if (!directiveFn) { - throw new Error(`${opts.directiveLabel} ${functionId} not found`) + throw new Error(`${opts.directiveLabel} ${functionName} not found`) } safeRemoveExports(ast) @@ -211,12 +229,13 @@ export function findDirectives( directive: string directiveLabel: string replacer?: ReplacerFn - splitFunctionId?: string | null + splitFunctionName?: string | null directiveSplitParam: string + devSplitImporter: string }, ) { const directiveFnsById: Record = {} - const functionIdCounts: Record = {} + const functionNameCounts: Record = {} let programPath: babel.NodePath @@ -324,25 +343,18 @@ export function findDirectives( } // Find the nearest variable name - const fnName = findNearestVariableName(directiveFn, opts.directiveLabel) - - // Make the functionId safe for use in a URL - const baseLabel = makeFileLocationUrlSafe( - `${opts.filename.replace( - path.extname(opts.filename), - '', - )}--${fnName}`.replace(opts.root, ''), - ) + let functionName = findNearestVariableName(directiveFn, opts.directiveLabel) // Count the number of functions with the same baseLabel - functionIdCounts[baseLabel] = (functionIdCounts[baseLabel] || 0) + 1 + functionNameCounts[functionName] = + (functionNameCounts[functionName] || 0) + 1 - // If there are multiple functions with the same baseLabel, + // If there are multiple functions with the same fnName, // append a unique identifier to the functionId - const functionId = - functionIdCounts[baseLabel] > 1 - ? `${baseLabel}_${functionIdCounts[baseLabel] - 1}` - : baseLabel + functionName = + functionNameCounts[functionName]! > 1 + ? `${functionName}_${functionNameCounts[functionName]! - 1}` + : functionName // Move the function to program level while preserving its position // in the program body @@ -354,7 +366,7 @@ export function findDirectives( const topParentIndex = programBody.indexOf(topParent.node as any) // Determine the reference name for the function - let referenceName = makeIdentifierSafe(fnName) + let referenceName = makeIdentifierSafe(functionName) // Crawl the scope to refresh all the bindings programPath.scope.crawl() @@ -424,20 +436,27 @@ export function findDirectives( ) as SupportedFunctionPath } - const [filename, searchParamsStr] = opts.filename.split('?') + const functionId = makeFileLocationUrlSafe( + `${opts.filename.replace( + path.extname(opts.filename), + '', + )}--${functionName}`.replace(opts.root, ''), + ) + const [filename, searchParamsStr] = opts.filename.split('?') const searchParams = new URLSearchParams(searchParamsStr) - searchParams.set(opts.directiveSplitParam, functionId) - const splitFileId = `${filename}?${searchParams.toString()}` + searchParams.set(opts.directiveSplitParam, functionName) + const splitFilename = `${filename}?${searchParams.toString()}` // If a replacer is provided, replace the function with the replacer - if (functionId !== opts.splitFunctionId && opts.replacer) { + if (opts.replacer) { const replacer = opts.replacer({ fn: '$$fn$$', splitImportFn: '$$splitImportFn$$', - // splitFileId, + // splitFilename, filename: filename!, functionId: functionId, + isSplitFn: functionName === opts.splitFunctionName, }) const replacement = babel.template.expression(replacer, { @@ -449,7 +468,10 @@ export function findDirectives( : {}), ...(replacer.includes('$$splitImportFn$$') ? { - $$splitImportFn$$: `(...args) => import(${JSON.stringify(splitFileId)}).then(module => module.default(...args))`, + $$splitImportFn$$: + process.env.NODE_ENV === 'production' + ? `(...args) => import(${JSON.stringify(splitFilename)}).then(module => module.default(...args))` + : `(...args) => ${opts.devSplitImporter}(${JSON.stringify(splitFilename)}).then(module => module.default(...args))`, } : {}), }) @@ -462,9 +484,11 @@ export function findDirectives( directiveFnsById[functionId] = { nodePath: directiveFn, referenceName, - functionName: fnName || '', + functionName: functionName || '', functionId: functionId, - splitFileId, + splitFilename, + filename: opts.filename, + chunkName: fileNameToChunkName(opts.root, splitFilename), } } } @@ -544,3 +568,8 @@ const safeRemoveExports = (ast: babel.types.File) => { }, }) } + +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, '_') +} diff --git a/packages/server-functions-vite-plugin/src/index.ts b/packages/server-functions-vite-plugin/src/index.ts index 8a96c502e9..e6f1f6cd69 100644 --- a/packages/server-functions-vite-plugin/src/index.ts +++ b/packages/server-functions-vite-plugin/src/index.ts @@ -1,11 +1,13 @@ import { fileURLToPath, pathToFileURL } from 'node:url' +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs' +import path from 'node:path' import { compileDirectives } from './compilers' import { logDiff } from './logger' import type { CompileDirectivesOpts, DirectiveFn } from './compilers' import type { Plugin } from 'vite' -const debug = Boolean(process.env.TSR_VITE_DEBUG) || (true as boolean) +const debug = Boolean(process.env.TSR_VITE_DEBUG) export type ServerFunctionsViteOptions = Pick< CompileDirectivesOpts, @@ -22,14 +24,52 @@ export type CreateServerRpcFn = ( const createDirectiveRx = (directive: string) => new RegExp(`"${directive}"|'${directive}'`, 'g') -export function createTanStackServerFnPlugin( - opts: ServerFunctionsViteOptions, -): { +export function createTanStackServerFnPlugin(_opts?: {}): { client: Array ssr: Array server: Array } { - let directiveFnsById: Record = {} + const ROOT = process.cwd() + const manifestFilename = + 'node_modules/.tanstack-start/server-functions-manifest.json' + const directiveFnsById: Record = {} + + const directiveFnsByIdToManifest = ( + directiveFnsById: Record, + ) => + Object.fromEntries( + Object.entries(directiveFnsById).map(([id, fn]) => [ + id, + { + functionName: fn.functionName, + referenceName: fn.referenceName, + splitFilename: fn.splitFilename, + filename: fn.filename, + chunkName: fn.chunkName, + }, + ]), + ) + + const readManifestPlugin = (): Plugin => ({ + name: 'tanstack-start-server-fn-vite-plugin-manifest', + enforce: 'pre', + resolveId: (id) => { + if (id === 'tsr:server-fn-manifest') { + return id + } + + return null + }, + load(id) { + if (id === 'tsr:server-fn-manifest') { + return `export default ${JSON.stringify( + directiveFnsByIdToManifest(directiveFnsById), + )}` + } + + return null + }, + }) return { client: [ @@ -44,32 +84,26 @@ export function createTanStackServerFnPlugin( // On the client, all we need is the function ID `createClientRpc(${JSON.stringify(opts.functionId)})`, onDirectiveFnsById: (d) => { - // When the client directives are compiled, save them so we + // When directives are compiled, save them so we // can create a manifest - directiveFnsById = d + Object.assign(directiveFnsById, d) }, }), // Now that we have the directiveFnsById, we need to create a new // virtual module that can be used to import that manifest + readManifestPlugin(), { - name: 'tanstack-start-server-fn-vite-plugin-manifest', - resolveId: (id) => { - if (id === 'virtual:tanstack-start-server-fn-manifest') { - return JSON.stringify( - Object.fromEntries( - Object.entries(directiveFnsById).map(([id, fn]) => [ - id, - { - functionName: fn.functionName, - referenceName: fn.referenceName, - splitFileId: fn.splitFileId, - }, - ]), - ), - ) - } - - return null + name: 'tanstack-start-server-fn-vite-plugin-build-client', + generateBundle() { + // We also need to create a production manifest so we can + // access it the server build, which does not run in the + // same vite build environment + console.log('Generating production manifest') + mkdirSync(path.dirname(manifestFilename), { recursive: true }) + writeFileSync( + path.join(ROOT, manifestFilename), + JSON.stringify(directiveFnsByIdToManifest(directiveFnsById)), + ) }, }, ], @@ -85,9 +119,16 @@ export function createTanStackServerFnPlugin( // is split into a worker. Similar to the client, we'll use the ID // to call into the worker using a local http event. `createSsrRpc(${JSON.stringify(opts.functionId)})`, + onDirectiveFnsById: (d) => { + // When directives are compiled, save them so we + // can create a manifest + Object.assign(directiveFnsById, d) + }, }), + readManifestPlugin(), ], server: [ + readManifestPlugin(), // On the server, we need to compile the server functions // so they can be called by other server functions. // This is also where we split the server function into a separate file @@ -96,13 +137,66 @@ export function createTanStackServerFnPlugin( directive: 'use server', directiveLabel: 'Server Function', getRuntimeCode: () => - `import { createServerRpc } from '@tanstack/start/ssr-runtime'`, + `import { createServerRpc } from '@tanstack/start/server-runtime'`, replacer: (opts) => // By using the provided splitImportFn, we can both trigger vite // to create a new chunk/entry for the server function and also // replace other function references to it with the import statement - `createServerRpc(${JSON.stringify(opts.functionId)}, ${JSON.stringify(opts.splitImportFn)})`, + `createServerRpc(${JSON.stringify(opts.functionId)}, ${opts.isSplitFn ? opts.fn : opts.splitImportFn})`, + onDirectiveFnsById: (d) => { + // When directives are compiled, save them so we + // can create a manifest + Object.assign(directiveFnsById, d) + }, }), + (() => { + let serverFunctionsManifest: Record + return { + name: 'tanstack-start-server-fn-vite-plugin-build-', + enforce: 'post', + apply: 'build', + config(config) { + // We use a file to store the manifest so we can access it between + // vite environments + serverFunctionsManifest = JSON.parse( + readFileSync(path.join(ROOT, manifestFilename), 'utf-8'), + ) + + return { + build: { + rollupOptions: { + output: { + chunkFileNames: '[name].mjs', + entryFileNames: '[name].mjs', + }, + treeshake: true, + }, + }, + } + }, + + configResolved(config) { + const serverFnEntries = Object.fromEntries( + Object.entries(serverFunctionsManifest).map(([id, fn]) => { + return [fn.chunkName, fn.splitFilename] + }), + ) + + config.build.rollupOptions.input = { + entry: Array.isArray(config.build.rollupOptions.input) + ? config.build.rollupOptions.input[0] + : typeof config.build.rollupOptions.input === 'object' && + 'entry' in config.build.rollupOptions.input + ? config.build.rollupOptions.input.entry + : ((() => { + throw new Error('Invalid input') + }) as any), + ...serverFnEntries, + } + console.log(config.build.rollupOptions.input) + }, + } + })(), ], } } @@ -136,12 +230,15 @@ export function TanStackDirectiveFunctionsPlugin( code, root: ROOT, filename: id, + // globalThis.app currently refers to Vinxi's app instance. In the future, it can just be the + // vite dev server instance we get from Nitro. + devSplitImporter: `(globalThis.app.getRouter('server').internals.devServer.ssrLoadModule)`, }) opts.onDirectiveFnsById?.(directiveFnsById) if (debug) console.info('Directive Input/Output') - if (debug) logDiff(code, compiledResult.code.replace(/ctx/g, 'blah')) + if (debug) logDiff(code, compiledResult.code) return compiledResult }, diff --git a/packages/server-functions-vite-plugin/src/logger.ts b/packages/server-functions-vite-plugin/src/logger.ts index e1a3c37eea..fd777080c3 100644 --- a/packages/server-functions-vite-plugin/src/logger.ts +++ b/packages/server-functions-vite-plugin/src/logger.ts @@ -1,8 +1,8 @@ import chalk from 'chalk' -import { diffChars } from 'diff' +import { diffWords } from 'diff' export function logDiff(oldStr: string, newStr: string) { - const differences = diffChars(oldStr, newStr) + const differences = diffWords(oldStr, newStr) let output = '' let unchangedLines = '' diff --git a/packages/server-functions-vite-plugin/tests/compiler.test.ts b/packages/server-functions-vite-plugin/tests/compiler.test.ts index 4aeb219618..7092e1e348 100644 --- a/packages/server-functions-vite-plugin/tests/compiler.test.ts +++ b/packages/server-functions-vite-plugin/tests/compiler.test.ts @@ -14,6 +14,21 @@ const clientConfig: Omit = { filename: ${JSON.stringify(opts.filename)}, functionId: ${JSON.stringify(opts.functionId)}, })`, + devSplitImporter: `devImport`, +} + +const ssrConfig: Omit = { + directive: 'use server', + directiveLabel: 'Server function', + root: './test-files', + filename: 'test.ts', + getRuntimeCode: () => 'import { createSsrRpc } from "my-rpc-lib-server"', + replacer: (opts) => + `createSsrRpc({ + filename: ${JSON.stringify(opts.filename)}, + functionId: ${JSON.stringify(opts.functionId)}, + })`, + devSplitImporter: `devImport`, } const serverConfig: Omit = { @@ -23,11 +38,18 @@ const serverConfig: Omit = { filename: 'test.ts', getRuntimeCode: () => 'import { createServerRpc } from "my-rpc-lib-server"', replacer: (opts) => + // On the server build, we need different code for the split function + // vs any other server functions the split function may reference + + // For the split function itself, we use the original function. + // For any other server functions the split function may reference, + // we use the splitImportFn which is a dynamic import of the split file. `createServerRpc({ - fn: ${opts.splitImportFn}, + fn: ${opts.isSplitFn ? opts.fn : opts.splitImportFn}, filename: ${JSON.stringify(opts.filename)}, functionId: ${JSON.stringify(opts.functionId)}, })`, + devSplitImporter: `devImport`, } describe('server function compilation', () => { @@ -104,14 +126,14 @@ describe('server function compilation', () => { ...clientConfig, code, }) - const ssr = compileDirectives({ ...serverConfig, code }) + const ssr = compileDirectives({ ...ssrConfig, code }) const splitFiles = Object.entries(ssr.directiveFnsById) .map(([_fnId, directiveFn]) => { - return `// ${directiveFn.functionName}\n\n${ + return `// ${directiveFn.functionId}\n\n${ compileDirectives({ ...serverConfig, code, - filename: directiveFn.splitFileId, + filename: directiveFn.splitFilename, }).compiledResult.code }` }) @@ -171,57 +193,48 @@ describe('server function compilation', () => { `) expect(ssr.compiledResult.code).toMatchInlineSnapshot(` - "import { createServerRpc } from "my-rpc-lib-server"; - const namedFunction_wrapper_namedFunction = createServerRpc({ - fn: (...args) => import("test.ts?tsr-directive-use-server-split=test--namedFunction_wrapper_namedFunction").then(module => module.default(...args)), + "import { createSsrRpc } from "my-rpc-lib-server"; + const namedFunction_wrapper_namedFunction = createSsrRpc({ filename: "test.ts", functionId: "test--namedFunction_wrapper_namedFunction" }); export const namedFunction = wrapper(namedFunction_wrapper_namedFunction); - const arrowFunction_wrapper = createServerRpc({ - fn: (...args) => import("test.ts?tsr-directive-use-server-split=test--arrowFunction_wrapper").then(module => module.default(...args)), + const arrowFunction_wrapper = createSsrRpc({ filename: "test.ts", functionId: "test--arrowFunction_wrapper" }); export const arrowFunction = wrapper(arrowFunction_wrapper); - const anonymousFunction_wrapper = createServerRpc({ - fn: (...args) => import("test.ts?tsr-directive-use-server-split=test--anonymousFunction_wrapper").then(module => module.default(...args)), + const anonymousFunction_wrapper = createSsrRpc({ filename: "test.ts", functionId: "test--anonymousFunction_wrapper" }); export const anonymousFunction = wrapper(anonymousFunction_wrapper); - const multipleDirectives_multipleDirectives = createServerRpc({ - fn: (...args) => import("test.ts?tsr-directive-use-server-split=test--multipleDirectives_multipleDirectives").then(module => module.default(...args)), + const multipleDirectives_multipleDirectives = createSsrRpc({ filename: "test.ts", functionId: "test--multipleDirectives_multipleDirectives" }); export const multipleDirectives = multipleDirectives_multipleDirectives; - const iife_1 = createServerRpc({ - fn: (...args) => import("test.ts?tsr-directive-use-server-split=test--iife").then(module => module.default(...args)), + const iife_1 = createSsrRpc({ filename: "test.ts", functionId: "test--iife" }); export const iife = iife_1(); - const defaultExportFn_1 = createServerRpc({ - fn: (...args) => import("test.ts?tsr-directive-use-server-split=test--defaultExportFn").then(module => module.default(...args)), + const defaultExportFn_1 = createSsrRpc({ filename: "test.ts", functionId: "test--defaultExportFn" }); export default defaultExportFn_1; - const namedExportFn_1 = createServerRpc({ - fn: (...args) => import("test.ts?tsr-directive-use-server-split=test--namedExportFn").then(module => module.default(...args)), + const namedExportFn_1 = createSsrRpc({ filename: "test.ts", functionId: "test--namedExportFn" }); export const namedExportFn = namedExportFn_1; - const exportedArrowFunction_wrapper = createServerRpc({ - fn: (...args) => import("test.ts?tsr-directive-use-server-split=test--exportedArrowFunction_wrapper").then(module => module.default(...args)), + const exportedArrowFunction_wrapper = createSsrRpc({ filename: "test.ts", functionId: "test--exportedArrowFunction_wrapper" }); export const exportedArrowFunction = wrapper(exportedArrowFunction_wrapper); - const namedExportConst_1 = createServerRpc({ - fn: (...args) => import("test.ts?tsr-directive-use-server-split=test--namedExportConst").then(module => module.default(...args)), + const namedExportConst_1 = createSsrRpc({ filename: "test.ts", functionId: "test--namedExportConst" }); @@ -234,77 +247,122 @@ describe('server function compilation', () => { expect(splitFiles).toMatchInlineSnapshot( ` - "// namedFunction_wrapper_namedFunction + "// test--namedFunction_wrapper_namedFunction - const namedFunction_wrapper_namedFunction = function namedFunction() { - return 'hello'; - }; + import { createServerRpc } from "my-rpc-lib-server"; + const namedFunction_wrapper_namedFunction = createServerRpc({ + fn: function namedFunction() { + return 'hello'; + }, + filename: "test.ts", + functionId: "test--namedFunction_wrapper_namedFunction" + }); export default namedFunction_wrapper_namedFunction; - // arrowFunction_wrapper + // test--arrowFunction_wrapper - const arrowFunction_wrapper = () => { - return 'hello'; - }; + import { createServerRpc } from "my-rpc-lib-server"; + const arrowFunction_wrapper = createServerRpc({ + fn: () => { + return 'hello'; + }, + filename: "test.ts", + functionId: "test--arrowFunction_wrapper" + }); export default arrowFunction_wrapper; - // anonymousFunction_wrapper + // test--anonymousFunction_wrapper - const anonymousFunction_wrapper = function () { - return 'hello'; - }; + import { createServerRpc } from "my-rpc-lib-server"; + const anonymousFunction_wrapper = createServerRpc({ + fn: function () { + return 'hello'; + }, + filename: "test.ts", + functionId: "test--anonymousFunction_wrapper" + }); export default anonymousFunction_wrapper; - // multipleDirectives_multipleDirectives + // test--multipleDirectives_multipleDirectives - const multipleDirectives_multipleDirectives = function multipleDirectives() { - 'use strict'; + import { createServerRpc } from "my-rpc-lib-server"; + const multipleDirectives_multipleDirectives = createServerRpc({ + fn: function multipleDirectives() { + 'use strict'; - return 'hello'; - }; + return 'hello'; + }, + filename: "test.ts", + functionId: "test--multipleDirectives_multipleDirectives" + }); export default multipleDirectives_multipleDirectives; - // iife + // test--iife - const iife_1 = function () { - return 'hello'; - }; + import { createServerRpc } from "my-rpc-lib-server"; + const iife_1 = createServerRpc({ + fn: function () { + return 'hello'; + }, + filename: "test.ts", + functionId: "test--iife" + }); export default iife_1; - // defaultExportFn + // test--defaultExportFn - const defaultExportFn_1 = function defaultExportFn() { - return 'hello'; - }; + import { createServerRpc } from "my-rpc-lib-server"; + const defaultExportFn_1 = createServerRpc({ + fn: function defaultExportFn() { + return 'hello'; + }, + filename: "test.ts", + functionId: "test--defaultExportFn" + }); export default defaultExportFn_1; - // namedExportFn + // test--namedExportFn - const namedExportFn_1 = function namedExportFn() { - return 'hello'; - }; + import { createServerRpc } from "my-rpc-lib-server"; + const namedExportFn_1 = createServerRpc({ + fn: function namedExportFn() { + return 'hello'; + }, + filename: "test.ts", + functionId: "test--namedExportFn" + }); export default namedExportFn_1; - // exportedArrowFunction_wrapper + // test--exportedArrowFunction_wrapper - const exportedArrowFunction_wrapper = () => { - return 'hello'; - }; + import { createServerRpc } from "my-rpc-lib-server"; + const exportedArrowFunction_wrapper = createServerRpc({ + fn: () => { + return 'hello'; + }, + filename: "test.ts", + functionId: "test--exportedArrowFunction_wrapper" + }); export default exportedArrowFunction_wrapper; - // namedExportConst + // test--namedExportConst - const namedExportConst_1 = () => { - return usedFn(); - }; + import { createServerRpc } from "my-rpc-lib-server"; + const namedExportConst_1 = createServerRpc({ + fn: () => { + return usedFn(); + }, + filename: "test.ts", + functionId: "test--namedExportConst" + }); function usedFn() { return 'hello'; } @@ -596,14 +654,14 @@ describe('server function compilation', () => { ` const client = compileDirectives({ ...clientConfig, code }) - const ssr = compileDirectives({ ...serverConfig, code }) + const ssr = compileDirectives({ ...ssrConfig, code }) const splitFiles = Object.entries(ssr.directiveFnsById) .map(([_fnId, directiveFn]) => { - return `// ${directiveFn.functionName}\n\n${ + return `// ${directiveFn.functionId}\n\n${ compileDirectives({ ...serverConfig, code, - filename: directiveFn.splitFileId, + filename: directiveFn.splitFilename, }).compiledResult.code }` }) @@ -617,16 +675,25 @@ describe('server function compilation', () => { });" `) expect(ssr.compiledResult.code).toMatchInlineSnapshot(` - "import { createServerRpc } from "my-rpc-lib-server"; - createServerRpc({ - fn: (...args) => import("test.ts?tsr-directive-use-server-split=test--multiDirective").then(module => module.default(...args)), + "import { createSsrRpc } from "my-rpc-lib-server"; + createSsrRpc({ filename: "test.ts", functionId: "test--multiDirective" });" `) expect(splitFiles).toMatchInlineSnapshot(` - "// multiDirective + "// test--multiDirective + import { createServerRpc } from "my-rpc-lib-server"; + createServerRpc({ + fn: function multiDirective() { + 'use strict'; + + return 'hello'; + }, + filename: "test.ts", + functionId: "test--multiDirective" + }); export default multiDirective_1;" `) }) @@ -640,14 +707,14 @@ describe('server function compilation', () => { ` const client = compileDirectives({ ...clientConfig, code }) - const ssr = compileDirectives({ ...serverConfig, code }) + const ssr = compileDirectives({ ...ssrConfig, code }) const splitFiles = Object.entries(ssr.directiveFnsById) .map(([_fnId, directiveFn]) => { - return `// ${directiveFn.functionName}\n\n${ + return `// ${directiveFn.functionId}\n\n${ compileDirectives({ ...serverConfig, code, - filename: directiveFn.splitFileId, + filename: directiveFn.splitFilename, }).compiledResult.code }` }) @@ -663,9 +730,8 @@ describe('server function compilation', () => { `) expect(ssr.compiledResult.code).toMatchInlineSnapshot(` - "import { createServerRpc } from "my-rpc-lib-server"; - const iife_1 = createServerRpc({ - fn: (...args) => import("test.ts?tsr-directive-use-server-split=test--iife").then(module => module.default(...args)), + "import { createSsrRpc } from "my-rpc-lib-server"; + const iife_1 = createSsrRpc({ filename: "test.ts", functionId: "test--iife" }); @@ -673,11 +739,16 @@ describe('server function compilation', () => { `) expect(splitFiles).toMatchInlineSnapshot(` - "// iife + "// test--iife - const iife_1 = function () { - return 'hello'; - }; + import { createServerRpc } from "my-rpc-lib-server"; + const iife_1 = createServerRpc({ + fn: function () { + return 'hello'; + }, + filename: "test.ts", + functionId: "test--iife" + }); export default iife_1;" `) }) @@ -696,15 +767,15 @@ describe('server function compilation', () => { ` const client = compileDirectives({ ...clientConfig, code }) - const ssr = compileDirectives({ ...serverConfig, code }) + const ssr = compileDirectives({ ...ssrConfig, code }) const splitFiles = Object.entries(ssr.directiveFnsById) .map(([_fnId, directiveFn]) => { - return `// ${directiveFn.functionName}\n\n${ + return `// ${directiveFn.functionId}\n\n${ compileDirectives({ ...serverConfig, code, - filename: directiveFn.splitFileId, + filename: directiveFn.splitFilename, }).compiledResult.code }` }) @@ -725,15 +796,13 @@ describe('server function compilation', () => { `) expect(ssr.compiledResult.code).toMatchInlineSnapshot(` - "import { createServerRpc } from "my-rpc-lib-server"; - const outer_useServer = createServerRpc({ - fn: (...args) => import("test.ts?tsr-directive-use-server-split=test--outer_useServer").then(module => module.default(...args)), + "import { createSsrRpc } from "my-rpc-lib-server"; + const outer_useServer = createSsrRpc({ filename: "test.ts", functionId: "test--outer_useServer" }); outer(outer_useServer); - const outer_useServer_1 = createServerRpc({ - fn: (...args) => import("test.ts?tsr-directive-use-server-split=test--outer_useServer_1").then(module => module.default(...args)), + const outer_useServer_1 = createSsrRpc({ filename: "test.ts", functionId: "test--outer_useServer_1" }); @@ -741,15 +810,19 @@ describe('server function compilation', () => { `) expect(splitFiles).toMatchInlineSnapshot(` - "// outer_useServer + "// test--outer_useServer import { createServerRpc } from "my-rpc-lib-server"; - const outer_useServer = function useServer() { - return 'hello'; - }; + const outer_useServer = createServerRpc({ + fn: function useServer() { + return 'hello'; + }, + filename: "test.ts", + functionId: "test--outer_useServer" + }); outer(outer_useServer); const outer_useServer_1 = createServerRpc({ - fn: (...args) => import("test.ts?tsr-directive-use-server-split=test--outer_useServer_1").then(module => module.default(...args)), + fn: (...args) => devImport("test.ts?tsr-directive-use-server-split=test--outer_useServer_1").then(module => module.default(...args)), filename: "test.ts", functionId: "test--outer_useServer_1" }); @@ -757,18 +830,22 @@ describe('server function compilation', () => { export default outer_useServer; - // outer_useServer + // test--outer_useServer_1 import { createServerRpc } from "my-rpc-lib-server"; const outer_useServer = createServerRpc({ - fn: (...args) => import("test.ts?tsr-directive-use-server-split=test--outer_useServer").then(module => module.default(...args)), + fn: (...args) => devImport("test.ts?tsr-directive-use-server-split=test--outer_useServer").then(module => module.default(...args)), filename: "test.ts", functionId: "test--outer_useServer" }); outer(outer_useServer); - const outer_useServer_1 = function useServer() { - return 'hello'; - }; + const outer_useServer_1 = createServerRpc({ + fn: function useServer() { + return 'hello'; + }, + filename: "test.ts", + functionId: "test--outer_useServer_1" + }); outer(outer_useServer_1); export default outer_useServer_1;" `) @@ -796,14 +873,14 @@ describe('server function compilation', () => { ` const client = compileDirectives({ ...clientConfig, code }) - const ssr = compileDirectives({ ...serverConfig, code }) + const ssr = compileDirectives({ ...ssrConfig, code }) const splitFiles = Object.entries(ssr.directiveFnsById) .map(([_fnId, directive]) => { return `// ${directive.functionName}\n\n${ compileDirectives({ ...serverConfig, code, - filename: directive.splitFileId, + filename: directive.splitFilename, }).compiledResult.code }` }) @@ -827,15 +904,13 @@ describe('server function compilation', () => { expect(ssr.compiledResult.code).toMatchInlineSnapshot(` "'use server'; - import { createServerRpc } from "my-rpc-lib-server"; - const useServer_1 = createServerRpc({ - fn: (...args) => import("test.ts?tsr-directive-use-server-split=test--useServer").then(module => module.default(...args)), + import { createSsrRpc } from "my-rpc-lib-server"; + const useServer_1 = createSsrRpc({ filename: "test.ts", functionId: "test--useServer" }); export const useServer = useServer_1; - const defaultExport_1 = createServerRpc({ - fn: (...args) => import("test.ts?tsr-directive-use-server-split=test--defaultExport").then(module => module.default(...args)), + const defaultExport_1 = createSsrRpc({ filename: "test.ts", functionId: "test--defaultExport" }); @@ -846,9 +921,14 @@ describe('server function compilation', () => { 'use server'; - const useServer_1 = function useServer() { - return usedInUseServer(); - }; + import { createServerRpc } from "my-rpc-lib-server"; + const useServer_1 = createServerRpc({ + fn: function useServer() { + return usedInUseServer(); + }, + filename: "test.ts", + functionId: "test--useServer" + }); function usedInUseServer() { return 'hello'; } @@ -859,10 +939,145 @@ describe('server function compilation', () => { 'use server'; - const defaultExport_1 = function defaultExport() { - return 'hello'; - }; + import { createServerRpc } from "my-rpc-lib-server"; + const defaultExport_1 = createServerRpc({ + fn: function defaultExport() { + return 'hello'; + }, + filename: "test.ts", + functionId: "test--defaultExport" + }); export default defaultExport_1;" `) }) + + test('createServerFn with identifier', () => { + // The following code is the client output of the tanstack-start-vite-plugin + // that compiles `createServerFn` calls to automatically add the `use server` + // directive in the right places. + const clientOrSsrCode = `import { createServerFn } from '@tanstack/start'; + export const myServerFn = createServerFn().handler(opts => { + "use server"; + + return myServerFn.__executeServer(opts); + }); + + export const myServerFn2 = createServerFn().handler(opts => { + "use server"; + + return myServerFn2.__executeServer(opts); + });` + + // The following code is the server output of the tanstack-start-vite-plugin + // that compiles `createServerFn` calls to automatically add the `use server` + // directive in the right places. + const serverCode = `import { createServerFn } from '@tanstack/start'; + const myFunc = () => { + return 'hello from the server' + }; + export const myServerFn = createServerFn().handler(opts => { + "use server"; + + return myServerFn.__executeServer(opts); + }, myFunc); + + const myFunc2 = () => { + return myServerFn({ data: 'hello 2 from the server' }); + }; + export const myServerFn2 = createServerFn().handler(opts => { + "use server"; + + return myServerFn2.__executeServer(opts); + }, myFunc2);` + + const client = compileDirectives({ ...clientConfig, code: clientOrSsrCode }) + const ssr = compileDirectives({ ...ssrConfig, code: clientOrSsrCode }) + const splitFiles = Object.entries(ssr.directiveFnsById) + .map(([_fnId, directiveFn]) => { + return `// ${directiveFn.functionId}\n\n${ + compileDirectives({ + ...serverConfig, + code: serverCode, + filename: directiveFn.splitFilename, + }).compiledResult.code + }` + }) + .join('\n\n\n') + + expect(client.compiledResult.code).toMatchInlineSnapshot(` + "import { createClientRpc } from "my-rpc-lib-client"; + import { createServerFn } from '@tanstack/start'; + const myServerFn_createServerFn_handler = createClientRpc({ + filename: "test.ts", + functionId: "test--myServerFn_createServerFn_handler" + }); + export const myServerFn = createServerFn().handler(myServerFn_createServerFn_handler); + const myServerFn2_createServerFn_handler = createClientRpc({ + filename: "test.ts", + functionId: "test--myServerFn2_createServerFn_handler" + }); + export const myServerFn2 = createServerFn().handler(myServerFn2_createServerFn_handler);" + `) + expect(ssr.compiledResult.code).toMatchInlineSnapshot(` + "import { createSsrRpc } from "my-rpc-lib-server"; + import { createServerFn } from '@tanstack/start'; + const myServerFn_createServerFn_handler = createSsrRpc({ + filename: "test.ts", + functionId: "test--myServerFn_createServerFn_handler" + }); + export const myServerFn = createServerFn().handler(myServerFn_createServerFn_handler); + const myServerFn2_createServerFn_handler = createSsrRpc({ + filename: "test.ts", + functionId: "test--myServerFn2_createServerFn_handler" + }); + export const myServerFn2 = createServerFn().handler(myServerFn2_createServerFn_handler);" + `) + expect(splitFiles).toMatchInlineSnapshot(` + "// test--myServerFn_createServerFn_handler + + import { createServerRpc } from "my-rpc-lib-server"; + import { createServerFn } from '@tanstack/start'; + const myFunc = () => { + return 'hello from the server'; + }; + const myServerFn_createServerFn_handler = createServerRpc({ + fn: opts => { + return myServerFn.__executeServer(opts); + }, + filename: "test.ts", + functionId: "test--myServerFn_createServerFn_handler" + }); + const myServerFn = createServerFn().handler(myServerFn_createServerFn_handler, myFunc); + export default myServerFn_createServerFn_handler; + + + // test--myServerFn2_createServerFn_handler + + import { createServerRpc } from "my-rpc-lib-server"; + import { createServerFn } from '@tanstack/start'; + const myFunc = () => { + return 'hello from the server'; + }; + const myServerFn_createServerFn_handler = createServerRpc({ + fn: (...args) => devImport("test.ts?tsr-directive-use-server-split=test--myServerFn_createServerFn_handler").then(module => module.default(...args)), + filename: "test.ts", + functionId: "test--myServerFn_createServerFn_handler" + }); + const myFunc2 = () => { + return myServerFn({ + data: 'hello 2 from the server' + }); + }; + const myServerFn2_createServerFn_handler = createServerRpc({ + fn: opts => { + return myServerFn2.__executeServer(opts); + }, + filename: "test.ts", + functionId: "test--myServerFn2_createServerFn_handler" + }); + const myServerFn = createServerFn().handler(myServerFn_createServerFn_handler, myFunc); + const myServerFn2 = createServerFn().handler(myServerFn2_createServerFn_handler, myFunc2); + export default myServerFn2_createServerFn_handler;" + `) + }) }) diff --git a/packages/start-vite-plugin/src/ast.ts b/packages/start-vite-plugin/src/ast.ts index 4f1cb2f04e..99333fa6c4 100644 --- a/packages/start-vite-plugin/src/ast.ts +++ b/packages/start-vite-plugin/src/ast.ts @@ -4,7 +4,7 @@ export type ParseAstOptions = { code: string filename: string root: string - env: 'server' | 'client' + env: 'server' | 'client' | 'ssr' } export function parseAst(opts: ParseAstOptions) { diff --git a/packages/start-vite-plugin/src/compilers.ts b/packages/start-vite-plugin/src/compilers.ts index 41b54b8ac2..9024436413 100644 --- a/packages/start-vite-plugin/src/compilers.ts +++ b/packages/start-vite-plugin/src/compilers.ts @@ -318,7 +318,22 @@ function handleCreateServerFnCallExpression( // })(optsOut) // }) - removeUseServerDirective(handlerFnPath) + // If the handler function is an identifier and we're on the client, we need to + // remove the bound function from the file. + // If we're on the server, you can leave it, since it will get referenced + // as a second argument. + + if (t.isIdentifier(handlerFn)) { + if (opts.env === 'client' || opts.env === 'ssr') { + // Find the binding for the handler function + const binding = handlerFnPath.scope.getBinding(handlerFn.name) + // Remove it + if (binding) { + binding.path.remove() + } + } + // If the env is server, just leave it alone + } handlerFnPath.replaceWith( t.arrowFunctionExpression( @@ -344,46 +359,10 @@ function handleCreateServerFnCallExpression( } } -function removeUseServerDirective(path: babel.NodePath) { - path.traverse({ - Directive(path) { - if (path.node.value.value === 'use server') { - path.remove() - } - }, - }) -} - function handleCreateMiddlewareCallExpression( path: babel.NodePath, opts: ParseAstOptions, ) { - // const firstArg = path.node.arguments[0] - - // if (!t.isObjectExpression(firstArg)) { - // throw new Error( - // 'createMiddleware must be called with an object of options!', - // ) - // } - - // const idProperty = firstArg.properties.find((prop) => { - // return ( - // t.isObjectProperty(prop) && - // t.isIdentifier(prop.key) && - // prop.key.name === 'id' - // ) - // }) - - // if ( - // !idProperty || - // !t.isObjectProperty(idProperty) || - // !t.isStringLiteral(idProperty.value) - // ) { - // throw new Error( - // 'createMiddleware must be called with an "id" property!', - // ) - // } - const rootCallExpression = getRootCallExpression(path) if (debug) @@ -392,106 +371,6 @@ function handleCreateMiddlewareCallExpression( rootCallExpression.toString(), ) - // Check if the call is assigned to a variable - // if (!rootCallExpression.parentPath.isVariableDeclarator()) { - // TODO: move this logic out to eslint or something like - // the router generator code that can do autofixes on save. - - // // If not assigned to a variable, wrap the call in a variable declaration - // const variableDeclaration = t.variableDeclaration('const', [ - // t.variableDeclarator(t.identifier(middlewareName), path.node), - // ]) - - // // The parent could be an expression statement, if it is, we need to replace - // // it with the variable declaration - // if (path.parentPath.isExpressionStatement()) { - // path.parentPath.replaceWith(variableDeclaration) - // } else { - // // If the parent is not an expression statement, then it is a statement - // // that is not an expression, like a variable declaration or a return statement. - // // In this case, we need to insert the variable declaration before the statement - // path.parentPath.insertBefore(variableDeclaration) - // } - - // // Now we need to export it. Just add an export statement - // // to the program body - // path.findParent((parentPath) => { - // if (parentPath.isProgram()) { - // parentPath.node.body.push( - // t.exportNamedDeclaration(null, [ - // t.exportSpecifier( - // t.identifier(middlewareName), - // t.identifier(middlewareName), - // ), - // ]), - // ) - // } - // return false - // }) - - // throw new Error( - // 'createMiddleware must be assigned to a variable and exported!', - // ) - // } - - // const variableDeclarator = rootCallExpression.parentPath.node - // const existingVariableName = (variableDeclarator.id as t.Identifier).name - - // const program = rootCallExpression.findParent((parentPath) => { - // return parentPath.isProgram() - // }) as babel.NodePath - - // let isExported = false as boolean - - // program.traverse({ - // ExportNamedDeclaration: (path) => { - // if ( - // path.isExportNamedDeclaration() && - // path.node.declaration && - // t.isVariableDeclaration(path.node.declaration) && - // path.node.declaration.declarations.some((decl) => { - // return ( - // t.isVariableDeclarator(decl) && - // t.isIdentifier(decl.id) && - // decl.id.name === existingVariableName - // ) - // }) - // ) { - // isExported = true - // } - // }, - // }) - - // If not exported, export it - // if (!isExported) { - // TODO: move this logic out to eslint or something like - // the router generator code that can do autofixes on save. - - // path.parentPath.parentPath.insertAfter( - // t.exportNamedDeclaration(null, [ - // t.exportSpecifier( - // t.identifier(existingVariableName), - // t.identifier(existingVariableName), - // ), - // ]), - // ) - - // throw new Error( - // 'createMiddleware must be exported as a named export!', - // ) - // } - - // The function is the 'fn' property of the object passed to createMiddleware - - // const firstArg = path.node.arguments[0] - // if (t.isObjectExpression(firstArg)) { - // // Was called with some options - // } - - // Traverse the member expression and find the call expressions for - // the validator, handler, and middleware methods. Check to make sure they - // are children of the createMiddleware call expression. - const callExpressionPaths = { middleware: null as babel.NodePath | null, validator: null as babel.NodePath | null, @@ -526,8 +405,8 @@ function handleCreateMiddlewareCallExpression( ) } - // If we're on the client, remove the validator call expression - if (opts.env === 'client') { + // If we're on the client or ssr, remove the validator call expression + if (opts.env === 'client' || opts.env === 'ssr') { if (t.isMemberExpression(callExpressionPaths.validator.node.callee)) { callExpressionPaths.validator.replaceWith( callExpressionPaths.validator.node.callee.object, @@ -544,9 +423,9 @@ function handleCreateMiddlewareCallExpression( throw new Error('createMiddleware must be called with a "use" property!') } - // If we're on the client, remove the use call expression + // If we're on the client, remove the server call expression - if (opts.env === 'client') { + if (opts.env === 'client' || opts.env === 'ssr') { if (t.isMemberExpression(callExpressionPaths.server.node.callee)) { callExpressionPaths.server.replaceWith( callExpressionPaths.server.node.callee.object, @@ -563,7 +442,12 @@ function buildEnvOnlyCallExpressionHandler(env: 'client' | 'server') { if (debug) console.info(`Handling ${env}Only call expression:`, path.toString()) - if (opts.env === env) { + const isEnvMatch = + env === 'client' + ? opts.env === 'client' + : opts.env === 'server' || opts.env === 'ssr' + + if (isEnvMatch) { // extract the inner function from the call expression const innerInputExpression = path.node.arguments[0] @@ -648,7 +532,9 @@ function handleCreateIsomorphicFnCallExpression( ) } - const envCallExpression = callExpressionPaths[opts.env] + const resolvedEnv = opts.env === 'ssr' ? 'client' : opts.env + + const envCallExpression = callExpressionPaths[resolvedEnv] if (!envCallExpression) { // if we don't have an implementation for this environment, default to a no-op @@ -662,7 +548,7 @@ function handleCreateIsomorphicFnCallExpression( if (!t.isExpression(innerInputExpression)) { throw new Error( - `createIsomorphicFn().${opts.env}(func) must be called with a function!`, + `createIsomorphicFn().${resolvedEnv}(func) must be called with a function!`, ) } diff --git a/packages/start-vite-plugin/src/index.ts b/packages/start-vite-plugin/src/index.ts index bd40710f2a..1245d7d082 100644 --- a/packages/start-vite-plugin/src/index.ts +++ b/packages/start-vite-plugin/src/index.ts @@ -7,7 +7,7 @@ import type { Plugin } from 'vite' const debug = Boolean(process.env.TSR_VITE_DEBUG) export type TanStackStartViteOptions = { - env: 'server' | 'client' + env: 'server' | 'ssr' | 'client' } const transformFuncs = [ @@ -22,7 +22,7 @@ const eitherFuncRegex = new RegExp( `(function ${transformFuncs.join('|function ')})`, ) -export function TanStackStartViteServerFn( +export function TanStackStartVitePlugin( opts: TanStackStartViteOptions, ): Plugin { let ROOT: string = process.cwd() diff --git a/packages/start-vite-plugin/tests/createServerFn/createServerFn.test.ts b/packages/start-vite-plugin/tests/createServerFn/createServerFn.test.ts index 19b86a0c01..d46d1babb7 100644 --- a/packages/start-vite-plugin/tests/createServerFn/createServerFn.test.ts +++ b/packages/start-vite-plugin/tests/createServerFn/createServerFn.test.ts @@ -59,4 +59,48 @@ describe('createServerFn compiles correctly', async () => { }) }).toThrowError() }) + + test('should work with identifiers of functions', () => { + const code = ` + import { createServerFn } from '@tanstack/start' + const myFunc = () => { + return 'hello from the server' + } + const myServerFn = createServerFn().handler(myFunc)` + + const compiledResultClient = compileStartOutput({ + root: '/test', + filename: 'test.ts', + code, + env: 'client', + }) + + const compiledResultServer = compileStartOutput({ + root: '/test', + filename: 'test.ts', + code, + env: 'server', + }) + + expect(compiledResultClient.code).toMatchInlineSnapshot(` + "import { createServerFn } from '@tanstack/start'; + const myServerFn = createServerFn().handler(opts => { + "use server"; + + return myServerFn.__executeServer(opts); + });" + `) + + expect(compiledResultServer.code).toMatchInlineSnapshot(` + "import { createServerFn } from '@tanstack/start'; + const myFunc = () => { + return 'hello from the server'; + }; + const myServerFn = createServerFn().handler(opts => { + "use server"; + + return myServerFn.__executeServer(opts); + }, myFunc);" + `) + }) }) diff --git a/packages/start-vite-plugin/tests/createServerFn/snapshots/client/createServerFnDestructured.tsx b/packages/start-vite-plugin/tests/createServerFn/snapshots/client/createServerFnDestructured.tsx index be1b58b186..752850e42e 100644 --- a/packages/start-vite-plugin/tests/createServerFn/snapshots/client/createServerFnDestructured.tsx +++ b/packages/start-vite-plugin/tests/createServerFn/snapshots/client/createServerFnDestructured.tsx @@ -35,11 +35,6 @@ export const withVariable = createServerFn({ return withVariable.__executeServer(opts); }); -async function abstractedFunction() { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -} function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { return async (input: unknown) => { return fn(schema.parse(input)); diff --git a/packages/start-vite-plugin/tests/createServerFn/snapshots/client/createServerFnDestructuredRename.tsx b/packages/start-vite-plugin/tests/createServerFn/snapshots/client/createServerFnDestructuredRename.tsx index f51f0ade21..55710f4321 100644 --- a/packages/start-vite-plugin/tests/createServerFn/snapshots/client/createServerFnDestructuredRename.tsx +++ b/packages/start-vite-plugin/tests/createServerFn/snapshots/client/createServerFnDestructuredRename.tsx @@ -21,11 +21,6 @@ export const withVariable = serverFn({ return withVariable.__executeServer(opts); }); -async function abstractedFunction() { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -} function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { return async (input: unknown) => { return fn(schema.parse(input)); diff --git a/packages/start-vite-plugin/tests/createServerFn/snapshots/client/createServerFnStarImport.tsx b/packages/start-vite-plugin/tests/createServerFn/snapshots/client/createServerFnStarImport.tsx index 750a52532a..b33435a9fe 100644 --- a/packages/start-vite-plugin/tests/createServerFn/snapshots/client/createServerFnStarImport.tsx +++ b/packages/start-vite-plugin/tests/createServerFn/snapshots/client/createServerFnStarImport.tsx @@ -21,11 +21,6 @@ export const withVariable = TanStackStart.createServerFn({ return withVariable.__executeServer(opts); }); -async function abstractedFunction() { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -} function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { return async (input: unknown) => { return fn(schema.parse(input)); diff --git a/packages/start-vite-plugin/tests/createServerFn/snapshots/server/createServerFnStarImport.tsx b/packages/start-vite-plugin/tests/createServerFn/snapshots/server/createServerFnStarImport.tsx index 66088cb181..3f79037fe7 100644 --- a/packages/start-vite-plugin/tests/createServerFn/snapshots/server/createServerFnStarImport.tsx +++ b/packages/start-vite-plugin/tests/createServerFn/snapshots/server/createServerFnStarImport.tsx @@ -7,6 +7,8 @@ export const withUseServer = TanStackStart.createServerFn({ return withUseServer.__executeServer(opts); }, async function () { + 'use server'; + console.info('Fetching posts...'); await new Promise(r => setTimeout(r, 500)); return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); diff --git a/packages/start/src/client-runtime/fetcher.tsx b/packages/start/src/client-runtime/fetcher.tsx index 70eea4b9ae..5cb729514e 100644 --- a/packages/start/src/client-runtime/fetcher.tsx +++ b/packages/start/src/client-runtime/fetcher.tsx @@ -43,7 +43,13 @@ export async function fetcher( }), }) - if (encodedPayload) base += `&${encodedPayload}` + if (encodedPayload) { + if (base.includes('?')) { + base += `&${encodedPayload}` + } else { + base += `?${encodedPayload}` + } + } } // Create the request diff --git a/packages/start/src/client-runtime/getBaseUrl.tsx b/packages/start/src/client-runtime/getBaseUrl.tsx index dfcf7947ed..99cc564263 100644 --- a/packages/start/src/client-runtime/getBaseUrl.tsx +++ b/packages/start/src/client-runtime/getBaseUrl.tsx @@ -9,6 +9,6 @@ function sanitizeBase(base: string | undefined) { return base.replace(/^\/|\/$/g, '') } -export function getBaseUrl(base: string | undefined, id: string, name: string) { - return `${base}/${sanitizeBase(process.env.TSS_SERVER_BASE)}/?_serverFnId=${encodeURI(id)}&_serverFnName=${encodeURI(name)}` +export function getBaseUrl(base: string | undefined, functionId: string) { + return `${base}/${sanitizeBase(process.env.TSS_SERVER_BASE)}/${encodeURI(functionId)}` } diff --git a/packages/start/src/client-runtime/index.tsx b/packages/start/src/client-runtime/index.tsx index 59b4434d4d..680bde58be 100644 --- a/packages/start/src/client-runtime/index.tsx +++ b/packages/start/src/client-runtime/index.tsx @@ -1,20 +1,15 @@ import { fetcher } from './fetcher' import { getBaseUrl } from './getBaseUrl' -import type { CreateRpcFn } from '@tanstack/directive-functions-plugin' +import type { CreateClientRpcFn } from '@tanstack/directive-functions-plugin' -export const createClientRpc: CreateRpcFn = (opts) => { - const base = getBaseUrl( - window.location.origin, - opts.filename, - opts.functionId, - ) +export const createClientRpc: CreateClientRpcFn = (functionId) => { + const base = getBaseUrl(window.location.origin, functionId) const fn = (...args: Array) => fetcher(base, args, fetch) return Object.assign(fn, { url: base, - filename: opts.filename, - functionId: opts.functionId, + functionId, }) } diff --git a/packages/start/src/client/createServerFn.ts b/packages/start/src/client/createServerFn.ts index 6408e783cd..de490aec65 100644 --- a/packages/start/src/client/createServerFn.ts +++ b/packages/start/src/client/createServerFn.ts @@ -221,7 +221,7 @@ export function createServerFn< invariant( extractedFn.url, - `createServerFn must be called with a function that is marked with the 'use server' pragma. Are you using the @tanstack/start-vite-plugin ?`, + `createServerFn must be called with a function that has a 'url' property. Are you using the @tanstack/start-vite-plugin properly?`, ) const resolvedMiddleware = [ diff --git a/packages/start/src/config/index.ts b/packages/start/src/config/index.ts index c6e9c80d0d..beb35e419e 100644 --- a/packages/start/src/config/index.ts +++ b/packages/start/src/config/index.ts @@ -7,13 +7,14 @@ import { resolve } from 'import-meta-resolve' import { TanStackRouterVite } from '@tanstack/router-plugin/vite' import { TanStackStartViteDeadCodeElimination, - TanStackStartViteServerFn, + TanStackStartVitePlugin, } from '@tanstack/start-vite-plugin' import { getConfig } from '@tanstack/router-generator' import { createApp } from 'vinxi' import { config } from 'vinxi/plugins/config' // // @ts-expect-error // import { serverComponents } from '@vinxi/server-components/plugin' +import { createTanStackServerFnPlugin } from '@tanstack/directive-functions-plugin' import { tanstackStartVinxiFileRouter } from './vinxi-file-router.js' import { checkDeploymentPresetInput, @@ -119,6 +120,8 @@ export function defineConfig( const apiEntryExists = existsSync(apiEntry) + const TanStackServerFnsPlugin = createTanStackServerFnPlugin() + let vinxiApp = createApp({ server: { ...serverOptions, @@ -166,12 +169,7 @@ export function defineConfig( }), ...(viteConfig.plugins || []), ...(clientViteConfig.plugins || []), - Directive({ - getRuntimeCode: (opts) => - `import { createClientRpc } from '@tanstack/start/client-runtime'`, - replacer: (opts) => - `createClientRpc('${opts.filename}', '${opts.functionId}')`, - }), + TanStackServerFnsPlugin.client, viteReact(opts.react), // TODO: RSCS - enable this // serverComponents.client(), @@ -210,12 +208,7 @@ export function defineConfig( }), ...(getUserViteConfig(opts.vite).plugins || []), ...(getUserViteConfig(opts.routers?.ssr?.vite).plugins || []), - TanStackServerFnPluginServer({ - getRuntimeCode: (opts) => - `import { createServerRpc } from '@tanstack/start/ssr-runtime'`, - replacer: (opts) => - `createSsrRpc('${opts.filename}', '${opts.functionId}')`, - }), + TanStackServerFnsPlugin.ssr, config('start-ssr', { ssr: { external: ['@vinxi/react-server-dom/client'], @@ -256,16 +249,11 @@ export function defineConfig( ...injectDefineEnv('TSS_API_BASE', apiBase), }, }), - TanStackServerFnPluginServer({ - getRuntimeCode: (opts) => - `import { createServerRpc } from '@tanstack/start/server-runtime'`, - replacer: (opts) => - `createServerRpc('${opts.filename}', '${opts.functionId}')`, - // TODO: RSCS - remove this - // resolve: { - // conditions: [], - // }, - }), + TanStackServerFnsPlugin.server, + // TODO: RSCS - remove this + // resolve: { + // conditions: [], + // }, // TODO: RSCs - add this // serverComponents.serverActions({ // resolve: { @@ -401,8 +389,8 @@ function withStartPlugins(opts: TanStackStartOutputConfig, router: RouterType) { ...tsrConfig.experimental, }, }), - TanStackStartViteServerFn({ - env: router === 'client' ? 'client' : 'server', + TanStackStartVitePlugin({ + env: router === 'server' ? 'server' : 'client', }), ], [ diff --git a/packages/start/src/server-handler/index.tsx b/packages/start/src/server-handler/index.tsx index 51c9881985..54151ba682 100644 --- a/packages/start/src/server-handler/index.tsx +++ b/packages/start/src/server-handler/index.tsx @@ -1,4 +1,6 @@ /// +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' import { defaultTransformer, isNotFound, @@ -11,7 +13,8 @@ import { getResponseStatus, toWebRequest, } from 'vinxi/http' -import { getManifest } from 'vinxi/manifest' +// @ts-expect-error +import serverFnManifest from 'tsr:server-fn-manifest' import type { H3Event } from 'vinxi/server' export default eventHandler(handleServerAction) @@ -23,28 +26,44 @@ async function handleServerAction(event: H3Event) { export async function handleServerRequest(request: Request, _event?: H3Event) { const method = request.method const url = new URL(request.url, 'http://localhost:3000') + // extract the serverFnId from the url as host/_server/:serverFnId + // Define a regex to match the path and extract the :thing part + const regex = /\/_server\/([^/?#]+)/ + + // Execute the regex + const match = url.pathname.match(regex) + const serverFnId = match ? match[1] : null const search = Object.fromEntries(url.searchParams.entries()) as { - _serverFnId?: string - _serverFnName?: string payload?: any } - const serverFnId = search._serverFnId - const serverFnName = search._serverFnName - - if (!serverFnId || !serverFnName) { - throw new Error('Invalid request') - } - invariant(typeof serverFnId === 'string', 'Invalid server action') - if (process.env.NODE_ENV === 'development') - console.info(`ServerFn Request: ${serverFnId} - ${serverFnName}`) - if (process.env.NODE_ENV === 'development') console.info() + const serverFnInfo = serverFnManifest[serverFnId] - const action = (await getManifest('server').chunks[serverFnId]?.import())?.[ - serverFnName - ] as Function + invariant(serverFnInfo, 'Server function not found') + + if (process.env.NODE_ENV === 'development') + console.info(`\nServerFn Request: ${serverFnId}`) + + let action: Function + if (process.env.NODE_ENV === 'development') { + action = (await (globalThis as any).app + .getRouter('server') + .internals.devServer.ssrLoadModule(serverFnInfo.splitFilename) + .then((d: any) => d.default)) as Function + } else { + const router = (globalThis as any).app.getRouter('server') + const filePath = join( + router.outDir, + router.base, + serverFnInfo.chunkName + '.mjs', + ) + const url = pathToFileURL(filePath).toString() + action = (await import(url).then((d) => d.default)) as Function + } + + invariant(action, 'Server function not found') const response = await (async () => { try { diff --git a/packages/start/src/server-runtime/index.tsx b/packages/start/src/server-runtime/index.tsx index 1b222d6ec9..4434abec24 100644 --- a/packages/start/src/server-runtime/index.tsx +++ b/packages/start/src/server-runtime/index.tsx @@ -1,13 +1,16 @@ -// import { getBaseUrl } from '../client-runtime/getBaseUrl' -import type { CreateRpcFn } from '@tanstack/directive-functions-plugin' +import { getBaseUrl } from '../client-runtime/getBaseUrl' +import type { CreateServerRpcFn } from '@tanstack/directive-functions-plugin' -export const createServerRpc: CreateRpcFn = (opts) => { - // const functionUrl = getBaseUrl('http://localhost:3000', id, name) - const functionUrl = 'https://localhost:3000' +const fakeHost = 'http://localhost:3000' - return Object.assign(opts.fn, { - url: functionUrl, - filename: opts.filename, - functionId: opts.functionId, +export const createServerRpc: CreateServerRpcFn = ( + functionId, + splitImportFn, +) => { + const functionUrl = getBaseUrl(fakeHost, functionId) + + return Object.assign(splitImportFn, { + url: functionUrl.replace(fakeHost, ''), + functionId, }) } diff --git a/packages/start/src/ssr-runtime/index.tsx b/packages/start/src/ssr-runtime/index.tsx index 4a148fdda2..88688d9446 100644 --- a/packages/start/src/ssr-runtime/index.tsx +++ b/packages/start/src/ssr-runtime/index.tsx @@ -4,7 +4,7 @@ import invariant from 'tiny-invariant' import { fetcher } from '../client-runtime/fetcher' import { getBaseUrl } from '../client-runtime/getBaseUrl' import { handleServerRequest } from '../server-handler/index' -import type { CreateRpcFn } from '@tanstack/directive-functions-plugin' +import type { CreateSsrRpcFn } from '@tanstack/directive-functions-plugin' export function createIncomingMessage( url: string, @@ -78,10 +78,10 @@ export function createIncomingMessage( const fakeHost = 'http://localhost:3000' -export const createSsrRpc: CreateRpcFn = (opts) => { - const functionUrl = getBaseUrl(fakeHost, opts.filename, opts.functionId) +export const createSsrRpc: CreateSsrRpcFn = (functionId) => { + const functionUrl = getBaseUrl(fakeHost, functionId) - const proxyFn = (...args: Array) => { + const ssrFn = (...args: Array) => { invariant( args.length === 1, 'Server functions can only accept a single argument', @@ -149,9 +149,8 @@ export const createSsrRpc: CreateRpcFn = (opts) => { }) } - return Object.assign(proxyFn, { + return Object.assign(ssrFn, { url: functionUrl.replace(fakeHost, ''), - filename: opts.filename, - functionId: opts.functionId, + functionId, }) } diff --git a/packages/start/vite.config.ts b/packages/start/vite.config.ts index 7f3b092680..196e0fc33a 100644 --- a/packages/start/vite.config.ts +++ b/packages/start/vite.config.ts @@ -16,7 +16,7 @@ const config = defineConfig({ export default mergeConfig( config, tanstackViteConfig({ - externalDeps: ['@tanstack/start/router-manifest'], + externalDeps: ['@tanstack/start/router-manifest', 'tsr:server-fn-manifest'], entry: [ './src/client/index.tsx', './src/server/index.tsx', From 97af6f7366dd9096bd4a3fa72bc09f01699e4862 Mon Sep 17 00:00:00 2001 From: Tanner Linsley Date: Sun, 22 Dec 2024 22:22:35 -0700 Subject: [PATCH 12/13] move serverFnFetcher to start client --- .../server-functions-vite-plugin/src/index.ts | 3 +-- packages/start/src/client-runtime/index.tsx | 6 +++--- packages/start/src/client/index.tsx | 1 + .../fetcher.tsx => client/serverFnFetcher.tsx} | 16 ++++++++-------- packages/start/src/ssr-runtime/index.tsx | 4 ++-- 5 files changed, 15 insertions(+), 15 deletions(-) rename packages/start/src/{client-runtime/fetcher.tsx => client/serverFnFetcher.tsx} (92%) diff --git a/packages/server-functions-vite-plugin/src/index.ts b/packages/server-functions-vite-plugin/src/index.ts index e6f1f6cd69..7f42dd8db7 100644 --- a/packages/server-functions-vite-plugin/src/index.ts +++ b/packages/server-functions-vite-plugin/src/index.ts @@ -91,7 +91,6 @@ export function createTanStackServerFnPlugin(_opts?: {}): { }), // Now that we have the directiveFnsById, we need to create a new // virtual module that can be used to import that manifest - readManifestPlugin(), { name: 'tanstack-start-server-fn-vite-plugin-build-client', generateBundle() { @@ -108,6 +107,7 @@ export function createTanStackServerFnPlugin(_opts?: {}): { }, ], ssr: [ + readManifestPlugin(), // The SSR plugin is used to compile the server directives TanStackDirectiveFunctionsPlugin({ directive: 'use server', @@ -125,7 +125,6 @@ export function createTanStackServerFnPlugin(_opts?: {}): { Object.assign(directiveFnsById, d) }, }), - readManifestPlugin(), ], server: [ readManifestPlugin(), diff --git a/packages/start/src/client-runtime/index.tsx b/packages/start/src/client-runtime/index.tsx index 680bde58be..c4bf7b8536 100644 --- a/packages/start/src/client-runtime/index.tsx +++ b/packages/start/src/client-runtime/index.tsx @@ -1,11 +1,11 @@ -import { fetcher } from './fetcher' +import { serverFnFetcher } from '../client' import { getBaseUrl } from './getBaseUrl' import type { CreateClientRpcFn } from '@tanstack/directive-functions-plugin' export const createClientRpc: CreateClientRpcFn = (functionId) => { const base = getBaseUrl(window.location.origin, functionId) - const fn = (...args: Array) => fetcher(base, args, fetch) + const fn = (...args: Array) => serverFnFetcher(base, args, fetch) return Object.assign(fn, { url: base, @@ -13,4 +13,4 @@ export const createClientRpc: CreateClientRpcFn = (functionId) => { }) } -export { fetcher } +export { serverFnFetcher } diff --git a/packages/start/src/client/index.tsx b/packages/start/src/client/index.tsx index 08f8b6f2df..12b6942ca5 100644 --- a/packages/start/src/client/index.tsx +++ b/packages/start/src/client/index.tsx @@ -50,3 +50,4 @@ export { StartClient } from './StartClient' export { mergeHeaders } from './headers' export { renderRsc } from './renderRSC' export { useServerFn } from './useServerFn' +export { serverFnFetcher } from './serverFnFetcher' diff --git a/packages/start/src/client-runtime/fetcher.tsx b/packages/start/src/client/serverFnFetcher.tsx similarity index 92% rename from packages/start/src/client-runtime/fetcher.tsx rename to packages/start/src/client/serverFnFetcher.tsx index 5cb729514e..7aac71c7f1 100644 --- a/packages/start/src/client-runtime/fetcher.tsx +++ b/packages/start/src/client/serverFnFetcher.tsx @@ -5,10 +5,10 @@ import { isPlainObject, isRedirect, } from '@tanstack/react-router' -import type { MiddlewareOptions } from '../client/createServerFn' +import type { MiddlewareOptions } from './createServerFn' -export async function fetcher( - base: string, +export async function serverFnFetcher( + url: string, args: Array, handler: (request: Request) => Promise, ) { @@ -44,16 +44,16 @@ export async function fetcher( }) if (encodedPayload) { - if (base.includes('?')) { - base += `&${encodedPayload}` + if (url.includes('?')) { + url += `&${encodedPayload}` } else { - base += `?${encodedPayload}` + url += `?${encodedPayload}` } } } // Create the request - const request = new Request(base, { + const request = new Request(url, { method: first.method, headers, ...getFetcherRequestOptions(first), @@ -83,7 +83,7 @@ export async function fetcher( // If not a custom fetcher, just proxy the arguments // through as a POST request - const request = new Request(base, { + const request = new Request(url, { method: 'POST', headers: { Accept: 'application/json', diff --git a/packages/start/src/ssr-runtime/index.tsx b/packages/start/src/ssr-runtime/index.tsx index 88688d9446..5547b756ee 100644 --- a/packages/start/src/ssr-runtime/index.tsx +++ b/packages/start/src/ssr-runtime/index.tsx @@ -1,7 +1,7 @@ import { Readable } from 'node:stream' import { getEvent, getRequestHeaders } from 'vinxi/http' import invariant from 'tiny-invariant' -import { fetcher } from '../client-runtime/fetcher' +import { serverFnFetcher } from '../client' import { getBaseUrl } from '../client-runtime/getBaseUrl' import { handleServerRequest } from '../server-handler/index' import type { CreateSsrRpcFn } from '@tanstack/directive-functions-plugin' @@ -87,7 +87,7 @@ export const createSsrRpc: CreateSsrRpcFn = (functionId) => { 'Server functions can only accept a single argument', ) - return fetcher(functionUrl, args, async (request) => { + return serverFnFetcher(functionUrl, args, async (request) => { const event = getEvent() const ogRequestHeaders = getRequestHeaders(event) From e1d96fa9361b02dba4c36d879f2f3381c082e68b Mon Sep 17 00:00:00 2001 From: Tanner Linsley Date: Sun, 22 Dec 2024 22:23:10 -0700 Subject: [PATCH 13/13] checkpoint --- .../react/start-basic/app/routes/posts.tsx | 18 ++++++++- .../react/start-basic/app/utils/posts.tsx | 6 +-- .../src/compilers.ts | 27 ++++++++++--- packages/start-vite-plugin/src/compilers.ts | 19 +++++++++- packages/start/src/client/createServerFn.ts | 4 +- .../start/src/client/createServerFnClient.ts | 38 +++++++++++++++++++ packages/start/src/client/index.tsx | 1 + 7 files changed, 100 insertions(+), 13 deletions(-) create mode 100644 packages/start/src/client/createServerFnClient.ts diff --git a/examples/react/start-basic/app/routes/posts.tsx b/examples/react/start-basic/app/routes/posts.tsx index ae49032459..2b397ec6ba 100644 --- a/examples/react/start-basic/app/routes/posts.tsx +++ b/examples/react/start-basic/app/routes/posts.tsx @@ -1,8 +1,22 @@ import { Link, Outlet, createFileRoute } from '@tanstack/react-router' -import { fetchPosts } from '../utils/posts' +import { createServerFnClient } from '@tanstack/start' + +const serverFnClient = createServerFnClient({ + baseUrl: + process.env.NODE_ENV === 'production' + ? 'https://my-site.com/_server' + : 'http://localhost:3000/_server', +}) export const Route = createFileRoute('/posts')({ - loader: async () => fetchPosts(), + // loader: async () => fetchPosts(), + loader: () => + serverFnClient + .fetch({ + functionId: 'fetchPosts', + method: 'GET', + }) + .then((d) => d.result), component: PostsComponent, }) diff --git a/examples/react/start-basic/app/utils/posts.tsx b/examples/react/start-basic/app/utils/posts.tsx index 99e43f5197..6cc1be1438 100644 --- a/examples/react/start-basic/app/utils/posts.tsx +++ b/examples/react/start-basic/app/utils/posts.tsx @@ -9,7 +9,7 @@ export type PostType = { body: string } -export const fetchPost = createServerFn({ method: 'GET' }) +export const fetchPost = createServerFn({ id: 'fetchPost', method: 'GET' }) .middleware([logMiddleware]) .validator((d: string) => d) .handler(async ({ data }) => { @@ -28,8 +28,8 @@ export const fetchPost = createServerFn({ method: 'GET' }) return post }) -export const fetchPosts = createServerFn({ method: 'GET' }) - .middleware([logMiddleware]) +export const fetchPosts = createServerFn({ id: 'fetchPosts', method: 'GET' }) + // .middleware([logMiddleware]) .handler(async () => { console.info('Fetching posts...') return axios diff --git a/packages/server-functions-vite-plugin/src/compilers.ts b/packages/server-functions-vite-plugin/src/compilers.ts index eb16b459bc..ea2d2b46fe 100644 --- a/packages/server-functions-vite-plugin/src/compilers.ts +++ b/packages/server-functions-vite-plugin/src/compilers.ts @@ -15,6 +15,7 @@ if ('default' in generate) { } export interface DirectiveFn { + hasStableId: boolean nodePath: SupportedFunctionPath functionName: string functionId: string @@ -332,6 +333,8 @@ export function findDirectives( function compileDirective(directiveFn: SupportedFunctionPath) { // Remove the directive directive from the function body + let directiveId: string | undefined + if ( babel.types.isFunction(directiveFn.node) && babel.types.isBlockStatement(directiveFn.node.body) @@ -340,6 +343,15 @@ export function findDirectives( directiveFn.node.body.directives.filter( (directive) => directive.value.value !== opts.directive, ) + + // Look for an optional id: \d+ directive + const idDirective = directiveFn.node.body.directives.find((directive) => + directive.value.value.startsWith('id:'), + ) + + if (idDirective) { + directiveId = idDirective.value.value.split(':')[1]?.trim() + } } // Find the nearest variable name @@ -436,12 +448,14 @@ export function findDirectives( ) as SupportedFunctionPath } - const functionId = makeFileLocationUrlSafe( - `${opts.filename.replace( - path.extname(opts.filename), - '', - )}--${functionName}`.replace(opts.root, ''), - ) + const functionId = + directiveId || + makeFileLocationUrlSafe( + `${opts.filename.replace( + path.extname(opts.filename), + '', + )}--${functionName}`.replace(opts.root, ''), + ) const [filename, searchParamsStr] = opts.filename.split('?') const searchParams = new URLSearchParams(searchParamsStr) @@ -482,6 +496,7 @@ export function findDirectives( // Finally register the directive to // our map of directives directiveFnsById[functionId] = { + hasStableId: !!directiveId, nodePath: directiveFn, referenceName, functionName: functionName || '', diff --git a/packages/start-vite-plugin/src/compilers.ts b/packages/start-vite-plugin/src/compilers.ts index 9024436413..2eaeb16fef 100644 --- a/packages/start-vite-plugin/src/compilers.ts +++ b/packages/start-vite-plugin/src/compilers.ts @@ -223,6 +223,18 @@ function handleCreateServerFnCallExpression( ) }) + let serverFnId: string | undefined + + calledOptions?.node.properties.find((prop) => { + return ( + t.isObjectProperty(prop) && + t.isIdentifier(prop.key) && + prop.key.name === 'id' && + t.isStringLiteral(prop.value) && + (serverFnId = prop.value.value) + ) + }) + const callExpressionPaths = { middleware: null as babel.NodePath | null, validator: null as babel.NodePath | null, @@ -349,7 +361,12 @@ function handleCreateServerFnCallExpression( ), ), ], - [t.directive(t.directiveLiteral('use server'))], + [ + t.directive(t.directiveLiteral('use server')), + serverFnId + ? t.directive(t.directiveLiteral(`id: ${serverFnId}`)) + : (undefined as any), + ].filter(Boolean), ), ), ) diff --git a/packages/start/src/client/createServerFn.ts b/packages/start/src/client/createServerFn.ts index de490aec65..40b0c6d4ab 100644 --- a/packages/start/src/client/createServerFn.ts +++ b/packages/start/src/client/createServerFn.ts @@ -96,6 +96,7 @@ type ServerFnBaseOptions< TMiddlewares = unknown, TInput = unknown, > = { + id?: string method: TMethod validateClient?: boolean middleware?: Constrain> @@ -173,7 +174,8 @@ export function createServerFn< TValidator = undefined, >( options?: { - method: TMethod + id?: string + method?: TMethod }, __opts?: ServerFnBaseOptions, ): ServerFnBuilder { diff --git a/packages/start/src/client/createServerFnClient.ts b/packages/start/src/client/createServerFnClient.ts new file mode 100644 index 0000000000..afb67f261e --- /dev/null +++ b/packages/start/src/client/createServerFnClient.ts @@ -0,0 +1,38 @@ +import { serverFnFetcher } from './serverFnFetcher' +import type { CompiledFetcherFnOptions } from './createServerFn' + +type ServerFnClient = { + fetch: ( + opts: Omit & { + data?: any + functionId: string + }, + ) => Promise +} + +export function createServerFnClient(clientOpts: { + baseUrl: string +}): ServerFnClient { + return { + fetch: (fetchOpts) => { + return serverFnFetcher( + joinPaths(clientOpts.baseUrl, fetchOpts.functionId), + [fetchOpts], + fetch, + ) + }, + } +} + +function joinPaths(...paths: Array) { + const firstPath = paths[0] || '' + const lastPath = paths[paths.length - 1] || '' + const prefix = firstPath.startsWith('/') ? '/' : '' + const suffix = lastPath.endsWith('/') ? '/' : '' + + return ( + prefix + + paths.map((path) => path.replace(/(^\/+|\/+$)/g, '')).join('/') + + suffix + ) +} diff --git a/packages/start/src/client/index.tsx b/packages/start/src/client/index.tsx index 12b6942ca5..7e9155537a 100644 --- a/packages/start/src/client/index.tsx +++ b/packages/start/src/client/index.tsx @@ -51,3 +51,4 @@ export { mergeHeaders } from './headers' export { renderRsc } from './renderRSC' export { useServerFn } from './useServerFn' export { serverFnFetcher } from './serverFnFetcher' +export { createServerFnClient } from './createServerFnClient'