@tanstack/start-server-core 1.121.0-alpha.15 → 1.121.0-alpha.17

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.
@@ -73,8 +73,10 @@ function createStartHandler({
73
73
  const history$1 = history.createMemoryHistory({
74
74
  initialEntries: [href]
75
75
  });
76
+ const APP_BASE = process.env.TSS_APP_BASE || "/";
76
77
  const router = createRouter();
77
- ssrServer.attachRouterServerSsrUtils(router, await routerManifest.getStartManifest());
78
+ const startRoutesManifest = await routerManifest.getStartManifest({ basePath: APP_BASE });
79
+ ssrServer.attachRouterServerSsrUtils(router, startRoutesManifest);
78
80
  router.update({
79
81
  history: history$1
80
82
  });
@@ -86,7 +88,7 @@ function createStartHandler({
86
88
  );
87
89
  }
88
90
  const serverFnBase = routerCore.joinPaths([
89
- "/",
91
+ APP_BASE,
90
92
  routerCore.trimPath(process.env.TSS_SERVER_FN_BASE),
91
93
  "/"
92
94
  ]);
@@ -107,7 +109,8 @@ function createStartHandler({
107
109
  if (serverRouteTreeModule) {
108
110
  const [_matchedRoutes, response3] = await handleServerRoutes({
109
111
  routeTree: serverRouteTreeModule.routeTree,
110
- request
112
+ request,
113
+ basePath: APP_BASE
111
114
  });
112
115
  if (response3) return response3;
113
116
  }
@@ -196,7 +199,8 @@ function createStartHandler({
196
199
  }
197
200
  async function handleServerRoutes({
198
201
  routeTree,
199
- request
202
+ request,
203
+ basePath
200
204
  }) {
201
205
  const { flatRoutes, routesById, routesByPath } = routerCore.processRouteTree({
202
206
  routeTree,
@@ -213,7 +217,7 @@ async function handleServerRoutes({
213
217
  });
214
218
  const { matchedRoutes, foundRoute, routeParams } = routerCore.getMatchedRoutes({
215
219
  pathname: history$1.location.pathname,
216
- basepath: "/",
220
+ basepath: basePath,
217
221
  caseSensitive: true,
218
222
  routesByPath,
219
223
  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, await 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,gBAAA;AAAA,IACZC,sBAAmB;AAAA,IACnB;AAAA,MACE,gBAAgB;AAAA,IAClB;AAAA,IACA,GAAG,KAAK,OAAO,MAAM,QAAQ,IAAI,CAAC,UAAU;AAC1C,aAAO,MAAM;AAAA,IACd,CAAA;AAAA,EACH;AAEA,QAAM,EAAE,SAAA,IAAa,KAAK,OAAO;AAEjC,MAAI,UAAU;AACF,cAAAD,gBAAA,aAAa,SAAS,SAAS,OAAO;AAAA,EAAA;AAE3C,SAAA;AACT;AAEO,SAAS,mBAA8C;AAAA,EAC5D;AACF,GAEmC;AACjC,SAAO,CAAC,OAAO;AACb,UAAM,gBAAgB,WAAW;AAEjC,UAAM,uBAAuC,OAAO,EAAE,cAAc;AAMvD,iBAAA,QAAQ,eAAgB,OAAO,MAAM;AACrC,iBAAA,QAAQE,MAAU,gBAAyC;AAClE,gBAAM,eAAe,IAAI,QAAQA,MAAK,cAAc;AACpD,iBAAO,qBAAqB,EAAE,SAAS,cAAc;AAAA,QAAA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SAAS,kBAAkB,aAAmB,KAAW;AACvD,MAAI,QAAQ;AAEN,QAAA,OAAO,OAAOkB,SAAc;AAChC;AACM,UAAA,aAAa,YAAY,KAAK;AAChC,QAAA,CAAC,WAAmBA,QAAAA;AAElB,UAAA,SAAS,MAAM,WAAW;AAAA,MAC9B,GAAGA;AAAAA;AAAAA,MAEH,MAAM,OAAO,YAAkB;AAEvB,cAAA,aAAa,MAAM,KAAK,EAAE,GAAGA,MAAK,GAAG,SAAS;AAGpD,eAAO,OAAO,OAAOA,MAAK,gBAAgB,UAAU,CAAC;AAAA,MAAA;AAAA;AAAA,IACvD,CAED,EAAE,MAAM,CAAC,QAAc;AAClB,UAAA,kBAAkB,GAAG,GAAG;AACnB,eAAA;AAAA,UACL,UAAU;AAAA,QACZ;AAAA,MAAA;AAGI,YAAA;AAAA,IAAA,CACP;AAID,WAAO,OAAO,OAAOA,MAAK,gBAAgB,MAAM,CAAC;AAAA,EACnD;AAEO,SAAA,gBAAgB,KAAK,GAAG,CAAC;AAClC;AAEA,SAAS,gBAAgB,QAAc;AACjC,MAAA,kBAAkB,MAAM,GAAG;AACtB,WAAA;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,EAAA;AAGK,SAAA;AACT;AAEA,SAAS,kBAAkB,KAAW;AACpC,SAAO,WAAW,GAAG,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 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 const APP_BASE = process.env.TSS_APP_BASE || '/'\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 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 // 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 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 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: 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","response","json","dehydrateRouter","isRedirect","isResolvedRedirect","requestHandler","processRouteTree","getMatchedRoutes","rootRouteId","method","flattenMiddlewares","ctx"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BO,SAAS,wBAAwB,MAA6B;AACnE,MAAI,UAAUA,gBAAA;AAAA,IACZC,sBAAmB;AAAA,IACnB;AAAA,MACE,gBAAgB;AAAA,IAClB;AAAA,IACA,GAAG,KAAK,OAAO,MAAM,QAAQ,IAAI,CAAC,UAAU;AAC1C,aAAO,MAAM;AAAA,IACd,CAAA;AAAA,EACH;AAEA,QAAM,EAAE,SAAA,IAAa,KAAK,OAAO;AAEjC,MAAI,UAAU;AACF,cAAAD,gBAAA,aAAa,SAAS,SAAS,OAAO;AAAA,EAAA;AAE3C,SAAA;AACT;AAEO,SAAS,mBAA8C;AAAA,EAC5D;AACF,GAEmC;AACjC,SAAO,CAAC,OAAO;AACb,UAAM,gBAAgB,WAAW;AAEjC,UAAM,uBAAuC,OAAO,EAAE,cAAc;AAMvD,iBAAA,QAAQ,eAAgB,OAAO,MAAM;AACrC,iBAAA,QAAQE,MAAU,gBAAyC;AAClE,gBAAM,eAAe,IAAI,QAAQA,MAAK,cAAc;AACpD,iBAAO,qBAAqB,EAAE,SAAS,cAAc;AAAA,QAAA;AAGvD,iBAAS,YAAY;AAEjB,iBAAA,QAAQ,QAAQ,IAAI,QAAQ,KAC5B,QAAQ,QAAQ,IAAI,SAAS,KAC7B;AAAA,QAAA;AAIJ,YAAI,OAAO,UAAU,YAAY,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AAW;AACvD,MAAI,QAAQ;AAEN,QAAA,OAAO,OAAOkB,SAAc;AAChC;AACM,UAAA,aAAa,YAAY,KAAK;AAChC,QAAA,CAAC,WAAmBA,QAAAA;AAElB,UAAA,SAAS,MAAM,WAAW;AAAA,MAC9B,GAAGA;AAAAA;AAAAA,MAEH,MAAM,OAAO,YAAkB;AAEvB,cAAA,aAAa,MAAM,KAAK,EAAE,GAAGA,MAAK,GAAG,SAAS;AAGpD,eAAO,OAAO,OAAOA,MAAK,gBAAgB,UAAU,CAAC;AAAA,MAAA;AAAA;AAAA,IACvD,CAED,EAAE,MAAM,CAAC,QAAc;AAClB,UAAA,kBAAkB,GAAG,GAAG;AACnB,eAAA;AAAA,UACL,UAAU;AAAA,QACZ;AAAA,MAAA;AAGI,YAAA;AAAA,IAAA,CACP;AAID,WAAO,OAAO,OAAOA,MAAK,gBAAgB,MAAM,CAAC;AAAA,EACnD;AAEO,SAAA,gBAAgB,KAAK,GAAG,CAAC;AAClC;AAEA,SAAS,gBAAgB,QAAc;AACjC,MAAA,kBAAkB,MAAM,GAAG;AACtB,WAAA;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,EAAA;AAGK,SAAA;AACT;AAEA,SAAS,kBAAkB,KAAW;AACpC,SAAO,WAAW,GAAG,KAAKR,WAAAA,WAAW,GAAG;AAC1C;AAEA,SAAS,WAAW,UAA0C;AAC5D,SAAO,oBAAoB;AAC7B;;;"}
@@ -23,7 +23,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
23
23
  ));
24
24
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
25
25
  const routerCore = require("@tanstack/router-core");
26
- async function getStartManifest() {
26
+ async function getStartManifest(opts) {
27
27
  const { tsrStartManifest } = await import("tanstack-start-router-manifest:v");
28
28
  const startManifest = tsrStartManifest();
29
29
  const rootRoute = startManifest.routes[routerCore.rootRouteId] = startManifest.routes[routerCore.rootRouteId] || {};
@@ -34,7 +34,8 @@ async function getStartManifest() {
34
34
  );
35
35
  }
36
36
  if (process.env.NODE_ENV === "development") {
37
- const script = `${globalThis.TSS_INJECTED_HEAD_SCRIPTS ? globalThis.TSS_INJECTED_HEAD_SCRIPTS + "; " : ""}import(${JSON.stringify(process.env.TSS_CLIENT_ENTRY)})`;
37
+ const clientEntry = routerCore.joinPaths([opts.basePath, process.env.TSS_CLIENT_ENTRY]);
38
+ const script = `${globalThis.TSS_INJECTED_HEAD_SCRIPTS ? globalThis.TSS_INJECTED_HEAD_SCRIPTS + "; " : ""}import('${clientEntry}')`;
38
39
  rootRoute.assets.push({
39
40
  tag: "script",
40
41
  attrs: {
@@ -1 +1 @@
1
- {"version":3,"file":"router-manifest.cjs","sources":["../../src/router-manifest.ts"],"sourcesContent":["import { 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 async function getStartManifest() {\n const { tsrStartManifest } = await import('tanstack-start-router-manifest:v')\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":["rootRouteId"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAaA,eAAsB,mBAAmB;AACvC,QAAM,EAAE,iBAAA,IAAqB,MAAM,OAAO,kCAAkC;AAC5E,QAAM,gBAAgB,iBAAiB;AAEjC,QAAA,YAAa,cAAc,OAAOA,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'\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 async function getStartManifest(opts: { basePath: string }) {\n const { tsrStartManifest } = await import('tanstack-start-router-manifest:v')\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":["rootRouteId","joinPaths"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAaA,eAAsB,iBAAiB,MAA4B;AACjE,QAAM,EAAE,iBAAA,IAAqB,MAAM,OAAO,kCAAkC;AAC5E,QAAM,gBAAgB,iBAAiB;AAEjC,QAAA,YAAa,cAAc,OAAOA,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;;"}
@@ -7,7 +7,9 @@ declare global {
7
7
  * special assets that are needed for the client. It does not include relationships
8
8
  * between routes or any other data that is not needed for the client.
9
9
  */
10
- export declare function getStartManifest(): Promise<{
10
+ export declare function getStartManifest(opts: {
11
+ basePath: string;
12
+ }): Promise<{
11
13
  routes: {
12
14
  [k: string]: {
13
15
  preloads: string[] | undefined;
@@ -49,8 +49,10 @@ function createStartHandler({
49
49
  const history = createMemoryHistory({
50
50
  initialEntries: [href]
51
51
  });
52
+ const APP_BASE = process.env.TSS_APP_BASE || "/";
52
53
  const router = createRouter();
53
- attachRouterServerSsrUtils(router, await getStartManifest());
54
+ const startRoutesManifest = await getStartManifest({ basePath: APP_BASE });
55
+ attachRouterServerSsrUtils(router, startRoutesManifest);
54
56
  router.update({
55
57
  history
56
58
  });
@@ -62,7 +64,7 @@ function createStartHandler({
62
64
  );
63
65
  }
64
66
  const serverFnBase = joinPaths([
65
- "/",
67
+ APP_BASE,
66
68
  trimPath(process.env.TSS_SERVER_FN_BASE),
67
69
  "/"
68
70
  ]);
@@ -83,7 +85,8 @@ function createStartHandler({
83
85
  if (serverRouteTreeModule) {
84
86
  const [_matchedRoutes, response3] = await handleServerRoutes({
85
87
  routeTree: serverRouteTreeModule.routeTree,
86
- request
88
+ request,
89
+ basePath: APP_BASE
87
90
  });
88
91
  if (response3) return response3;
89
92
  }
@@ -172,7 +175,8 @@ function createStartHandler({
172
175
  }
173
176
  async function handleServerRoutes({
174
177
  routeTree,
175
- request
178
+ request,
179
+ basePath
176
180
  }) {
177
181
  const { flatRoutes, routesById, routesByPath } = processRouteTree({
178
182
  routeTree,
@@ -189,7 +193,7 @@ async function handleServerRoutes({
189
193
  });
190
194
  const { matchedRoutes, foundRoute, routeParams } = getMatchedRoutes({
191
195
  pathname: history.location.pathname,
192
- basepath: "/",
196
+ basepath: basePath,
193
197
  caseSensitive: true,
194
198
  routesByPath,
195
199
  routesById,
@@ -1 +1 @@
1
- {"version":3,"file":"createStartHandler.js","sources":["../../src/createStartHandler.ts"],"sourcesContent":["import { createMemoryHistory } from '@tanstack/history'\nimport {\n flattenMiddlewares,\n json,\n mergeHeaders,\n} from '@tanstack/start-client-core'\nimport {\n getMatchedRoutes,\n isRedirect,\n isResolvedRedirect,\n joinPaths,\n processRouteTree,\n rootRouteId,\n trimPath,\n} from '@tanstack/router-core'\nimport { getResponseHeaders, requestHandler } from './h3'\nimport { attachRouterServerSsrUtils, dehydrateRouter } from './ssr-server'\nimport { getStartManifest } from './router-manifest'\nimport { handleServerAction } from './server-functions-handler'\nimport type { AnyServerRoute, AnyServerRouteWithTypes } from './serverRoute'\nimport type { RequestHandler } from './h3'\nimport type { AnyRouter } from '@tanstack/router-core'\nimport type { HandlerCallback } from './handlerCallback'\n\ntype TODO = any\n\nexport type CustomizeStartHandler<TRouter extends AnyRouter> = (\n cb: HandlerCallback<TRouter>,\n) => RequestHandler\n\nexport function getStartResponseHeaders(opts: { router: AnyRouter }) {\n let headers = mergeHeaders(\n getResponseHeaders(),\n {\n 'Content-Type': 'text/html; charset=UTF-8',\n },\n ...opts.router.state.matches.map((match) => {\n return match.headers\n }),\n )\n // Handle Redirects\n const { redirect } = opts.router.state\n\n if (redirect) {\n headers = mergeHeaders(headers, redirect.headers)\n }\n return headers\n}\n\nexport function createStartHandler<TRouter extends AnyRouter>({\n createRouter,\n}: {\n createRouter: () => TRouter\n}): CustomizeStartHandler<TRouter> {\n return (cb) => {\n const originalFetch = globalThis.fetch\n\n const startRequestResolver: RequestHandler = async ({ request }) => {\n // Patching fetch function to use our request resolver\n // if the input starts with `/` which is a common pattern for\n // client-side routing.\n // When we encounter similar requests, we can assume that the\n // user wants to use the same origin as the current request.\n globalThis.fetch = async function (input, init) {\n function resolve(url: URL, requestOptions: RequestInit | undefined) {\n const fetchRequest = new Request(url, requestOptions)\n return startRequestResolver({ request: fetchRequest })\n }\n\n function getOrigin() {\n return (\n request.headers.get('Origin') ||\n request.headers.get('Referer') ||\n 'http://localhost'\n )\n }\n\n if (typeof input === 'string' && input.startsWith('/')) {\n // e.g: fetch('/api/data')\n const url = new URL(input, getOrigin())\n return resolve(url, init)\n } else if (\n typeof input === 'object' &&\n 'url' in input &&\n typeof input.url === 'string' &&\n input.url.startsWith('/')\n ) {\n // e.g: fetch(new Request('/api/data'))\n const url = new URL(input.url, getOrigin())\n return resolve(url, init)\n }\n\n // If not, it should just use the original fetch\n return originalFetch(input, init)\n }\n\n const url = new URL(request.url)\n const href = url.href.replace(url.origin, '')\n\n // Create a history for the client-side router\n const history = createMemoryHistory({\n initialEntries: [href],\n })\n\n // Create the client-side router\n const router = createRouter()\n\n // Attach the server-side SSR utils to the client-side router\n attachRouterServerSsrUtils(router, await getStartManifest())\n\n // Update the client-side router with the history and context\n router.update({\n history,\n })\n\n const response = await (async () => {\n try {\n if (!process.env.TSS_SERVER_FN_BASE) {\n throw new Error(\n 'tanstack/start-server-core: TSS_SERVER_FN_BASE must be defined in your environment for createStartHandler()',\n )\n }\n\n // First, let's attempt to handle server functions\n // Add trailing slash to sanitise user defined TSS_SERVER_FN_BASE\n const serverFnBase = joinPaths([\n '/',\n trimPath(process.env.TSS_SERVER_FN_BASE),\n '/',\n ])\n if (href.startsWith(serverFnBase)) {\n return await handleServerAction({ request })\n }\n\n // Then move on to attempting to load server routes\n const serverRouteTreeModule = await (async () => {\n try {\n return (await import(\n // @ts-expect-error\n 'tanstack-start-server-routes-manifest:v'\n )) as { routeTree: AnyServerRoute }\n } catch (e) {\n console.log(e)\n return undefined\n }\n })()\n\n // If we have a server route tree, then we try matching to see if we have a\n // server route that matches the request.\n if (serverRouteTreeModule) {\n const [_matchedRoutes, response] = await handleServerRoutes({\n routeTree: serverRouteTreeModule.routeTree,\n request,\n })\n\n if (response) return response\n }\n\n const requestAcceptHeader = request.headers.get('Accept') || '*/*'\n const splitRequestAcceptHeader = requestAcceptHeader.split(',')\n\n const supportedMimeTypes = ['*/*', 'text/html']\n const isRouterAcceptSupported = supportedMimeTypes.some((mimeType) =>\n splitRequestAcceptHeader.some((acceptedMimeType) =>\n acceptedMimeType.trim().startsWith(mimeType),\n ),\n )\n\n if (!isRouterAcceptSupported) {\n return json(\n {\n error: 'Only HTML requests are supported here',\n },\n {\n status: 500,\n },\n )\n }\n\n // If no Server Routes were found, so fallback to normal SSR matching using\n // the router\n\n await router.load()\n\n // If there was a redirect, skip rendering the page at all\n if (router.state.redirect) return router.state.redirect\n\n dehydrateRouter(router)\n\n const responseHeaders = getStartResponseHeaders({ router })\n const response = await cb({\n request,\n router,\n responseHeaders,\n })\n\n return response\n } catch (err) {\n if (err instanceof Response) {\n return err\n }\n\n throw err\n }\n })()\n\n if (isRedirect(response)) {\n if (isResolvedRedirect(response)) {\n if (request.headers.get('x-tsr-redirect') === 'manual') {\n return json(\n {\n ...response.options,\n isSerializedRedirect: true,\n },\n {\n headers: response.headers,\n },\n )\n }\n return response\n }\n if (\n response.options.to &&\n typeof response.options.to === 'string' &&\n !response.options.to.startsWith('/')\n ) {\n throw new Error(\n `Server side redirects must use absolute paths via the 'href' or 'to' options. Received: ${JSON.stringify(response.options)}`,\n )\n }\n\n if (\n ['params', 'search', 'hash'].some(\n (d) => typeof (response.options as any)[d] === 'function',\n )\n ) {\n throw new Error(\n `Server side redirects must use static search, params, and hash values and do not support functional values. Received functional values for: ${Object.keys(\n response.options,\n )\n .filter((d) => typeof (response.options as any)[d] === 'function')\n .map((d) => `\"${d}\"`)\n .join(', ')}`,\n )\n }\n\n const redirect = router.resolveRedirect(response)\n\n if (request.headers.get('x-tsr-redirect') === 'manual') {\n return json(\n {\n ...response.options,\n isSerializedRedirect: true,\n },\n {\n headers: response.headers,\n },\n )\n }\n\n return redirect\n }\n\n return response\n }\n\n return requestHandler(startRequestResolver)\n }\n}\n\nasync function handleServerRoutes({\n routeTree,\n request,\n}: {\n routeTree: AnyServerRouteWithTypes\n request: Request\n}) {\n const { flatRoutes, routesById, routesByPath } = processRouteTree({\n routeTree,\n initRoute: (route, i) => {\n route.init({\n originalIndex: i,\n })\n },\n })\n\n const url = new URL(request.url)\n const pathname = url.pathname\n\n const history = createMemoryHistory({\n initialEntries: [pathname],\n })\n\n const { matchedRoutes, foundRoute, routeParams } =\n getMatchedRoutes<AnyServerRouteWithTypes>({\n pathname: history.location.pathname,\n basepath: '/',\n caseSensitive: true,\n routesByPath,\n routesById,\n flatRoutes,\n })\n\n let response: Response | undefined\n\n if (foundRoute && foundRoute.id !== rootRouteId) {\n // We've found a server route that matches the request, so we can call it.\n // TODO: Get the input type-signature correct\n // TODO: Perform the middlewares?\n // TODO: Error handling? What happens when its `throw redirect()` vs `throw new Error()`?\n\n const method = Object.keys(foundRoute.options.methods).find(\n (method) => method.toLowerCase() === request.method.toLowerCase(),\n )\n\n if (method) {\n const handler = foundRoute.options.methods[method]\n\n if (handler) {\n const middlewares = flattenMiddlewares(\n matchedRoutes.flatMap((r) => r.options.middleware).filter(Boolean),\n ).map((d) => d.options.server)\n\n middlewares.push(handlerToMiddleware(handler) as TODO)\n\n // TODO: This is starting to feel too much like a server function\n // Do generalize the existing middleware execution? Or do we need to\n // build a new middleware execution system for server routes?\n const ctx = await executeMiddleware(middlewares, {\n request,\n context: {},\n params: routeParams,\n pathname: history.location.pathname,\n })\n\n response = ctx.response\n }\n }\n }\n\n // We return the matched routes too so if\n // the app router happens to match the same path,\n // it can use any request middleware from server routes\n return [matchedRoutes, response] as const\n}\n\nfunction handlerToMiddleware(\n handler: AnyServerRouteWithTypes['options']['methods'][string],\n) {\n return async ({ next: _next, ...rest }: TODO) => ({\n response: await handler(rest),\n })\n}\n\nfunction executeMiddleware(middlewares: TODO, ctx: TODO) {\n let index = -1\n\n const next = async (ctx: TODO) => {\n index++\n const middleware = middlewares[index]\n if (!middleware) return ctx\n\n const result = await middleware({\n ...ctx,\n // Allow the middleware to call the next middleware in the chain\n next: async (nextCtx: TODO) => {\n // Allow the caller to extend the context for the next middleware\n const nextResult = await next({ ...ctx, ...nextCtx })\n\n // Merge the result into the context\\\n return Object.assign(ctx, handleCtxResult(nextResult))\n },\n // Allow the middleware result to extend the return context\n }).catch((err: TODO) => {\n if (isSpecialResponse(err)) {\n return {\n response: err,\n }\n }\n\n throw err\n })\n\n // Merge the middleware result into the context, just in case it\n // returns a partial context\n return Object.assign(ctx, handleCtxResult(result))\n }\n\n return handleCtxResult(next(ctx))\n}\n\nfunction handleCtxResult(result: TODO) {\n if (isSpecialResponse(result)) {\n return {\n response: result,\n }\n }\n\n return result\n}\n\nfunction isSpecialResponse(err: TODO) {\n return isResponse(err) || isRedirect(err)\n}\n\nfunction isResponse(response: Response): response is Response {\n return response instanceof Response\n}\n"],"names":["url","response","method","ctx"],"mappings":";;;;;;;AA8BO,SAAS,wBAAwB,MAA6B;AACnE,MAAI,UAAU;AAAA,IACZ,mBAAmB;AAAA,IACnB;AAAA,MACE,gBAAgB;AAAA,IAClB;AAAA,IACA,GAAG,KAAK,OAAO,MAAM,QAAQ,IAAI,CAAC,UAAU;AAC1C,aAAO,MAAM;AAAA,IACd,CAAA;AAAA,EACH;AAEA,QAAM,EAAE,SAAA,IAAa,KAAK,OAAO;AAEjC,MAAI,UAAU;AACF,cAAA,aAAa,SAAS,SAAS,OAAO;AAAA,EAAA;AAE3C,SAAA;AACT;AAEO,SAAS,mBAA8C;AAAA,EAC5D;AACF,GAEmC;AACjC,SAAO,CAAC,OAAO;AACb,UAAM,gBAAgB,WAAW;AAEjC,UAAM,uBAAuC,OAAO,EAAE,cAAc;AAMvD,iBAAA,QAAQ,eAAgB,OAAO,MAAM;AACrC,iBAAA,QAAQA,MAAU,gBAAyC;AAClE,gBAAM,eAAe,IAAI,QAAQA,MAAK,cAAc;AACpD,iBA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AAK;AAChC,QAAA,CAAC,WAAmBA,QAAAA;AAElB,UAAA,SAAS,MAAM,WAAW;AAAA,MAC9B,GAAGA;AAAAA;AAAAA,MAEH,MAAM,OAAO,YAAkB;AAEvB,cAAA,aAAa,MAAM,KAAK,EAAE,GAAGA,MAAK,GAAG,SAAS;AAGpD,eAAO,OAAO,OAAOA,MAAK,gBAAgB,UAAU,CAAC;AAAA,MAAA;AAAA;AAAA,IACvD,CAED,EAAE,MAAM,CAAC,QAAc;AAClB,UAAA,kBAAkB,GAAG,GAAG;AACnB,eAAA;AAAA,UACL,UAAU;AAAA,QACZ;AAAA,MAAA;AAGI,YAAA;AAAA,IAAA,CACP;AAID,WAAO,OAAO,OAAOA,MAAK,gBAAgB,MAAM,CAAC;AAAA,EACnD;AAEO,SAAA,gBAAgB,KAAK,GAAG,CAAC;AAClC;AAEA,SAAS,gBAAgB,QAAc;AACjC,MAAA,kBAAkB,MAAM,GAAG;AACtB,WAAA;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,EAAA;AAGK,SAAA;AACT;AAEA,SAAS,kBAAkB,KAAW;AACpC,SAAO,WAAW,GAAG,KAAK,WAAW,GAAG;AAC1C;AAEA,SAAS,WAAW,UAA0C;AAC5D,SAAO,oBAAoB;AAC7B;"}
1
+ {"version":3,"file":"createStartHandler.js","sources":["../../src/createStartHandler.ts"],"sourcesContent":["import { createMemoryHistory } from '@tanstack/history'\nimport {\n flattenMiddlewares,\n json,\n mergeHeaders,\n} from '@tanstack/start-client-core'\nimport {\n getMatchedRoutes,\n isRedirect,\n isResolvedRedirect,\n joinPaths,\n processRouteTree,\n rootRouteId,\n trimPath,\n} from '@tanstack/router-core'\nimport { getResponseHeaders, requestHandler } from './h3'\nimport { attachRouterServerSsrUtils, dehydrateRouter } from './ssr-server'\nimport { getStartManifest } from './router-manifest'\nimport { handleServerAction } from './server-functions-handler'\nimport 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 const APP_BASE = process.env.TSS_APP_BASE || '/'\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 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 // 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 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 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: basePath,\n caseSensitive: true,\n routesByPath,\n routesById,\n flatRoutes,\n })\n\n let response: Response | undefined\n\n if (foundRoute && foundRoute.id !== rootRouteId) {\n // We've found a server route that matches the request, so we can call it.\n // TODO: Get the input type-signature correct\n // TODO: Perform the middlewares?\n // TODO: Error handling? What happens when its `throw redirect()` vs `throw new Error()`?\n\n const method = Object.keys(foundRoute.options.methods).find(\n (method) => method.toLowerCase() === request.method.toLowerCase(),\n )\n\n if (method) {\n const handler = foundRoute.options.methods[method]\n\n if (handler) {\n const middlewares = flattenMiddlewares(\n matchedRoutes.flatMap((r) => r.options.middleware).filter(Boolean),\n ).map((d) => d.options.server)\n\n middlewares.push(handlerToMiddleware(handler) as TODO)\n\n // TODO: This is starting to feel too much like a server function\n // Do generalize the existing middleware execution? Or do we need to\n // build a new middleware execution system for server routes?\n const ctx = await executeMiddleware(middlewares, {\n request,\n context: {},\n params: routeParams,\n pathname: history.location.pathname,\n })\n\n response = ctx.response\n }\n }\n }\n\n // We return the matched routes too so if\n // the app router happens to match the same path,\n // it can use any request middleware from server routes\n return [matchedRoutes, response] as const\n}\n\nfunction handlerToMiddleware(\n handler: AnyServerRouteWithTypes['options']['methods'][string],\n) {\n return async ({ next: _next, ...rest }: TODO) => ({\n response: await handler(rest),\n })\n}\n\nfunction executeMiddleware(middlewares: TODO, ctx: TODO) {\n let index = -1\n\n const next = async (ctx: TODO) => {\n index++\n const middleware = middlewares[index]\n if (!middleware) return ctx\n\n const result = await middleware({\n ...ctx,\n // Allow the middleware to call the next middleware in the chain\n next: async (nextCtx: TODO) => {\n // Allow the caller to extend the context for the next middleware\n const nextResult = await next({ ...ctx, ...nextCtx })\n\n // Merge the result into the context\\\n return Object.assign(ctx, handleCtxResult(nextResult))\n },\n // Allow the middleware result to extend the return context\n }).catch((err: TODO) => {\n if (isSpecialResponse(err)) {\n return {\n response: err,\n }\n }\n\n throw err\n })\n\n // Merge the middleware result into the context, just in case it\n // returns a partial context\n return Object.assign(ctx, handleCtxResult(result))\n }\n\n return handleCtxResult(next(ctx))\n}\n\nfunction handleCtxResult(result: TODO) {\n if (isSpecialResponse(result)) {\n return {\n response: result,\n }\n }\n\n return result\n}\n\nfunction isSpecialResponse(err: TODO) {\n return isResponse(err) || isRedirect(err)\n}\n\nfunction isResponse(response: Response): response is Response {\n return response instanceof Response\n}\n"],"names":["url","response","method","ctx"],"mappings":";;;;;;;AA8BO,SAAS,wBAAwB,MAA6B;AACnE,MAAI,UAAU;AAAA,IACZ,mBAAmB;AAAA,IACnB;AAAA,MACE,gBAAgB;AAAA,IAClB;AAAA,IACA,GAAG,KAAK,OAAO,MAAM,QAAQ,IAAI,CAAC,UAAU;AAC1C,aAAO,MAAM;AAAA,IACd,CAAA;AAAA,EACH;AAEA,QAAM,EAAE,SAAA,IAAa,KAAK,OAAO;AAEjC,MAAI,UAAU;AACF,cAAA,aAAa,SAAS,SAAS,OAAO;AAAA,EAAA;AAE3C,SAAA;AACT;AAEO,SAAS,mBAA8C;AAAA,EAC5D;AACF,GAEmC;AACjC,SAAO,CAAC,OAAO;AACb,UAAM,gBAAgB,WAAW;AAEjC,UAAM,uBAAuC,OAAO,EAAE,cAAc;AAMvD,iBAAA,QAAQ,eAAgB,OAAO,MAAM;AACrC,iBAAA,QAAQA,MAAU,gBAAyC;AAClE,gBAAM,eAAe,IAAI,QAAQA,MAAK,cAAc;AACpD,iBAAO,qBAAqB,EAAE,SAAS,cAAc;AAAA,QAAA;AAGvD,iBAAS,YAAY;AAEjB,iBAAA,QAAQ,QAAQ,IAAI,QAAQ,KAC5B,QAAQ,QAAQ,IAAI,SAAS,KAC7B;AAAA,QAAA;AAIJ,YAAI,OAAO,UAAU,YAAY,MAAM,WAAW,GAAG,GAAG;AAEtD,gBAAMA,OAAM,IAAI,IAAI,OAAO,WAAW;AAC/B,iBAAA,QAAQA,MAAK,IAAI;AAAA,QAExB,WAAA,OAAO,UAAU,YACjB,SAAS,SACT,OAAO,MAAM,QAAQ,YACrB,MAAM,IAAI,WAAW,GAAG,GACxB;AAEA,gBAAMA,OAAM,IAAI,IAAI,MAAM,KAAK,WAAW;AACnC,iBAAA,QAAQA,MAAK,IAAI;AAAA,QAAA;AAInB,eAAA,cAAc,OAAO,IAAI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AAAA,IAAA,CACP;AAID,WAAO,OAAO,OAAOA,MAAK,gBAAgB,MAAM,CAAC;AAAA,EACnD;AAEO,SAAA,gBAAgB,KAAK,GAAG,CAAC;AAClC;AAEA,SAAS,gBAAgB,QAAc;AACjC,MAAA,kBAAkB,MAAM,GAAG;AACtB,WAAA;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,EAAA;AAGK,SAAA;AACT;AAEA,SAAS,kBAAkB,KAAW;AACpC,SAAO,WAAW,GAAG,KAAK,WAAW,GAAG;AAC1C;AAEA,SAAS,WAAW,UAA0C;AAC5D,SAAO,oBAAoB;AAC7B;"}
@@ -7,7 +7,9 @@ declare global {
7
7
  * special assets that are needed for the client. It does not include relationships
8
8
  * between routes or any other data that is not needed for the client.
9
9
  */
10
- export declare function getStartManifest(): Promise<{
10
+ export declare function getStartManifest(opts: {
11
+ basePath: string;
12
+ }): Promise<{
11
13
  routes: {
12
14
  [k: string]: {
13
15
  preloads: string[] | undefined;
@@ -1,5 +1,5 @@
1
- import { rootRouteId } from "@tanstack/router-core";
2
- async function getStartManifest() {
1
+ import { rootRouteId, joinPaths } from "@tanstack/router-core";
2
+ async function getStartManifest(opts) {
3
3
  const { tsrStartManifest } = await import("tanstack-start-router-manifest:v");
4
4
  const startManifest = tsrStartManifest();
5
5
  const rootRoute = startManifest.routes[rootRouteId] = startManifest.routes[rootRouteId] || {};
@@ -10,7 +10,8 @@ async function getStartManifest() {
10
10
  );
11
11
  }
12
12
  if (process.env.NODE_ENV === "development") {
13
- const script = `${globalThis.TSS_INJECTED_HEAD_SCRIPTS ? globalThis.TSS_INJECTED_HEAD_SCRIPTS + "; " : ""}import(${JSON.stringify(process.env.TSS_CLIENT_ENTRY)})`;
13
+ const clientEntry = joinPaths([opts.basePath, process.env.TSS_CLIENT_ENTRY]);
14
+ const script = `${globalThis.TSS_INJECTED_HEAD_SCRIPTS ? globalThis.TSS_INJECTED_HEAD_SCRIPTS + "; " : ""}import('${clientEntry}')`;
14
15
  rootRoute.assets.push({
15
16
  tag: "script",
16
17
  attrs: {
@@ -1 +1 @@
1
- {"version":3,"file":"router-manifest.js","sources":["../../src/router-manifest.ts"],"sourcesContent":["import { 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 async function getStartManifest() {\n const { tsrStartManifest } = await import('tanstack-start-router-manifest:v')\n const startManifest = tsrStartManifest()\n\n const rootRoute = (startManifest.routes[rootRouteId] =\n startManifest.routes[rootRouteId] || {})\n\n rootRoute.assets = rootRoute.assets || []\n\n // Get the entry for the client\n // const ClientManifest = getManifest('client')\n\n // const importPath =\n // ClientManifest.inputs[ClientManifest.handler]?.output.path\n // if (!importPath) {\n // invariant(importPath, 'Could not find client entry in manifest')\n // }\n\n if (process.env.NODE_ENV === 'development' && !process.env.TSS_CLIENT_ENTRY) {\n throw new Error(\n 'tanstack/start-server-core: TSS_CLIENT_ENTRY must be defined in your environment for getStartManifest()',\n )\n }\n\n if (process.env.NODE_ENV === 'development') {\n // Always fake that HMR is ready\n // const CLIENT_BASE = sanitizeBase(process.env.TSS_CLIENT_BASE || '')\n\n // if (!CLIENT_BASE) {\n // throw new Error(\n // 'tanstack/start-router-manifest: TSS_CLIENT_BASE must be defined in your environment for getFullRouterManifest()',\n // )\n // }\n\n const script = `${globalThis.TSS_INJECTED_HEAD_SCRIPTS ? globalThis.TSS_INJECTED_HEAD_SCRIPTS + '; ' : ''}import(${JSON.stringify(process.env.TSS_CLIENT_ENTRY)})`\n\n rootRoute.assets.push({\n tag: 'script',\n attrs: {\n type: 'module',\n suppressHydrationWarning: true,\n async: true,\n },\n children: script,\n })\n }\n\n const manifest = {\n ...startManifest,\n routes: Object.fromEntries(\n Object.entries(startManifest.routes).map(([k, v]) => {\n const { preloads, assets } = v\n return [\n k,\n {\n preloads,\n assets,\n },\n ]\n }),\n ),\n }\n\n // Strip out anything that isn't needed for the client\n return manifest\n}\n"],"names":[],"mappings":";AAaA,eAAsB,mBAAmB;AACvC,QAAM,EAAE,iBAAA,IAAqB,MAAM,OAAO,kCAAkC;AAC5E,QAAM,gBAAgB,iBAAiB;AAEjC,QAAA,YAAa,cAAc,OAAO,WAAW,IACjD,cAAc,OAAO,WAAW,KAAK,CAAC;AAE9B,YAAA,SAAS,UAAU,UAAU,CAAC;AAWxC,MAAI,QAAQ,IAAI,aAAa,iBAAiB,CAAC,QAAQ,IAAI,kBAAkB;AAC3E,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EAAA;AAGE,MAAA,QAAQ,IAAI,aAAa,eAAe;AAU1C,UAAM,SAAS,GAAG,WAAW,4BAA4B,WAAW,4BAA4B,OAAO,EAAE,UAAU,KAAK,UAAU,QAAQ,IAAI,gBAAgB,CAAC;AAE/J,cAAU,OAAO,KAAK;AAAA,MACpB,KAAK;AAAA,MACL,OAAO;AAAA,QACL,MAAM;AAAA,QACN,0BAA0B;AAAA,QAC1B,OAAO;AAAA,MACT;AAAA,MACA,UAAU;AAAA,IAAA,CACX;AAAA,EAAA;AAGH,QAAM,WAAW;AAAA,IACf,GAAG;AAAA,IACH,QAAQ,OAAO;AAAA,MACb,OAAO,QAAQ,cAAc,MAAM,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM;AAC7C,cAAA,EAAE,UAAU,OAAA,IAAW;AACtB,eAAA;AAAA,UACL;AAAA,UACA;AAAA,YACE;AAAA,YACA;AAAA,UAAA;AAAA,QAEJ;AAAA,MACD,CAAA;AAAA,IAAA;AAAA,EAEL;AAGO,SAAA;AACT;"}
1
+ {"version":3,"file":"router-manifest.js","sources":["../../src/router-manifest.ts"],"sourcesContent":["import { joinPaths, rootRouteId } from '@tanstack/router-core'\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 async function getStartManifest(opts: { basePath: string }) {\n const { tsrStartManifest } = await import('tanstack-start-router-manifest:v')\n const startManifest = tsrStartManifest()\n\n const rootRoute = (startManifest.routes[rootRouteId] =\n startManifest.routes[rootRouteId] || {})\n\n rootRoute.assets = rootRoute.assets || []\n\n // Get the entry for the client\n // const ClientManifest = getManifest('client')\n\n // const importPath =\n // ClientManifest.inputs[ClientManifest.handler]?.output.path\n // if (!importPath) {\n // invariant(importPath, 'Could not find client entry in manifest')\n // }\n\n if (process.env.NODE_ENV === 'development' && !process.env.TSS_CLIENT_ENTRY) {\n throw new Error(\n 'tanstack/start-server-core: TSS_CLIENT_ENTRY must be defined in your environment for getStartManifest()',\n )\n }\n\n if (process.env.NODE_ENV === 'development') {\n // Always fake that HMR is ready\n // const CLIENT_BASE = sanitizeBase(process.env.TSS_CLIENT_BASE || '')\n\n // if (!CLIENT_BASE) {\n // throw new Error(\n // 'tanstack/start-router-manifest: TSS_CLIENT_BASE must be defined in your environment for getFullRouterManifest()',\n // )\n // }\n\n const clientEntry = joinPaths([opts.basePath, process.env.TSS_CLIENT_ENTRY])\n\n const script = `${globalThis.TSS_INJECTED_HEAD_SCRIPTS ? globalThis.TSS_INJECTED_HEAD_SCRIPTS + '; ' : ''}import('${clientEntry}')`\n\n rootRoute.assets.push({\n tag: 'script',\n attrs: {\n type: 'module',\n suppressHydrationWarning: true,\n async: true,\n },\n children: script,\n })\n }\n\n const manifest = {\n ...startManifest,\n routes: Object.fromEntries(\n Object.entries(startManifest.routes).map(([k, v]) => {\n const { preloads, assets } = v\n return [\n k,\n {\n preloads,\n assets,\n },\n ]\n }),\n ),\n }\n\n // Strip out anything that isn't needed for the client\n return manifest\n}\n"],"names":[],"mappings":";AAaA,eAAsB,iBAAiB,MAA4B;AACjE,QAAM,EAAE,iBAAA,IAAqB,MAAM,OAAO,kCAAkC;AAC5E,QAAM,gBAAgB,iBAAiB;AAEjC,QAAA,YAAa,cAAc,OAAO,WAAW,IACjD,cAAc,OAAO,WAAW,KAAK,CAAC;AAE9B,YAAA,SAAS,UAAU,UAAU,CAAC;AAWxC,MAAI,QAAQ,IAAI,aAAa,iBAAiB,CAAC,QAAQ,IAAI,kBAAkB;AAC3E,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EAAA;AAGE,MAAA,QAAQ,IAAI,aAAa,eAAe;AAUpC,UAAA,cAAc,UAAU,CAAC,KAAK,UAAU,QAAQ,IAAI,gBAAgB,CAAC;AAErE,UAAA,SAAS,GAAG,WAAW,4BAA4B,WAAW,4BAA4B,OAAO,EAAE,WAAW,WAAW;AAE/H,cAAU,OAAO,KAAK;AAAA,MACpB,KAAK;AAAA,MACL,OAAO;AAAA,QACL,MAAM;AAAA,QACN,0BAA0B;AAAA,QAC1B,OAAO;AAAA,MACT;AAAA,MACA,UAAU;AAAA,IAAA,CACX;AAAA,EAAA;AAGH,QAAM,WAAW;AAAA,IACf,GAAG;AAAA,IACH,QAAQ,OAAO;AAAA,MACb,OAAO,QAAQ,cAAc,MAAM,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM;AAC7C,cAAA,EAAE,UAAU,OAAA,IAAW;AACtB,eAAA;AAAA,UACL;AAAA,UACA;AAAA,YACE;AAAA,YACA;AAAA,UAAA;AAAA,QAEJ;AAAA,MACD,CAAA;AAAA,IAAA;AAAA,EAEL;AAGO,SAAA;AACT;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/start-server-core",
3
- "version": "1.121.0-alpha.15",
3
+ "version": "1.121.0-alpha.17",
4
4
  "description": "Modern and scalable routing for React applications",
5
5
  "author": "Tanner Linsley",
6
6
  "license": "MIT",
@@ -54,8 +54,8 @@
54
54
  "tiny-warning": "^1.0.3",
55
55
  "unctx": "^2.4.1",
56
56
  "@tanstack/history": "^1.121.0-alpha.1",
57
- "@tanstack/router-core": "^1.121.0-alpha.14",
58
- "@tanstack/start-client-core": "^1.121.0-alpha.14"
57
+ "@tanstack/start-client-core": "^1.121.0-alpha.14",
58
+ "@tanstack/router-core": "^1.121.0-alpha.14"
59
59
  },
60
60
  "devDependencies": {
61
61
  "@types/jsesc": "^3.0.3",
@@ -102,11 +102,14 @@ export function createStartHandler<TRouter extends AnyRouter>({
102
102
  initialEntries: [href],
103
103
  })
104
104
 
105
+ const APP_BASE = process.env.TSS_APP_BASE || '/'
106
+
105
107
  // Create the client-side router
106
108
  const router = createRouter()
107
109
 
108
110
  // Attach the server-side SSR utils to the client-side router
109
- attachRouterServerSsrUtils(router, await getStartManifest())
111
+ const startRoutesManifest = await getStartManifest({ basePath: APP_BASE })
112
+ attachRouterServerSsrUtils(router, startRoutesManifest)
110
113
 
111
114
  // Update the client-side router with the history and context
112
115
  router.update({
@@ -124,7 +127,7 @@ export function createStartHandler<TRouter extends AnyRouter>({
124
127
  // First, let's attempt to handle server functions
125
128
  // Add trailing slash to sanitise user defined TSS_SERVER_FN_BASE
126
129
  const serverFnBase = joinPaths([
127
- '/',
130
+ APP_BASE,
128
131
  trimPath(process.env.TSS_SERVER_FN_BASE),
129
132
  '/',
130
133
  ])
@@ -151,6 +154,7 @@ export function createStartHandler<TRouter extends AnyRouter>({
151
154
  const [_matchedRoutes, response] = await handleServerRoutes({
152
155
  routeTree: serverRouteTreeModule.routeTree,
153
156
  request,
157
+ basePath: APP_BASE,
154
158
  })
155
159
 
156
160
  if (response) return response
@@ -271,9 +275,11 @@ export function createStartHandler<TRouter extends AnyRouter>({
271
275
  async function handleServerRoutes({
272
276
  routeTree,
273
277
  request,
278
+ basePath,
274
279
  }: {
275
280
  routeTree: AnyServerRouteWithTypes
276
281
  request: Request
282
+ basePath: string
277
283
  }) {
278
284
  const { flatRoutes, routesById, routesByPath } = processRouteTree({
279
285
  routeTree,
@@ -294,7 +300,7 @@ async function handleServerRoutes({
294
300
  const { matchedRoutes, foundRoute, routeParams } =
295
301
  getMatchedRoutes<AnyServerRouteWithTypes>({
296
302
  pathname: history.location.pathname,
297
- basepath: '/',
303
+ basepath: basePath,
298
304
  caseSensitive: true,
299
305
  routesByPath,
300
306
  routesById,
@@ -1,4 +1,4 @@
1
- import { rootRouteId } from '@tanstack/router-core'
1
+ import { joinPaths, rootRouteId } from '@tanstack/router-core'
2
2
 
3
3
  declare global {
4
4
  // eslint-disable-next-line no-var
@@ -11,7 +11,7 @@ declare global {
11
11
  * special assets that are needed for the client. It does not include relationships
12
12
  * between routes or any other data that is not needed for the client.
13
13
  */
14
- export async function getStartManifest() {
14
+ export async function getStartManifest(opts: { basePath: string }) {
15
15
  const { tsrStartManifest } = await import('tanstack-start-router-manifest:v')
16
16
  const startManifest = tsrStartManifest()
17
17
 
@@ -45,7 +45,9 @@ export async function getStartManifest() {
45
45
  // )
46
46
  // }
47
47
 
48
- const script = `${globalThis.TSS_INJECTED_HEAD_SCRIPTS ? globalThis.TSS_INJECTED_HEAD_SCRIPTS + '; ' : ''}import(${JSON.stringify(process.env.TSS_CLIENT_ENTRY)})`
48
+ const clientEntry = joinPaths([opts.basePath, process.env.TSS_CLIENT_ENTRY])
49
+
50
+ const script = `${globalThis.TSS_INJECTED_HEAD_SCRIPTS ? globalThis.TSS_INJECTED_HEAD_SCRIPTS + '; ' : ''}import('${clientEntry}')`
49
51
 
50
52
  rootRoute.assets.push({
51
53
  tag: 'script',