@tanstack/start-server-core 1.132.0-alpha.14 → 1.132.0-alpha.16
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.
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createMemoryHistory } from "@tanstack/history";
|
|
2
2
|
import { json, mergeHeaders, flattenMiddlewares } from "@tanstack/start-client-core";
|
|
3
|
-
import { joinPaths, trimPath, processRouteTree, isRedirect, isResolvedRedirect, getMatchedRoutes } from "@tanstack/router-core";
|
|
3
|
+
import { joinPaths, trimPath, processRouteTree, isRedirect, isResolvedRedirect, executeRewriteInput, rewriteBasepath, getMatchedRoutes } from "@tanstack/router-core";
|
|
4
4
|
import { attachRouterServerSsrUtils } from "@tanstack/router-core/ssr/server";
|
|
5
5
|
import { runWithStartContext } from "@tanstack/start-storage-context";
|
|
6
6
|
import { requestHandler, getResponseHeaders } from "./request-response.js";
|
|
@@ -31,14 +31,22 @@ function createStartHandler({
|
|
|
31
31
|
return (cb) => {
|
|
32
32
|
const originalFetch = globalThis.fetch;
|
|
33
33
|
const startRequestResolver = async (request) => {
|
|
34
|
+
function getOrigin() {
|
|
35
|
+
const originHeader = request.headers.get("Origin");
|
|
36
|
+
if (originHeader) {
|
|
37
|
+
return originHeader;
|
|
38
|
+
}
|
|
39
|
+
try {
|
|
40
|
+
return new URL(request.url).origin;
|
|
41
|
+
} catch (_) {
|
|
42
|
+
}
|
|
43
|
+
return "http://localhost";
|
|
44
|
+
}
|
|
34
45
|
globalThis.fetch = async function(input, init) {
|
|
35
46
|
function resolve(url2, requestOptions) {
|
|
36
47
|
const fetchRequest = new Request(url2, requestOptions);
|
|
37
48
|
return startRequestResolver(fetchRequest);
|
|
38
49
|
}
|
|
39
|
-
function getOrigin() {
|
|
40
|
-
return request.headers.get("Origin") || request.headers.get("Referer") || "http://localhost";
|
|
41
|
-
}
|
|
42
50
|
if (typeof input === "string" && input.startsWith("/")) {
|
|
43
51
|
const url2 = new URL(input, getOrigin());
|
|
44
52
|
return resolve(url2, init);
|
|
@@ -52,20 +60,22 @@ function createStartHandler({
|
|
|
52
60
|
const href = url.href.replace(url.origin, "");
|
|
53
61
|
const APP_BASE = process.env.TSS_APP_BASE || "/";
|
|
54
62
|
const router = await createRouter();
|
|
55
|
-
const history = createMemoryHistory({
|
|
56
|
-
initialEntries: [href]
|
|
57
|
-
});
|
|
58
63
|
const isPrerendering = process.env.TSS_PRERENDERING === "true";
|
|
59
64
|
let isShell = process.env.TSS_SHELL === "true";
|
|
60
65
|
if (isPrerendering && !isShell) {
|
|
61
66
|
isShell = request.headers.get(HEADERS.TSS_SHELL) === "true";
|
|
62
67
|
}
|
|
63
68
|
const serializationAdapters = (router.options.serializationAdapters ?? []).concat(ServerFunctionSerializationAdapter);
|
|
69
|
+
const history = createMemoryHistory({
|
|
70
|
+
initialEntries: [href]
|
|
71
|
+
});
|
|
72
|
+
const origin = router.options.origin ?? getOrigin();
|
|
64
73
|
router.update({
|
|
65
74
|
history,
|
|
66
75
|
isShell,
|
|
67
76
|
isPrerendering,
|
|
68
|
-
serializationAdapters
|
|
77
|
+
serializationAdapters,
|
|
78
|
+
origin
|
|
69
79
|
});
|
|
70
80
|
const response = await runWithStartContext({ router }, async () => {
|
|
71
81
|
try {
|
|
@@ -207,11 +217,13 @@ function createStartHandler({
|
|
|
207
217
|
};
|
|
208
218
|
}
|
|
209
219
|
async function handleServerRoutes(opts) {
|
|
210
|
-
|
|
220
|
+
let url = new URL(opts.request.url);
|
|
221
|
+
if (opts.basePath) {
|
|
222
|
+
url = executeRewriteInput(rewriteBasepath({ basepath: opts.basePath }), url);
|
|
223
|
+
}
|
|
211
224
|
const pathname = url.pathname;
|
|
212
225
|
const serverTreeResult = getMatchedRoutes({
|
|
213
226
|
pathname,
|
|
214
|
-
basepath: opts.basePath,
|
|
215
227
|
caseSensitive: true,
|
|
216
228
|
routesByPath: opts.processedServerRouteTree.routesByPath,
|
|
217
229
|
routesById: opts.processedServerRouteTree.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 trimPath,\n} from '@tanstack/router-core'\nimport { attachRouterServerSsrUtils } from '@tanstack/router-core/ssr/server'\nimport { runWithStartContext } from '@tanstack/start-storage-context'\nimport { getResponseHeaders, requestHandler } from './request-response'\nimport { getStartManifest } from './router-manifest'\nimport { handleServerAction } from './server-functions-handler'\nimport { VIRTUAL_MODULES } from './virtual-modules'\nimport { loadVirtualModule } from './loadVirtualModule'\n\nimport { HEADERS } from './constants'\nimport { ServerFunctionSerializationAdapter } from './serializer/ServerFunctionSerializationAdapter'\nimport type {\n AnyServerRouteWithTypes,\n ServerRouteMethodHandlerFn,\n} from './serverRoute'\nimport type { RequestHandler } from './request-response'\nimport type {\n AnyRoute,\n AnyRouter,\n Awaitable,\n Manifest,\n ProcessRouteTreeResult,\n} from '@tanstack/router-core'\nimport type { HandlerCallback } from '@tanstack/router-core/ssr/server'\n\ntype TODO = any\n\nexport type CustomizeStartHandler<TRouter extends AnyRouter> = (\n cb: HandlerCallback<TRouter>,\n) => RequestHandler\n\nfunction getStartResponseHeaders(opts: { router: AnyRouter }) {\n const headers = mergeHeaders(\n getResponseHeaders() as Headers,\n {\n 'Content-Type': 'text/html; charset=utf-8',\n },\n ...opts.router.state.matches.map((match) => {\n return match.headers\n }),\n )\n return headers\n}\n\nexport function createStartHandler<TRouter extends AnyRouter>({\n createRouter,\n}: {\n createRouter: () => Awaitable<TRouter>\n}): CustomizeStartHandler<TRouter> {\n let routeTreeModule: {\n serverRouteTree: AnyServerRouteWithTypes | undefined\n routeTree: AnyRoute | undefined\n } | null = null\n let startRoutesManifest: Manifest | null = null\n let processedServerRouteTree:\n | ProcessRouteTreeResult<AnyServerRouteWithTypes>\n | undefined = undefined\n\n return (cb) => {\n const originalFetch = globalThis.fetch\n\n const startRequestResolver: RequestHandler = async (request) => {\n // Patching fetch function to use our request resolver\n // if the input starts with `/` which is a common pattern for\n // client-side routing.\n // When we encounter similar requests, we can assume that the\n // user wants to use the same origin as the current request.\n globalThis.fetch = async function (input, init) {\n function resolve(url: URL, requestOptions: RequestInit | undefined) {\n const fetchRequest = new Request(url, requestOptions)\n return startRequestResolver(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 const APP_BASE = process.env.TSS_APP_BASE || '/'\n\n // TODO how does this work with base path? does the router need to be configured the same as APP_BASE?\n const router = await createRouter()\n\n // Create a history for the client-side router\n const history = createMemoryHistory({\n initialEntries: [href],\n })\n\n // Update the client-side router with the history\n const isPrerendering = process.env.TSS_PRERENDERING === 'true'\n // env var is set during dev is SPA mode is enabled\n let isShell = process.env.TSS_SHELL === 'true'\n if (isPrerendering && !isShell) {\n // only read the shell header if we are prerendering\n // to avoid runtime behavior changes by injecting this header\n // the header is set by the prerender plugin\n isShell = request.headers.get(HEADERS.TSS_SHELL) === 'true'\n }\n // insert start specific default serialization adapters\n const serializationAdapters = (\n router.options.serializationAdapters ?? []\n ).concat(ServerFunctionSerializationAdapter)\n\n router.update({\n history,\n isShell,\n isPrerendering,\n serializationAdapters,\n })\n\n const response = await runWithStartContext({ router }, async () => {\n try {\n if (!process.env.TSS_SERVER_FN_BASE) {\n throw new Error(\n 'tanstack/start-server-core: TSS_SERVER_FN_BASE must be defined in your environment for createStartHandler()',\n )\n }\n\n // First, let's attempt to handle server functions\n // Add trailing slash to sanitise user defined TSS_SERVER_FN_BASE\n const serverFnBase = joinPaths([\n APP_BASE,\n trimPath(process.env.TSS_SERVER_FN_BASE),\n '/',\n ])\n if (href.startsWith(serverFnBase)) {\n return await handleServerAction({ request })\n }\n\n if (routeTreeModule === null) {\n try {\n routeTreeModule = await loadVirtualModule(\n VIRTUAL_MODULES.routeTree,\n )\n if (routeTreeModule.serverRouteTree) {\n processedServerRouteTree =\n processRouteTree<AnyServerRouteWithTypes>({\n routeTree: routeTreeModule.serverRouteTree,\n initRoute: (route, i) => {\n route.init({\n originalIndex: i,\n })\n },\n })\n }\n } catch (e) {\n console.log(e)\n }\n }\n\n const executeRouter = async () => {\n const requestAcceptHeader = request.headers.get('Accept') || '*/*'\n const splitRequestAcceptHeader = requestAcceptHeader.split(',')\n\n const supportedMimeTypes = ['*/*', 'text/html']\n const isRouterAcceptSupported = supportedMimeTypes.some(\n (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 the startRoutesManifest is not loaded yet, load it once\n if (startRoutesManifest === null) {\n startRoutesManifest = await getStartManifest({\n basePath: APP_BASE,\n })\n }\n\n // Attach the server-side SSR utils to the client-side router\n attachRouterServerSsrUtils(router, startRoutesManifest)\n\n await router.load()\n\n // If there was a redirect, skip rendering the page at all\n if (router.state.redirect) {\n return router.state.redirect\n }\n\n await router.serverSsr!.dehydrate()\n\n const responseHeaders = getStartResponseHeaders({ router })\n const response = await cb({\n request,\n router,\n responseHeaders,\n })\n\n return response\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 (processedServerRouteTree) {\n const [_matchedRoutes, response] = await handleServerRoutes({\n processedServerRouteTree,\n router,\n request,\n basePath: APP_BASE,\n executeRouter,\n })\n\n if (response) return response\n }\n\n // Server Routes did not produce a response, so fallback to normal SSR matching using the router\n const routerResponse = await executeRouter()\n return routerResponse\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. The redirect() method's \"to\" property accepts an internal path only. Use the \"href\" property to provide an external URL. 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(opts: {\n router: AnyRouter\n processedServerRouteTree: ProcessRouteTreeResult<AnyServerRouteWithTypes>\n request: Request\n basePath: string\n executeRouter: () => Promise<Response>\n}) {\n const url = new URL(opts.request.url)\n const pathname = url.pathname\n\n const serverTreeResult = getMatchedRoutes<AnyServerRouteWithTypes>({\n pathname,\n basepath: opts.basePath,\n caseSensitive: true,\n routesByPath: opts.processedServerRouteTree.routesByPath,\n routesById: opts.processedServerRouteTree.routesById,\n flatRoutes: opts.processedServerRouteTree.flatRoutes,\n })\n\n const routeTreeResult = opts.router.getMatchedRoutes(pathname, undefined)\n\n let response: Response | undefined\n let matchedRoutes: Array<AnyServerRouteWithTypes> = []\n matchedRoutes = serverTreeResult.matchedRoutes\n // check if the app route tree found a match that is deeper than the server route tree\n if (routeTreeResult.foundRoute) {\n if (\n serverTreeResult.matchedRoutes.length <\n routeTreeResult.matchedRoutes.length\n ) {\n const closestCommon = [...routeTreeResult.matchedRoutes]\n .reverse()\n .find((r) => {\n return opts.processedServerRouteTree.routesById[r.id] !== undefined\n })\n if (closestCommon) {\n // walk up the tree and collect all parents\n let routeId = closestCommon.id\n matchedRoutes = []\n do {\n const route = opts.processedServerRouteTree.routesById[routeId]\n if (!route) {\n break\n }\n matchedRoutes.push(route)\n routeId = route.parentRoute?.id\n } while (routeId)\n\n matchedRoutes.reverse()\n }\n }\n }\n\n if (matchedRoutes.length) {\n // We've found a server route that (partially) matches the request, so we can call it.\n // TODO: Error handling? What happens when its `throw redirect()` vs `throw new Error()`?\n\n const middlewares = flattenMiddlewares(\n matchedRoutes.flatMap((r) => r.options.middleware).filter(Boolean),\n ).map((d) => d.options.server)\n\n if (serverTreeResult.foundRoute?.options.methods) {\n const method = Object.keys(\n serverTreeResult.foundRoute.options.methods,\n ).find(\n (method) => method.toLowerCase() === opts.request.method.toLowerCase(),\n )\n\n if (method) {\n const handler = serverTreeResult.foundRoute.options.methods[method]\n if (handler) {\n if (typeof handler === 'function') {\n middlewares.push(handlerToMiddleware(handler) as TODO)\n } else {\n if (\n handler._options.middlewares &&\n handler._options.middlewares.length\n ) {\n middlewares.push(\n ...flattenMiddlewares(handler._options.middlewares as any).map(\n (d) => d.options.server,\n ),\n )\n }\n if (handler._options.handler) {\n middlewares.push(handlerToMiddleware(handler._options.handler))\n }\n }\n }\n }\n }\n\n // eventually, execute the router\n middlewares.push(handlerToMiddleware(opts.executeRouter))\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: opts.request,\n context: {},\n params: serverTreeResult.routeParams,\n pathname,\n })\n\n response = ctx.response\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: ServerRouteMethodHandlerFn<\n AnyServerRouteWithTypes,\n any,\n any,\n any,\n any\n >,\n) {\n return async ({ next: _next, ...rest }: TODO) => {\n const response = await handler(rest)\n if (response) {\n return { response }\n }\n return _next(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({\n ...ctx,\n ...nextCtx,\n context: {\n ...ctx.context,\n ...(nextCtx?.context || {}),\n },\n })\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":";;;;;;;;;;;;AA4CA,SAAS,wBAAwB,MAA6B;AAC5D,QAAM,UAAU;AAAA,IACd,mBAAA;AAAA,IACA;AAAA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AA,QAC3B,CACD;AAGD,eAAO,OAAO,OAAOA,MAAK,gBAAgB,UAAU,CAAC;AAAA,MACvD;AAAA;AAAA,IAAA,CAED,EAAE,MAAM,CAAC,QAAc;AACtB,UAAI,kBAAkB,GAAG,GAAG;AAC1B,eAAO;AAAA,UACL,UAAU;AAAA,QAAA;AAAA,MAEd;AAEA,YAAM;AAAA,IACR,CAAC;AAID,WAAO,OAAO,OAAOA,MAAK,gBAAgB,MAAM,CAAC;AAAA,EACnD;AAEA,SAAO,gBAAgB,KAAK,GAAG,CAAC;AAClC;AAEA,SAAS,gBAAgB,QAAc;AACrC,MAAI,kBAAkB,MAAM,GAAG;AAC7B,WAAO;AAAA,MACL,UAAU;AAAA,IAAA;AAAA,EAEd;AAEA,SAAO;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 executeRewriteInput,\n getMatchedRoutes,\n isRedirect,\n isResolvedRedirect,\n joinPaths,\n processRouteTree,\n rewriteBasepath,\n trimPath,\n} from '@tanstack/router-core'\nimport { attachRouterServerSsrUtils } from '@tanstack/router-core/ssr/server'\nimport { runWithStartContext } from '@tanstack/start-storage-context'\nimport { getResponseHeaders, requestHandler } from './request-response'\nimport { getStartManifest } from './router-manifest'\nimport { handleServerAction } from './server-functions-handler'\nimport { VIRTUAL_MODULES } from './virtual-modules'\nimport { loadVirtualModule } from './loadVirtualModule'\n\nimport { HEADERS } from './constants'\nimport { ServerFunctionSerializationAdapter } from './serializer/ServerFunctionSerializationAdapter'\nimport type {\n AnyServerRouteWithTypes,\n ServerRouteMethodHandlerFn,\n} from './serverRoute'\nimport type { RequestHandler } from './request-response'\nimport type {\n AnyRoute,\n AnyRouter,\n Awaitable,\n Manifest,\n ProcessRouteTreeResult,\n} from '@tanstack/router-core'\nimport type { HandlerCallback } from '@tanstack/router-core/ssr/server'\n\ntype TODO = any\n\nexport type CustomizeStartHandler<TRouter extends AnyRouter> = (\n cb: HandlerCallback<TRouter>,\n) => RequestHandler\n\nfunction getStartResponseHeaders(opts: { router: AnyRouter }) {\n const headers = mergeHeaders(\n getResponseHeaders() as Headers,\n {\n 'Content-Type': 'text/html; charset=utf-8',\n },\n ...opts.router.state.matches.map((match) => {\n return match.headers\n }),\n )\n return headers\n}\n\nexport function createStartHandler<TRouter extends AnyRouter>({\n createRouter,\n}: {\n createRouter: () => Awaitable<TRouter>\n}): CustomizeStartHandler<TRouter> {\n let routeTreeModule: {\n serverRouteTree: AnyServerRouteWithTypes | undefined\n routeTree: AnyRoute | undefined\n } | null = null\n let startRoutesManifest: Manifest | null = null\n let processedServerRouteTree:\n | ProcessRouteTreeResult<AnyServerRouteWithTypes>\n | undefined = undefined\n\n return (cb) => {\n const originalFetch = globalThis.fetch\n\n const startRequestResolver: RequestHandler = async (request) => {\n function getOrigin() {\n const originHeader = request.headers.get('Origin')\n if (originHeader) {\n return originHeader\n }\n try {\n return new URL(request.url).origin\n } catch (_) {}\n return 'http://localhost'\n }\n\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(fetchRequest)\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 const APP_BASE = process.env.TSS_APP_BASE || '/'\n\n // TODO how does this work with base path? does the router need to be configured the same as APP_BASE?\n const router = await createRouter()\n\n // Update the client-side router with the history\n const isPrerendering = process.env.TSS_PRERENDERING === 'true'\n // env var is set during dev is SPA mode is enabled\n let isShell = process.env.TSS_SHELL === 'true'\n if (isPrerendering && !isShell) {\n // only read the shell header if we are prerendering\n // to avoid runtime behavior changes by injecting this header\n // the header is set by the prerender plugin\n isShell = request.headers.get(HEADERS.TSS_SHELL) === 'true'\n }\n // insert start specific default serialization adapters\n const serializationAdapters = (\n router.options.serializationAdapters ?? []\n ).concat(ServerFunctionSerializationAdapter)\n\n // Create a history for the client-side router\n const history = createMemoryHistory({\n initialEntries: [href],\n })\n\n const origin = router.options.origin ?? getOrigin()\n router.update({\n history,\n isShell,\n isPrerendering,\n serializationAdapters,\n origin,\n })\n\n const response = await runWithStartContext({ router }, async () => {\n try {\n if (!process.env.TSS_SERVER_FN_BASE) {\n throw new Error(\n 'tanstack/start-server-core: TSS_SERVER_FN_BASE must be defined in your environment for createStartHandler()',\n )\n }\n\n // First, let's attempt to handle server functions\n // Add trailing slash to sanitise user defined TSS_SERVER_FN_BASE\n const serverFnBase = joinPaths([\n APP_BASE,\n trimPath(process.env.TSS_SERVER_FN_BASE),\n '/',\n ])\n if (href.startsWith(serverFnBase)) {\n return await handleServerAction({ request })\n }\n\n if (routeTreeModule === null) {\n try {\n routeTreeModule = await loadVirtualModule(\n VIRTUAL_MODULES.routeTree,\n )\n if (routeTreeModule.serverRouteTree) {\n processedServerRouteTree =\n processRouteTree<AnyServerRouteWithTypes>({\n routeTree: routeTreeModule.serverRouteTree,\n initRoute: (route, i) => {\n route.init({\n originalIndex: i,\n })\n },\n })\n }\n } catch (e) {\n console.log(e)\n }\n }\n\n const executeRouter = async () => {\n const requestAcceptHeader = request.headers.get('Accept') || '*/*'\n const splitRequestAcceptHeader = requestAcceptHeader.split(',')\n\n const supportedMimeTypes = ['*/*', 'text/html']\n const isRouterAcceptSupported = supportedMimeTypes.some(\n (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 the startRoutesManifest is not loaded yet, load it once\n if (startRoutesManifest === null) {\n startRoutesManifest = await getStartManifest({\n basePath: APP_BASE,\n })\n }\n\n // Attach the server-side SSR utils to the client-side router\n attachRouterServerSsrUtils(router, startRoutesManifest)\n\n await router.load()\n\n // If there was a redirect, skip rendering the page at all\n if (router.state.redirect) {\n return router.state.redirect\n }\n\n await router.serverSsr!.dehydrate()\n\n const responseHeaders = getStartResponseHeaders({ router })\n const response = await cb({\n request,\n router,\n responseHeaders,\n })\n\n return response\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 (processedServerRouteTree) {\n const [_matchedRoutes, response] = await handleServerRoutes({\n processedServerRouteTree,\n router,\n request,\n basePath: APP_BASE,\n executeRouter,\n })\n\n if (response) return response\n }\n\n // Server Routes did not produce a response, so fallback to normal SSR matching using the router\n const routerResponse = await executeRouter()\n return routerResponse\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. The redirect() method's \"to\" property accepts an internal path only. Use the \"href\" property to provide an external URL. 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(opts: {\n router: AnyRouter\n processedServerRouteTree: ProcessRouteTreeResult<AnyServerRouteWithTypes>\n request: Request\n basePath: string\n executeRouter: () => Promise<Response>\n}) {\n let url = new URL(opts.request.url)\n if (opts.basePath) {\n url = executeRewriteInput(rewriteBasepath({ basepath: opts.basePath }), url)\n }\n const pathname = url.pathname\n\n const serverTreeResult = getMatchedRoutes<AnyServerRouteWithTypes>({\n pathname,\n caseSensitive: true,\n routesByPath: opts.processedServerRouteTree.routesByPath,\n routesById: opts.processedServerRouteTree.routesById,\n flatRoutes: opts.processedServerRouteTree.flatRoutes,\n })\n\n const routeTreeResult = opts.router.getMatchedRoutes(pathname, undefined)\n\n let response: Response | undefined\n let matchedRoutes: Array<AnyServerRouteWithTypes> = []\n matchedRoutes = serverTreeResult.matchedRoutes\n // check if the app route tree found a match that is deeper than the server route tree\n if (routeTreeResult.foundRoute) {\n if (\n serverTreeResult.matchedRoutes.length <\n routeTreeResult.matchedRoutes.length\n ) {\n const closestCommon = [...routeTreeResult.matchedRoutes]\n .reverse()\n .find((r) => {\n return opts.processedServerRouteTree.routesById[r.id] !== undefined\n })\n if (closestCommon) {\n // walk up the tree and collect all parents\n let routeId = closestCommon.id\n matchedRoutes = []\n do {\n const route = opts.processedServerRouteTree.routesById[routeId]\n if (!route) {\n break\n }\n matchedRoutes.push(route)\n routeId = route.parentRoute?.id\n } while (routeId)\n\n matchedRoutes.reverse()\n }\n }\n }\n\n if (matchedRoutes.length) {\n // We've found a server route that (partially) matches the request, so we can call it.\n // TODO: Error handling? What happens when its `throw redirect()` vs `throw new Error()`?\n\n const middlewares = flattenMiddlewares(\n matchedRoutes.flatMap((r) => r.options.middleware).filter(Boolean),\n ).map((d) => d.options.server)\n\n if (serverTreeResult.foundRoute?.options.methods) {\n const method = Object.keys(\n serverTreeResult.foundRoute.options.methods,\n ).find(\n (method) => method.toLowerCase() === opts.request.method.toLowerCase(),\n )\n\n if (method) {\n const handler = serverTreeResult.foundRoute.options.methods[method]\n if (handler) {\n if (typeof handler === 'function') {\n middlewares.push(handlerToMiddleware(handler) as TODO)\n } else {\n if (\n handler._options.middlewares &&\n handler._options.middlewares.length\n ) {\n middlewares.push(\n ...flattenMiddlewares(handler._options.middlewares as any).map(\n (d) => d.options.server,\n ),\n )\n }\n if (handler._options.handler) {\n middlewares.push(handlerToMiddleware(handler._options.handler))\n }\n }\n }\n }\n }\n\n // eventually, execute the router\n middlewares.push(handlerToMiddleware(opts.executeRouter))\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: opts.request,\n context: {},\n params: serverTreeResult.routeParams,\n pathname,\n })\n\n response = ctx.response\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: ServerRouteMethodHandlerFn<\n AnyServerRouteWithTypes,\n any,\n any,\n any,\n any\n >,\n) {\n return async ({ next: _next, ...rest }: TODO) => {\n const response = await handler(rest)\n if (response) {\n return { response }\n }\n return _next(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({\n ...ctx,\n ...nextCtx,\n context: {\n ...ctx.context,\n ...(nextCtx?.context || {}),\n },\n })\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":";;;;;;;;;;;;AA8CA,SAAS,wBAAwB,MAA6B;AAC5D,QAAM,UAAU;AAAA,IACd,mBAAA;AAAA,IACA;AAAA,MACE,gBAAgB;AAAA,IAAA;AAAA,IAElB,GAAG,KAAK,OAAO,MAAM,QAAQ,IAAI,CAAC,UAAU;AAC1C,aAAO,MAAM;AAAA,IACf,CAAC;AAAA,EAAA;AAEH,SAAO;AACT;AAEO,SAAS,mBAA8C;AAAA,EAC5D;AACF,GAEmC;AACjC,MAAI,kBAGO;AACX,MAAI,sBAAuC;AAC3C,MAAI,2BAEY;AAEhB,SAAO,CAAC,OAAO;AACb,UAAM,gBAAgB,WAAW;AAEjC,UAAM,uBAAuC,OAAO,YAAY;AAC9D,eAAS,YAAY;AACnB,cAAM,eAAe,QAAQ,QAAQ,IAAI,QAAQ;AACjD,YAAI,cAAc;AAChB,iBAAO;AAAA,QACT;AACA,YAAI;AACF,iBAAO,IAAI,IAAI,QAAQ,GAAG,EAAE;AAAA,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MAAK,gBAAgB,MAAM,CAAC;AAAA,EACnD;AAEA,SAAO,gBAAgB,KAAK,GAAG,CAAC;AAClC;AAEA,SAAS,gBAAgB,QAAc;AACrC,MAAI,kBAAkB,MAAM,GAAG;AAC7B,WAAO;AAAA,MACL,UAAU;AAAA,IAAA;AAAA,EAEd;AAEA,SAAO;AACT;AAEA,SAAS,kBAAkB,KAAW;AACpC,SAAO,WAAW,GAAG,KAAK,WAAW,GAAG;AAC1C;AAEA,SAAS,WAAW,UAA0C;AAC5D,SAAO,oBAAoB;AAC7B;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tanstack/start-server-core",
|
|
3
|
-
"version": "1.132.0-alpha.
|
|
3
|
+
"version": "1.132.0-alpha.16",
|
|
4
4
|
"description": "Modern and scalable routing for React applications",
|
|
5
5
|
"author": "Tanner Linsley",
|
|
6
6
|
"license": "MIT",
|
|
@@ -49,10 +49,10 @@
|
|
|
49
49
|
"h3": "2.0.0-beta.4",
|
|
50
50
|
"seroval": "^1.3.2",
|
|
51
51
|
"tiny-invariant": "^1.3.3",
|
|
52
|
-
"@tanstack/router-core": "1.132.0-alpha.12",
|
|
53
52
|
"@tanstack/history": "1.132.0-alpha.1",
|
|
54
|
-
"@tanstack/
|
|
55
|
-
"@tanstack/start-
|
|
53
|
+
"@tanstack/router-core": "1.132.0-alpha.16",
|
|
54
|
+
"@tanstack/start-client-core": "1.132.0-alpha.16",
|
|
55
|
+
"@tanstack/start-storage-context": "1.132.0-alpha.16"
|
|
56
56
|
},
|
|
57
57
|
"scripts": {}
|
|
58
58
|
}
|
|
@@ -5,11 +5,13 @@ import {
|
|
|
5
5
|
mergeHeaders,
|
|
6
6
|
} from '@tanstack/start-client-core'
|
|
7
7
|
import {
|
|
8
|
+
executeRewriteInput,
|
|
8
9
|
getMatchedRoutes,
|
|
9
10
|
isRedirect,
|
|
10
11
|
isResolvedRedirect,
|
|
11
12
|
joinPaths,
|
|
12
13
|
processRouteTree,
|
|
14
|
+
rewriteBasepath,
|
|
13
15
|
trimPath,
|
|
14
16
|
} from '@tanstack/router-core'
|
|
15
17
|
import { attachRouterServerSsrUtils } from '@tanstack/router-core/ssr/server'
|
|
@@ -73,6 +75,17 @@ export function createStartHandler<TRouter extends AnyRouter>({
|
|
|
73
75
|
const originalFetch = globalThis.fetch
|
|
74
76
|
|
|
75
77
|
const startRequestResolver: RequestHandler = async (request) => {
|
|
78
|
+
function getOrigin() {
|
|
79
|
+
const originHeader = request.headers.get('Origin')
|
|
80
|
+
if (originHeader) {
|
|
81
|
+
return originHeader
|
|
82
|
+
}
|
|
83
|
+
try {
|
|
84
|
+
return new URL(request.url).origin
|
|
85
|
+
} catch (_) {}
|
|
86
|
+
return 'http://localhost'
|
|
87
|
+
}
|
|
88
|
+
|
|
76
89
|
// Patching fetch function to use our request resolver
|
|
77
90
|
// if the input starts with `/` which is a common pattern for
|
|
78
91
|
// client-side routing.
|
|
@@ -84,14 +97,6 @@ export function createStartHandler<TRouter extends AnyRouter>({
|
|
|
84
97
|
return startRequestResolver(fetchRequest)
|
|
85
98
|
}
|
|
86
99
|
|
|
87
|
-
function getOrigin() {
|
|
88
|
-
return (
|
|
89
|
-
request.headers.get('Origin') ||
|
|
90
|
-
request.headers.get('Referer') ||
|
|
91
|
-
'http://localhost'
|
|
92
|
-
)
|
|
93
|
-
}
|
|
94
|
-
|
|
95
100
|
if (typeof input === 'string' && input.startsWith('/')) {
|
|
96
101
|
// e.g: fetch('/api/data')
|
|
97
102
|
const url = new URL(input, getOrigin())
|
|
@@ -119,11 +124,6 @@ export function createStartHandler<TRouter extends AnyRouter>({
|
|
|
119
124
|
// TODO how does this work with base path? does the router need to be configured the same as APP_BASE?
|
|
120
125
|
const router = await createRouter()
|
|
121
126
|
|
|
122
|
-
// Create a history for the client-side router
|
|
123
|
-
const history = createMemoryHistory({
|
|
124
|
-
initialEntries: [href],
|
|
125
|
-
})
|
|
126
|
-
|
|
127
127
|
// Update the client-side router with the history
|
|
128
128
|
const isPrerendering = process.env.TSS_PRERENDERING === 'true'
|
|
129
129
|
// env var is set during dev is SPA mode is enabled
|
|
@@ -139,11 +139,18 @@ export function createStartHandler<TRouter extends AnyRouter>({
|
|
|
139
139
|
router.options.serializationAdapters ?? []
|
|
140
140
|
).concat(ServerFunctionSerializationAdapter)
|
|
141
141
|
|
|
142
|
+
// Create a history for the client-side router
|
|
143
|
+
const history = createMemoryHistory({
|
|
144
|
+
initialEntries: [href],
|
|
145
|
+
})
|
|
146
|
+
|
|
147
|
+
const origin = router.options.origin ?? getOrigin()
|
|
142
148
|
router.update({
|
|
143
149
|
history,
|
|
144
150
|
isShell,
|
|
145
151
|
isPrerendering,
|
|
146
152
|
serializationAdapters,
|
|
153
|
+
origin,
|
|
147
154
|
})
|
|
148
155
|
|
|
149
156
|
const response = await runWithStartContext({ router }, async () => {
|
|
@@ -335,12 +342,14 @@ async function handleServerRoutes(opts: {
|
|
|
335
342
|
basePath: string
|
|
336
343
|
executeRouter: () => Promise<Response>
|
|
337
344
|
}) {
|
|
338
|
-
|
|
345
|
+
let url = new URL(opts.request.url)
|
|
346
|
+
if (opts.basePath) {
|
|
347
|
+
url = executeRewriteInput(rewriteBasepath({ basepath: opts.basePath }), url)
|
|
348
|
+
}
|
|
339
349
|
const pathname = url.pathname
|
|
340
350
|
|
|
341
351
|
const serverTreeResult = getMatchedRoutes<AnyServerRouteWithTypes>({
|
|
342
352
|
pathname,
|
|
343
|
-
basepath: opts.basePath,
|
|
344
353
|
caseSensitive: true,
|
|
345
354
|
routesByPath: opts.processedServerRouteTree.routesByPath,
|
|
346
355
|
routesById: opts.processedServerRouteTree.routesById,
|