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

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,26 +1,4 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __copyProps = (to, from, except, desc) => {
9
- if (from && typeof from === "object" || typeof from === "function") {
10
- for (let key of __getOwnPropNames(from))
11
- if (!__hasOwnProp.call(to, key) && key !== except)
12
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13
- }
14
- return to;
15
- };
16
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
17
- // If the importer is in node compatibility mode or this is not an ESM
18
- // file that has been converted to a CommonJS file using a Babel-
19
- // compatible transform (i.e. "__esModule" has not been set), then set
20
- // "default" to the CommonJS "module.exports" for node compatibility.
21
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
- mod
23
- ));
24
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
25
3
  const history = require("@tanstack/history");
26
4
  const startClientCore = require("@tanstack/start-client-core");
@@ -29,6 +7,8 @@ const h3 = require("./h3.cjs");
29
7
  const ssrServer = require("./ssr-server.cjs");
30
8
  const routerManifest = require("./router-manifest.cjs");
31
9
  const serverFunctionsHandler = require("./server-functions-handler.cjs");
10
+ const virtualModules = require("./virtual-modules.cjs");
11
+ const loadVirtualModule = require("./loadVirtualModule.cjs");
32
12
  function getStartResponseHeaders(opts) {
33
13
  let headers = startClientCore.mergeHeaders(
34
14
  h3.getResponseHeaders(),
@@ -48,6 +28,7 @@ function getStartResponseHeaders(opts) {
48
28
  function createStartHandler({
49
29
  createRouter
50
30
  }) {
31
+ let serverRouteTree = null;
51
32
  return (cb) => {
52
33
  const originalFetch = globalThis.fetch;
53
34
  const startRequestResolver = async ({ request }) => {
@@ -73,8 +54,10 @@ function createStartHandler({
73
54
  const history$1 = history.createMemoryHistory({
74
55
  initialEntries: [href]
75
56
  });
57
+ const APP_BASE = process.env.TSS_APP_BASE || "/";
76
58
  const router = createRouter();
77
- ssrServer.attachRouterServerSsrUtils(router, routerManifest.getStartManifest());
59
+ const startRoutesManifest = await routerManifest.getStartManifest({ basePath: APP_BASE });
60
+ ssrServer.attachRouterServerSsrUtils(router, startRoutesManifest);
78
61
  router.update({
79
62
  history: history$1
80
63
  });
@@ -86,28 +69,25 @@ function createStartHandler({
86
69
  );
87
70
  }
88
71
  const serverFnBase = routerCore.joinPaths([
89
- "/",
72
+ APP_BASE,
90
73
  routerCore.trimPath(process.env.TSS_SERVER_FN_BASE),
91
74
  "/"
92
75
  ]);
93
76
  if (href.startsWith(serverFnBase)) {
94
77
  return await serverFunctionsHandler.handleServerAction({ request });
95
78
  }
96
- const serverRouteTreeModule = await (async () => {
79
+ if (serverRouteTree === null) {
97
80
  try {
98
- return await import(
99
- // @ts-expect-error
100
- "tanstack-start-server-routes-manifest:v"
101
- );
81
+ serverRouteTree = (await loadVirtualModule.loadVirtualModule(virtualModules.VIRTUAL_MODULES.routeTree)).serverRouteTree;
102
82
  } catch (e) {
103
83
  console.log(e);
104
- return void 0;
105
84
  }
106
- })();
107
- if (serverRouteTreeModule) {
85
+ }
86
+ if (serverRouteTree) {
108
87
  const [_matchedRoutes, response3] = await handleServerRoutes({
109
- routeTree: serverRouteTreeModule.routeTree,
110
- request
88
+ routeTree: serverRouteTree,
89
+ request,
90
+ basePath: APP_BASE
111
91
  });
112
92
  if (response3) return response3;
113
93
  }
@@ -196,7 +176,8 @@ function createStartHandler({
196
176
  }
197
177
  async function handleServerRoutes({
198
178
  routeTree,
199
- request
179
+ request,
180
+ basePath
200
181
  }) {
201
182
  const { flatRoutes, routesById, routesByPath } = routerCore.processRouteTree({
202
183
  routeTree,
@@ -213,7 +194,7 @@ async function handleServerRoutes({
213
194
  });
214
195
  const { matchedRoutes, foundRoute, routeParams } = routerCore.getMatchedRoutes({
215
196
  pathname: history$1.location.pathname,
216
- basepath: "/",
197
+ basepath: basePath,
217
198
  caseSensitive: true,
218
199
  routesByPath,
219
200
  routesById,
@@ -1 +1 @@
1
- {"version":3,"file":"createStartHandler.cjs","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":["mergeHeaders","getResponseHeaders","url","history","createMemoryHistory","attachRouterServerSsrUtils","getStartManifest","joinPaths","trimPath","handleServerAction","response","json","dehydrateRouter","isRedirect","isResolvedRedirect","requestHandler","processRouteTree","getMatchedRoutes","rootRouteId","method","flattenMiddlewares","ctx"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BO,SAAS,wBAAwB,MAA6B;AACnE,MAAI,UAAUA,g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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,KAAKR,WAAAA,WAAW,GAAG;AAC1C;AAEA,SAAS,WAAW,UAA0C;AAC5D,SAAO,oBAAoB;AAC7B;;;"}
1
+ {"version":3,"file":"createStartHandler.cjs","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":["mergeHeaders","getResponseHeaders","url","history","createMemoryHistory","getStartManifest","attachRouterServerSsrUtils","joinPaths","trimPath","handleServerAction","loadVirtualModule","VIRTUAL_MODULES","response","json","dehydrateRouter","isRedirect","isResolvedRedirect","requestHandler","processRouteTree","getMatchedRoutes","rootRouteId","method","flattenMiddlewares","ctx"],"mappings":";;;;;;;;;;;AAgCO,SAAS,wBAAwB,MAA6B;AACnE,MAAI,UAAUA,gBAAA;AAAA,IACZC,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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,KAAKR,WAAAA,WAAW,GAAG;AAC1C;AAEA,SAAS,WAAW,UAA0C;AAC5D,SAAO,oBAAoB;AAC7B;;;"}
@@ -8,6 +8,7 @@ const ssrServer = require("./ssr-server.cjs");
8
8
  const serverFunctionsHandler = require("./server-functions-handler.cjs");
9
9
  const h3 = require("./h3.cjs");
10
10
  const serverRoute = require("./serverRoute.cjs");
11
+ const virtualModules = require("./virtual-modules.cjs");
11
12
  const h3$1 = require("h3");
12
13
  exports.transformPipeableStreamWithRouter = transformStreamWithRouter.transformPipeableStreamWithRouter;
13
14
  exports.transformReadableStreamWithRouter = transformStreamWithRouter.transformReadableStreamWithRouter;
@@ -94,7 +95,9 @@ exports.updateSession = h3.updateSession;
94
95
  exports.useSession = h3.useSession;
95
96
  exports.writeEarlyHints = h3.writeEarlyHints;
96
97
  exports.createServerFileRoute = serverRoute.createServerFileRoute;
98
+ exports.createServerRootRoute = serverRoute.createServerRootRoute;
97
99
  exports.createServerRoute = serverRoute.createServerRoute;
100
+ exports.VIRTUAL_MODULES = virtualModules.VIRTUAL_MODULES;
98
101
  Object.defineProperty(exports, "H3Error", {
99
102
  enumerable: true,
100
103
  get: () => h3$1.H3Error
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -7,5 +7,6 @@ export type { HandlerCallback } from './handlerCallback.cjs';
7
7
  export { attachRouterServerSsrUtils, dehydrateRouter } from './ssr-server.cjs';
8
8
  export { handleServerAction } from './server-functions-handler.cjs';
9
9
  export * from './h3.cjs';
10
- export { createServerRoute, createServerFileRoute } from './serverRoute.cjs';
11
- export type { CreateServerFileRoute } from './serverRoute.cjs';
10
+ export { createServerRoute, createServerFileRoute, createServerRootRoute, } from './serverRoute.cjs';
11
+ export type { CreateServerFileRoute, ServerFileRoutesByPath, } from './serverRoute.cjs';
12
+ export * from './virtual-modules.cjs';
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") {
10
+ for (let key of __getOwnPropNames(from))
11
+ if (!__hasOwnProp.call(to, key) && key !== except)
12
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13
+ }
14
+ return to;
15
+ };
16
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
17
+ // If the importer is in node compatibility mode or this is not an ESM
18
+ // file that has been converted to a CommonJS file using a Babel-
19
+ // compatible transform (i.e. "__esModule" has not been set), then set
20
+ // "default" to the CommonJS "module.exports" for node compatibility.
21
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
+ mod
23
+ ));
24
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
25
+ const virtualModules = require("./virtual-modules.cjs");
26
+ async function loadVirtualModule(id) {
27
+ switch (id) {
28
+ case virtualModules.VIRTUAL_MODULES.routeTree:
29
+ return await import("tanstack-start-route-tree:v");
30
+ case virtualModules.VIRTUAL_MODULES.startManifest:
31
+ return await import("tanstack-start-manifest:v");
32
+ case virtualModules.VIRTUAL_MODULES.serverFnManifest:
33
+ return await import("tanstack-start-server-fn-manifest:v");
34
+ default:
35
+ throw new Error(`Unknown virtual module: ${id}`);
36
+ }
37
+ }
38
+ exports.loadVirtualModule = loadVirtualModule;
39
+ //# sourceMappingURL=loadVirtualModule.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loadVirtualModule.cjs","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":["VIRTUAL_MODULES"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAOA,eAAsB,kBACpB,IAC8B;AAC9B,UAAQ,IAAI;AAAA,IACV,KAAKA,eAAgB,gBAAA;AACX,aAAA,MAAM,OAAO,6BAA6B;AAAA,IACpD,KAAKA,eAAgB,gBAAA;AACX,aAAA,MAAM,OAAO,2BAA2B;AAAA,IAClD,KAAKA,eAAgB,gBAAA;AACX,aAAA,MAAM,OAAO,qCAAqC;AAAA,IAC5D;AACE,YAAM,IAAI,MAAM,2BAA2B,EAAE,EAAE;AAAA,EAAA;AAErD;;"}
@@ -0,0 +1,6 @@
1
+ import { VirtualModules } from './virtual-modules.cjs';
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]>;
@@ -1,9 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const tanstackStartRouterManifest_v = require("tanstack-start-router-manifest:v");
4
3
  const routerCore = require("@tanstack/router-core");
5
- function getStartManifest() {
6
- const startManifest = tanstackStartRouterManifest_v.tsrStartManifest();
4
+ const virtualModules = require("./virtual-modules.cjs");
5
+ const loadVirtualModule = require("./loadVirtualModule.cjs");
6
+ async function getStartManifest(opts) {
7
+ const { tsrStartManifest } = await loadVirtualModule.loadVirtualModule(
8
+ virtualModules.VIRTUAL_MODULES.startManifest
9
+ );
10
+ const startManifest = tsrStartManifest();
7
11
  const rootRoute = startManifest.routes[routerCore.rootRouteId] = startManifest.routes[routerCore.rootRouteId] || {};
8
12
  rootRoute.assets = rootRoute.assets || [];
9
13
  if (process.env.NODE_ENV === "development" && !process.env.TSS_CLIENT_ENTRY) {
@@ -12,7 +16,8 @@ function getStartManifest() {
12
16
  );
13
17
  }
14
18
  if (process.env.NODE_ENV === "development") {
15
- const script = `${globalThis.TSS_INJECTED_HEAD_SCRIPTS ? globalThis.TSS_INJECTED_HEAD_SCRIPTS + "; " : ""}import(${JSON.stringify(process.env.TSS_CLIENT_ENTRY)})`;
19
+ const clientEntry = routerCore.joinPaths([opts.basePath, process.env.TSS_CLIENT_ENTRY]);
20
+ const script = `${globalThis.TSS_INJECTED_HEAD_SCRIPTS ? globalThis.TSS_INJECTED_HEAD_SCRIPTS + "; " : ""}import('${clientEntry}')`;
16
21
  rootRoute.assets.push({
17
22
  tag: "script",
18
23
  attrs: {
@@ -1 +1 @@
1
- {"version":3,"file":"router-manifest.cjs","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":["tsrStartManifest","rootRouteId"],"mappings":";;;;AAcO,SAAS,mBAAmB;AACjC,QAAM,gBAAgBA,8BAAAA,iBAAiB;AAEjC,QAAA,YAAa,cAAc,OAAOC,WAAAA,WAAW,IACjD,cAAc,OAAOA,WAAW,WAAA,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.cjs","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":["loadVirtualModule","VIRTUAL_MODULES","rootRouteId","joinPaths"],"mappings":";;;;;AAUA,eAAsB,iBAAiB,MAA4B;AAC3D,QAAA,EAAE,iBAAiB,IAAI,MAAMA,kBAAA;AAAA,IACjCC,+BAAgB;AAAA,EAClB;AACA,QAAM,gBAAgB,iBAAiB;AAEjC,QAAA,YAAa,cAAc,OAAOC,WAAAA,WAAW,IACjD,cAAc,OAAOA,WAAW,WAAA,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,cAAcC,qBAAU,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,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
+ }>;
@@ -3,9 +3,9 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const routerCore = require("@tanstack/router-core");
4
4
  const invariant = require("tiny-invariant");
5
5
  const startClientCore = require("@tanstack/start-client-core");
6
- const _serverFnManifest = require("tanstack-start-server-fn-manifest:v");
7
6
  const h3 = require("./h3.cjs");
8
- const serverFnManifest = _serverFnManifest;
7
+ const virtualModules = require("./virtual-modules.cjs");
8
+ const loadVirtualModule = require("./loadVirtualModule.cjs");
9
9
  function sanitizeBase(base) {
10
10
  if (!base) {
11
11
  throw new Error(
@@ -32,6 +32,9 @@ const handleServerAction = async ({ request }) => {
32
32
  if (typeof serverFnId !== "string") {
33
33
  throw new Error("Invalid server action param for serverFnId: " + serverFnId);
34
34
  }
35
+ const { default: serverFnManifest } = await loadVirtualModule.loadVirtualModule(
36
+ virtualModules.VIRTUAL_MODULES.serverFnManifest
37
+ );
35
38
  const serverFnInfo = serverFnManifest[serverFnId];
36
39
  if (!serverFnInfo) {
37
40
  console.info("serverFnManifest", serverFnManifest);
@@ -1 +1 @@
1
- {"version":3,"file":"server-functions-handler.cjs","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","startSerializer","isNotFound","getResponseStatus","getEvent"],"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,S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AAK;AAAA,MAAA;AAGjC,cAAQ,KAAK;AACb,cAAQ,KAAK,kBAAkB;AAC/B,cAAQ,KAAK;AACb,cAAQ,MAAM,KAAK;AACnB,cAAQ,KAAK;AAEb,aAAO,IAAI,SAASD,gBAAAA,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.cjs","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":["loadVirtualModule","VIRTUAL_MODULES","payload","startSerializer","isNotFound","getResponseStatus","getEvent"],"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,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;AAG7E,QAAM,EAAE,SAAS,iBAAiB,IAAI,MAAMA,kBAAA;AAAA,IAC1CC,+BAAgB;AAAA,EAClB;AAEM,QA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ACR,SAAS;AAAA,MACP,gBAAgB;AAAA,MAChB,GAAI,WAAW,CAAA;AAAA,IAAC;AAAA,EAClB,CACD;AACH;;"}
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const routerCore = require("@tanstack/router-core");
4
- function createServerFileRoute(__) {
4
+ function createServerFileRoute(_) {
5
5
  return createServerRoute();
6
6
  }
7
7
  function createServerRoute(__, __opts) {
@@ -81,6 +81,7 @@ function createServerRoute(__, __opts) {
81
81
  };
82
82
  return route;
83
83
  }
84
+ const createServerRootRoute = createServerRoute;
84
85
  const createMethodBuilder = (__opts) => {
85
86
  return {
86
87
  _options: __opts || {},
@@ -96,5 +97,6 @@ const createMethodBuilder = (__opts) => {
96
97
  };
97
98
  };
98
99
  exports.createServerFileRoute = createServerFileRoute;
100
+ exports.createServerRootRoute = createServerRootRoute;
99
101
  exports.createServerRoute = createServerRoute;
100
102
  //# sourceMappingURL=serverRoute.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"serverRoute.cjs","sources":["../../src/serverRoute.ts"],"sourcesContent":["import { joinPaths, rootRouteId, trimPathLeft } from '@tanstack/router-core'\nimport type {\n Assign,\n Constrain,\n Expand,\n ResolveParams,\n RouteConstraints,\n TrimPathRight,\n} from '@tanstack/router-core'\nimport type {\n AnyRequestMiddleware,\n AssignAllServerContext,\n} from '@tanstack/start-client-core'\n\ntype TODO = any\n\nexport function createServerFileRoute<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TChildren,\n>(__?: never): ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren> {\n return createServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren>(\n undefined,\n )\n}\n\nexport interface ServerRouteOptions<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TMiddlewares,\n> {\n id: TId\n path: TPath\n pathname: TFullPath\n originalIndex: number\n getParentRoute?: () => TParentRoute\n middleware: Constrain<TMiddlewares, ReadonlyArray<AnyRequestMiddleware>>\n methods: Record<\n string,\n ServerRouteMethodHandlerFn<TParentRoute, TFullPath, TMiddlewares, any, any>\n >\n caseSensitive?: boolean\n}\n\nexport type ServerRouteManifest = {\n middleware: boolean\n methods: Record<string, { middleware: boolean }>\n}\n\nexport function createServerRoute<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TChildren,\n>(\n __?: never,\n __opts?: Partial<\n ServerRouteOptions<TParentRoute, TId, TPath, TFullPath, undefined>\n >,\n): ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren> {\n const options = __opts || {}\n\n const route: ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren> = {\n path: '' as TPath,\n id: '' as TId,\n fullPath: '' as TFullPath,\n to: '' as TrimPathRight<TFullPath>,\n options: options as TODO,\n parentRoute: undefined as unknown as TParentRoute,\n _types: {} as TODO,\n // children: undefined as TChildren,\n middleware: (middlewares: TODO) =>\n createServerRoute(undefined, {\n ...options,\n middleware: middlewares,\n }) as TODO,\n methods: (methodsOrGetMethods: TODO) => {\n const methods = (() => {\n if (typeof methodsOrGetMethods === 'function') {\n return methodsOrGetMethods(createMethodBuilder())\n }\n\n return methodsOrGetMethods\n })()\n\n return createServerRoute(undefined, {\n ...__opts,\n methods,\n }) as TODO\n },\n update: (opts) =>\n createServerRoute(undefined, {\n ...options,\n ...opts,\n }) as TODO,\n init: (opts: { originalIndex: number }): void => {\n options.originalIndex = opts.originalIndex\n\n const isRoot = !options.path && !options.id\n\n route.parentRoute = options.getParentRoute?.() as TParentRoute\n\n if (isRoot) {\n route.path = rootRouteId as TPath\n } else if (!(route.parentRoute as any)) {\n throw new Error(\n `Child Route instances must pass a 'getParentRoute: () => ParentRoute' option that returns a ServerRoute instance.`,\n )\n }\n\n let path: undefined | string = isRoot ? rootRouteId : options.path\n\n // If the path is anything other than an index path, trim it up\n if (path && path !== '/') {\n path = trimPathLeft(path)\n }\n\n const customId = options.id || path\n\n // Strip the parentId prefix from the first level of children\n let id = isRoot\n ? rootRouteId\n : joinPaths([\n route.parentRoute.id === rootRouteId ? '' : route.parentRoute.id,\n customId,\n ])\n\n if (path === rootRouteId) {\n path = '/'\n }\n\n if (id !== rootRouteId) {\n id = joinPaths(['/', id])\n }\n\n const fullPath =\n id === rootRouteId ? '/' : joinPaths([route.parentRoute.fullPath, path])\n\n route.path = path as TPath\n route.id = id as TId\n route.fullPath = fullPath as TFullPath\n route.to = fullPath as TrimPathRight<TFullPath>\n },\n\n _addFileChildren: (children) => {\n if (Array.isArray(children)) {\n route.children = children as TChildren as TODO\n }\n\n if (typeof children === 'object' && children !== null) {\n route.children = Object.values(children) as TChildren as TODO\n }\n\n return route as any\n },\n\n _addFileTypes: <TFileTypes>() => route,\n }\n\n return route\n}\n\nexport type ServerRouteAddFileChildrenFn<\n in out TParentRoute extends AnyServerRouteWithTypes,\n in out TId extends RouteConstraints['TId'],\n in out TPath extends RouteConstraints['TPath'],\n in out TFullPath extends RouteConstraints['TFullPath'],\n in out TMiddlewares,\n in out TMethods,\n in out TChildren,\n> = (\n children: TChildren,\n) => ServerRouteWithTypes<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TMethods,\n TChildren\n>\n\nconst createMethodBuilder = <\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n>(\n __opts?: TODO,\n): ServerRouteMethodBuilder<TParentRoute, TFullPath, TMiddlewares> => {\n return {\n _options: __opts || {},\n _types: {} as TODO,\n middleware: (middlewares) =>\n createMethodBuilder({\n ...__opts,\n middlewares,\n }) as TODO,\n handler: (handler) =>\n createMethodBuilder({\n ...__opts,\n handler,\n }) as TODO,\n }\n}\n\nexport type CreateServerFileRoute<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TChildren,\n> = (\n options?: undefined,\n) => ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren>\n\nexport type AnyServerRouteWithTypes = ServerRouteWithTypes<\n any,\n any,\n any,\n any,\n any,\n any,\n any\n>\n\nexport interface ServerRouteWithTypes<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TMiddlewares,\n TMethods,\n TChildren,\n> {\n _types: ServerRouteTypes<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TMethods\n >\n path: TPath\n id: TId\n fullPath: TFullPath\n to: TrimPathRight<TFullPath>\n parentRoute: TParentRoute\n children?: TChildren\n options: ServerRouteOptions<TParentRoute, TId, TPath, TFullPath, TMiddlewares>\n update: (\n opts: ServerRouteOptions<TParentRoute, TId, TPath, TFullPath, undefined>,\n ) => ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren>\n init: (opts: { originalIndex: number }) => void\n _addFileChildren: ServerRouteAddFileChildrenFn<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TMethods,\n TChildren\n >\n _addFileTypes: () => ServerRouteWithTypes<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TMethods,\n TChildren\n >\n}\n\nexport interface ServerRouteTypes<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TMiddlewares,\n TMethods,\n> {\n id: TId\n path: TPath\n fullPath: TFullPath\n middlewares: TMiddlewares\n methods: TMethods\n parentRoute: TParentRoute\n allContext: ResolveAllServerContext<TParentRoute, TMiddlewares>\n}\n\nexport type ResolveAllServerContext<\n TParentRoute extends AnyServerRouteWithTypes,\n TMiddlewares,\n> = unknown extends TParentRoute\n ? AssignAllServerContext<TMiddlewares>\n : Assign<\n TParentRoute['_types']['allContext'],\n AssignAllServerContext<TMiddlewares>\n >\n\nexport type AnyServerRoute = AnyServerRouteWithTypes\n\nexport interface ServerRoute<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TChildren,\n> extends ServerRouteWithTypes<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n undefined,\n undefined,\n TChildren\n >,\n ServerRouteMiddleware<TParentRoute, TId, TPath, TFullPath, TChildren>,\n ServerRouteMethods<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n undefined,\n TChildren\n > {}\n\nexport interface ServerRouteMiddleware<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TChildren,\n> {\n middleware: <const TNewMiddleware>(\n middleware: Constrain<TNewMiddleware, ReadonlyArray<AnyRequestMiddleware>>,\n ) => ServerRouteAfterMiddleware<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TNewMiddleware,\n TChildren\n >\n}\n\nexport interface ServerRouteAfterMiddleware<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TMiddlewares,\n TChildren,\n> extends ServerRouteWithTypes<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n undefined,\n TChildren\n >,\n ServerRouteMethods<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TChildren\n > {}\n\nexport interface ServerRouteMethods<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TMiddlewares,\n TChildren,\n> {\n methods: <const TMethods>(\n methodsOrGetMethods: Constrain<\n TMethods,\n ServerRouteMethodsOptions<TParentRoute, TFullPath, TMiddlewares>\n >,\n ) => ServerRouteAfterMethods<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TMethods,\n TChildren\n >\n}\n\nexport type ServerRouteMethodsOptions<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n> =\n | ServerRouteMethodsRecord<TParentRoute, TFullPath, TMiddlewares>\n | ((\n api: ServerRouteMethodBuilder<TParentRoute, TFullPath, TMiddlewares>,\n ) => ServerRouteMethodsRecord<TParentRoute, TFullPath, TMiddlewares>)\n\nexport interface ServerRouteMethodsRecord<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n> {\n GET?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n POST?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n PUT?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n PATCH?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n DELETE?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n OPTIONS?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n HEAD?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n}\n\nexport type ServerRouteMethodRecordValue<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n> =\n | ServerRouteMethodHandlerFn<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n undefined,\n any\n >\n | AnyRouteMethodsBuilder\n\nexport type ServerRouteVerb = (typeof ServerRouteVerbs)[number]\n\nexport const ServerRouteVerbs = [\n 'GET',\n 'POST',\n 'PUT',\n 'PATCH',\n 'DELETE',\n 'OPTIONS',\n 'HEAD',\n] as const\n\nexport type ServerRouteMethodHandlerFn<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse,\n> = (\n ctx: ServerRouteMethodHandlerCtx<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares\n >,\n) => TResponse | Promise<TResponse>\n\nexport interface ServerRouteMethodHandlerCtx<\n in out TParentRoute extends AnyServerRouteWithTypes,\n in out TFullPath extends string,\n in out TMiddlewares,\n in out TMethodMiddlewares,\n> {\n context: Expand<\n AssignAllMethodContext<TParentRoute, TMiddlewares, TMethodMiddlewares>\n >\n request: Request\n params: Expand<ResolveParams<TFullPath>>\n pathname: TFullPath\n}\n\nexport type MergeMethodMiddlewares<TMiddlewares, TMethodMiddlewares> =\n TMiddlewares extends ReadonlyArray<any>\n ? TMethodMiddlewares extends ReadonlyArray<any>\n ? readonly [...TMiddlewares, ...TMethodMiddlewares]\n : TMiddlewares\n : TMethodMiddlewares\n\nexport type AssignAllMethodContext<\n TParentRoute extends AnyServerRouteWithTypes,\n TMiddlewares,\n TMethodMiddlewares,\n> = ResolveAllServerContext<\n TParentRoute,\n MergeMethodMiddlewares<TMiddlewares, TMethodMiddlewares>\n>\n\nexport type AnyRouteMethodsBuilder = ServerRouteMethodBuilderWithTypes<\n any,\n any,\n any,\n any\n>\n\nexport interface ServerRouteMethodBuilder<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n> extends ServerRouteMethodBuilderWithTypes<\n TFullPath,\n TMiddlewares,\n undefined,\n undefined\n >,\n ServerRouteMethodBuilderMiddleware<TParentRoute, TFullPath, TMiddlewares>,\n ServerRouteMethodBuilderHandler<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n undefined\n > {}\n\nexport interface ServerRouteMethodBuilderWithTypes<\n TFullPath extends string,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse,\n> {\n _options: TODO\n _types: ServerRouteMethodBuilderTypes<\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse\n >\n}\n\nexport interface ServerRouteMethodBuilderTypes<\n in out TFullPath extends string,\n in out TMiddlewares,\n in out TMethodMiddlewares,\n in out TResponse,\n> {\n middlewares: TMiddlewares\n methodMiddleware: TMethodMiddlewares\n fullPath: TFullPath\n response: TResponse\n}\n\nexport interface ServerRouteMethodBuilderMiddleware<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n> {\n middleware: <const TNewMethodMiddlewares>(\n middleware: Constrain<\n TNewMethodMiddlewares,\n ReadonlyArray<AnyRequestMiddleware>\n >,\n ) => ServerRouteMethodBuilderAfterMiddleware<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TNewMethodMiddlewares\n >\n}\n\nexport interface ServerRouteMethodBuilderAfterMiddleware<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n TMethodMiddlewares,\n> extends ServerRouteMethodBuilderWithTypes<\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n undefined\n >,\n ServerRouteMethodBuilderHandler<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares\n > {}\n\nexport interface ServerRouteMethodBuilderHandler<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n TMethodMiddlewares,\n> {\n handler: <TResponse>(\n handler: ServerRouteMethodHandlerFn<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse\n >,\n ) => ServerRouteMethodBuilderAfterHandler<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse\n >\n}\n\nexport interface ServerRouteMethodBuilderAfterHandler<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse,\n> extends ServerRouteMethodBuilderWithTypes<\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse\n > {\n opts: ServerRouteMethod<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares\n >\n}\n\nexport interface ServerRouteMethod<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n TMethodMiddlewares,\n> {\n middleware?: Constrain<TMiddlewares, Array<AnyRequestMiddleware>>\n handler?: ServerRouteMethodHandlerFn<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n undefined\n >\n}\n\nexport interface ServerRouteAfterMethods<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TMiddlewares,\n TMethods,\n TChildren,\n> extends ServerRouteWithTypes<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TMethods,\n TChildren\n > {\n options: ServerRouteOptions<TParentRoute, TId, TPath, TFullPath, TMiddlewares>\n}\n"],"names":["rootRouteId","trimPathLeft","joinPaths"],"mappings":";;;AAgBO,SAAS,sBAMd,IAAyE;AAClE,SAAA,kBAEP;AACF;AA2BgB,SAAA,kBAOd,IACA,QAG6D;AACvD,QAAA,UAAU,UAAU,CAAC;AAE3B,QAAM,QAAqE;AAAA,IACzE,MAAM;AAAA,IACN,IAAI;AAAA,IACJ,UAAU;AAAA,IACV,IAAI;AAAA,IACJ;AAAA,IACA,aAAa;AAAA,IACb,QAAQ,CAAC;AAAA;AAAA,IAET,YAAY,CAAC,gBACX,kBAAkB,QAAW;AAAA,MAC3B,GAAG;AAAA,MACH,YAAY;AAAA,IAAA,CACb;AAAA,IACH,SAAS,CAAC,wBAA8B;AACtC,YAAM,WAAW,MAAM;AACjB,YAAA,OAAO,wBAAwB,YAAY;AACtC,iBAAA,oBAAoB,qBAAqB;AAAA,QAAA;AAG3C,eAAA;AAAA,MAAA,GACN;AAEH,aAAO,kBAAkB,QAAW;AAAA,QAClC,GAAG;AAAA,QACH;AAAA,MAA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IAEA,eAAe,MAAkB;AAAA,EACnC;AAEO,SAAA;AACT;AAsBA,MAAM,sBAAsB,CAK1B,WACoE;AAC7D,SAAA;AAAA,IACL,UAAU,UAAU,CAAC;AAAA,IACrB,QAAQ,CAAC;AAAA,IACT,YAAY,CAAC,gBACX,oBAAoB;AAAA,MAClB,GAAG;AAAA,MACH;AAAA,IAAA,CACD;AAAA,IACH,SAAS,CAAC,YACR,oBAAoB;AAAA,MAClB,GAAG;AAAA,MACH;AAAA,IACD,CAAA;AAAA,EACL;AACF;;;"}
1
+ {"version":3,"file":"serverRoute.cjs","sources":["../../src/serverRoute.ts"],"sourcesContent":["import { joinPaths, rootRouteId, trimPathLeft } from '@tanstack/router-core'\nimport type {\n Assign,\n Constrain,\n Expand,\n ResolveParams,\n RouteConstraints,\n TrimPathRight,\n} from '@tanstack/router-core'\nimport type {\n AnyRequestMiddleware,\n AssignAllServerContext,\n} from '@tanstack/start-client-core'\n\nexport function createServerFileRoute<\n TFilePath extends keyof ServerFileRoutesByPath,\n TParentRoute extends\n AnyServerRouteWithTypes = ServerFileRoutesByPath[TFilePath]['parentRoute'],\n TId extends RouteConstraints['TId'] = ServerFileRoutesByPath[TFilePath]['id'],\n TPath extends\n RouteConstraints['TPath'] = ServerFileRoutesByPath[TFilePath]['path'],\n TFullPath extends\n RouteConstraints['TFullPath'] = ServerFileRoutesByPath[TFilePath]['fullPath'],\n TChildren = ServerFileRoutesByPath[TFilePath]['children'],\n>(_: TFilePath): ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren> {\n return createServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren>(\n undefined,\n )\n}\n\nexport interface ServerFileRoutesByPath {}\n\nexport interface ServerRouteOptions<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TMiddlewares,\n> {\n id: TId\n path: TPath\n pathname: TFullPath\n originalIndex: number\n getParentRoute?: () => TParentRoute\n middleware: Constrain<TMiddlewares, ReadonlyArray<AnyRequestMiddleware>>\n methods: Record<\n string,\n ServerRouteMethodHandlerFn<TParentRoute, TFullPath, TMiddlewares, any, any>\n >\n caseSensitive?: boolean\n}\n\nexport type ServerRouteManifest = {\n middleware: boolean\n methods: Record<string, { middleware: boolean }>\n}\n\nexport function createServerRoute<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TChildren,\n>(\n __?: never,\n __opts?: Partial<\n ServerRouteOptions<TParentRoute, TId, TPath, TFullPath, undefined>\n >,\n): ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren> {\n const options = __opts || {}\n\n const route: ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren> = {\n path: '' as TPath,\n id: '' as TId,\n fullPath: '' as TFullPath,\n to: '' as TrimPathRight<TFullPath>,\n options: options as ServerRouteOptions<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n any\n >,\n parentRoute: undefined as unknown as TParentRoute,\n _types: {} as ServerRouteTypes<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n undefined,\n undefined\n >,\n // children: undefined as TChildren,\n middleware: (middlewares) =>\n createServerRoute(undefined, {\n ...options,\n middleware: middlewares,\n }) as never,\n methods: (methodsOrGetMethods) => {\n const methods = (() => {\n if (typeof methodsOrGetMethods === 'function') {\n return methodsOrGetMethods(createMethodBuilder())\n }\n\n return methodsOrGetMethods\n })()\n\n return createServerRoute(undefined, {\n ...__opts,\n methods: methods as never,\n }) as never\n },\n update: (opts) =>\n createServerRoute(undefined, {\n ...options,\n ...opts,\n }),\n init: (opts: { originalIndex: number }): void => {\n options.originalIndex = opts.originalIndex\n\n const isRoot = !options.path && !options.id\n\n route.parentRoute = options.getParentRoute?.() as TParentRoute\n\n if (isRoot) {\n route.path = rootRouteId as TPath\n } else if (!(route.parentRoute as any)) {\n throw new Error(\n `Child Route instances must pass a 'getParentRoute: () => ParentRoute' option that returns a ServerRoute instance.`,\n )\n }\n\n let path: undefined | string = isRoot ? rootRouteId : options.path\n\n // If the path is anything other than an index path, trim it up\n if (path && path !== '/') {\n path = trimPathLeft(path)\n }\n\n const customId = options.id || path\n\n // Strip the parentId prefix from the first level of children\n let id = isRoot\n ? rootRouteId\n : joinPaths([\n route.parentRoute.id === rootRouteId ? '' : route.parentRoute.id,\n customId,\n ])\n\n if (path === rootRouteId) {\n path = '/'\n }\n\n if (id !== rootRouteId) {\n id = joinPaths(['/', id])\n }\n\n const fullPath =\n id === rootRouteId ? '/' : joinPaths([route.parentRoute.fullPath, path])\n\n route.path = path as TPath\n route.id = id as TId\n route.fullPath = fullPath as TFullPath\n route.to = fullPath as TrimPathRight<TFullPath>\n },\n\n _addFileChildren: (children) => {\n if (Array.isArray(children)) {\n route.children = children as TChildren\n }\n\n if (typeof children === 'object' && children !== null) {\n route.children = Object.values(children) as TChildren\n }\n\n return route\n },\n\n _addFileTypes: <TFileTypes>() => route,\n }\n\n return route\n}\n\n// TODO this needs to be restricted to only allow middleware, no methods\n// TODO we also need to restrict pathless server routes to only allow middleware\nexport const createServerRootRoute = createServerRoute\n\nexport type ServerRouteAddFileChildrenFn<\n in out TParentRoute extends AnyServerRouteWithTypes,\n in out TId extends RouteConstraints['TId'],\n in out TPath extends RouteConstraints['TPath'],\n in out TFullPath extends RouteConstraints['TFullPath'],\n in out TMiddlewares,\n in out TMethods,\n in out TChildren,\n> = (\n children: TChildren,\n) => ServerRouteWithTypes<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TMethods,\n TChildren\n>\n\nconst createMethodBuilder = <\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n>(\n __opts?: ServerRouteMethodBuilderOptions<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n unknown,\n unknown\n >,\n): ServerRouteMethodBuilder<TParentRoute, TFullPath, TMiddlewares> => {\n return {\n _options: (__opts || {}) as never,\n _types: {} as never,\n middleware: (middlewares) =>\n createMethodBuilder({\n ...__opts,\n middlewares,\n }) as never,\n handler: (handler) =>\n createMethodBuilder({\n ...__opts,\n handler: handler as never,\n }) as never,\n }\n}\n\nexport interface ServerRouteMethodBuilderOptions<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse,\n> {\n handler?: ServerRouteMethodHandlerFn<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse\n >\n middlewares?: Constrain<\n TMethodMiddlewares,\n ReadonlyArray<AnyRequestMiddleware>\n >\n}\n\nexport type CreateServerFileRoute<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TChildren,\n> = () => ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren>\n\nexport type AnyServerRouteWithTypes = ServerRouteWithTypes<\n any,\n any,\n any,\n any,\n any,\n any,\n any\n>\n\nexport interface ServerRouteWithTypes<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TMiddlewares,\n TMethods,\n TChildren,\n> {\n _types: ServerRouteTypes<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TMethods\n >\n path: TPath\n id: TId\n fullPath: TFullPath\n to: TrimPathRight<TFullPath>\n parentRoute: TParentRoute\n children?: TChildren\n options: ServerRouteOptions<TParentRoute, TId, TPath, TFullPath, TMiddlewares>\n update: (\n opts: ServerRouteOptions<TParentRoute, TId, TPath, TFullPath, undefined>,\n ) => ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren>\n init: (opts: { originalIndex: number }) => void\n _addFileChildren: ServerRouteAddFileChildrenFn<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TMethods,\n TChildren\n >\n _addFileTypes: () => ServerRouteWithTypes<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TMethods,\n TChildren\n >\n}\n\nexport interface ServerRouteTypes<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TMiddlewares,\n TMethods,\n> {\n id: TId\n path: TPath\n fullPath: TFullPath\n middlewares: TMiddlewares\n methods: TMethods\n parentRoute: TParentRoute\n allContext: ResolveAllServerContext<TParentRoute, TMiddlewares>\n}\n\nexport type ResolveAllServerContext<\n TParentRoute extends AnyServerRouteWithTypes,\n TMiddlewares,\n> = unknown extends TParentRoute\n ? AssignAllServerContext<TMiddlewares>\n : Assign<\n TParentRoute['_types']['allContext'],\n AssignAllServerContext<TMiddlewares>\n >\n\nexport type AnyServerRoute = AnyServerRouteWithTypes\n\nexport interface ServerRoute<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TChildren,\n> extends ServerRouteWithTypes<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n undefined,\n undefined,\n TChildren\n >,\n ServerRouteMiddleware<TParentRoute, TId, TPath, TFullPath, TChildren>,\n ServerRouteMethods<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n undefined,\n TChildren\n > {}\n\nexport interface ServerRouteMiddleware<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TChildren,\n> {\n middleware: <const TNewMiddleware>(\n middleware: Constrain<TNewMiddleware, ReadonlyArray<AnyRequestMiddleware>>,\n ) => ServerRouteAfterMiddleware<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TNewMiddleware,\n TChildren\n >\n}\n\nexport interface ServerRouteAfterMiddleware<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TMiddlewares,\n TChildren,\n> extends ServerRouteWithTypes<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n undefined,\n TChildren\n >,\n ServerRouteMethods<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TChildren\n > {}\n\nexport interface ServerRouteMethods<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TMiddlewares,\n TChildren,\n> {\n methods: <const TMethods>(\n methodsOrGetMethods: Constrain<\n TMethods,\n ServerRouteMethodsOptions<TParentRoute, TFullPath, TMiddlewares>\n >,\n ) => ServerRouteAfterMethods<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TMethods,\n TChildren\n >\n}\n\nexport type ServerRouteMethodsOptions<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n> =\n | ServerRouteMethodsRecord<TParentRoute, TFullPath, TMiddlewares>\n | ((\n api: ServerRouteMethodBuilder<TParentRoute, TFullPath, TMiddlewares>,\n ) => ServerRouteMethodsRecord<TParentRoute, TFullPath, TMiddlewares>)\n\nexport interface ServerRouteMethodsRecord<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n> {\n GET?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n POST?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n PUT?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n PATCH?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n DELETE?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n OPTIONS?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n HEAD?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n}\n\nexport type ServerRouteMethodRecordValue<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n> =\n | ServerRouteMethodHandlerFn<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n undefined,\n any\n >\n | AnyRouteMethodsBuilder\n\nexport type ServerRouteVerb = (typeof ServerRouteVerbs)[number]\n\nexport const ServerRouteVerbs = [\n 'GET',\n 'POST',\n 'PUT',\n 'PATCH',\n 'DELETE',\n 'OPTIONS',\n 'HEAD',\n] as const\n\nexport type ServerRouteMethodHandlerFn<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse,\n> = (\n ctx: ServerRouteMethodHandlerCtx<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares\n >,\n) => TResponse | Promise<TResponse>\n\nexport interface ServerRouteMethodHandlerCtx<\n in out TParentRoute extends AnyServerRouteWithTypes,\n in out TFullPath extends string,\n in out TMiddlewares,\n in out TMethodMiddlewares,\n> {\n context: Expand<\n AssignAllMethodContext<TParentRoute, TMiddlewares, TMethodMiddlewares>\n >\n request: Request\n params: Expand<ResolveParams<TFullPath>>\n pathname: TFullPath\n}\n\nexport type MergeMethodMiddlewares<TMiddlewares, TMethodMiddlewares> =\n TMiddlewares extends ReadonlyArray<any>\n ? TMethodMiddlewares extends ReadonlyArray<any>\n ? readonly [...TMiddlewares, ...TMethodMiddlewares]\n : TMiddlewares\n : TMethodMiddlewares\n\nexport type AssignAllMethodContext<\n TParentRoute extends AnyServerRouteWithTypes,\n TMiddlewares,\n TMethodMiddlewares,\n> = ResolveAllServerContext<\n TParentRoute,\n MergeMethodMiddlewares<TMiddlewares, TMethodMiddlewares>\n>\n\nexport type AnyRouteMethodsBuilder = ServerRouteMethodBuilderWithTypes<\n any,\n any,\n any,\n any,\n any\n>\n\nexport interface ServerRouteMethodBuilder<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n> extends ServerRouteMethodBuilderWithTypes<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n undefined,\n undefined\n >,\n ServerRouteMethodBuilderMiddleware<TParentRoute, TFullPath, TMiddlewares>,\n ServerRouteMethodBuilderHandler<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n undefined\n > {}\n\nexport interface ServerRouteMethodBuilderWithTypes<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse,\n> {\n _options: ServerRouteMethodBuilderOptions<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse\n >\n _types: ServerRouteMethodBuilderTypes<\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse\n >\n}\n\nexport interface ServerRouteMethodBuilderTypes<\n in out TFullPath extends string,\n in out TMiddlewares,\n in out TMethodMiddlewares,\n in out TResponse,\n> {\n middlewares: TMiddlewares\n methodMiddleware: TMethodMiddlewares\n fullPath: TFullPath\n response: TResponse\n}\n\nexport interface ServerRouteMethodBuilderMiddleware<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n> {\n middleware: <const TNewMethodMiddlewares>(\n middleware: Constrain<\n TNewMethodMiddlewares,\n ReadonlyArray<AnyRequestMiddleware>\n >,\n ) => ServerRouteMethodBuilderAfterMiddleware<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TNewMethodMiddlewares\n >\n}\n\nexport interface ServerRouteMethodBuilderAfterMiddleware<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n TMethodMiddlewares,\n> extends ServerRouteMethodBuilderWithTypes<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n undefined\n >,\n ServerRouteMethodBuilderHandler<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares\n > {}\n\nexport interface ServerRouteMethodBuilderHandler<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n TMethodMiddlewares,\n> {\n handler: <TResponse>(\n handler: ServerRouteMethodHandlerFn<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse\n >,\n ) => ServerRouteMethodBuilderAfterHandler<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse\n >\n}\n\nexport interface ServerRouteMethodBuilderAfterHandler<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse,\n> extends ServerRouteMethodBuilderWithTypes<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse\n > {\n opts: ServerRouteMethod<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares\n >\n}\n\nexport interface ServerRouteMethod<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n TMethodMiddlewares,\n> {\n middleware?: Constrain<TMiddlewares, Array<AnyRequestMiddleware>>\n handler?: ServerRouteMethodHandlerFn<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n undefined\n >\n}\n\nexport interface ServerRouteAfterMethods<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TMiddlewares,\n TMethods,\n TChildren,\n> extends ServerRouteWithTypes<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TMethods,\n TChildren\n > {\n options: ServerRouteOptions<TParentRoute, TId, TPath, TFullPath, TMiddlewares>\n}\n"],"names":["rootRouteId","trimPathLeft","joinPaths"],"mappings":";;;AAcO,SAAS,sBAUd,GAA2E;AACpE,SAAA,kBAEP;AACF;A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