@tanstack/start-server-core 1.120.4-alpha.7 → 1.120.4-alpha.8
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.
|
@@ -67,7 +67,11 @@ function createStartHandler({
|
|
|
67
67
|
"tanstack/start-server-core: TSS_SERVER_FN_BASE must be defined in your environment for createStartHandler()"
|
|
68
68
|
);
|
|
69
69
|
}
|
|
70
|
-
const serverFnBase =
|
|
70
|
+
const serverFnBase = routerCore.joinPaths([
|
|
71
|
+
"/",
|
|
72
|
+
routerCore.trimPath(process.env.TSS_SERVER_FN_BASE),
|
|
73
|
+
"/"
|
|
74
|
+
]);
|
|
71
75
|
if (href.startsWith(serverFnBase)) {
|
|
72
76
|
return await serverFunctionsHandler.handleServerAction({ request });
|
|
73
77
|
}
|
|
@@ -80,7 +84,7 @@ function createStartHandler({
|
|
|
80
84
|
}
|
|
81
85
|
})();
|
|
82
86
|
if (serverRouteTreeModule) {
|
|
83
|
-
const [
|
|
87
|
+
const [_matchedRoutes, response3] = await handleServerRoutes({
|
|
84
88
|
routeTree: serverRouteTreeModule.routeTree,
|
|
85
89
|
request
|
|
86
90
|
});
|
|
@@ -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 processRouteTree,\n rootRouteId,\n tsrRedirectHeaderKey,\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 return requestHandler(async ({ request }) => {\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 = process.env.TSS_SERVER_FN_BASE.startsWith('/')\n ? process.env.TSS_SERVER_FN_BASE\n : '/' + process.env.TSS_SERVER_FN_BASE\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 // @ts-expect-error\n return (await import('tanstack:server-routes')) as {\n routeTree: AnyServerRoute\n }\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 (\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: redirect.headers,\n },\n )\n }\n\n return redirect\n }\n\n // Add Access-Control-Expose-Headers\n // With HTTPs the response/header objects are immutable, therefore we must clone them\n const body =\n response.status === 204 ? null : await response.clone().blob()\n const headers = new Headers(response.headers)\n headers.append('Access-Control-Expose-Headers', tsrRedirectHeaderKey)\n\n return new Response(body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n })\n })\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, ...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 err instanceof Response || isRedirect(err)\n}\n"],"names":["mergeHeaders","getResponseHeaders","requestHandler","history","createMemoryHistory","attachRouterServerSsrUtils","getStartManifest","handleServerAction","response","json","dehydrateRouter","isRedirect","tsrRedirectHeaderKey","processRouteTree","getMatchedRoutes","rootRouteId","method","flattenMiddlewares","ctx"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BO,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,WAA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M,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;AAC7B,SAAA,eAAe,YAAYP,WAAA,WAAW,GAAG;AAClD;;;"}
|
|
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 joinPaths,\n processRouteTree,\n rootRouteId,\n trimPath,\n tsrRedirectHeaderKey,\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 return requestHandler(async ({ request }) => {\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 // @ts-expect-error\n return (await import('tanstack:server-routes')) as {\n routeTree: AnyServerRoute\n }\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 (\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: redirect.headers,\n },\n )\n }\n\n return redirect\n }\n\n // Add Access-Control-Expose-Headers\n // With HTTPs the response/header objects are immutable, therefore we must clone them\n const body =\n response.status === 204 ? null : await response.clone().blob()\n const headers = new Headers(response.headers)\n headers.append('Access-Control-Expose-Headers', tsrRedirectHeaderKey)\n\n return new Response(body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n })\n })\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, ...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 err instanceof Response || isRedirect(err)\n}\n"],"names":["mergeHeaders","getResponseHeaders","requestHandler","history","createMemoryHistory","attachRouterServerSsrUtils","getStartManifest","joinPaths","trimPath","handleServerAction","response","json","dehydrateRouter","isRedirect","tsrRedirectHeaderKey","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,WAAOE,GAAe,eAAA,OAAO,EAAE,cAAc;AAC3C,YAAM,MAAM,IAAI,IAAI,QAAQ,GAAG;AAC/B,YAAM,OAAO,IAAI,KAAK,QAAQ,IAAI,QAAQ,EAAE;AAG5C,YAAMC,YAAUC,QAAAA,oBAAoB;AAAA,QAClC,gBAAgB,CAAC,IAAI;AAAA,MAAA,CACtB;AAGD,YAAM,SAAS,aAAa;AAGDC,2CAAA,QAAQC,eAAAA,kBAAkB;AAGrD,aAAO,OAAO;AAAA,QACZH,SAAAA;AAAAA,MAAA,CACD;AAEK,YAAA,WAAW,OAAO,YAAY;AAC9B,YAAA;AACE,cAAA,CAAC,QAAQ,IAAI,oBAAoB;AACnC,kBAAM,IAAI;AAAA,cACR;AAAA,YACF;AAAA,UAAA;A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W,IAAI;AAAA,MAAA;AAAA,IACjB;AAAA,EACF;AAMK,SAAA,CAAC,eAAe,QAAQ;AACjC;AAEA,SAAS,oBACP,SACA;AACA,SAAO,OAAO,EAAE,MAAM,GAAG,YAAkB;AAAA,IACzC,UAAU,MAAM,QAAQ,IAAI;AAAA,EAAA;AAEhC;AAEA,SAAS,kBAAkB,aAAmB,KAAW;AACvD,MAAI,QAAQ;AAEN,QAAA,OAAO,OAAOiB,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;AAC7B,SAAA,eAAe,YAAYP,WAAA,WAAW,GAAG;AAClD;;;"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createMemoryHistory } from "@tanstack/history";
|
|
2
2
|
import { mergeHeaders, json, flattenMiddlewares } from "@tanstack/start-client-core";
|
|
3
|
-
import { isRedirect, tsrRedirectHeaderKey, processRouteTree, getMatchedRoutes, rootRouteId } from "@tanstack/router-core";
|
|
3
|
+
import { joinPaths, trimPath, isRedirect, tsrRedirectHeaderKey, processRouteTree, getMatchedRoutes, rootRouteId } from "@tanstack/router-core";
|
|
4
4
|
import { getResponseHeaders, requestHandler } from "./h3.js";
|
|
5
5
|
import { attachRouterServerSsrUtils, dehydrateRouter } from "./ssr-server.js";
|
|
6
6
|
import { getStartManifest } from "./router-manifest.js";
|
|
@@ -43,7 +43,11 @@ function createStartHandler({
|
|
|
43
43
|
"tanstack/start-server-core: TSS_SERVER_FN_BASE must be defined in your environment for createStartHandler()"
|
|
44
44
|
);
|
|
45
45
|
}
|
|
46
|
-
const serverFnBase =
|
|
46
|
+
const serverFnBase = joinPaths([
|
|
47
|
+
"/",
|
|
48
|
+
trimPath(process.env.TSS_SERVER_FN_BASE),
|
|
49
|
+
"/"
|
|
50
|
+
]);
|
|
47
51
|
if (href.startsWith(serverFnBase)) {
|
|
48
52
|
return await handleServerAction({ request });
|
|
49
53
|
}
|
|
@@ -56,7 +60,7 @@ function createStartHandler({
|
|
|
56
60
|
}
|
|
57
61
|
})();
|
|
58
62
|
if (serverRouteTreeModule) {
|
|
59
|
-
const [
|
|
63
|
+
const [_matchedRoutes, response3] = await handleServerRoutes({
|
|
60
64
|
routeTree: serverRouteTreeModule.routeTree,
|
|
61
65
|
request
|
|
62
66
|
});
|
|
@@ -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 processRouteTree,\n rootRouteId,\n tsrRedirectHeaderKey,\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 return requestHandler(async ({ request }) => {\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 = process.env.TSS_SERVER_FN_BASE.startsWith('/')\n ? process.env.TSS_SERVER_FN_BASE\n : '/' + process.env.TSS_SERVER_FN_BASE\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 // @ts-expect-error\n return (await import('tanstack:server-routes')) as {\n routeTree: AnyServerRoute\n }\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 (\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: redirect.headers,\n },\n )\n }\n\n return redirect\n }\n\n // Add Access-Control-Expose-Headers\n // With HTTPs the response/header objects are immutable, therefore we must clone them\n const body =\n response.status === 204 ? null : await response.clone().blob()\n const headers = new Headers(response.headers)\n headers.append('Access-Control-Expose-Headers', tsrRedirectHeaderKey)\n\n return new Response(body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n })\n })\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, ...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 err instanceof Response || isRedirect(err)\n}\n"],"names":["response","method","ctx"],"mappings":";;;;;;;AA4BO,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,WAAO,eAAe,OAAO,EAAE,cAAc;AAC3C,YAAM,MAAM,IAAI,IAAI,QAAQ,GAAG;AAC/B,YAAM,OAAO,IA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B,KAAW;AAC7B,SAAA,eAAe,YAAY,WAAW,GAAG;AAClD;"}
|
|
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 joinPaths,\n processRouteTree,\n rootRouteId,\n trimPath,\n tsrRedirectHeaderKey,\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 return requestHandler(async ({ request }) => {\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 // @ts-expect-error\n return (await import('tanstack:server-routes')) as {\n routeTree: AnyServerRoute\n }\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 (\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: redirect.headers,\n },\n )\n }\n\n return redirect\n }\n\n // Add Access-Control-Expose-Headers\n // With HTTPs the response/header objects are immutable, therefore we must clone them\n const body =\n response.status === 204 ? null : await response.clone().blob()\n const headers = new Headers(response.headers)\n headers.append('Access-Control-Expose-Headers', tsrRedirectHeaderKey)\n\n return new Response(body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n })\n })\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, ...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 err instanceof Response || isRedirect(err)\n}\n"],"names":["response","method","ctx"],"mappings":";;;;;;;AA8BO,SAAS,wBAAwB,MAA6B;AACnE,MAAI,UAAU;AAAA,IACZ,mBAAmB;AAAA,IACnB;AAAA,MACE,gBAAgB;AAAA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AAA;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;AAC7B,SAAA,eAAe,YAAY,WAAW,GAAG;AAClD;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tanstack/start-server-core",
|
|
3
|
-
"version": "1.120.4-alpha.
|
|
3
|
+
"version": "1.120.4-alpha.8",
|
|
4
4
|
"description": "Modern and scalable routing for React applications",
|
|
5
5
|
"author": "Tanner Linsley",
|
|
6
6
|
"license": "MIT",
|
|
@@ -54,9 +54,9 @@
|
|
|
54
54
|
"tiny-warning": "^1.0.3",
|
|
55
55
|
"unctx": "^2.4.1",
|
|
56
56
|
"undici": "^7.8.0",
|
|
57
|
-
"@tanstack/
|
|
57
|
+
"@tanstack/history": "^1.120.4-alpha.1",
|
|
58
58
|
"@tanstack/start-client-core": "^1.120.4-alpha.1",
|
|
59
|
-
"@tanstack/
|
|
59
|
+
"@tanstack/router-core": "^1.120.4-alpha.1"
|
|
60
60
|
},
|
|
61
61
|
"devDependencies": {
|
|
62
62
|
"@types/jsesc": "^3.0.3",
|
|
@@ -7,8 +7,10 @@ import {
|
|
|
7
7
|
import {
|
|
8
8
|
getMatchedRoutes,
|
|
9
9
|
isRedirect,
|
|
10
|
+
joinPaths,
|
|
10
11
|
processRouteTree,
|
|
11
12
|
rootRouteId,
|
|
13
|
+
trimPath,
|
|
12
14
|
tsrRedirectHeaderKey,
|
|
13
15
|
} from '@tanstack/router-core'
|
|
14
16
|
import { getResponseHeaders, requestHandler } from './h3'
|
|
@@ -81,9 +83,11 @@ export function createStartHandler<TRouter extends AnyRouter>({
|
|
|
81
83
|
|
|
82
84
|
// First, let's attempt to handle server functions
|
|
83
85
|
// Add trailing slash to sanitise user defined TSS_SERVER_FN_BASE
|
|
84
|
-
const serverFnBase =
|
|
85
|
-
|
|
86
|
-
|
|
86
|
+
const serverFnBase = joinPaths([
|
|
87
|
+
'/',
|
|
88
|
+
trimPath(process.env.TSS_SERVER_FN_BASE),
|
|
89
|
+
'/',
|
|
90
|
+
])
|
|
87
91
|
if (href.startsWith(serverFnBase)) {
|
|
88
92
|
return await handleServerAction({ request })
|
|
89
93
|
}
|
|
@@ -104,7 +108,7 @@ export function createStartHandler<TRouter extends AnyRouter>({
|
|
|
104
108
|
// If we have a server route tree, then we try matching to see if we have a
|
|
105
109
|
// server route that matches the request.
|
|
106
110
|
if (serverRouteTreeModule) {
|
|
107
|
-
const [
|
|
111
|
+
const [_matchedRoutes, response] = await handleServerRoutes({
|
|
108
112
|
routeTree: serverRouteTreeModule.routeTree,
|
|
109
113
|
request,
|
|
110
114
|
})
|