@tanstack/start-server-core 1.121.0-alpha.7 → 1.121.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/cjs/createStartHandler.cjs +17 -36
  2. package/dist/cjs/createStartHandler.cjs.map +1 -1
  3. package/dist/cjs/index.cjs +3 -0
  4. package/dist/cjs/index.cjs.map +1 -1
  5. package/dist/cjs/index.d.cts +3 -2
  6. package/dist/cjs/loadVirtualModule.cjs +39 -0
  7. package/dist/cjs/loadVirtualModule.cjs.map +1 -0
  8. package/dist/cjs/loadVirtualModule.d.cts +6 -0
  9. package/dist/cjs/router-manifest.cjs +9 -4
  10. package/dist/cjs/router-manifest.cjs.map +1 -1
  11. package/dist/cjs/router-manifest.d.cts +4 -5
  12. package/dist/cjs/server-functions-handler.cjs +5 -2
  13. package/dist/cjs/server-functions-handler.cjs.map +1 -1
  14. package/dist/cjs/serverRoute.cjs +3 -1
  15. package/dist/cjs/serverRoute.cjs.map +1 -1
  16. package/dist/cjs/serverRoute.d.cts +15 -10
  17. package/dist/cjs/virtual-modules.cjs +9 -0
  18. package/dist/cjs/virtual-modules.cjs.map +1 -0
  19. package/dist/cjs/virtual-modules.d.cts +10 -0
  20. package/dist/esm/createStartHandler.js +17 -14
  21. package/dist/esm/createStartHandler.js.map +1 -1
  22. package/dist/esm/index.d.ts +3 -2
  23. package/dist/esm/index.js +4 -1
  24. package/dist/esm/index.js.map +1 -1
  25. package/dist/esm/loadVirtualModule.d.ts +6 -0
  26. package/dist/esm/loadVirtualModule.js +17 -0
  27. package/dist/esm/loadVirtualModule.js.map +1 -0
  28. package/dist/esm/router-manifest.d.ts +4 -5
  29. package/dist/esm/router-manifest.js +9 -4
  30. package/dist/esm/router-manifest.js.map +1 -1
  31. package/dist/esm/server-functions-handler.js +5 -2
  32. package/dist/esm/server-functions-handler.js.map +1 -1
  33. package/dist/esm/serverRoute.d.ts +15 -10
  34. package/dist/esm/serverRoute.js +3 -1
  35. package/dist/esm/serverRoute.js.map +1 -1
  36. package/dist/esm/virtual-modules.d.ts +10 -0
  37. package/dist/esm/virtual-modules.js +9 -0
  38. package/dist/esm/virtual-modules.js.map +1 -0
  39. package/package.json +4 -4
  40. package/src/createStartHandler.ts +24 -13
  41. package/src/global.d.ts +6 -0
  42. package/src/index.tsx +11 -2
  43. package/src/loadVirtualModule.ts +21 -0
  44. package/src/router-manifest.ts +10 -9
  45. package/src/server-functions-handler.ts +6 -11
  46. package/src/serverRoute.ts +85 -29
  47. package/src/tanstack-start.d.ts +14 -1
  48. package/src/virtual-modules.ts +13 -0
@@ -1,7 +1,8 @@
1
1
  import { Assign, Constrain, Expand, ResolveParams, RouteConstraints, TrimPathRight } from '@tanstack/router-core';
2
2
  import { AnyRequestMiddleware, AssignAllServerContext } from '@tanstack/start-client-core';
3
- type TODO = any;
4
- export declare function createServerFileRoute<TParentRoute extends AnyServerRouteWithTypes, TId extends RouteConstraints['TId'], TPath extends RouteConstraints['TPath'], TFullPath extends RouteConstraints['TFullPath'], TChildren>(__?: never): ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren>;
3
+ export declare function createServerFileRoute<TFilePath extends keyof ServerFileRoutesByPath, TParentRoute extends AnyServerRouteWithTypes = ServerFileRoutesByPath[TFilePath]['parentRoute'], TId extends RouteConstraints['TId'] = ServerFileRoutesByPath[TFilePath]['id'], TPath extends RouteConstraints['TPath'] = ServerFileRoutesByPath[TFilePath]['path'], TFullPath extends RouteConstraints['TFullPath'] = ServerFileRoutesByPath[TFilePath]['fullPath'], TChildren = ServerFileRoutesByPath[TFilePath]['children']>(_: TFilePath): ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren>;
4
+ export interface ServerFileRoutesByPath {
5
+ }
5
6
  export interface ServerRouteOptions<TParentRoute extends AnyServerRouteWithTypes, TId extends RouteConstraints['TId'], TPath extends RouteConstraints['TPath'], TFullPath extends RouteConstraints['TFullPath'], TMiddlewares> {
6
7
  id: TId;
7
8
  path: TPath;
@@ -19,8 +20,13 @@ export type ServerRouteManifest = {
19
20
  }>;
20
21
  };
21
22
  export declare function createServerRoute<TParentRoute extends AnyServerRouteWithTypes, TId extends RouteConstraints['TId'], TPath extends RouteConstraints['TPath'], TFullPath extends RouteConstraints['TFullPath'], TChildren>(__?: never, __opts?: Partial<ServerRouteOptions<TParentRoute, TId, TPath, TFullPath, undefined>>): ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren>;
23
+ export declare const createServerRootRoute: typeof createServerRoute;
22
24
  export type ServerRouteAddFileChildrenFn<in out TParentRoute extends AnyServerRouteWithTypes, in out TId extends RouteConstraints['TId'], in out TPath extends RouteConstraints['TPath'], in out TFullPath extends RouteConstraints['TFullPath'], in out TMiddlewares, in out TMethods, in out TChildren> = (children: TChildren) => ServerRouteWithTypes<TParentRoute, TId, TPath, TFullPath, TMiddlewares, TMethods, TChildren>;
23
- export type CreateServerFileRoute<TParentRoute extends AnyServerRouteWithTypes, TId extends RouteConstraints['TId'], TPath extends RouteConstraints['TPath'], TFullPath extends RouteConstraints['TFullPath'], TChildren> = (options?: undefined) => ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren>;
25
+ export interface ServerRouteMethodBuilderOptions<TParentRoute extends AnyServerRouteWithTypes, TFullPath extends string, TMiddlewares, TMethodMiddlewares, TResponse> {
26
+ handler?: ServerRouteMethodHandlerFn<TParentRoute, TFullPath, TMiddlewares, TMethodMiddlewares, TResponse>;
27
+ middlewares?: Constrain<TMethodMiddlewares, ReadonlyArray<AnyRequestMiddleware>>;
28
+ }
29
+ export type CreateServerFileRoute<TParentRoute extends AnyServerRouteWithTypes, TId extends RouteConstraints['TId'], TPath extends RouteConstraints['TPath'], TFullPath extends RouteConstraints['TFullPath'], TChildren> = () => ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren>;
24
30
  export type AnyServerRouteWithTypes = ServerRouteWithTypes<any, any, any, any, any, any, any>;
25
31
  export interface ServerRouteWithTypes<TParentRoute extends AnyServerRouteWithTypes, TId extends RouteConstraints['TId'], TPath extends RouteConstraints['TPath'], TFullPath extends RouteConstraints['TFullPath'], TMiddlewares, TMethods, TChildren> {
26
32
  _types: ServerRouteTypes<TParentRoute, TId, TPath, TFullPath, TMiddlewares, TMethods>;
@@ -81,11 +87,11 @@ export interface ServerRouteMethodHandlerCtx<in out TParentRoute extends AnyServ
81
87
  }
82
88
  export type MergeMethodMiddlewares<TMiddlewares, TMethodMiddlewares> = TMiddlewares extends ReadonlyArray<any> ? TMethodMiddlewares extends ReadonlyArray<any> ? readonly [...TMiddlewares, ...TMethodMiddlewares] : TMiddlewares : TMethodMiddlewares;
83
89
  export type AssignAllMethodContext<TParentRoute extends AnyServerRouteWithTypes, TMiddlewares, TMethodMiddlewares> = ResolveAllServerContext<TParentRoute, MergeMethodMiddlewares<TMiddlewares, TMethodMiddlewares>>;
84
- export type AnyRouteMethodsBuilder = ServerRouteMethodBuilderWithTypes<any, any, any, any>;
85
- export interface ServerRouteMethodBuilder<TParentRoute extends AnyServerRouteWithTypes, TFullPath extends string, TMiddlewares> extends ServerRouteMethodBuilderWithTypes<TFullPath, TMiddlewares, undefined, undefined>, ServerRouteMethodBuilderMiddleware<TParentRoute, TFullPath, TMiddlewares>, ServerRouteMethodBuilderHandler<TParentRoute, TFullPath, TMiddlewares, undefined> {
90
+ export type AnyRouteMethodsBuilder = ServerRouteMethodBuilderWithTypes<any, any, any, any, any>;
91
+ export interface ServerRouteMethodBuilder<TParentRoute extends AnyServerRouteWithTypes, TFullPath extends string, TMiddlewares> extends ServerRouteMethodBuilderWithTypes<TParentRoute, TFullPath, TMiddlewares, undefined, undefined>, ServerRouteMethodBuilderMiddleware<TParentRoute, TFullPath, TMiddlewares>, ServerRouteMethodBuilderHandler<TParentRoute, TFullPath, TMiddlewares, undefined> {
86
92
  }
87
- export interface ServerRouteMethodBuilderWithTypes<TFullPath extends string, TMiddlewares, TMethodMiddlewares, TResponse> {
88
- _options: TODO;
93
+ export interface ServerRouteMethodBuilderWithTypes<TParentRoute extends AnyServerRouteWithTypes, TFullPath extends string, TMiddlewares, TMethodMiddlewares, TResponse> {
94
+ _options: ServerRouteMethodBuilderOptions<TParentRoute, TFullPath, TMiddlewares, TMethodMiddlewares, TResponse>;
89
95
  _types: ServerRouteMethodBuilderTypes<TFullPath, TMiddlewares, TMethodMiddlewares, TResponse>;
90
96
  }
91
97
  export interface ServerRouteMethodBuilderTypes<in out TFullPath extends string, in out TMiddlewares, in out TMethodMiddlewares, in out TResponse> {
@@ -97,12 +103,12 @@ export interface ServerRouteMethodBuilderTypes<in out TFullPath extends string,
97
103
  export interface ServerRouteMethodBuilderMiddleware<TParentRoute extends AnyServerRouteWithTypes, TFullPath extends string, TMiddlewares> {
98
104
  middleware: <const TNewMethodMiddlewares>(middleware: Constrain<TNewMethodMiddlewares, ReadonlyArray<AnyRequestMiddleware>>) => ServerRouteMethodBuilderAfterMiddleware<TParentRoute, TFullPath, TMiddlewares, TNewMethodMiddlewares>;
99
105
  }
100
- export interface ServerRouteMethodBuilderAfterMiddleware<TParentRoute extends AnyServerRouteWithTypes, TFullPath extends string, TMiddlewares, TMethodMiddlewares> extends ServerRouteMethodBuilderWithTypes<TFullPath, TMiddlewares, TMethodMiddlewares, undefined>, ServerRouteMethodBuilderHandler<TParentRoute, TFullPath, TMiddlewares, TMethodMiddlewares> {
106
+ export interface ServerRouteMethodBuilderAfterMiddleware<TParentRoute extends AnyServerRouteWithTypes, TFullPath extends string, TMiddlewares, TMethodMiddlewares> extends ServerRouteMethodBuilderWithTypes<TParentRoute, TFullPath, TMiddlewares, TMethodMiddlewares, undefined>, ServerRouteMethodBuilderHandler<TParentRoute, TFullPath, TMiddlewares, TMethodMiddlewares> {
101
107
  }
102
108
  export interface ServerRouteMethodBuilderHandler<TParentRoute extends AnyServerRouteWithTypes, TFullPath extends string, TMiddlewares, TMethodMiddlewares> {
103
109
  handler: <TResponse>(handler: ServerRouteMethodHandlerFn<TParentRoute, TFullPath, TMiddlewares, TMethodMiddlewares, TResponse>) => ServerRouteMethodBuilderAfterHandler<TParentRoute, TFullPath, TMiddlewares, TMethodMiddlewares, TResponse>;
104
110
  }
105
- export interface ServerRouteMethodBuilderAfterHandler<TParentRoute extends AnyServerRouteWithTypes, TFullPath extends string, TMiddlewares, TMethodMiddlewares, TResponse> extends ServerRouteMethodBuilderWithTypes<TFullPath, TMiddlewares, TMethodMiddlewares, TResponse> {
111
+ export interface ServerRouteMethodBuilderAfterHandler<TParentRoute extends AnyServerRouteWithTypes, TFullPath extends string, TMiddlewares, TMethodMiddlewares, TResponse> extends ServerRouteMethodBuilderWithTypes<TParentRoute, TFullPath, TMiddlewares, TMethodMiddlewares, TResponse> {
106
112
  opts: ServerRouteMethod<TParentRoute, TFullPath, TMiddlewares, TMethodMiddlewares>;
107
113
  }
108
114
  export interface ServerRouteMethod<TParentRoute extends AnyServerRouteWithTypes, TFullPath extends string, TMiddlewares, TMethodMiddlewares> {
@@ -112,4 +118,3 @@ export interface ServerRouteMethod<TParentRoute extends AnyServerRouteWithTypes,
112
118
  export interface ServerRouteAfterMethods<TParentRoute extends AnyServerRouteWithTypes, TId extends RouteConstraints['TId'], TPath extends RouteConstraints['TPath'], TFullPath extends RouteConstraints['TFullPath'], TMiddlewares, TMethods, TChildren> extends ServerRouteWithTypes<TParentRoute, TId, TPath, TFullPath, TMiddlewares, TMethods, TChildren> {
113
119
  options: ServerRouteOptions<TParentRoute, TId, TPath, TFullPath, TMiddlewares>;
114
120
  }
115
- export {};
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const VIRTUAL_MODULES = {
4
+ routeTree: "tanstack-start-route-tree:v",
5
+ startManifest: "tanstack-start-manifest:v",
6
+ serverFnManifest: "tanstack-start-server-fn-manifest:v"
7
+ };
8
+ exports.VIRTUAL_MODULES = VIRTUAL_MODULES;
9
+ //# sourceMappingURL=virtual-modules.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"virtual-modules.cjs","sources":["../../src/virtual-modules.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/consistent-type-imports */\n\nexport const VIRTUAL_MODULES = {\n routeTree: 'tanstack-start-route-tree:v',\n startManifest: 'tanstack-start-manifest:v',\n serverFnManifest: 'tanstack-start-server-fn-manifest:v',\n} as const\n\nexport type VirtualModules = {\n [VIRTUAL_MODULES.routeTree]: typeof import('tanstack-start-route-tree:v')\n [VIRTUAL_MODULES.startManifest]: typeof import('tanstack-start-manifest:v')\n [VIRTUAL_MODULES.serverFnManifest]: typeof import('tanstack-start-server-fn-manifest:v')\n}\n"],"names":[],"mappings":";;AAEO,MAAM,kBAAkB;AAAA,EAC7B,WAAW;AAAA,EACX,eAAe;AAAA,EACf,kBAAkB;AACpB;;"}
@@ -0,0 +1,10 @@
1
+ export declare const VIRTUAL_MODULES: {
2
+ readonly routeTree: "tanstack-start-route-tree:v";
3
+ readonly startManifest: "tanstack-start-manifest:v";
4
+ readonly serverFnManifest: "tanstack-start-server-fn-manifest:v";
5
+ };
6
+ export type VirtualModules = {
7
+ [VIRTUAL_MODULES.routeTree]: typeof import('tanstack-start-route-tree:v');
8
+ [VIRTUAL_MODULES.startManifest]: typeof import('tanstack-start-manifest:v');
9
+ [VIRTUAL_MODULES.serverFnManifest]: typeof import('tanstack-start-server-fn-manifest:v');
10
+ };
@@ -5,6 +5,8 @@ import { getResponseHeaders, requestHandler } from "./h3.js";
5
5
  import { attachRouterServerSsrUtils, dehydrateRouter } from "./ssr-server.js";
6
6
  import { getStartManifest } from "./router-manifest.js";
7
7
  import { handleServerAction } from "./server-functions-handler.js";
8
+ import { VIRTUAL_MODULES } from "./virtual-modules.js";
9
+ import { loadVirtualModule } from "./loadVirtualModule.js";
8
10
  function getStartResponseHeaders(opts) {
9
11
  let headers = mergeHeaders(
10
12
  getResponseHeaders(),
@@ -24,6 +26,7 @@ function getStartResponseHeaders(opts) {
24
26
  function createStartHandler({
25
27
  createRouter
26
28
  }) {
29
+ let serverRouteTree = null;
27
30
  return (cb) => {
28
31
  const originalFetch = globalThis.fetch;
29
32
  const startRequestResolver = async ({ request }) => {
@@ -49,8 +52,10 @@ function createStartHandler({
49
52
  const history = createMemoryHistory({
50
53
  initialEntries: [href]
51
54
  });
55
+ const APP_BASE = process.env.TSS_APP_BASE || "/";
52
56
  const router = createRouter();
53
- attachRouterServerSsrUtils(router, getStartManifest());
57
+ const startRoutesManifest = await getStartManifest({ basePath: APP_BASE });
58
+ attachRouterServerSsrUtils(router, startRoutesManifest);
54
59
  router.update({
55
60
  history
56
61
  });
@@ -62,28 +67,25 @@ function createStartHandler({
62
67
  );
63
68
  }
64
69
  const serverFnBase = joinPaths([
65
- "/",
70
+ APP_BASE,
66
71
  trimPath(process.env.TSS_SERVER_FN_BASE),
67
72
  "/"
68
73
  ]);
69
74
  if (href.startsWith(serverFnBase)) {
70
75
  return await handleServerAction({ request });
71
76
  }
72
- const serverRouteTreeModule = await (async () => {
77
+ if (serverRouteTree === null) {
73
78
  try {
74
- return await import(
75
- // @ts-expect-error
76
- "tanstack-start-server-routes-manifest:v"
77
- );
79
+ serverRouteTree = (await loadVirtualModule(VIRTUAL_MODULES.routeTree)).serverRouteTree;
78
80
  } catch (e) {
79
81
  console.log(e);
80
- return void 0;
81
82
  }
82
- })();
83
- if (serverRouteTreeModule) {
83
+ }
84
+ if (serverRouteTree) {
84
85
  const [_matchedRoutes, response3] = await handleServerRoutes({
85
- routeTree: serverRouteTreeModule.routeTree,
86
- request
86
+ routeTree: serverRouteTree,
87
+ request,
88
+ basePath: APP_BASE
87
89
  });
88
90
  if (response3) return response3;
89
91
  }
@@ -172,7 +174,8 @@ function createStartHandler({
172
174
  }
173
175
  async function handleServerRoutes({
174
176
  routeTree,
175
- request
177
+ request,
178
+ basePath
176
179
  }) {
177
180
  const { flatRoutes, routesById, routesByPath } = processRouteTree({
178
181
  routeTree,
@@ -189,7 +192,7 @@ async function handleServerRoutes({
189
192
  });
190
193
  const { matchedRoutes, foundRoute, routeParams } = getMatchedRoutes({
191
194
  pathname: history.location.pathname,
192
- basepath: "/",
195
+ basepath: basePath,
193
196
  caseSensitive: true,
194
197
  routesByPath,
195
198
  routesById,
@@ -1 +1 @@
1
- {"version":3,"file":"createStartHandler.js","sources":["../../src/createStartHandler.ts"],"sourcesContent":["import { createMemoryHistory } from '@tanstack/history'\nimport {\n flattenMiddlewares,\n json,\n mergeHeaders,\n} from '@tanstack/start-client-core'\nimport {\n getMatchedRoutes,\n isRedirect,\n isResolvedRedirect,\n joinPaths,\n processRouteTree,\n rootRouteId,\n trimPath,\n} from '@tanstack/router-core'\nimport { getResponseHeaders, requestHandler } from './h3'\nimport { attachRouterServerSsrUtils, dehydrateRouter } from './ssr-server'\nimport { getStartManifest } from './router-manifest'\nimport { handleServerAction } from './server-functions-handler'\nimport type { AnyServerRoute, AnyServerRouteWithTypes } from './serverRoute'\nimport type { RequestHandler } from './h3'\nimport type { AnyRouter } from '@tanstack/router-core'\nimport type { HandlerCallback } from './handlerCallback'\n\ntype TODO = any\n\nexport type CustomizeStartHandler<TRouter extends AnyRouter> = (\n cb: HandlerCallback<TRouter>,\n) => RequestHandler\n\nexport function getStartResponseHeaders(opts: { router: AnyRouter }) {\n let headers = mergeHeaders(\n getResponseHeaders(),\n {\n 'Content-Type': 'text/html; charset=UTF-8',\n },\n ...opts.router.state.matches.map((match) => {\n return match.headers\n }),\n )\n // Handle Redirects\n const { redirect } = opts.router.state\n\n if (redirect) {\n headers = mergeHeaders(headers, redirect.headers)\n }\n return headers\n}\n\nexport function createStartHandler<TRouter extends AnyRouter>({\n createRouter,\n}: {\n createRouter: () => TRouter\n}): CustomizeStartHandler<TRouter> {\n return (cb) => {\n const originalFetch = globalThis.fetch\n\n const startRequestResolver: RequestHandler = async ({ request }) => {\n // Patching fetch function to use our request resolver\n // if the input starts with `/` which is a common pattern for\n // client-side routing.\n // When we encounter similar requests, we can assume that the\n // user wants to use the same origin as the current request.\n globalThis.fetch = async function (input, init) {\n function resolve(url: URL, requestOptions: RequestInit | undefined) {\n const fetchRequest = new Request(url, requestOptions)\n return startRequestResolver({ request: fetchRequest })\n }\n\n function getOrigin() {\n return (\n request.headers.get('Origin') ||\n request.headers.get('Referer') ||\n 'http://localhost'\n )\n }\n\n if (typeof input === 'string' && input.startsWith('/')) {\n // e.g: fetch('/api/data')\n const url = new URL(input, getOrigin())\n return resolve(url, init)\n } else if (\n typeof input === 'object' &&\n 'url' in input &&\n typeof input.url === 'string' &&\n input.url.startsWith('/')\n ) {\n // e.g: fetch(new Request('/api/data'))\n const url = new URL(input.url, getOrigin())\n return resolve(url, init)\n }\n\n // If not, it should just use the original fetch\n return originalFetch(input, init)\n }\n\n const url = new URL(request.url)\n const href = url.href.replace(url.origin, '')\n\n // Create a history for the client-side router\n const history = createMemoryHistory({\n initialEntries: [href],\n })\n\n // Create the client-side router\n const router = createRouter()\n\n // Attach the server-side SSR utils to the client-side router\n attachRouterServerSsrUtils(router, getStartManifest())\n\n // Update the client-side router with the history and context\n router.update({\n history,\n })\n\n const response = await (async () => {\n try {\n if (!process.env.TSS_SERVER_FN_BASE) {\n throw new Error(\n 'tanstack/start-server-core: TSS_SERVER_FN_BASE must be defined in your environment for createStartHandler()',\n )\n }\n\n // First, let's attempt to handle server functions\n // Add trailing slash to sanitise user defined TSS_SERVER_FN_BASE\n const serverFnBase = joinPaths([\n '/',\n trimPath(process.env.TSS_SERVER_FN_BASE),\n '/',\n ])\n if (href.startsWith(serverFnBase)) {\n return await handleServerAction({ request })\n }\n\n // Then move on to attempting to load server routes\n const serverRouteTreeModule = await (async () => {\n try {\n return (await import(\n // @ts-expect-error\n 'tanstack-start-server-routes-manifest:v'\n )) as { routeTree: AnyServerRoute }\n } catch (e) {\n console.log(e)\n return undefined\n }\n })()\n\n // If we have a server route tree, then we try matching to see if we have a\n // server route that matches the request.\n if (serverRouteTreeModule) {\n const [_matchedRoutes, response] = await handleServerRoutes({\n routeTree: serverRouteTreeModule.routeTree,\n request,\n })\n\n if (response) return response\n }\n\n const requestAcceptHeader = request.headers.get('Accept') || '*/*'\n const splitRequestAcceptHeader = requestAcceptHeader.split(',')\n\n const supportedMimeTypes = ['*/*', 'text/html']\n const isRouterAcceptSupported = supportedMimeTypes.some((mimeType) =>\n splitRequestAcceptHeader.some((acceptedMimeType) =>\n acceptedMimeType.trim().startsWith(mimeType),\n ),\n )\n\n if (!isRouterAcceptSupported) {\n return json(\n {\n error: 'Only HTML requests are supported here',\n },\n {\n status: 500,\n },\n )\n }\n\n // If no Server Routes were found, so fallback to normal SSR matching using\n // the router\n\n await router.load()\n\n // If there was a redirect, skip rendering the page at all\n if (router.state.redirect) return router.state.redirect\n\n dehydrateRouter(router)\n\n const responseHeaders = getStartResponseHeaders({ router })\n const response = await cb({\n request,\n router,\n responseHeaders,\n })\n\n return response\n } catch (err) {\n if (err instanceof Response) {\n return err\n }\n\n throw err\n }\n })()\n\n if (isRedirect(response)) {\n if (isResolvedRedirect(response)) {\n if (request.headers.get('x-tsr-redirect') === 'manual') {\n return json(\n {\n ...response.options,\n isSerializedRedirect: true,\n },\n {\n headers: response.headers,\n },\n )\n }\n return response\n }\n if (\n response.options.to &&\n typeof response.options.to === 'string' &&\n !response.options.to.startsWith('/')\n ) {\n throw new Error(\n `Server side redirects must use absolute paths via the 'href' or 'to' options. Received: ${JSON.stringify(response.options)}`,\n )\n }\n\n if (\n ['params', 'search', 'hash'].some(\n (d) => typeof (response.options as any)[d] === 'function',\n )\n ) {\n throw new Error(\n `Server side redirects must use static search, params, and hash values and do not support functional values. Received functional values for: ${Object.keys(\n response.options,\n )\n .filter((d) => typeof (response.options as any)[d] === 'function')\n .map((d) => `\"${d}\"`)\n .join(', ')}`,\n )\n }\n\n const redirect = router.resolveRedirect(response)\n\n if (request.headers.get('x-tsr-redirect') === 'manual') {\n return json(\n {\n ...response.options,\n isSerializedRedirect: true,\n },\n {\n headers: response.headers,\n },\n )\n }\n\n return redirect\n }\n\n return response\n }\n\n return requestHandler(startRequestResolver)\n }\n}\n\nasync function handleServerRoutes({\n routeTree,\n request,\n}: {\n routeTree: AnyServerRouteWithTypes\n request: Request\n}) {\n const { flatRoutes, routesById, routesByPath } = processRouteTree({\n routeTree,\n initRoute: (route, i) => {\n route.init({\n originalIndex: i,\n })\n },\n })\n\n const url = new URL(request.url)\n const pathname = url.pathname\n\n const history = createMemoryHistory({\n initialEntries: [pathname],\n })\n\n const { matchedRoutes, foundRoute, routeParams } =\n getMatchedRoutes<AnyServerRouteWithTypes>({\n pathname: history.location.pathname,\n basepath: '/',\n caseSensitive: true,\n routesByPath,\n routesById,\n flatRoutes,\n })\n\n let response: Response | undefined\n\n if (foundRoute && foundRoute.id !== rootRouteId) {\n // We've found a server route that matches the request, so we can call it.\n // TODO: Get the input type-signature correct\n // TODO: Perform the middlewares?\n // TODO: Error handling? What happens when its `throw redirect()` vs `throw new Error()`?\n\n const method = Object.keys(foundRoute.options.methods).find(\n (method) => method.toLowerCase() === request.method.toLowerCase(),\n )\n\n if (method) {\n const handler = foundRoute.options.methods[method]\n\n if (handler) {\n const middlewares = flattenMiddlewares(\n matchedRoutes.flatMap((r) => r.options.middleware).filter(Boolean),\n ).map((d) => d.options.server)\n\n middlewares.push(handlerToMiddleware(handler) as TODO)\n\n // TODO: This is starting to feel too much like a server function\n // Do generalize the existing middleware execution? Or do we need to\n // build a new middleware execution system for server routes?\n const ctx = await executeMiddleware(middlewares, {\n request,\n context: {},\n params: routeParams,\n pathname: history.location.pathname,\n })\n\n response = ctx.response\n }\n }\n }\n\n // We return the matched routes too so if\n // the app router happens to match the same path,\n // it can use any request middleware from server routes\n return [matchedRoutes, response] as const\n}\n\nfunction handlerToMiddleware(\n handler: AnyServerRouteWithTypes['options']['methods'][string],\n) {\n return async ({ next: _next, ...rest }: TODO) => ({\n response: await handler(rest),\n })\n}\n\nfunction executeMiddleware(middlewares: TODO, ctx: TODO) {\n let index = -1\n\n const next = async (ctx: TODO) => {\n index++\n const middleware = middlewares[index]\n if (!middleware) return ctx\n\n const result = await middleware({\n ...ctx,\n // Allow the middleware to call the next middleware in the chain\n next: async (nextCtx: TODO) => {\n // Allow the caller to extend the context for the next middleware\n const nextResult = await next({ ...ctx, ...nextCtx })\n\n // Merge the result into the context\\\n return Object.assign(ctx, handleCtxResult(nextResult))\n },\n // Allow the middleware result to extend the return context\n }).catch((err: TODO) => {\n if (isSpecialResponse(err)) {\n return {\n response: err,\n }\n }\n\n throw err\n })\n\n // Merge the middleware result into the context, just in case it\n // returns a partial context\n return Object.assign(ctx, handleCtxResult(result))\n }\n\n return handleCtxResult(next(ctx))\n}\n\nfunction handleCtxResult(result: TODO) {\n if (isSpecialResponse(result)) {\n return {\n response: result,\n }\n }\n\n return result\n}\n\nfunction isSpecialResponse(err: TODO) {\n return isResponse(err) || isRedirect(err)\n}\n\nfunction isResponse(response: Response): response is Response {\n return response instanceof Response\n}\n"],"names":["url","response","method","ctx"],"mappings":";;;;;;;AA8BO,SAAS,wBAAwB,MAA6B;AACnE,MAAI,UAAU;AAAA,IACZ,mBAAmB;AAAA,IACnB;AAAA,MACE,gBAAgB;AAAA,IAClB;AAAA,IACA,GAAG,KAAK,OAAO,MAAM,QAAQ,IAAI,CAAC,UAAU;AAC1C,aAAO,MAAM;AAAA,IACd,CAAA;AAAA,EACH;AAEA,QAAM,EAAE,SAAA,IAAa,KAAK,OAAO;AAEjC,MAAI,UAAU;AACF,cAAA,aAAa,SAAS,SAAS,OAAO;AAAA,EAAA;AAE3C,SAAA;AACT;AAEO,SAAS,mBAA8C;AAAA,EAC5D;AACF,GAEmC;AACjC,SAAO,CAAC,OAAO;AACb,UAAM,gBAAgB,WAAW;AAEjC,UAAM,uBAAuC,OAAO,EAAE,cAAc;AAMvD,iBAAA,QAAQ,eAAgB,OAAO,MAAM;AACrC,iBAAA,QAAQA,MAAU,gBAAyC;AAClE,gBAAM,eAAe,IAAI,QAAQA,MAAK,cAAc;AACpD,iBAAO,qBAAqB,EAAE,SAAS,cAAc;AAAA,QAAA;AAGv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AS,MAAM,WAAW;AAAA,MAC9B,GAAGA;AAAAA;AAAAA,MAEH,MAAM,OAAO,YAAkB;AAEvB,cAAA,aAAa,MAAM,KAAK,EAAE,GAAGA,MAAK,GAAG,SAAS;AAGpD,eAAO,OAAO,OAAOA,MAAK,gBAAgB,UAAU,CAAC;AAAA,MAAA;AAAA;AAAA,IACvD,CAED,EAAE,MAAM,CAAC,QAAc;AAClB,UAAA,kBAAkB,GAAG,GAAG;AACnB,eAAA;AAAA,UACL,UAAU;AAAA,QACZ;AAAA,MAAA;AAGI,YAAA;AAAA,IAAA,CACP;AAID,WAAO,OAAO,OAAOA,MAAK,gBAAgB,MAAM,CAAC;AAAA,EACnD;AAEO,SAAA,gBAAgB,KAAK,GAAG,CAAC;AAClC;AAEA,SAAS,gBAAgB,QAAc;AACjC,MAAA,kBAAkB,MAAM,GAAG;AACtB,WAAA;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,EAAA;AAGK,SAAA;AACT;AAEA,SAAS,kBAAkB,KAAW;AACpC,SAAO,WAAW,GAAG,KAAK,WAAW,GAAG;AAC1C;AAEA,SAAS,WAAW,UAA0C;AAC5D,SAAO,oBAAoB;AAC7B;"}
1
+ {"version":3,"file":"createStartHandler.js","sources":["../../src/createStartHandler.ts"],"sourcesContent":["import { createMemoryHistory } from '@tanstack/history'\nimport {\n flattenMiddlewares,\n json,\n mergeHeaders,\n} from '@tanstack/start-client-core'\nimport {\n getMatchedRoutes,\n isRedirect,\n isResolvedRedirect,\n joinPaths,\n processRouteTree,\n rootRouteId,\n trimPath,\n} from '@tanstack/router-core'\nimport { getResponseHeaders, requestHandler } from './h3'\nimport { attachRouterServerSsrUtils, dehydrateRouter } from './ssr-server'\nimport { getStartManifest } from './router-manifest'\nimport { handleServerAction } from './server-functions-handler'\nimport { VIRTUAL_MODULES } from './virtual-modules'\nimport { loadVirtualModule } from './loadVirtualModule'\nimport type { AnyServerRoute, AnyServerRouteWithTypes } from './serverRoute'\nimport type { RequestHandler } from './h3'\nimport type { AnyRouter } from '@tanstack/router-core'\nimport type { HandlerCallback } from './handlerCallback'\n\ntype TODO = any\n\nexport type CustomizeStartHandler<TRouter extends AnyRouter> = (\n cb: HandlerCallback<TRouter>,\n) => RequestHandler\n\nexport function getStartResponseHeaders(opts: { router: AnyRouter }) {\n let headers = mergeHeaders(\n getResponseHeaders(),\n {\n 'Content-Type': 'text/html; charset=UTF-8',\n },\n ...opts.router.state.matches.map((match) => {\n return match.headers\n }),\n )\n // Handle Redirects\n const { redirect } = opts.router.state\n\n if (redirect) {\n headers = mergeHeaders(headers, redirect.headers)\n }\n return headers\n}\n\nexport function createStartHandler<TRouter extends AnyRouter>({\n createRouter,\n}: {\n createRouter: () => TRouter\n}): CustomizeStartHandler<TRouter> {\n let serverRouteTree: AnyServerRoute | undefined | null = null\n\n return (cb) => {\n const originalFetch = globalThis.fetch\n\n const startRequestResolver: RequestHandler = async ({ request }) => {\n // Patching fetch function to use our request resolver\n // if the input starts with `/` which is a common pattern for\n // client-side routing.\n // When we encounter similar requests, we can assume that the\n // user wants to use the same origin as the current request.\n globalThis.fetch = async function (input, init) {\n function resolve(url: URL, requestOptions: RequestInit | undefined) {\n const fetchRequest = new Request(url, requestOptions)\n return startRequestResolver({ request: fetchRequest })\n }\n\n function getOrigin() {\n return (\n request.headers.get('Origin') ||\n request.headers.get('Referer') ||\n 'http://localhost'\n )\n }\n\n if (typeof input === 'string' && input.startsWith('/')) {\n // e.g: fetch('/api/data')\n const url = new URL(input, getOrigin())\n return resolve(url, init)\n } else if (\n typeof input === 'object' &&\n 'url' in input &&\n typeof input.url === 'string' &&\n input.url.startsWith('/')\n ) {\n // e.g: fetch(new Request('/api/data'))\n const url = new URL(input.url, getOrigin())\n return resolve(url, init)\n }\n\n // If not, it should just use the original fetch\n return originalFetch(input, init)\n }\n\n const url = new URL(request.url)\n const href = url.href.replace(url.origin, '')\n\n // Create a history for the client-side router\n const history = createMemoryHistory({\n initialEntries: [href],\n })\n\n const APP_BASE = process.env.TSS_APP_BASE || '/'\n\n // TODO do not create a router instance before we need it\n // Create the client-side router\n const router = createRouter()\n\n // TODO only build startRoutesManifest once, not per request\n // Attach the server-side SSR utils to the client-side router\n const startRoutesManifest = await getStartManifest({ basePath: APP_BASE })\n attachRouterServerSsrUtils(router, startRoutesManifest)\n\n // Update the client-side router with the history and context\n router.update({\n history,\n })\n\n const response = await (async () => {\n try {\n if (!process.env.TSS_SERVER_FN_BASE) {\n throw new Error(\n 'tanstack/start-server-core: TSS_SERVER_FN_BASE must be defined in your environment for createStartHandler()',\n )\n }\n\n // First, let's attempt to handle server functions\n // Add trailing slash to sanitise user defined TSS_SERVER_FN_BASE\n const serverFnBase = joinPaths([\n APP_BASE,\n trimPath(process.env.TSS_SERVER_FN_BASE),\n '/',\n ])\n if (href.startsWith(serverFnBase)) {\n return await handleServerAction({ request })\n }\n\n if (serverRouteTree === null) {\n try {\n serverRouteTree = (\n await loadVirtualModule(VIRTUAL_MODULES.routeTree)\n ).serverRouteTree\n } catch (e) {\n console.log(e)\n }\n }\n\n // If we have a server route tree, then we try matching to see if we have a\n // server route that matches the request.\n if (serverRouteTree) {\n const [_matchedRoutes, response] = await handleServerRoutes({\n routeTree: serverRouteTree,\n request,\n basePath: APP_BASE,\n })\n\n if (response) return response\n }\n\n const requestAcceptHeader = request.headers.get('Accept') || '*/*'\n const splitRequestAcceptHeader = requestAcceptHeader.split(',')\n\n const supportedMimeTypes = ['*/*', 'text/html']\n const isRouterAcceptSupported = supportedMimeTypes.some((mimeType) =>\n splitRequestAcceptHeader.some((acceptedMimeType) =>\n acceptedMimeType.trim().startsWith(mimeType),\n ),\n )\n\n if (!isRouterAcceptSupported) {\n return json(\n {\n error: 'Only HTML requests are supported here',\n },\n {\n status: 500,\n },\n )\n }\n\n // If no Server Routes were found, so fallback to normal SSR matching using\n // the router\n\n await router.load()\n\n // If there was a redirect, skip rendering the page at all\n if (router.state.redirect) return router.state.redirect\n\n dehydrateRouter(router)\n\n const responseHeaders = getStartResponseHeaders({ router })\n const response = await cb({\n request,\n router,\n responseHeaders,\n })\n\n return response\n } catch (err) {\n if (err instanceof Response) {\n return err\n }\n\n throw err\n }\n })()\n\n if (isRedirect(response)) {\n if (isResolvedRedirect(response)) {\n if (request.headers.get('x-tsr-redirect') === 'manual') {\n return json(\n {\n ...response.options,\n isSerializedRedirect: true,\n },\n {\n headers: response.headers,\n },\n )\n }\n return response\n }\n if (\n response.options.to &&\n typeof response.options.to === 'string' &&\n !response.options.to.startsWith('/')\n ) {\n throw new Error(\n `Server side redirects must use absolute paths via the 'href' or 'to' options. Received: ${JSON.stringify(response.options)}`,\n )\n }\n\n if (\n ['params', 'search', 'hash'].some(\n (d) => typeof (response.options as any)[d] === 'function',\n )\n ) {\n throw new Error(\n `Server side redirects must use static search, params, and hash values and do not support functional values. Received functional values for: ${Object.keys(\n response.options,\n )\n .filter((d) => typeof (response.options as any)[d] === 'function')\n .map((d) => `\"${d}\"`)\n .join(', ')}`,\n )\n }\n\n const redirect = router.resolveRedirect(response)\n\n if (request.headers.get('x-tsr-redirect') === 'manual') {\n return json(\n {\n ...response.options,\n isSerializedRedirect: true,\n },\n {\n headers: response.headers,\n },\n )\n }\n\n return redirect\n }\n\n return response\n }\n\n return requestHandler(startRequestResolver)\n }\n}\n\nasync function handleServerRoutes({\n routeTree,\n request,\n basePath,\n}: {\n routeTree: AnyServerRouteWithTypes\n request: Request\n basePath: string\n}) {\n // TODO only process server route tree once, not per request\n const { flatRoutes, routesById, routesByPath } = processRouteTree({\n routeTree,\n initRoute: (route, i) => {\n route.init({\n originalIndex: i,\n })\n },\n })\n\n const url = new URL(request.url)\n const pathname = url.pathname\n\n // TODO history seems not to be needed, we can just use the pathname\n const history = createMemoryHistory({\n initialEntries: [pathname],\n })\n\n const { matchedRoutes, foundRoute, routeParams } =\n getMatchedRoutes<AnyServerRouteWithTypes>({\n pathname: history.location.pathname,\n basepath: basePath,\n caseSensitive: true,\n routesByPath,\n routesById,\n flatRoutes,\n })\n\n let response: Response | undefined\n\n if (foundRoute && foundRoute.id !== rootRouteId) {\n // We've found a server route that matches the request, so we can call it.\n // TODO: Get the input type-signature correct\n // TODO: Perform the middlewares?\n // TODO: Error handling? What happens when its `throw redirect()` vs `throw new Error()`?\n\n const method = Object.keys(foundRoute.options.methods).find(\n (method) => method.toLowerCase() === request.method.toLowerCase(),\n )\n\n if (method) {\n const handler = foundRoute.options.methods[method]\n\n if (handler) {\n const middlewares = flattenMiddlewares(\n matchedRoutes.flatMap((r) => r.options.middleware).filter(Boolean),\n ).map((d) => d.options.server)\n\n middlewares.push(handlerToMiddleware(handler) as TODO)\n\n // TODO: This is starting to feel too much like a server function\n // Do generalize the existing middleware execution? Or do we need to\n // build a new middleware execution system for server routes?\n const ctx = await executeMiddleware(middlewares, {\n request,\n context: {},\n params: routeParams,\n pathname: history.location.pathname,\n })\n\n response = ctx.response\n }\n }\n }\n\n // We return the matched routes too so if\n // the app router happens to match the same path,\n // it can use any request middleware from server routes\n return [matchedRoutes, response] as const\n}\n\nfunction handlerToMiddleware(\n handler: AnyServerRouteWithTypes['options']['methods'][string],\n) {\n return async ({ next: _next, ...rest }: TODO) => ({\n response: await handler(rest),\n })\n}\n\nfunction executeMiddleware(middlewares: TODO, ctx: TODO) {\n let index = -1\n\n const next = async (ctx: TODO) => {\n index++\n const middleware = middlewares[index]\n if (!middleware) return ctx\n\n const result = await middleware({\n ...ctx,\n // Allow the middleware to call the next middleware in the chain\n next: async (nextCtx: TODO) => {\n // Allow the caller to extend the context for the next middleware\n const nextResult = await next({ ...ctx, ...nextCtx })\n\n // Merge the result into the context\\\n return Object.assign(ctx, handleCtxResult(nextResult))\n },\n // Allow the middleware result to extend the return context\n }).catch((err: TODO) => {\n if (isSpecialResponse(err)) {\n return {\n response: err,\n }\n }\n\n throw err\n })\n\n // Merge the middleware result into the context, just in case it\n // returns a partial context\n return Object.assign(ctx, handleCtxResult(result))\n }\n\n return handleCtxResult(next(ctx))\n}\n\nfunction handleCtxResult(result: TODO) {\n if (isSpecialResponse(result)) {\n return {\n response: result,\n }\n }\n\n return result\n}\n\nfunction isSpecialResponse(err: TODO) {\n return isResponse(err) || isRedirect(err)\n}\n\nfunction isResponse(response: Response): response is Response {\n return response instanceof Response\n}\n"],"names":["url","response","method","ctx"],"mappings":";;;;;;;;;AAgCO,SAAS,wBAAwB,MAA6B;AACnE,MAAI,UAAU;AAAA,IACZ,mBAAmB;AAAA,IACnB;AAAA,MACE,gBAAgB;AAAA,IAClB;AAAA,IACA,GAAG,KAAK,OAAO,MAAM,QAAQ,IAAI,CAAC,UAAU;AAC1C,aAAO,MAAM;AAAA,IACd,CAAA;AAAA,EACH;AAEA,QAAM,EAAE,SAAA,IAAa,KAAK,OAAO;AAEjC,MAAI,UAAU;AACF,cAAA,aAAa,SAAS,SAAS,OAAO;AAAA,EAAA;AAE3C,SAAA;AACT;AAEO,SAAS,mBAA8C;AAAA,EAC5D;AACF,GAEmC;AACjC,MAAI,kBAAqD;AAEzD,SAAO,CAAC,OAAO;AACb,UAAM,gBAAgB,WAAW;AAEjC,UAAM,uBAAuC,OAAO,EAAE,cAAc;AAMvD,iBAAA,QAAQ,eAAgB,OAAO,MAAM;AACrC,iBAAA,QAAQA,MAAU,gBAAyC;AAClE,gBAAM,eAAe,IAAI,QAAQA,MAAK,cAAc;AACpD,iBAAO,qBAAqB,EAAE,SAAS,cAAc;AAAA,QAAA;AAGvD,iBAAS,YAAY;AAEjB,iBAAA,QAAQ,QAAQ,IAAI,QAAQ,KAC5B,QAAQ,QAAQ,IAAI,SAAS,KAC7B;AAAA,QAAA;AAIJ,YAAI,OAAO,UAAU,YAAY,MAAM,WAAW,GAAG,GAAG;AAEtD,gBAAMA,OAAM,IAAI,IAAI,OAAO,WAAW;AAC/B,iBAAA,QAAQA,MAAK,IAAI;AAAA,QAExB,WAAA,OAAO,UAAU,YACjB,SAAS,SACT,OAAO,MAAM,QAAQ,YACrB,MAAM,IAAI,WAAW,GAAG,GACxB;AAEA,gBAAMA,OAA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G;AACnB,eAAA;AAAA,UACL,UAAU;AAAA,QACZ;AAAA,MAAA;AAGI,YAAA;AAAA,IAAA,CACP;AAID,WAAO,OAAO,OAAOA,MAAK,gBAAgB,MAAM,CAAC;AAAA,EACnD;AAEO,SAAA,gBAAgB,KAAK,GAAG,CAAC;AAClC;AAEA,SAAS,gBAAgB,QAAc;AACjC,MAAA,kBAAkB,MAAM,GAAG;AACtB,WAAA;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,EAAA;AAGK,SAAA;AACT;AAEA,SAAS,kBAAkB,KAAW;AACpC,SAAO,WAAW,GAAG,KAAK,WAAW,GAAG;AAC1C;AAEA,SAAS,WAAW,UAA0C;AAC5D,SAAO,oBAAoB;AAC7B;"}
@@ -7,5 +7,6 @@ export type { HandlerCallback } from './handlerCallback.js';
7
7
  export { attachRouterServerSsrUtils, dehydrateRouter } from './ssr-server.js';
8
8
  export { handleServerAction } from './server-functions-handler.js';
9
9
  export * from './h3.js';
10
- export { createServerRoute, createServerFileRoute } from './serverRoute.js';
11
- export type { CreateServerFileRoute } from './serverRoute.js';
10
+ export { createServerRoute, createServerFileRoute, createServerRootRoute, } from './serverRoute.js';
11
+ export type { CreateServerFileRoute, ServerFileRoutesByPath, } from './serverRoute.js';
12
+ export * from './virtual-modules.js';
package/dist/esm/index.js CHANGED
@@ -5,13 +5,15 @@ import { defineHandlerCallback } from "./handlerCallback.js";
5
5
  import { attachRouterServerSsrUtils, dehydrateRouter } from "./ssr-server.js";
6
6
  import { handleServerAction } from "./server-functions-handler.js";
7
7
  import { HTTPEventSymbol, appendCorsHeaders, appendCorsPreflightHeaders, appendHeader, appendHeaders, appendResponseHeader, appendResponseHeaders, assertMethod, clearResponseHeaders, clearSession, defaultContentType, defineEventHandler, defineMiddleware, deleteCookie, eventHandler, fetchWithEvent, getContext, getCookie, getEvent, getHeader, getHeaders, getProxyRequestHeaders, getQuery, getRequestFingerprint, getRequestHeader, getRequestHeaders, getRequestHost, getRequestIP, getRequestProtocol, getRequestURL, getRequestWebStream, getResponseHeader, getResponseHeaders, getResponseStatus, getResponseStatusText, getRouterParam, getRouterParams, getSession, getValidatedQuery, getValidatedRouterParams, getWebRequest, handleCacheHeaders, handleCors, isEvent, isMethod, isPreflightRequest, parseCookies, proxyRequest, readBody, readFormData, readMultipartFormData, readRawBody, readValidatedBody, removeResponseHeader, requestHandler, runWithEvent, sealSession, send, sendError, sendNoContent, sendProxy, sendRedirect, sendStream, sendWebResponse, setContext, setCookie, setHeader, setHeaders, setResponseHeader, setResponseHeaders, setResponseStatus, unsealSession, updateSession, useSession, writeEarlyHints } from "./h3.js";
8
- import { createServerFileRoute, createServerRoute } from "./serverRoute.js";
8
+ import { createServerFileRoute, createServerRootRoute, createServerRoute } from "./serverRoute.js";
9
+ import { VIRTUAL_MODULES } from "./virtual-modules.js";
9
10
  import { H3Error, H3Event, MIMES, callNodeListener, createApp, createAppEventHandler, createError, createEvent, createRouter, defineLazyEventHandler, defineNodeListener, defineNodeMiddleware, defineRequestMiddleware, defineResponseMiddleware, defineWebSocket, dynamicEventHandler, fromNodeMiddleware, fromPlainHandler, fromWebHandler, isCorsOriginAllowed, isError, isEventHandler, isStream, isWebResponse, lazyEventHandler, promisifyNodeListener, sanitizeStatusCode, sanitizeStatusMessage, serveStatic, splitCookiesString, toEventHandler, toNodeListener, toPlainHandler, toWebHandler, toWebRequest, useBase } from "h3";
10
11
  export {
11
12
  H3Error,
12
13
  H3Event,
13
14
  HTTPEventSymbol,
14
15
  MIMES,
16
+ VIRTUAL_MODULES,
15
17
  appendCorsHeaders,
16
18
  appendCorsPreflightHeaders,
17
19
  appendHeader,
@@ -30,6 +32,7 @@ export {
30
32
  createRequestHandler,
31
33
  createRouter,
32
34
  createServerFileRoute,
35
+ createServerRootRoute,
33
36
  createServerRoute,
34
37
  createStartHandler,
35
38
  defaultContentType,
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;"}
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;"}
@@ -0,0 +1,6 @@
1
+ import { VirtualModules } from './virtual-modules.js';
2
+ /**
3
+ * we need to explicitly enumerate all imports with string literals,
4
+ * otherwise vite will not pick them up during build
5
+ */
6
+ export declare function loadVirtualModule<TId extends keyof VirtualModules>(id: TId): Promise<VirtualModules[TId]>;
@@ -0,0 +1,17 @@
1
+ import { VIRTUAL_MODULES } from "./virtual-modules.js";
2
+ async function loadVirtualModule(id) {
3
+ switch (id) {
4
+ case VIRTUAL_MODULES.routeTree:
5
+ return await import("tanstack-start-route-tree:v");
6
+ case VIRTUAL_MODULES.startManifest:
7
+ return await import("tanstack-start-manifest:v");
8
+ case VIRTUAL_MODULES.serverFnManifest:
9
+ return await import("tanstack-start-server-fn-manifest:v");
10
+ default:
11
+ throw new Error(`Unknown virtual module: ${id}`);
12
+ }
13
+ }
14
+ export {
15
+ loadVirtualModule
16
+ };
17
+ //# sourceMappingURL=loadVirtualModule.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loadVirtualModule.js","sources":["../../src/loadVirtualModule.ts"],"sourcesContent":["import { VIRTUAL_MODULES } from './virtual-modules'\nimport type { VirtualModules } from './virtual-modules'\n\n/**\n * we need to explicitly enumerate all imports with string literals,\n * otherwise vite will not pick them up during build\n */\nexport async function loadVirtualModule<TId extends keyof VirtualModules>(\n id: TId,\n): Promise<VirtualModules[TId]> {\n switch (id) {\n case VIRTUAL_MODULES.routeTree:\n return (await import('tanstack-start-route-tree:v')) as any\n case VIRTUAL_MODULES.startManifest:\n return (await import('tanstack-start-manifest:v')) as any\n case VIRTUAL_MODULES.serverFnManifest:\n return (await import('tanstack-start-server-fn-manifest:v')) as any\n default:\n throw new Error(`Unknown virtual module: ${id}`)\n }\n}\n"],"names":[],"mappings":";AAOA,eAAsB,kBACpB,IAC8B;AAC9B,UAAQ,IAAI;AAAA,IACV,KAAK,gBAAgB;AACX,aAAA,MAAM,OAAO,6BAA6B;AAAA,IACpD,KAAK,gBAAgB;AACX,aAAA,MAAM,OAAO,2BAA2B;AAAA,IAClD,KAAK,gBAAgB;AACX,aAAA,MAAM,OAAO,qCAAqC;AAAA,IAC5D;AACE,YAAM,IAAI,MAAM,2BAA2B,EAAE,EAAE;AAAA,EAAA;AAErD;"}
@@ -1,17 +1,16 @@
1
- declare global {
2
- var TSS_INJECTED_HEAD_SCRIPTS: string | undefined;
3
- }
4
1
  /**
5
2
  * @description Returns the router manifest that should be sent to the client.
6
3
  * This includes only the assets and preloads for the current route and any
7
4
  * special assets that are needed for the client. It does not include relationships
8
5
  * between routes or any other data that is not needed for the client.
9
6
  */
10
- export declare function getStartManifest(): {
7
+ export declare function getStartManifest(opts: {
8
+ basePath: string;
9
+ }): Promise<{
11
10
  routes: {
12
11
  [k: string]: {
13
12
  preloads: string[] | undefined;
14
13
  assets: import('@tanstack/router-core').RouterManagedTag[] | undefined;
15
14
  };
16
15
  };
17
- };
16
+ }>;
@@ -1,6 +1,10 @@
1
- import { tsrStartManifest } from "tanstack-start-router-manifest:v";
2
- import { rootRouteId } from "@tanstack/router-core";
3
- function getStartManifest() {
1
+ import { rootRouteId, joinPaths } from "@tanstack/router-core";
2
+ import { VIRTUAL_MODULES } from "./virtual-modules.js";
3
+ import { loadVirtualModule } from "./loadVirtualModule.js";
4
+ async function getStartManifest(opts) {
5
+ const { tsrStartManifest } = await loadVirtualModule(
6
+ VIRTUAL_MODULES.startManifest
7
+ );
4
8
  const startManifest = tsrStartManifest();
5
9
  const rootRoute = startManifest.routes[rootRouteId] = startManifest.routes[rootRouteId] || {};
6
10
  rootRoute.assets = rootRoute.assets || [];
@@ -10,7 +14,8 @@ function getStartManifest() {
10
14
  );
11
15
  }
12
16
  if (process.env.NODE_ENV === "development") {
13
- const script = `${globalThis.TSS_INJECTED_HEAD_SCRIPTS ? globalThis.TSS_INJECTED_HEAD_SCRIPTS + "; " : ""}import(${JSON.stringify(process.env.TSS_CLIENT_ENTRY)})`;
17
+ const clientEntry = joinPaths([opts.basePath, process.env.TSS_CLIENT_ENTRY]);
18
+ const script = `${globalThis.TSS_INJECTED_HEAD_SCRIPTS ? globalThis.TSS_INJECTED_HEAD_SCRIPTS + "; " : ""}import('${clientEntry}')`;
14
19
  rootRoute.assets.push({
15
20
  tag: "script",
16
21
  attrs: {
@@ -1 +1 @@
1
- {"version":3,"file":"router-manifest.js","sources":["../../src/router-manifest.ts"],"sourcesContent":["import { tsrStartManifest } from 'tanstack-start-router-manifest:v'\nimport { rootRouteId } from '@tanstack/router-core'\n\ndeclare global {\n // eslint-disable-next-line no-var\n var TSS_INJECTED_HEAD_SCRIPTS: string | undefined\n}\n\n/**\n * @description Returns the router manifest that should be sent to the client.\n * This includes only the assets and preloads for the current route and any\n * special assets that are needed for the client. It does not include relationships\n * between routes or any other data that is not needed for the client.\n */\nexport function getStartManifest() {\n const startManifest = tsrStartManifest()\n\n const rootRoute = (startManifest.routes[rootRouteId] =\n startManifest.routes[rootRouteId] || {})\n\n rootRoute.assets = rootRoute.assets || []\n\n // Get the entry for the client\n // const ClientManifest = getManifest('client')\n\n // const importPath =\n // ClientManifest.inputs[ClientManifest.handler]?.output.path\n // if (!importPath) {\n // invariant(importPath, 'Could not find client entry in manifest')\n // }\n\n if (process.env.NODE_ENV === 'development' && !process.env.TSS_CLIENT_ENTRY) {\n throw new Error(\n 'tanstack/start-server-core: TSS_CLIENT_ENTRY must be defined in your environment for getStartManifest()',\n )\n }\n\n if (process.env.NODE_ENV === 'development') {\n // Always fake that HMR is ready\n // const CLIENT_BASE = sanitizeBase(process.env.TSS_CLIENT_BASE || '')\n\n // if (!CLIENT_BASE) {\n // throw new Error(\n // 'tanstack/start-router-manifest: TSS_CLIENT_BASE must be defined in your environment for getFullRouterManifest()',\n // )\n // }\n\n const script = `${globalThis.TSS_INJECTED_HEAD_SCRIPTS ? globalThis.TSS_INJECTED_HEAD_SCRIPTS + '; ' : ''}import(${JSON.stringify(process.env.TSS_CLIENT_ENTRY)})`\n\n rootRoute.assets.push({\n tag: 'script',\n attrs: {\n type: 'module',\n suppressHydrationWarning: true,\n async: true,\n },\n children: script,\n })\n }\n\n const manifest = {\n ...startManifest,\n routes: Object.fromEntries(\n Object.entries(startManifest.routes).map(([k, v]) => {\n const { preloads, assets } = v\n return [\n k,\n {\n preloads,\n assets,\n },\n ]\n }),\n ),\n }\n\n // Strip out anything that isn't needed for the client\n return manifest\n}\n"],"names":[],"mappings":";;AAcO,SAAS,mBAAmB;AACjC,QAAM,gBAAgB,iBAAiB;AAEjC,QAAA,YAAa,cAAc,OAAO,WAAW,IACjD,cAAc,OAAO,WAAW,KAAK,CAAC;AAE9B,YAAA,SAAS,UAAU,UAAU,CAAC;AAWxC,MAAI,QAAQ,IAAI,aAAa,iBAAiB,CAAC,QAAQ,IAAI,kBAAkB;AAC3E,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EAAA;AAGE,MAAA,QAAQ,IAAI,aAAa,eAAe;AAU1C,UAAM,SAAS,GAAG,WAAW,4BAA4B,WAAW,4BAA4B,OAAO,EAAE,UAAU,KAAK,UAAU,QAAQ,IAAI,gBAAgB,CAAC;AAE/J,cAAU,OAAO,KAAK;AAAA,MACpB,KAAK;AAAA,MACL,OAAO;AAAA,QACL,MAAM;AAAA,QACN,0BAA0B;AAAA,QAC1B,OAAO;AAAA,MACT;AAAA,MACA,UAAU;AAAA,IAAA,CACX;AAAA,EAAA;AAGH,QAAM,WAAW;AAAA,IACf,GAAG;AAAA,IACH,QAAQ,OAAO;AAAA,MACb,OAAO,QAAQ,cAAc,MAAM,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM;AAC7C,cAAA,EAAE,UAAU,OAAA,IAAW;AACtB,eAAA;AAAA,UACL;AAAA,UACA;AAAA,YACE;AAAA,YACA;AAAA,UAAA;AAAA,QAEJ;AAAA,MACD,CAAA;AAAA,IAAA;AAAA,EAEL;AAGO,SAAA;AACT;"}
1
+ {"version":3,"file":"router-manifest.js","sources":["../../src/router-manifest.ts"],"sourcesContent":["import { joinPaths, rootRouteId } from '@tanstack/router-core'\nimport { VIRTUAL_MODULES } from './virtual-modules'\nimport { loadVirtualModule } from './loadVirtualModule'\n\n/**\n * @description Returns the router manifest that should be sent to the client.\n * This includes only the assets and preloads for the current route and any\n * special assets that are needed for the client. It does not include relationships\n * between routes or any other data that is not needed for the client.\n */\nexport async function getStartManifest(opts: { basePath: string }) {\n const { tsrStartManifest } = await loadVirtualModule(\n VIRTUAL_MODULES.startManifest,\n )\n const startManifest = tsrStartManifest()\n\n const rootRoute = (startManifest.routes[rootRouteId] =\n startManifest.routes[rootRouteId] || {})\n\n rootRoute.assets = rootRoute.assets || []\n\n // Get the entry for the client\n // const ClientManifest = getManifest('client')\n\n // const importPath =\n // ClientManifest.inputs[ClientManifest.handler]?.output.path\n // if (!importPath) {\n // invariant(importPath, 'Could not find client entry in manifest')\n // }\n\n if (process.env.NODE_ENV === 'development' && !process.env.TSS_CLIENT_ENTRY) {\n throw new Error(\n 'tanstack/start-server-core: TSS_CLIENT_ENTRY must be defined in your environment for getStartManifest()',\n )\n }\n\n if (process.env.NODE_ENV === 'development') {\n // Always fake that HMR is ready\n // const CLIENT_BASE = sanitizeBase(process.env.TSS_CLIENT_BASE || '')\n\n // if (!CLIENT_BASE) {\n // throw new Error(\n // 'tanstack/start-router-manifest: TSS_CLIENT_BASE must be defined in your environment for getFullRouterManifest()',\n // )\n // }\n\n const clientEntry = joinPaths([opts.basePath, process.env.TSS_CLIENT_ENTRY])\n\n const script = `${globalThis.TSS_INJECTED_HEAD_SCRIPTS ? globalThis.TSS_INJECTED_HEAD_SCRIPTS + '; ' : ''}import('${clientEntry}')`\n\n rootRoute.assets.push({\n tag: 'script',\n attrs: {\n type: 'module',\n suppressHydrationWarning: true,\n async: true,\n },\n children: script,\n })\n }\n\n const manifest = {\n ...startManifest,\n routes: Object.fromEntries(\n Object.entries(startManifest.routes).map(([k, v]) => {\n const { preloads, assets } = v\n return [\n k,\n {\n preloads,\n assets,\n },\n ]\n }),\n ),\n }\n\n // Strip out anything that isn't needed for the client\n return manifest\n}\n"],"names":[],"mappings":";;;AAUA,eAAsB,iBAAiB,MAA4B;AAC3D,QAAA,EAAE,iBAAiB,IAAI,MAAM;AAAA,IACjC,gBAAgB;AAAA,EAClB;AACA,QAAM,gBAAgB,iBAAiB;AAEjC,QAAA,YAAa,cAAc,OAAO,WAAW,IACjD,cAAc,OAAO,WAAW,KAAK,CAAC;AAE9B,YAAA,SAAS,UAAU,UAAU,CAAC;AAWxC,MAAI,QAAQ,IAAI,aAAa,iBAAiB,CAAC,QAAQ,IAAI,kBAAkB;AAC3E,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EAAA;AAGE,MAAA,QAAQ,IAAI,aAAa,eAAe;AAUpC,UAAA,cAAc,UAAU,CAAC,KAAK,UAAU,QAAQ,IAAI,gBAAgB,CAAC;AAErE,UAAA,SAAS,GAAG,WAAW,4BAA4B,WAAW,4BAA4B,OAAO,EAAE,WAAW,WAAW;AAE/H,cAAU,OAAO,KAAK;AAAA,MACpB,KAAK;AAAA,MACL,OAAO;AAAA,QACL,MAAM;AAAA,QACN,0BAA0B;AAAA,QAC1B,OAAO;AAAA,MACT;AAAA,MACA,UAAU;AAAA,IAAA,CACX;AAAA,EAAA;AAGH,QAAM,WAAW;AAAA,IACf,GAAG;AAAA,IACH,QAAQ,OAAO;AAAA,MACb,OAAO,QAAQ,cAAc,MAAM,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM;AAC7C,cAAA,EAAE,UAAU,OAAA,IAAW;AACtB,eAAA;AAAA,UACL;AAAA,UACA;AAAA,YACE;AAAA,YACA;AAAA,UAAA;AAAA,QAEJ;AAAA,MACD,CAAA;AAAA,IAAA;AAAA,EAEL;AAGO,SAAA;AACT;"}
@@ -1,9 +1,9 @@
1
1
  import { isNotFound } from "@tanstack/router-core";
2
2
  import invariant from "tiny-invariant";
3
3
  import { startSerializer } from "@tanstack/start-client-core";
4
- import _serverFnManifest from "tanstack-start-server-fn-manifest:v";
5
4
  import { getResponseStatus, getEvent } from "./h3.js";
6
- const serverFnManifest = _serverFnManifest;
5
+ import { VIRTUAL_MODULES } from "./virtual-modules.js";
6
+ import { loadVirtualModule } from "./loadVirtualModule.js";
7
7
  function sanitizeBase(base) {
8
8
  if (!base) {
9
9
  throw new Error(
@@ -30,6 +30,9 @@ const handleServerAction = async ({ request }) => {
30
30
  if (typeof serverFnId !== "string") {
31
31
  throw new Error("Invalid server action param for serverFnId: " + serverFnId);
32
32
  }
33
+ const { default: serverFnManifest } = await loadVirtualModule(
34
+ VIRTUAL_MODULES.serverFnManifest
35
+ );
33
36
  const serverFnInfo = serverFnManifest[serverFnId];
34
37
  if (!serverFnInfo) {
35
38
  console.info("serverFnManifest", serverFnManifest);
@@ -1 +1 @@
1
- {"version":3,"file":"server-functions-handler.js","sources":["../../src/server-functions-handler.ts"],"sourcesContent":["import { isNotFound } from '@tanstack/router-core'\nimport invariant from 'tiny-invariant'\nimport { startSerializer } from '@tanstack/start-client-core'\n// @ts-expect-error\nimport _serverFnManifest from 'tanstack-start-server-fn-manifest:v'\nimport { getEvent, getResponseStatus } from './h3'\n\nconst serverFnManifest = _serverFnManifest as Record<\n string,\n {\n functionName: string\n extractedFilename: string\n importer: () => Promise<any>\n }\n>\n\nfunction sanitizeBase(base: string | undefined) {\n if (!base) {\n throw new Error(\n '🚨 process.env.TSS_SERVER_FN_BASE is required in start/server-handler/index',\n )\n }\n\n return base.replace(/^\\/|\\/$/g, '')\n}\n\nexport const handleServerAction = async ({ request }: { request: Request }) => {\n const controller = new AbortController()\n const signal = controller.signal\n const abort = () => controller.abort()\n request.signal.addEventListener('abort', abort)\n\n const method = request.method\n const url = new URL(request.url, 'http://localhost:3000')\n // extract the serverFnId from the url as host/_serverFn/:serverFnId\n // Define a regex to match the path and extract the :thing part\n const regex = new RegExp(\n `${sanitizeBase(process.env.TSS_SERVER_FN_BASE)}/([^/?#]+)`,\n )\n\n // Execute the regex\n const match = url.pathname.match(regex)\n const serverFnId = match ? match[1] : null\n const search = Object.fromEntries(url.searchParams.entries()) as {\n payload?: any\n createServerFn?: boolean\n }\n\n const isCreateServerFn = 'createServerFn' in search\n const isRaw = 'raw' in search\n\n if (typeof serverFnId !== 'string') {\n throw new Error('Invalid server action param for serverFnId: ' + serverFnId)\n }\n\n const serverFnInfo = serverFnManifest[serverFnId]\n\n if (!serverFnInfo) {\n console.info('serverFnManifest', serverFnManifest)\n throw new Error('Server function info not found for ' + serverFnId)\n }\n\n const fnModule: undefined | { [key: string]: any } =\n await serverFnInfo.importer()\n\n if (!fnModule) {\n console.info('serverFnInfo', serverFnInfo)\n throw new Error('Server function module not resolved for ' + serverFnId)\n }\n\n const action = fnModule[serverFnInfo.functionName]\n\n if (!action) {\n console.info('serverFnInfo', serverFnInfo)\n console.info('fnModule', fnModule)\n throw new Error(\n `Server function module export not resolved for serverFn ID: ${serverFnId}`,\n )\n }\n\n // Known FormData 'Content-Type' header values\n const formDataContentTypes = [\n 'multipart/form-data',\n 'application/x-www-form-urlencoded',\n ]\n\n const response = await (async () => {\n try {\n let result = await (async () => {\n // FormData\n if (\n request.headers.get('Content-Type') &&\n formDataContentTypes.some((type) =>\n request.headers.get('Content-Type')?.includes(type),\n )\n ) {\n // We don't support GET requests with FormData payloads... that seems impossible\n invariant(\n method.toLowerCase() !== 'get',\n 'GET requests with FormData payloads are not supported',\n )\n\n return await action(await request.formData(), signal)\n }\n\n // Get requests use the query string\n if (method.toLowerCase() === 'get') {\n // By default the payload is the search params\n let payload: any = search\n\n // If this GET request was created by createServerFn,\n // then the payload will be on the payload param\n if (isCreateServerFn) {\n payload = search.payload\n }\n\n // If there's a payload, we should try to parse it\n payload = payload ? startSerializer.parse(payload) : payload\n\n // Send it through!\n return await action(payload, signal)\n }\n\n // This must be a POST request, likely JSON???\n const jsonPayloadAsString = await request.text()\n\n // We should probably try to deserialize the payload\n // as JSON, but we'll just pass it through for now.\n const payload = startSerializer.parse(jsonPayloadAsString)\n\n // If this POST request was created by createServerFn,\n // it's payload will be the only argument\n if (isCreateServerFn) {\n return await action(payload, signal)\n }\n\n // Otherwise, we'll spread the payload. Need to\n // support `use server` functions that take multiple\n // arguments.\n return await action(...(payload as any), signal)\n })()\n\n // Any time we get a Response back, we should just\n // return it immediately.\n if (result.result instanceof Response) {\n return result.result\n }\n\n // If this is a non createServerFn request, we need to\n // pull out the result from the result object\n if (!isCreateServerFn) {\n result = result.result\n\n // The result might again be a response,\n // and if it is, return it.\n if (result instanceof Response) {\n return result\n }\n }\n\n // if (!search.createServerFn) {\n // result = result.result\n // }\n\n // else if (\n // isPlainObject(result) &&\n // 'result' in result &&\n // result.result instanceof Response\n // ) {\n // return result.result\n // }\n\n // TODO: RSCs Where are we getting this package?\n // if (isValidElement(result)) {\n // const { renderToPipeableStream } = await import(\n // // @ts-expect-error\n // 'react-server-dom/server'\n // )\n\n // const pipeableStream = renderToPipeableStream(result)\n\n // setHeaders(event, {\n // 'Content-Type': 'text/x-component',\n // } as any)\n\n // sendStream(event, response)\n // event._handled = true\n\n // return new Response(null, { status: 200 })\n // }\n\n if (isNotFound(result)) {\n return isNotFoundResponse(result)\n }\n\n return new Response(\n result !== undefined ? startSerializer.stringify(result) : undefined,\n {\n status: getResponseStatus(getEvent()),\n headers: {\n 'Content-Type': 'application/json',\n },\n },\n )\n } catch (error: any) {\n if (error instanceof Response) {\n return error\n }\n // else if (\n // isPlainObject(error) &&\n // 'result' in error &&\n // error.result instanceof Response\n // ) {\n // return error.result\n // }\n\n // Currently this server-side context has no idea how to\n // build final URLs, so we need to defer that to the client.\n // The client will check for __redirect and __notFound keys,\n // and if they exist, it will handle them appropriately.\n\n if (isNotFound(error)) {\n return isNotFoundResponse(error)\n }\n\n console.info()\n console.info('Server Fn Error!')\n console.info()\n console.error(error)\n console.info()\n\n return new Response(startSerializer.stringify(error), {\n status: 500,\n headers: {\n 'Content-Type': 'application/json',\n },\n })\n }\n })()\n\n request.signal.removeEventListener('abort', abort)\n\n if (isRaw) {\n return response\n }\n\n return response\n}\n\nfunction isNotFoundResponse(error: any) {\n const { headers, ...rest } = error\n\n return new Response(JSON.stringify(rest), {\n status: 200,\n headers: {\n 'Content-Type': 'application/json',\n ...(headers || {}),\n },\n })\n}\n"],"names":["payload"],"mappings":";;;;;AAOA,MAAM,mBAAmB;AASzB,SAAS,aAAa,MAA0B;AAC9C,MAAI,CAAC,MAAM;AACT,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EAAA;AAGK,SAAA,KAAK,QAAQ,YAAY,EAAE;AACpC;AAEO,MAAM,qBAAqB,OAAO,EAAE,cAAoC;AACvE,QAAA,aAAa,IAAI,gBAAgB;AACvC,QAAM,SAAS,WAAW;AACpB,QAAA,QAAQ,MAAM,WAAW,MAAM;AAC7B,UAAA,OAAO,iBAAiB,SAAS,KAAK;AAE9C,QAAM,SAAS,QAAQ;AACvB,QAAM,MAAM,IAAI,IAAI,QAAQ,KAAK,uBAAuB;AAGxD,QAAM,QAAQ,IAAI;AAAA,IAChB,GAAG,aAAa,QAAQ,IAAI,kBAAkB,CAAC;AAAA,EACjD;AAGA,QAAM,QAAQ,IAAI,SAAS,MAAM,KAAK;AACtC,QAAM,aAAa,QAAQ,MAAM,CAAC,IAAI;AACtC,QAAM,SAAS,OAAO,YAAY,IAAI,aAAa,SAAS;AAK5D,QAAM,mBAAmB,oBAAoB;AAC7C,QAAM,QAAQ,SAAS;AAEnB,MAAA,OAAO,eAAe,UAAU;AAC5B,UAAA,IAAI,MAAM,iDAAiD,UAAU;AAAA,EAAA;AAGvE,QAAA,eAAe,iBAAiB,UAAU;AAEhD,MAAI,CAAC,cAAc;AACT,YAAA,KAAK,oBAAoB,gBAAgB;AAC3C,UAAA,IAAI,MAAM,wCAAwC,UAAU;AAAA,EAAA;AAG9D,QAAA,WACJ,MAAM,aAAa,SAAS;AAE9B,MAAI,CAAC,UAAU;AACL,YAAA,KAAK,gBAAgB,YAAY;AACnC,UAAA,IAA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AA,MACT;AAkCE,UAAA,WAAW,MAAM,GAAG;AACtB,eAAO,mBAAmB,MAAM;AAAA,MAAA;AAGlC,aAAO,IAAI;AAAA,QACT,WAAW,SAAY,gBAAgB,UAAU,MAAM,IAAI;AAAA,QAC3D;AAAA,UACE,QAAQ,kBAAkB,UAAU;AAAA,UACpC,SAAS;AAAA,YACP,gBAAgB;AAAA,UAAA;AAAA,QAClB;AAAA,MAEJ;AAAA,aACO,OAAY;AACnB,UAAI,iBAAiB,UAAU;AACtB,eAAA;AAAA,MAAA;AAeL,UAAA,WAAW,KAAK,GAAG;AACrB,eAAO,mBAAmB,KAAK;AAAA,MAAA;AAGjC,cAAQ,KAAK;AACb,cAAQ,KAAK,kBAAkB;AAC/B,cAAQ,KAAK;AACb,cAAQ,MAAM,KAAK;AACnB,cAAQ,KAAK;AAEb,aAAO,IAAI,SAAS,gBAAgB,UAAU,KAAK,GAAG;AAAA,QACpD,QAAQ;AAAA,QACR,SAAS;AAAA,UACP,gBAAgB;AAAA,QAAA;AAAA,MAClB,CACD;AAAA,IAAA;AAAA,EACH,GACC;AAEK,UAAA,OAAO,oBAAoB,SAAS,KAAK;AAEjD,MAAI,OAAO;AACF,WAAA;AAAA,EAAA;AAGF,SAAA;AACT;AAEA,SAAS,mBAAmB,OAAY;AACtC,QAAM,EAAE,SAAS,GAAG,KAAA,IAAS;AAE7B,SAAO,IAAI,SAAS,KAAK,UAAU,IAAI,GAAG;AAAA,IACxC,QAAQ;AAAA,IACR,SAAS;AAAA,MACP,gBAAgB;AAAA,MAChB,GAAI,WAAW,CAAA;AAAA,IAAC;AAAA,EAClB,CACD;AACH;"}
1
+ {"version":3,"file":"server-functions-handler.js","sources":["../../src/server-functions-handler.ts"],"sourcesContent":["import { isNotFound } from '@tanstack/router-core'\nimport invariant from 'tiny-invariant'\nimport { startSerializer } from '@tanstack/start-client-core'\nimport { getEvent, getResponseStatus } from './h3'\nimport { VIRTUAL_MODULES } from './virtual-modules'\nimport { loadVirtualModule } from './loadVirtualModule'\n\nfunction sanitizeBase(base: string | undefined) {\n if (!base) {\n throw new Error(\n '🚨 process.env.TSS_SERVER_FN_BASE is required in start/server-handler/index',\n )\n }\n\n return base.replace(/^\\/|\\/$/g, '')\n}\n\nexport const handleServerAction = async ({ request }: { request: Request }) => {\n const controller = new AbortController()\n const signal = controller.signal\n const abort = () => controller.abort()\n request.signal.addEventListener('abort', abort)\n\n const method = request.method\n const url = new URL(request.url, 'http://localhost:3000')\n // extract the serverFnId from the url as host/_serverFn/:serverFnId\n // Define a regex to match the path and extract the :thing part\n const regex = new RegExp(\n `${sanitizeBase(process.env.TSS_SERVER_FN_BASE)}/([^/?#]+)`,\n )\n\n // Execute the regex\n const match = url.pathname.match(regex)\n const serverFnId = match ? match[1] : null\n const search = Object.fromEntries(url.searchParams.entries()) as {\n payload?: any\n createServerFn?: boolean\n }\n\n const isCreateServerFn = 'createServerFn' in search\n const isRaw = 'raw' in search\n\n if (typeof serverFnId !== 'string') {\n throw new Error('Invalid server action param for serverFnId: ' + serverFnId)\n }\n\n const { default: serverFnManifest } = await loadVirtualModule(\n VIRTUAL_MODULES.serverFnManifest,\n )\n\n const serverFnInfo = serverFnManifest[serverFnId]\n\n if (!serverFnInfo) {\n console.info('serverFnManifest', serverFnManifest)\n throw new Error('Server function info not found for ' + serverFnId)\n }\n\n const fnModule: undefined | { [key: string]: any } =\n await serverFnInfo.importer()\n\n if (!fnModule) {\n console.info('serverFnInfo', serverFnInfo)\n throw new Error('Server function module not resolved for ' + serverFnId)\n }\n\n const action = fnModule[serverFnInfo.functionName]\n\n if (!action) {\n console.info('serverFnInfo', serverFnInfo)\n console.info('fnModule', fnModule)\n throw new Error(\n `Server function module export not resolved for serverFn ID: ${serverFnId}`,\n )\n }\n\n // Known FormData 'Content-Type' header values\n const formDataContentTypes = [\n 'multipart/form-data',\n 'application/x-www-form-urlencoded',\n ]\n\n const response = await (async () => {\n try {\n let result = await (async () => {\n // FormData\n if (\n request.headers.get('Content-Type') &&\n formDataContentTypes.some((type) =>\n request.headers.get('Content-Type')?.includes(type),\n )\n ) {\n // We don't support GET requests with FormData payloads... that seems impossible\n invariant(\n method.toLowerCase() !== 'get',\n 'GET requests with FormData payloads are not supported',\n )\n\n return await action(await request.formData(), signal)\n }\n\n // Get requests use the query string\n if (method.toLowerCase() === 'get') {\n // By default the payload is the search params\n let payload: any = search\n\n // If this GET request was created by createServerFn,\n // then the payload will be on the payload param\n if (isCreateServerFn) {\n payload = search.payload\n }\n\n // If there's a payload, we should try to parse it\n payload = payload ? startSerializer.parse(payload) : payload\n\n // Send it through!\n return await action(payload, signal)\n }\n\n // This must be a POST request, likely JSON???\n const jsonPayloadAsString = await request.text()\n\n // We should probably try to deserialize the payload\n // as JSON, but we'll just pass it through for now.\n const payload = startSerializer.parse(jsonPayloadAsString)\n\n // If this POST request was created by createServerFn,\n // it's payload will be the only argument\n if (isCreateServerFn) {\n return await action(payload, signal)\n }\n\n // Otherwise, we'll spread the payload. Need to\n // support `use server` functions that take multiple\n // arguments.\n return await action(...(payload as any), signal)\n })()\n\n // Any time we get a Response back, we should just\n // return it immediately.\n if (result.result instanceof Response) {\n return result.result\n }\n\n // If this is a non createServerFn request, we need to\n // pull out the result from the result object\n if (!isCreateServerFn) {\n result = result.result\n\n // The result might again be a response,\n // and if it is, return it.\n if (result instanceof Response) {\n return result\n }\n }\n\n // if (!search.createServerFn) {\n // result = result.result\n // }\n\n // else if (\n // isPlainObject(result) &&\n // 'result' in result &&\n // result.result instanceof Response\n // ) {\n // return result.result\n // }\n\n // TODO: RSCs Where are we getting this package?\n // if (isValidElement(result)) {\n // const { renderToPipeableStream } = await import(\n // // @ts-expect-error\n // 'react-server-dom/server'\n // )\n\n // const pipeableStream = renderToPipeableStream(result)\n\n // setHeaders(event, {\n // 'Content-Type': 'text/x-component',\n // } as any)\n\n // sendStream(event, response)\n // event._handled = true\n\n // return new Response(null, { status: 200 })\n // }\n\n if (isNotFound(result)) {\n return isNotFoundResponse(result)\n }\n\n return new Response(\n result !== undefined ? startSerializer.stringify(result) : undefined,\n {\n status: getResponseStatus(getEvent()),\n headers: {\n 'Content-Type': 'application/json',\n },\n },\n )\n } catch (error: any) {\n if (error instanceof Response) {\n return error\n }\n // else if (\n // isPlainObject(error) &&\n // 'result' in error &&\n // error.result instanceof Response\n // ) {\n // return error.result\n // }\n\n // Currently this server-side context has no idea how to\n // build final URLs, so we need to defer that to the client.\n // The client will check for __redirect and __notFound keys,\n // and if they exist, it will handle them appropriately.\n\n if (isNotFound(error)) {\n return isNotFoundResponse(error)\n }\n\n console.info()\n console.info('Server Fn Error!')\n console.info()\n console.error(error)\n console.info()\n\n return new Response(startSerializer.stringify(error), {\n status: 500,\n headers: {\n 'Content-Type': 'application/json',\n },\n })\n }\n })()\n\n request.signal.removeEventListener('abort', abort)\n\n if (isRaw) {\n return response\n }\n\n return response\n}\n\nfunction isNotFoundResponse(error: any) {\n const { headers, ...rest } = error\n\n return new Response(JSON.stringify(rest), {\n status: 200,\n headers: {\n 'Content-Type': 'application/json',\n ...(headers || {}),\n },\n })\n}\n"],"names":["payload"],"mappings":";;;;;;AAOA,SAAS,aAAa,MAA0B;AAC9C,MAAI,CAAC,MAAM;AACT,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EAAA;AAGK,SAAA,KAAK,QAAQ,YAAY,EAAE;AACpC;AAEO,MAAM,qBAAqB,OAAO,EAAE,cAAoC;AACvE,QAAA,aAAa,IAAI,gBAAgB;AACvC,QAAM,SAAS,WAAW;AACpB,QAAA,QAAQ,MAAM,WAAW,MAAM;AAC7B,UAAA,OAAO,iBAAiB,SAAS,KAAK;AAE9C,QAAM,SAAS,QAAQ;AACvB,QAAM,MAAM,IAAI,IAAI,QAAQ,KAAK,uBAAuB;AAGxD,QAAM,QAAQ,IAAI;AAAA,IAChB,GAAG,aAAa,QAAQ,IAAI,kBAAkB,CAAC;AAAA,EACjD;AAGA,QAAM,QAAQ,IAAI,SAAS,MAAM,KAAK;AACtC,QAAM,a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UAAA,OAAO,oBAAoB,SAAS,KAAK;AAEjD,MAAI,OAAO;AACF,WAAA;AAAA,EAAA;AAGF,SAAA;AACT;AAEA,SAAS,mBAAmB,OAAY;AACtC,QAAM,EAAE,SAAS,GAAG,KAAA,IAAS;AAE7B,SAAO,IAAI,SAAS,KAAK,UAAU,IAAI,GAAG;AAAA,IACxC,QAAQ;AAAA,IACR,SAAS;AAAA,MACP,gBAAgB;AAAA,MAChB,GAAI,WAAW,CAAA;AAAA,IAAC;AAAA,EAClB,CACD;AACH;"}
@@ -1,7 +1,8 @@
1
1
  import { Assign, Constrain, Expand, ResolveParams, RouteConstraints, TrimPathRight } from '@tanstack/router-core';
2
2
  import { AnyRequestMiddleware, AssignAllServerContext } from '@tanstack/start-client-core';
3
- type TODO = any;
4
- export declare function createServerFileRoute<TParentRoute extends AnyServerRouteWithTypes, TId extends RouteConstraints['TId'], TPath extends RouteConstraints['TPath'], TFullPath extends RouteConstraints['TFullPath'], TChildren>(__?: never): ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren>;
3
+ export declare function createServerFileRoute<TFilePath extends keyof ServerFileRoutesByPath, TParentRoute extends AnyServerRouteWithTypes = ServerFileRoutesByPath[TFilePath]['parentRoute'], TId extends RouteConstraints['TId'] = ServerFileRoutesByPath[TFilePath]['id'], TPath extends RouteConstraints['TPath'] = ServerFileRoutesByPath[TFilePath]['path'], TFullPath extends RouteConstraints['TFullPath'] = ServerFileRoutesByPath[TFilePath]['fullPath'], TChildren = ServerFileRoutesByPath[TFilePath]['children']>(_: TFilePath): ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren>;
4
+ export interface ServerFileRoutesByPath {
5
+ }
5
6
  export interface ServerRouteOptions<TParentRoute extends AnyServerRouteWithTypes, TId extends RouteConstraints['TId'], TPath extends RouteConstraints['TPath'], TFullPath extends RouteConstraints['TFullPath'], TMiddlewares> {
6
7
  id: TId;
7
8
  path: TPath;
@@ -19,8 +20,13 @@ export type ServerRouteManifest = {
19
20
  }>;
20
21
  };
21
22
  export declare function createServerRoute<TParentRoute extends AnyServerRouteWithTypes, TId extends RouteConstraints['TId'], TPath extends RouteConstraints['TPath'], TFullPath extends RouteConstraints['TFullPath'], TChildren>(__?: never, __opts?: Partial<ServerRouteOptions<TParentRoute, TId, TPath, TFullPath, undefined>>): ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren>;
23
+ export declare const createServerRootRoute: typeof createServerRoute;
22
24
  export type ServerRouteAddFileChildrenFn<in out TParentRoute extends AnyServerRouteWithTypes, in out TId extends RouteConstraints['TId'], in out TPath extends RouteConstraints['TPath'], in out TFullPath extends RouteConstraints['TFullPath'], in out TMiddlewares, in out TMethods, in out TChildren> = (children: TChildren) => ServerRouteWithTypes<TParentRoute, TId, TPath, TFullPath, TMiddlewares, TMethods, TChildren>;
23
- export type CreateServerFileRoute<TParentRoute extends AnyServerRouteWithTypes, TId extends RouteConstraints['TId'], TPath extends RouteConstraints['TPath'], TFullPath extends RouteConstraints['TFullPath'], TChildren> = (options?: undefined) => ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren>;
25
+ export interface ServerRouteMethodBuilderOptions<TParentRoute extends AnyServerRouteWithTypes, TFullPath extends string, TMiddlewares, TMethodMiddlewares, TResponse> {
26
+ handler?: ServerRouteMethodHandlerFn<TParentRoute, TFullPath, TMiddlewares, TMethodMiddlewares, TResponse>;
27
+ middlewares?: Constrain<TMethodMiddlewares, ReadonlyArray<AnyRequestMiddleware>>;
28
+ }
29
+ export type CreateServerFileRoute<TParentRoute extends AnyServerRouteWithTypes, TId extends RouteConstraints['TId'], TPath extends RouteConstraints['TPath'], TFullPath extends RouteConstraints['TFullPath'], TChildren> = () => ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren>;
24
30
  export type AnyServerRouteWithTypes = ServerRouteWithTypes<any, any, any, any, any, any, any>;
25
31
  export interface ServerRouteWithTypes<TParentRoute extends AnyServerRouteWithTypes, TId extends RouteConstraints['TId'], TPath extends RouteConstraints['TPath'], TFullPath extends RouteConstraints['TFullPath'], TMiddlewares, TMethods, TChildren> {
26
32
  _types: ServerRouteTypes<TParentRoute, TId, TPath, TFullPath, TMiddlewares, TMethods>;
@@ -81,11 +87,11 @@ export interface ServerRouteMethodHandlerCtx<in out TParentRoute extends AnyServ
81
87
  }
82
88
  export type MergeMethodMiddlewares<TMiddlewares, TMethodMiddlewares> = TMiddlewares extends ReadonlyArray<any> ? TMethodMiddlewares extends ReadonlyArray<any> ? readonly [...TMiddlewares, ...TMethodMiddlewares] : TMiddlewares : TMethodMiddlewares;
83
89
  export type AssignAllMethodContext<TParentRoute extends AnyServerRouteWithTypes, TMiddlewares, TMethodMiddlewares> = ResolveAllServerContext<TParentRoute, MergeMethodMiddlewares<TMiddlewares, TMethodMiddlewares>>;
84
- export type AnyRouteMethodsBuilder = ServerRouteMethodBuilderWithTypes<any, any, any, any>;
85
- export interface ServerRouteMethodBuilder<TParentRoute extends AnyServerRouteWithTypes, TFullPath extends string, TMiddlewares> extends ServerRouteMethodBuilderWithTypes<TFullPath, TMiddlewares, undefined, undefined>, ServerRouteMethodBuilderMiddleware<TParentRoute, TFullPath, TMiddlewares>, ServerRouteMethodBuilderHandler<TParentRoute, TFullPath, TMiddlewares, undefined> {
90
+ export type AnyRouteMethodsBuilder = ServerRouteMethodBuilderWithTypes<any, any, any, any, any>;
91
+ export interface ServerRouteMethodBuilder<TParentRoute extends AnyServerRouteWithTypes, TFullPath extends string, TMiddlewares> extends ServerRouteMethodBuilderWithTypes<TParentRoute, TFullPath, TMiddlewares, undefined, undefined>, ServerRouteMethodBuilderMiddleware<TParentRoute, TFullPath, TMiddlewares>, ServerRouteMethodBuilderHandler<TParentRoute, TFullPath, TMiddlewares, undefined> {
86
92
  }
87
- export interface ServerRouteMethodBuilderWithTypes<TFullPath extends string, TMiddlewares, TMethodMiddlewares, TResponse> {
88
- _options: TODO;
93
+ export interface ServerRouteMethodBuilderWithTypes<TParentRoute extends AnyServerRouteWithTypes, TFullPath extends string, TMiddlewares, TMethodMiddlewares, TResponse> {
94
+ _options: ServerRouteMethodBuilderOptions<TParentRoute, TFullPath, TMiddlewares, TMethodMiddlewares, TResponse>;
89
95
  _types: ServerRouteMethodBuilderTypes<TFullPath, TMiddlewares, TMethodMiddlewares, TResponse>;
90
96
  }
91
97
  export interface ServerRouteMethodBuilderTypes<in out TFullPath extends string, in out TMiddlewares, in out TMethodMiddlewares, in out TResponse> {
@@ -97,12 +103,12 @@ export interface ServerRouteMethodBuilderTypes<in out TFullPath extends string,
97
103
  export interface ServerRouteMethodBuilderMiddleware<TParentRoute extends AnyServerRouteWithTypes, TFullPath extends string, TMiddlewares> {
98
104
  middleware: <const TNewMethodMiddlewares>(middleware: Constrain<TNewMethodMiddlewares, ReadonlyArray<AnyRequestMiddleware>>) => ServerRouteMethodBuilderAfterMiddleware<TParentRoute, TFullPath, TMiddlewares, TNewMethodMiddlewares>;
99
105
  }
100
- export interface ServerRouteMethodBuilderAfterMiddleware<TParentRoute extends AnyServerRouteWithTypes, TFullPath extends string, TMiddlewares, TMethodMiddlewares> extends ServerRouteMethodBuilderWithTypes<TFullPath, TMiddlewares, TMethodMiddlewares, undefined>, ServerRouteMethodBuilderHandler<TParentRoute, TFullPath, TMiddlewares, TMethodMiddlewares> {
106
+ export interface ServerRouteMethodBuilderAfterMiddleware<TParentRoute extends AnyServerRouteWithTypes, TFullPath extends string, TMiddlewares, TMethodMiddlewares> extends ServerRouteMethodBuilderWithTypes<TParentRoute, TFullPath, TMiddlewares, TMethodMiddlewares, undefined>, ServerRouteMethodBuilderHandler<TParentRoute, TFullPath, TMiddlewares, TMethodMiddlewares> {
101
107
  }
102
108
  export interface ServerRouteMethodBuilderHandler<TParentRoute extends AnyServerRouteWithTypes, TFullPath extends string, TMiddlewares, TMethodMiddlewares> {
103
109
  handler: <TResponse>(handler: ServerRouteMethodHandlerFn<TParentRoute, TFullPath, TMiddlewares, TMethodMiddlewares, TResponse>) => ServerRouteMethodBuilderAfterHandler<TParentRoute, TFullPath, TMiddlewares, TMethodMiddlewares, TResponse>;
104
110
  }
105
- export interface ServerRouteMethodBuilderAfterHandler<TParentRoute extends AnyServerRouteWithTypes, TFullPath extends string, TMiddlewares, TMethodMiddlewares, TResponse> extends ServerRouteMethodBuilderWithTypes<TFullPath, TMiddlewares, TMethodMiddlewares, TResponse> {
111
+ export interface ServerRouteMethodBuilderAfterHandler<TParentRoute extends AnyServerRouteWithTypes, TFullPath extends string, TMiddlewares, TMethodMiddlewares, TResponse> extends ServerRouteMethodBuilderWithTypes<TParentRoute, TFullPath, TMiddlewares, TMethodMiddlewares, TResponse> {
106
112
  opts: ServerRouteMethod<TParentRoute, TFullPath, TMiddlewares, TMethodMiddlewares>;
107
113
  }
108
114
  export interface ServerRouteMethod<TParentRoute extends AnyServerRouteWithTypes, TFullPath extends string, TMiddlewares, TMethodMiddlewares> {
@@ -112,4 +118,3 @@ export interface ServerRouteMethod<TParentRoute extends AnyServerRouteWithTypes,
112
118
  export interface ServerRouteAfterMethods<TParentRoute extends AnyServerRouteWithTypes, TId extends RouteConstraints['TId'], TPath extends RouteConstraints['TPath'], TFullPath extends RouteConstraints['TFullPath'], TMiddlewares, TMethods, TChildren> extends ServerRouteWithTypes<TParentRoute, TId, TPath, TFullPath, TMiddlewares, TMethods, TChildren> {
113
119
  options: ServerRouteOptions<TParentRoute, TId, TPath, TFullPath, TMiddlewares>;
114
120
  }
115
- export {};
@@ -1,5 +1,5 @@
1
1
  import { rootRouteId, trimPathLeft, joinPaths } from "@tanstack/router-core";
2
- function createServerFileRoute(__) {
2
+ function createServerFileRoute(_) {
3
3
  return createServerRoute();
4
4
  }
5
5
  function createServerRoute(__, __opts) {
@@ -79,6 +79,7 @@ function createServerRoute(__, __opts) {
79
79
  };
80
80
  return route;
81
81
  }
82
+ const createServerRootRoute = createServerRoute;
82
83
  const createMethodBuilder = (__opts) => {
83
84
  return {
84
85
  _options: __opts || {},
@@ -95,6 +96,7 @@ const createMethodBuilder = (__opts) => {
95
96
  };
96
97
  export {
97
98
  createServerFileRoute,
99
+ createServerRootRoute,
98
100
  createServerRoute
99
101
  };
100
102
  //# sourceMappingURL=serverRoute.js.map