@tanstack/start-server-core 1.151.2 → 1.151.6

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,7 +1,7 @@
1
1
  import { createMemoryHistory } from "@tanstack/history";
2
2
  import { flattenMiddlewares, createNullProtoObject, mergeHeaders, safeObjectMerge } from "@tanstack/start-client-core";
3
3
  import { isRedirect, isResolvedRedirect, executeRewriteInput } from "@tanstack/router-core";
4
- import { getOrigin, attachRouterServerSsrUtils } from "@tanstack/router-core/ssr/server";
4
+ import { getNormalizedURL, getOrigin, attachRouterServerSsrUtils } from "@tanstack/router-core/ssr/server";
5
5
  import { runWithStartContext } from "@tanstack/start-storage-context";
6
6
  import { requestHandler } from "./request-response.js";
7
7
  import { getStartManifest } from "./router-manifest.js";
@@ -119,8 +119,8 @@ function createStartHandler(cb) {
119
119
  let router = null;
120
120
  let cbWillCleanup = false;
121
121
  try {
122
- const url = new URL(request.url);
123
- const href = url.href.replace(url.origin, "");
122
+ const url = getNormalizedURL(request.url);
123
+ const href = url.pathname + url.search + url.hash;
124
124
  const origin = getOrigin(request);
125
125
  const entries = await getEntries();
126
126
  const startOptions = await entries.startEntry.startInstance?.getOptions() || {};
@@ -1 +1 @@
1
- {"version":3,"file":"createStartHandler.js","sources":["../../src/createStartHandler.ts"],"sourcesContent":["import { createMemoryHistory } from '@tanstack/history'\nimport {\n createNullProtoObject,\n flattenMiddlewares,\n mergeHeaders,\n safeObjectMerge,\n} from '@tanstack/start-client-core'\nimport {\n executeRewriteInput,\n isRedirect,\n isResolvedRedirect,\n} from '@tanstack/router-core'\nimport {\n attachRouterServerSsrUtils,\n getOrigin,\n} from '@tanstack/router-core/ssr/server'\nimport { runWithStartContext } from '@tanstack/start-storage-context'\nimport { requestHandler } from './request-response'\nimport { getStartManifest } from './router-manifest'\nimport { handleServerAction } from './server-functions-handler'\n\nimport { HEADERS } from './constants'\nimport { ServerFunctionSerializationAdapter } from './serializer/ServerFunctionSerializationAdapter'\nimport type {\n AnyFunctionMiddleware,\n AnyRequestMiddleware,\n AnyStartInstanceOptions,\n RouteMethod,\n RouteMethodHandlerFn,\n RouterEntry,\n StartEntry,\n} from '@tanstack/start-client-core'\nimport type { RequestHandler } from './request-handler'\nimport type {\n AnyRoute,\n AnyRouter,\n Manifest,\n Register,\n} from '@tanstack/router-core'\nimport type { HandlerCallback } from '@tanstack/router-core/ssr/server'\n\ntype TODO = any\n\ntype AnyMiddlewareServerFn =\n | AnyRequestMiddleware['options']['server']\n | AnyFunctionMiddleware['options']['server']\n\nfunction getStartResponseHeaders(opts: { router: AnyRouter }) {\n const headers = mergeHeaders(\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\n// Cached entries - promises stored immediately to prevent concurrent imports\n// that can cause race conditions during module initialization\nlet entriesPromise:\n | Promise<{\n startEntry: StartEntry\n routerEntry: RouterEntry\n }>\n | undefined\nlet manifestPromise: Promise<Manifest> | undefined\n\nasync function loadEntries() {\n // @ts-ignore when building, we currently don't respect tsconfig.ts' `include` so we are not picking up the .d.ts from start-client-core\n const routerEntry = (await import('#tanstack-router-entry')) as RouterEntry\n // @ts-ignore when building, we currently don't respect tsconfig.ts' `include` so we are not picking up the .d.ts from start-client-core\n const startEntry = (await import('#tanstack-start-entry')) as StartEntry\n return { startEntry, routerEntry }\n}\n\nfunction getEntries() {\n if (!entriesPromise) {\n entriesPromise = loadEntries()\n }\n return entriesPromise\n}\n\nfunction getManifest(matchedRoutes?: ReadonlyArray<AnyRoute>) {\n // In dev mode, always get fresh manifest (no caching) to include route-specific dev styles\n if (process.env.TSS_DEV_SERVER === 'true') {\n return getStartManifest(matchedRoutes)\n }\n // In prod, cache the manifest\n if (!manifestPromise) {\n manifestPromise = getStartManifest()\n }\n return manifestPromise\n}\n\n// Pre-computed constants\nconst ROUTER_BASEPATH = process.env.TSS_ROUTER_BASEPATH || '/'\nconst SERVER_FN_BASE = process.env.TSS_SERVER_FN_BASE\nconst IS_PRERENDERING = process.env.TSS_PRERENDERING === 'true'\nconst IS_SHELL_ENV = process.env.TSS_SHELL === 'true'\nconst IS_DEV = process.env.NODE_ENV === 'development'\n\n// Reusable error messages\nconst ERR_NO_RESPONSE = IS_DEV\n ? `It looks like you forgot to return a response from your server route handler. If you want to defer to the app router, make sure to have a component set in this route.`\n : 'Internal Server Error'\n\nconst ERR_NO_DEFER = IS_DEV\n ? `You cannot defer to the app router if there is no component defined on this route.`\n : 'Internal Server Error'\n\nfunction throwRouteHandlerError(): never {\n throw new Error(ERR_NO_RESPONSE)\n}\n\nfunction throwIfMayNotDefer(): never {\n throw new Error(ERR_NO_DEFER)\n}\n\n/**\n * Check if a value is a special response (Response or Redirect)\n */\nfunction isSpecialResponse(value: unknown): value is Response {\n return value instanceof Response || isRedirect(value)\n}\n\n/**\n * Normalize middleware result to context shape\n */\nfunction handleCtxResult(result: TODO) {\n if (isSpecialResponse(result)) {\n return { response: result }\n }\n return result\n}\n\n/**\n * Execute a middleware chain\n */\nfunction executeMiddleware(middlewares: Array<TODO>, ctx: TODO): Promise<TODO> {\n let index = -1\n\n const next = async (nextCtx?: TODO): Promise<TODO> => {\n // Merge context if provided using safeObjectMerge for prototype pollution prevention\n if (nextCtx) {\n if (nextCtx.context) {\n ctx.context = safeObjectMerge(ctx.context, nextCtx.context)\n }\n // Copy own properties except context (Object.keys returns only own enumerable properties)\n for (const key of Object.keys(nextCtx)) {\n if (key !== 'context') {\n ctx[key] = nextCtx[key]\n }\n }\n }\n\n index++\n const middleware = middlewares[index]\n if (!middleware) return ctx\n\n let result: TODO\n try {\n result = await middleware({ ...ctx, next })\n } catch (err) {\n if (isSpecialResponse(err)) {\n ctx.response = err\n return ctx\n }\n throw err\n }\n\n const normalized = handleCtxResult(result)\n if (normalized) {\n if (normalized.response !== undefined) {\n ctx.response = normalized.response\n }\n if (normalized.context) {\n ctx.context = safeObjectMerge(ctx.context, normalized.context)\n }\n }\n\n return ctx\n }\n\n return next()\n}\n\n/**\n * Wrap a route handler as middleware\n */\nfunction handlerToMiddleware(\n handler: RouteMethodHandlerFn<any, AnyRoute, any, any, any, any, any>,\n mayDefer: boolean = false,\n): TODO {\n if (mayDefer) {\n return handler\n }\n return async (ctx: TODO) => {\n const response = await handler({ ...ctx, next: throwIfMayNotDefer })\n if (!response) {\n throwRouteHandlerError()\n }\n return response\n }\n}\n\nexport function createStartHandler<TRegister = Register>(\n cb: HandlerCallback<AnyRouter>,\n): RequestHandler<TRegister> {\n const startRequestResolver: RequestHandler<Register> = async (\n request,\n requestOpts,\n ) => {\n let router: AnyRouter | null = null as AnyRouter | null\n let cbWillCleanup = false as boolean\n\n try {\n const url = new URL(request.url)\n const href = url.href.replace(url.origin, '')\n const origin = getOrigin(request)\n\n const entries = await getEntries()\n const startOptions: AnyStartInstanceOptions =\n (await entries.startEntry.startInstance?.getOptions()) ||\n ({} as AnyStartInstanceOptions)\n\n const serializationAdapters = [\n ...(startOptions.serializationAdapters || []),\n ServerFunctionSerializationAdapter,\n ]\n\n const requestStartOptions = {\n ...startOptions,\n serializationAdapters,\n }\n\n // Flatten request middlewares once\n const flattenedRequestMiddlewares = startOptions.requestMiddleware\n ? flattenMiddlewares(startOptions.requestMiddleware)\n : []\n\n // Create set for deduplication\n const executedRequestMiddlewares = new Set<TODO>(\n flattenedRequestMiddlewares,\n )\n\n // Memoized router getter\n const getRouter = async (): Promise<AnyRouter> => {\n if (router) return router\n\n router = await entries.routerEntry.getRouter()\n\n let isShell = IS_SHELL_ENV\n if (IS_PRERENDERING && !isShell) {\n isShell = request.headers.get(HEADERS.TSS_SHELL) === 'true'\n }\n\n const history = createMemoryHistory({\n initialEntries: [href],\n })\n\n router.update({\n history,\n isShell,\n isPrerendering: IS_PRERENDERING,\n origin: router.options.origin ?? origin,\n ...{\n defaultSsr: requestStartOptions.defaultSsr,\n serializationAdapters: [\n ...requestStartOptions.serializationAdapters,\n ...(router.options.serializationAdapters || []),\n ],\n },\n basepath: ROUTER_BASEPATH,\n })\n\n return router\n }\n\n // Check for server function requests first (early exit)\n if (SERVER_FN_BASE && url.pathname.startsWith(SERVER_FN_BASE)) {\n const serverFnId = url.pathname\n .slice(SERVER_FN_BASE.length)\n .split('/')[0]\n\n if (!serverFnId) {\n throw new Error('Invalid server action param for serverFnId')\n }\n\n const serverFnHandler = async ({ context }: TODO) => {\n return runWithStartContext(\n {\n getRouter,\n startOptions: requestStartOptions,\n contextAfterGlobalMiddlewares: context,\n request,\n executedRequestMiddlewares,\n },\n () =>\n handleServerAction({\n request,\n context: requestOpts?.context,\n serverFnId,\n }),\n )\n }\n\n const middlewares = flattenedRequestMiddlewares.map(\n (d) => d.options.server,\n )\n const ctx = await executeMiddleware([...middlewares, serverFnHandler], {\n request,\n context: createNullProtoObject(requestOpts?.context),\n })\n\n return handleRedirectResponse(ctx.response, request, getRouter)\n }\n\n // Router execution function\n const executeRouter = async (\n serverContext: TODO,\n matchedRoutes?: ReadonlyArray<AnyRoute>,\n ): Promise<Response> => {\n const acceptHeader = request.headers.get('Accept') || '*/*'\n const acceptParts = acceptHeader.split(',')\n const supportedMimeTypes = ['*/*', 'text/html']\n\n const isSupported = supportedMimeTypes.some((mimeType) =>\n acceptParts.some((part) => part.trim().startsWith(mimeType)),\n )\n\n if (!isSupported) {\n return Response.json(\n { error: 'Only HTML requests are supported here' },\n { status: 500 },\n )\n }\n\n const manifest = await getManifest(matchedRoutes)\n const routerInstance = await getRouter()\n\n attachRouterServerSsrUtils({\n router: routerInstance,\n manifest,\n })\n\n routerInstance.update({ additionalContext: { serverContext } })\n await routerInstance.load()\n\n if (routerInstance.state.redirect) {\n return routerInstance.state.redirect\n }\n\n await routerInstance.serverSsr!.dehydrate()\n\n const responseHeaders = getStartResponseHeaders({\n router: routerInstance,\n })\n cbWillCleanup = true\n\n return cb({\n request,\n router: routerInstance,\n responseHeaders,\n })\n }\n\n // Main request handler\n const requestHandlerMiddleware = async ({ context }: TODO) => {\n return runWithStartContext(\n {\n getRouter,\n startOptions: requestStartOptions,\n contextAfterGlobalMiddlewares: context,\n request,\n executedRequestMiddlewares,\n },\n async () => {\n try {\n return await handleServerRoutes({\n getRouter,\n request,\n url,\n executeRouter,\n context,\n executedRequestMiddlewares,\n })\n } catch (err) {\n if (err instanceof Response) {\n return err\n }\n throw err\n }\n },\n )\n }\n\n const middlewares = flattenedRequestMiddlewares.map(\n (d) => d.options.server,\n )\n const ctx = await executeMiddleware(\n [...middlewares, requestHandlerMiddleware],\n { request, context: createNullProtoObject(requestOpts?.context) },\n )\n\n return handleRedirectResponse(ctx.response, request, getRouter)\n } finally {\n if (router && !cbWillCleanup) {\n // Clean up router SSR state if it was set up but won't be cleaned up by the callback\n // (e.g., in redirect cases or early returns before the callback is invoked).\n // When the callback runs, it handles cleanup (either via transformStreamWithRouter\n // for streaming, or directly in renderRouterToString for non-streaming).\n router.serverSsr?.cleanup()\n }\n router = null\n }\n }\n\n return requestHandler(startRequestResolver)\n}\n\nasync function handleRedirectResponse(\n response: Response,\n request: Request,\n getRouter: () => Promise<AnyRouter>,\n): Promise<Response> {\n if (!isRedirect(response)) {\n return response\n }\n\n if (isResolvedRedirect(response)) {\n if (request.headers.get('x-tsr-serverFn') === 'true') {\n return Response.json(\n { ...response.options, isSerializedRedirect: true },\n { headers: response.headers },\n )\n }\n return response\n }\n\n const opts = response.options\n if (opts.to && typeof opts.to === 'string' && !opts.to.startsWith('/')) {\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(opts)}`,\n )\n }\n\n if (\n ['params', 'search', 'hash'].some(\n (d) => typeof (opts as TODO)[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 opts,\n )\n .filter((d) => typeof (opts as TODO)[d] === 'function')\n .map((d) => `\"${d}\"`)\n .join(', ')}`,\n )\n }\n\n const router = await getRouter()\n const redirect = router.resolveRedirect(response)\n\n if (request.headers.get('x-tsr-serverFn') === 'true') {\n return Response.json(\n { ...response.options, isSerializedRedirect: true },\n { headers: response.headers },\n )\n }\n\n return redirect\n}\n\nasync function handleServerRoutes({\n getRouter,\n request,\n url,\n executeRouter,\n context,\n executedRequestMiddlewares,\n}: {\n getRouter: () => Promise<AnyRouter>\n request: Request\n url: URL\n executeRouter: (\n serverContext: any,\n matchedRoutes?: ReadonlyArray<AnyRoute>,\n ) => Promise<Response>\n context: any\n executedRequestMiddlewares: Set<AnyRequestMiddleware>\n}): Promise<Response> {\n const router = await getRouter()\n const rewrittenUrl = executeRewriteInput(router.rewrite, url)\n const pathname = rewrittenUrl.pathname\n // this will perform a fuzzy match, however for server routes we need an exact match\n // if the route is not an exact match, executeRouter will handle rendering the app router\n // the match will be cached internally, so no extra work is done during the app router render\n const { matchedRoutes, foundRoute, routeParams } =\n router.getMatchedRoutes(pathname)\n\n const isExactMatch = foundRoute && routeParams['**'] === undefined\n\n // Collect and dedupe route middlewares\n const routeMiddlewares: Array<AnyMiddlewareServerFn> = []\n\n // Collect middleware from matched routes, filtering out those already executed\n // in the request phase\n for (const route of matchedRoutes) {\n const serverMiddleware = route.options.server?.middleware as\n | Array<AnyRequestMiddleware>\n | undefined\n if (serverMiddleware) {\n const flattened = flattenMiddlewares(serverMiddleware)\n for (const m of flattened) {\n if (!executedRequestMiddlewares.has(m)) {\n routeMiddlewares.push(m.options.server)\n }\n }\n }\n }\n\n // Add handler middleware if exact match\n const server = foundRoute?.options.server\n if (server?.handlers && isExactMatch) {\n const handlers =\n typeof server.handlers === 'function'\n ? server.handlers({ createHandlers: (d: any) => d })\n : server.handlers\n\n const requestMethod = request.method.toUpperCase() as RouteMethod\n const handler = handlers[requestMethod] ?? handlers['ANY']\n\n if (handler) {\n const mayDefer = !!foundRoute.options.component\n\n if (typeof handler === 'function') {\n routeMiddlewares.push(handlerToMiddleware(handler, mayDefer))\n } else {\n if (handler.middleware?.length) {\n const handlerMiddlewares = flattenMiddlewares(handler.middleware)\n for (const m of handlerMiddlewares) {\n routeMiddlewares.push(m.options.server)\n }\n }\n if (handler.handler) {\n routeMiddlewares.push(handlerToMiddleware(handler.handler, mayDefer))\n }\n }\n }\n }\n\n // Final middleware: execute router with matched routes for dev styles\n routeMiddlewares.push((ctx: TODO) =>\n executeRouter(ctx.context, matchedRoutes),\n )\n\n const ctx = await executeMiddleware(routeMiddlewares, {\n request,\n context,\n params: routeParams,\n pathname,\n })\n\n return ctx.response\n}\n"],"names":["middlewares","ctx"],"mappings":";;;;;;;;;;AA+CA,SAAS,wBAAwB,MAA6B;AAC5D,QAAM,UAAU;AAAA,IACd;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;AAIA,IAAI;AAMJ,IAAI;AAEJ,eAAe,cAAc;AAE3B,QAAM,cAAe,MAAM,OAAO,wBAAwB;AAE1D,QAAM,aAAc,MAAM,OAAO,uBAAuB;AACxD,SAAO,EAAE,YAAY,YAAA;AACvB;AAEA,SAAS,aAAa;AACpB,MAAI,CAAC,gBAAgB;AACnB,qBAAiB,YAAA;AAAA,EACnB;AACA,SAAO;AACT;AAEA,SAAS,YAAY,eAAyC;AAE5D,MAAI,QAAQ,IAAI,mBAAmB,QAAQ;AACzC,WAAO,iBAAiB,aAAa;AAAA,EACvC;AAEA,MAAI,CAAC,iBAAiB;AACpB,sBAAkB,iBAAA;AAAA,EACpB;AACA,SAAO;AACT;AAGA,MAAM,kBAAkB,QAAQ,IAAI,uBAAuB;AAC3D,MAAM,iBAAiB,QAAQ,IAAI;AACnC,MAAM,kBAAkB,QAAQ,IAAI,qBAAqB;AACzD,MAAM,eAAe,QAAQ,IAAI,cAAc;AAC/C,MAAM,SAAS,QAAQ,IAAI,aAAa;AAGxC,MAA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AAQ,MAAM;AAAA,UACxC;AAAA,QACF;AACA,YAAI,QAAQ,SAAS;AACnB,2BAAiB,KAAK,oBAAoB,QAAQ,SAAS,QAAQ,CAAC;AAAA,QACtE;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAGA,mBAAiB;AAAA,IAAK,CAACA,SACrB,cAAcA,KAAI,SAAS,aAAa;AAAA,EAAA;AAG1C,QAAM,MAAM,MAAM,kBAAkB,kBAAkB;AAAA,IACpD;AAAA,IACA;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,EAAA,CACD;AAED,SAAO,IAAI;AACb;"}
1
+ {"version":3,"file":"createStartHandler.js","sources":["../../src/createStartHandler.ts"],"sourcesContent":["import { createMemoryHistory } from '@tanstack/history'\nimport {\n createNullProtoObject,\n flattenMiddlewares,\n mergeHeaders,\n safeObjectMerge,\n} from '@tanstack/start-client-core'\nimport {\n executeRewriteInput,\n isRedirect,\n isResolvedRedirect,\n} from '@tanstack/router-core'\nimport {\n attachRouterServerSsrUtils,\n getNormalizedURL,\n getOrigin,\n} from '@tanstack/router-core/ssr/server'\nimport { runWithStartContext } from '@tanstack/start-storage-context'\nimport { requestHandler } from './request-response'\nimport { getStartManifest } from './router-manifest'\nimport { handleServerAction } from './server-functions-handler'\n\nimport { HEADERS } from './constants'\nimport { ServerFunctionSerializationAdapter } from './serializer/ServerFunctionSerializationAdapter'\nimport type {\n AnyFunctionMiddleware,\n AnyRequestMiddleware,\n AnyStartInstanceOptions,\n RouteMethod,\n RouteMethodHandlerFn,\n RouterEntry,\n StartEntry,\n} from '@tanstack/start-client-core'\nimport type { RequestHandler } from './request-handler'\nimport type {\n AnyRoute,\n AnyRouter,\n Manifest,\n Register,\n} from '@tanstack/router-core'\nimport type { HandlerCallback } from '@tanstack/router-core/ssr/server'\n\ntype TODO = any\n\ntype AnyMiddlewareServerFn =\n | AnyRequestMiddleware['options']['server']\n | AnyFunctionMiddleware['options']['server']\n\nfunction getStartResponseHeaders(opts: { router: AnyRouter }) {\n const headers = mergeHeaders(\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\n// Cached entries - promises stored immediately to prevent concurrent imports\n// that can cause race conditions during module initialization\nlet entriesPromise:\n | Promise<{\n startEntry: StartEntry\n routerEntry: RouterEntry\n }>\n | undefined\nlet manifestPromise: Promise<Manifest> | undefined\n\nasync function loadEntries() {\n // @ts-ignore when building, we currently don't respect tsconfig.ts' `include` so we are not picking up the .d.ts from start-client-core\n const routerEntry = (await import('#tanstack-router-entry')) as RouterEntry\n // @ts-ignore when building, we currently don't respect tsconfig.ts' `include` so we are not picking up the .d.ts from start-client-core\n const startEntry = (await import('#tanstack-start-entry')) as StartEntry\n return { startEntry, routerEntry }\n}\n\nfunction getEntries() {\n if (!entriesPromise) {\n entriesPromise = loadEntries()\n }\n return entriesPromise\n}\n\nfunction getManifest(matchedRoutes?: ReadonlyArray<AnyRoute>) {\n // In dev mode, always get fresh manifest (no caching) to include route-specific dev styles\n if (process.env.TSS_DEV_SERVER === 'true') {\n return getStartManifest(matchedRoutes)\n }\n // In prod, cache the manifest\n if (!manifestPromise) {\n manifestPromise = getStartManifest()\n }\n return manifestPromise\n}\n\n// Pre-computed constants\nconst ROUTER_BASEPATH = process.env.TSS_ROUTER_BASEPATH || '/'\nconst SERVER_FN_BASE = process.env.TSS_SERVER_FN_BASE\nconst IS_PRERENDERING = process.env.TSS_PRERENDERING === 'true'\nconst IS_SHELL_ENV = process.env.TSS_SHELL === 'true'\nconst IS_DEV = process.env.NODE_ENV === 'development'\n\n// Reusable error messages\nconst ERR_NO_RESPONSE = IS_DEV\n ? `It looks like you forgot to return a response from your server route handler. If you want to defer to the app router, make sure to have a component set in this route.`\n : 'Internal Server Error'\n\nconst ERR_NO_DEFER = IS_DEV\n ? `You cannot defer to the app router if there is no component defined on this route.`\n : 'Internal Server Error'\n\nfunction throwRouteHandlerError(): never {\n throw new Error(ERR_NO_RESPONSE)\n}\n\nfunction throwIfMayNotDefer(): never {\n throw new Error(ERR_NO_DEFER)\n}\n\n/**\n * Check if a value is a special response (Response or Redirect)\n */\nfunction isSpecialResponse(value: unknown): value is Response {\n return value instanceof Response || isRedirect(value)\n}\n\n/**\n * Normalize middleware result to context shape\n */\nfunction handleCtxResult(result: TODO) {\n if (isSpecialResponse(result)) {\n return { response: result }\n }\n return result\n}\n\n/**\n * Execute a middleware chain\n */\nfunction executeMiddleware(middlewares: Array<TODO>, ctx: TODO): Promise<TODO> {\n let index = -1\n\n const next = async (nextCtx?: TODO): Promise<TODO> => {\n // Merge context if provided using safeObjectMerge for prototype pollution prevention\n if (nextCtx) {\n if (nextCtx.context) {\n ctx.context = safeObjectMerge(ctx.context, nextCtx.context)\n }\n // Copy own properties except context (Object.keys returns only own enumerable properties)\n for (const key of Object.keys(nextCtx)) {\n if (key !== 'context') {\n ctx[key] = nextCtx[key]\n }\n }\n }\n\n index++\n const middleware = middlewares[index]\n if (!middleware) return ctx\n\n let result: TODO\n try {\n result = await middleware({ ...ctx, next })\n } catch (err) {\n if (isSpecialResponse(err)) {\n ctx.response = err\n return ctx\n }\n throw err\n }\n\n const normalized = handleCtxResult(result)\n if (normalized) {\n if (normalized.response !== undefined) {\n ctx.response = normalized.response\n }\n if (normalized.context) {\n ctx.context = safeObjectMerge(ctx.context, normalized.context)\n }\n }\n\n return ctx\n }\n\n return next()\n}\n\n/**\n * Wrap a route handler as middleware\n */\nfunction handlerToMiddleware(\n handler: RouteMethodHandlerFn<any, AnyRoute, any, any, any, any, any>,\n mayDefer: boolean = false,\n): TODO {\n if (mayDefer) {\n return handler\n }\n return async (ctx: TODO) => {\n const response = await handler({ ...ctx, next: throwIfMayNotDefer })\n if (!response) {\n throwRouteHandlerError()\n }\n return response\n }\n}\n\nexport function createStartHandler<TRegister = Register>(\n cb: HandlerCallback<AnyRouter>,\n): RequestHandler<TRegister> {\n const startRequestResolver: RequestHandler<Register> = async (\n request,\n requestOpts,\n ) => {\n let router: AnyRouter | null = null as AnyRouter | null\n let cbWillCleanup = false as boolean\n\n try {\n // normalizing and sanitizing the pathname here for server, so we always deal with the same format during SSR.\n const url = getNormalizedURL(request.url)\n const href = url.pathname + url.search + url.hash\n const origin = getOrigin(request)\n\n const entries = await getEntries()\n const startOptions: AnyStartInstanceOptions =\n (await entries.startEntry.startInstance?.getOptions()) ||\n ({} as AnyStartInstanceOptions)\n\n const serializationAdapters = [\n ...(startOptions.serializationAdapters || []),\n ServerFunctionSerializationAdapter,\n ]\n\n const requestStartOptions = {\n ...startOptions,\n serializationAdapters,\n }\n\n // Flatten request middlewares once\n const flattenedRequestMiddlewares = startOptions.requestMiddleware\n ? flattenMiddlewares(startOptions.requestMiddleware)\n : []\n\n // Create set for deduplication\n const executedRequestMiddlewares = new Set<TODO>(\n flattenedRequestMiddlewares,\n )\n\n // Memoized router getter\n const getRouter = async (): Promise<AnyRouter> => {\n if (router) return router\n\n router = await entries.routerEntry.getRouter()\n\n let isShell = IS_SHELL_ENV\n if (IS_PRERENDERING && !isShell) {\n isShell = request.headers.get(HEADERS.TSS_SHELL) === 'true'\n }\n\n const history = createMemoryHistory({\n initialEntries: [href],\n })\n\n router.update({\n history,\n isShell,\n isPrerendering: IS_PRERENDERING,\n origin: router.options.origin ?? origin,\n ...{\n defaultSsr: requestStartOptions.defaultSsr,\n serializationAdapters: [\n ...requestStartOptions.serializationAdapters,\n ...(router.options.serializationAdapters || []),\n ],\n },\n basepath: ROUTER_BASEPATH,\n })\n\n return router\n }\n\n // Check for server function requests first (early exit)\n if (SERVER_FN_BASE && url.pathname.startsWith(SERVER_FN_BASE)) {\n const serverFnId = url.pathname\n .slice(SERVER_FN_BASE.length)\n .split('/')[0]\n\n if (!serverFnId) {\n throw new Error('Invalid server action param for serverFnId')\n }\n\n const serverFnHandler = async ({ context }: TODO) => {\n return runWithStartContext(\n {\n getRouter,\n startOptions: requestStartOptions,\n contextAfterGlobalMiddlewares: context,\n request,\n executedRequestMiddlewares,\n },\n () =>\n handleServerAction({\n request,\n context: requestOpts?.context,\n serverFnId,\n }),\n )\n }\n\n const middlewares = flattenedRequestMiddlewares.map(\n (d) => d.options.server,\n )\n const ctx = await executeMiddleware([...middlewares, serverFnHandler], {\n request,\n context: createNullProtoObject(requestOpts?.context),\n })\n\n return handleRedirectResponse(ctx.response, request, getRouter)\n }\n\n // Router execution function\n const executeRouter = async (\n serverContext: TODO,\n matchedRoutes?: ReadonlyArray<AnyRoute>,\n ): Promise<Response> => {\n const acceptHeader = request.headers.get('Accept') || '*/*'\n const acceptParts = acceptHeader.split(',')\n const supportedMimeTypes = ['*/*', 'text/html']\n\n const isSupported = supportedMimeTypes.some((mimeType) =>\n acceptParts.some((part) => part.trim().startsWith(mimeType)),\n )\n\n if (!isSupported) {\n return Response.json(\n { error: 'Only HTML requests are supported here' },\n { status: 500 },\n )\n }\n\n const manifest = await getManifest(matchedRoutes)\n const routerInstance = await getRouter()\n\n attachRouterServerSsrUtils({\n router: routerInstance,\n manifest,\n })\n\n routerInstance.update({ additionalContext: { serverContext } })\n await routerInstance.load()\n\n if (routerInstance.state.redirect) {\n return routerInstance.state.redirect\n }\n\n await routerInstance.serverSsr!.dehydrate()\n\n const responseHeaders = getStartResponseHeaders({\n router: routerInstance,\n })\n cbWillCleanup = true\n\n return cb({\n request,\n router: routerInstance,\n responseHeaders,\n })\n }\n\n // Main request handler\n const requestHandlerMiddleware = async ({ context }: TODO) => {\n return runWithStartContext(\n {\n getRouter,\n startOptions: requestStartOptions,\n contextAfterGlobalMiddlewares: context,\n request,\n executedRequestMiddlewares,\n },\n async () => {\n try {\n return await handleServerRoutes({\n getRouter,\n request,\n url,\n executeRouter,\n context,\n executedRequestMiddlewares,\n })\n } catch (err) {\n if (err instanceof Response) {\n return err\n }\n throw err\n }\n },\n )\n }\n\n const middlewares = flattenedRequestMiddlewares.map(\n (d) => d.options.server,\n )\n const ctx = await executeMiddleware(\n [...middlewares, requestHandlerMiddleware],\n { request, context: createNullProtoObject(requestOpts?.context) },\n )\n\n return handleRedirectResponse(ctx.response, request, getRouter)\n } finally {\n if (router && !cbWillCleanup) {\n // Clean up router SSR state if it was set up but won't be cleaned up by the callback\n // (e.g., in redirect cases or early returns before the callback is invoked).\n // When the callback runs, it handles cleanup (either via transformStreamWithRouter\n // for streaming, or directly in renderRouterToString for non-streaming).\n router.serverSsr?.cleanup()\n }\n router = null\n }\n }\n\n return requestHandler(startRequestResolver)\n}\n\nasync function handleRedirectResponse(\n response: Response,\n request: Request,\n getRouter: () => Promise<AnyRouter>,\n): Promise<Response> {\n if (!isRedirect(response)) {\n return response\n }\n\n if (isResolvedRedirect(response)) {\n if (request.headers.get('x-tsr-serverFn') === 'true') {\n return Response.json(\n { ...response.options, isSerializedRedirect: true },\n { headers: response.headers },\n )\n }\n return response\n }\n\n const opts = response.options\n if (opts.to && typeof opts.to === 'string' && !opts.to.startsWith('/')) {\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(opts)}`,\n )\n }\n\n if (\n ['params', 'search', 'hash'].some(\n (d) => typeof (opts as TODO)[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 opts,\n )\n .filter((d) => typeof (opts as TODO)[d] === 'function')\n .map((d) => `\"${d}\"`)\n .join(', ')}`,\n )\n }\n\n const router = await getRouter()\n const redirect = router.resolveRedirect(response)\n\n if (request.headers.get('x-tsr-serverFn') === 'true') {\n return Response.json(\n { ...response.options, isSerializedRedirect: true },\n { headers: response.headers },\n )\n }\n\n return redirect\n}\n\nasync function handleServerRoutes({\n getRouter,\n request,\n url,\n executeRouter,\n context,\n executedRequestMiddlewares,\n}: {\n getRouter: () => Promise<AnyRouter>\n request: Request\n url: URL\n executeRouter: (\n serverContext: any,\n matchedRoutes?: ReadonlyArray<AnyRoute>,\n ) => Promise<Response>\n context: any\n executedRequestMiddlewares: Set<AnyRequestMiddleware>\n}): Promise<Response> {\n const router = await getRouter()\n const rewrittenUrl = executeRewriteInput(router.rewrite, url)\n const pathname = rewrittenUrl.pathname\n // this will perform a fuzzy match, however for server routes we need an exact match\n // if the route is not an exact match, executeRouter will handle rendering the app router\n // the match will be cached internally, so no extra work is done during the app router render\n const { matchedRoutes, foundRoute, routeParams } =\n router.getMatchedRoutes(pathname)\n\n const isExactMatch = foundRoute && routeParams['**'] === undefined\n\n // Collect and dedupe route middlewares\n const routeMiddlewares: Array<AnyMiddlewareServerFn> = []\n\n // Collect middleware from matched routes, filtering out those already executed\n // in the request phase\n for (const route of matchedRoutes) {\n const serverMiddleware = route.options.server?.middleware as\n | Array<AnyRequestMiddleware>\n | undefined\n if (serverMiddleware) {\n const flattened = flattenMiddlewares(serverMiddleware)\n for (const m of flattened) {\n if (!executedRequestMiddlewares.has(m)) {\n routeMiddlewares.push(m.options.server)\n }\n }\n }\n }\n\n // Add handler middleware if exact match\n const server = foundRoute?.options.server\n if (server?.handlers && isExactMatch) {\n const handlers =\n typeof server.handlers === 'function'\n ? server.handlers({ createHandlers: (d: any) => d })\n : server.handlers\n\n const requestMethod = request.method.toUpperCase() as RouteMethod\n const handler = handlers[requestMethod] ?? handlers['ANY']\n\n if (handler) {\n const mayDefer = !!foundRoute.options.component\n\n if (typeof handler === 'function') {\n routeMiddlewares.push(handlerToMiddleware(handler, mayDefer))\n } else {\n if (handler.middleware?.length) {\n const handlerMiddlewares = flattenMiddlewares(handler.middleware)\n for (const m of handlerMiddlewares) {\n routeMiddlewares.push(m.options.server)\n }\n }\n if (handler.handler) {\n routeMiddlewares.push(handlerToMiddleware(handler.handler, mayDefer))\n }\n }\n }\n }\n\n // Final middleware: execute router with matched routes for dev styles\n routeMiddlewares.push((ctx: TODO) =>\n executeRouter(ctx.context, matchedRoutes),\n )\n\n const ctx = await executeMiddleware(routeMiddlewares, {\n request,\n context,\n params: routeParams,\n pathname,\n })\n\n return ctx.response\n}\n"],"names":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IAAI;AACb;"}
@@ -1,6 +1,6 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
2
  import { H3Event, toResponse, getRequestIP as getRequestIP$1, getRequestHost as getRequestHost$1, getRequestURL, getRequestProtocol as getRequestProtocol$1, sanitizeStatusCode, sanitizeStatusMessage, parseCookies, setCookie as setCookie$1, deleteCookie as deleteCookie$1, useSession as useSession$1, getSession as getSession$1, updateSession as updateSession$1, sealSession as sealSession$1, unsealSession as unsealSession$1, clearSession as clearSession$1, getValidatedQuery as getValidatedQuery$1 } from "h3-v2";
3
- const GLOBAL_EVENT_STORAGE_KEY = Symbol.for("tanstack-start:event-storage");
3
+ const GLOBAL_EVENT_STORAGE_KEY = /* @__PURE__ */ Symbol.for("tanstack-start:event-storage");
4
4
  const globalObj = globalThis;
5
5
  if (!globalObj[GLOBAL_EVENT_STORAGE_KEY]) {
6
6
  globalObj[GLOBAL_EVENT_STORAGE_KEY] = new AsyncLocalStorage();
@@ -1 +1 @@
1
- {"version":3,"file":"request-response.js","sources":["../../src/request-response.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks'\n\nimport {\n H3Event,\n clearSession as h3_clearSession,\n deleteCookie as h3_deleteCookie,\n getRequestHost as h3_getRequestHost,\n getRequestIP as h3_getRequestIP,\n getRequestProtocol as h3_getRequestProtocol,\n getRequestURL as h3_getRequestURL,\n getSession as h3_getSession,\n getValidatedQuery as h3_getValidatedQuery,\n parseCookies as h3_parseCookies,\n sanitizeStatusCode as h3_sanitizeStatusCode,\n sanitizeStatusMessage as h3_sanitizeStatusMessage,\n sealSession as h3_sealSession,\n setCookie as h3_setCookie,\n toResponse as h3_toResponse,\n unsealSession as h3_unsealSession,\n updateSession as h3_updateSession,\n useSession as h3_useSession,\n} from 'h3-v2'\nimport type {\n RequestHeaderMap,\n RequestHeaderName,\n ResponseHeaderMap,\n ResponseHeaderName,\n TypedHeaders,\n} from 'fetchdts'\n\nimport type { CookieSerializeOptions } from 'cookie-es'\nimport type {\n Session,\n SessionConfig,\n SessionData,\n SessionManager,\n SessionUpdate,\n} from './session'\nimport type { StandardSchemaV1 } from '@standard-schema/spec'\nimport type { RequestHandler } from './request-handler'\n\ninterface StartEvent {\n h3Event: H3Event\n}\n\n// Use a global symbol to ensure the same AsyncLocalStorage instance is shared\n// across different bundles that may each bundle this module.\nconst GLOBAL_EVENT_STORAGE_KEY = Symbol.for('tanstack-start:event-storage')\n\nconst globalObj = globalThis as typeof globalThis & {\n [GLOBAL_EVENT_STORAGE_KEY]?: AsyncLocalStorage<StartEvent>\n}\n\nif (!globalObj[GLOBAL_EVENT_STORAGE_KEY]) {\n globalObj[GLOBAL_EVENT_STORAGE_KEY] = new AsyncLocalStorage<StartEvent>()\n}\n\nconst eventStorage = globalObj[GLOBAL_EVENT_STORAGE_KEY]\n\nexport type { ResponseHeaderName, RequestHeaderName }\n\ntype HeadersWithGetSetCookie = Headers & {\n getSetCookie?: () => Array<string>\n}\n\ntype MaybePromise<T> = T | Promise<T>\n\nfunction isPromiseLike<T>(value: MaybePromise<T>): value is Promise<T> {\n return typeof (value as Promise<T>).then === 'function'\n}\n\nfunction getSetCookieValues(headers: Headers): Array<string> {\n const headersWithSetCookie = headers as HeadersWithGetSetCookie\n if (typeof headersWithSetCookie.getSetCookie === 'function') {\n return headersWithSetCookie.getSetCookie()\n }\n const value = headers.get('set-cookie')\n return value ? [value] : []\n}\n\nfunction mergeEventResponseHeaders(response: Response, event: H3Event): void {\n if (response.ok) {\n return\n }\n\n const eventSetCookies = getSetCookieValues(event.res.headers)\n if (eventSetCookies.length === 0) {\n return\n }\n\n const responseSetCookies = getSetCookieValues(response.headers)\n response.headers.delete('set-cookie')\n for (const cookie of responseSetCookies) {\n response.headers.append('set-cookie', cookie)\n }\n for (const cookie of eventSetCookies) {\n response.headers.append('set-cookie', cookie)\n }\n}\n\nfunction attachResponseHeaders<T>(\n value: MaybePromise<T>,\n event: H3Event,\n): MaybePromise<T> {\n if (isPromiseLike(value)) {\n return value.then((resolved) => {\n if (resolved instanceof Response) {\n mergeEventResponseHeaders(resolved, event)\n }\n return resolved\n })\n }\n\n if (value instanceof Response) {\n mergeEventResponseHeaders(value, event)\n }\n\n return value\n}\n\nexport function requestHandler<TRegister = unknown>(\n handler: RequestHandler<TRegister>,\n) {\n return (request: Request, requestOpts: any): Promise<Response> | Response => {\n const h3Event = new H3Event(request)\n\n const response = eventStorage.run({ h3Event }, () =>\n handler(request, requestOpts),\n )\n return h3_toResponse(attachResponseHeaders(response, h3Event), h3Event)\n }\n}\n\nfunction getH3Event() {\n const event = eventStorage.getStore()\n if (!event) {\n throw new Error(\n `No StartEvent found in AsyncLocalStorage. Make sure you are using the function within the server runtime.`,\n )\n }\n return event.h3Event\n}\n\nexport function getRequest(): Request {\n const event = getH3Event()\n return event.req\n}\n\nexport function getRequestHeaders(): TypedHeaders<RequestHeaderMap> {\n // TODO `as any` not needed when fetchdts is updated\n return getH3Event().req.headers as any\n}\n\nexport function getRequestHeader(name: RequestHeaderName): string | undefined {\n return getRequestHeaders().get(name) || undefined\n}\n\nexport function getRequestIP(opts?: {\n /**\n * Use the X-Forwarded-For HTTP header set by proxies.\n *\n * Note: Make sure that this header can be trusted (your application running behind a CDN or reverse proxy) before enabling.\n */\n xForwardedFor?: boolean\n}) {\n return h3_getRequestIP(getH3Event(), opts)\n}\n\n/**\n * Get the request hostname.\n *\n * If `xForwardedHost` is `true`, it will use the `x-forwarded-host` header if it exists.\n *\n * If no host header is found, it will default to \"localhost\".\n */\nexport function getRequestHost(opts?: { xForwardedHost?: boolean }) {\n return h3_getRequestHost(getH3Event(), opts)\n}\n\n/**\n * Get the full incoming request URL.\n *\n * If `xForwardedHost` is `true`, it will use the `x-forwarded-host` header if it exists.\n *\n * If `xForwardedProto` is `false`, it will not use the `x-forwarded-proto` header.\n */\nexport function getRequestUrl(opts?: {\n xForwardedHost?: boolean\n xForwardedProto?: boolean\n}) {\n return h3_getRequestURL(getH3Event(), opts)\n}\n\n/**\n * Get the request protocol.\n *\n * If `x-forwarded-proto` header is set to \"https\", it will return \"https\". You can disable this behavior by setting `xForwardedProto` to `false`.\n *\n * If protocol cannot be determined, it will default to \"http\".\n */\nexport function getRequestProtocol(opts?: {\n xForwardedProto?: boolean\n}): 'http' | 'https' | (string & {}) {\n return h3_getRequestProtocol(getH3Event(), opts)\n}\n\nexport function setResponseHeaders(\n headers: TypedHeaders<ResponseHeaderMap>,\n): void {\n const event = getH3Event()\n for (const [name, value] of Object.entries(headers)) {\n event.res.headers.set(name, value)\n }\n}\n\nexport function getResponseHeaders(): TypedHeaders<ResponseHeaderMap> {\n const event = getH3Event()\n return event.res.headers\n}\n\nexport function getResponseHeader(\n name: ResponseHeaderName,\n): string | undefined {\n const event = getH3Event()\n return event.res.headers.get(name) || undefined\n}\n\nexport function setResponseHeader(\n name: ResponseHeaderName,\n value: string | Array<string>,\n): void {\n const event = getH3Event()\n if (Array.isArray(value)) {\n event.res.headers.delete(name)\n for (const valueItem of value) {\n event.res.headers.append(name, valueItem)\n }\n } else {\n event.res.headers.set(name, value)\n }\n}\nexport function removeResponseHeader(name: ResponseHeaderName): void {\n const event = getH3Event()\n event.res.headers.delete(name)\n}\n\nexport function clearResponseHeaders(\n headerNames?: Array<ResponseHeaderName>,\n): void {\n const event = getH3Event()\n // If headerNames is provided, clear only those headers\n if (headerNames && headerNames.length > 0) {\n for (const name of headerNames) {\n event.res.headers.delete(name)\n }\n // Otherwise, clear all headers\n } else {\n for (const name of event.res.headers.keys()) {\n event.res.headers.delete(name)\n }\n }\n}\n\nexport function getResponseStatus(): number {\n return getH3Event().res.status || 200\n}\n\nexport function setResponseStatus(code?: number, text?: string): void {\n const event = getH3Event()\n if (code) {\n event.res.status = h3_sanitizeStatusCode(code, event.res.status)\n }\n if (text) {\n event.res.statusText = h3_sanitizeStatusMessage(text)\n }\n}\n\n/**\n * Parse the request to get HTTP Cookie header string and return an object of all cookie name-value pairs.\n * @returns Object of cookie name-value pairs\n * ```ts\n * const cookies = getCookies()\n * ```\n */\nexport function getCookies(): Record<string, string> {\n const event = getH3Event()\n return h3_parseCookies(event)\n}\n\n/**\n * Get a cookie value by name.\n * @param name Name of the cookie to get\n * @returns {*} Value of the cookie (String or undefined)\n * ```ts\n * const authorization = getCookie('Authorization')\n * ```\n */\nexport function getCookie(name: string): string | undefined {\n return getCookies()[name] || undefined\n}\n\n/**\n * Set a cookie value by name.\n * @param name Name of the cookie to set\n * @param value Value of the cookie to set\n * @param options {CookieSerializeOptions} Options for serializing the cookie\n * ```ts\n * setCookie('Authorization', '1234567')\n * ```\n */\nexport function setCookie(\n name: string,\n value: string,\n options?: CookieSerializeOptions,\n): void {\n const event = getH3Event()\n h3_setCookie(event, name, value, options)\n}\n\n/**\n * Remove a cookie by name.\n * @param name Name of the cookie to delete\n * @param serializeOptions {CookieSerializeOptions} Cookie options\n * ```ts\n * deleteCookie('SessionId')\n * ```\n */\nexport function deleteCookie(\n name: string,\n options?: CookieSerializeOptions,\n): void {\n const event = getH3Event()\n h3_deleteCookie(event, name, options)\n}\n\nfunction getDefaultSessionConfig(config: SessionConfig): SessionConfig {\n return {\n name: 'start',\n ...config,\n }\n}\n\n/**\n * Create a session manager for the current request.\n */\nexport function useSession<TSessionData extends SessionData = SessionData>(\n config: SessionConfig,\n): Promise<SessionManager<TSessionData>> {\n const event = getH3Event()\n return h3_useSession(event, getDefaultSessionConfig(config))\n}\n/**\n * Get the session for the current request\n */\nexport function getSession<TSessionData extends SessionData = SessionData>(\n config: SessionConfig,\n): Promise<Session<TSessionData>> {\n const event = getH3Event()\n return h3_getSession(event, getDefaultSessionConfig(config))\n}\n\n/**\n * Update the session data for the current request.\n */\nexport function updateSession<TSessionData extends SessionData = SessionData>(\n config: SessionConfig,\n update?: SessionUpdate<TSessionData>,\n): Promise<Session<TSessionData>> {\n const event = getH3Event()\n return h3_updateSession(event, getDefaultSessionConfig(config), update)\n}\n\n/**\n * Encrypt and sign the session data for the current request.\n */\nexport function sealSession(config: SessionConfig): Promise<string> {\n const event = getH3Event()\n return h3_sealSession(event, getDefaultSessionConfig(config))\n}\n/**\n * Decrypt and verify the session data for the current request.\n */\nexport function unsealSession(\n config: SessionConfig,\n sealed: string,\n): Promise<Partial<Session>> {\n const event = getH3Event()\n return h3_unsealSession(event, getDefaultSessionConfig(config), sealed)\n}\n\n/**\n * Clear the session data for the current request.\n */\nexport function clearSession(config: Partial<SessionConfig>): Promise<void> {\n const event = getH3Event()\n return h3_clearSession(event, { name: 'start', ...config })\n}\n\nexport function getResponse() {\n const event = getH3Event()\n return event.res\n}\n\n// not public API (yet)\nexport function getValidatedQuery<TSchema extends StandardSchemaV1>(\n schema: StandardSchemaV1,\n): Promise<StandardSchemaV1.InferOutput<TSchema>> {\n return h3_getValidatedQuery(getH3Event(), schema)\n}\n"],"names":["h3_toResponse","h3_getRequestIP","h3_getRequestHost","h3_getRequestURL","h3_getRequestProtocol","h3_sanitizeStatusCode","h3_sanitizeStatusMessage","h3_parseCookies","h3_setCookie","h3_deleteCookie","h3_useSession","h3_getSession","h3_updateSession","h3_sealSession","h3_unsealSession","h3_clearSession","h3_getValidatedQuery"],"mappings":";;AA+CA,MAAM,2BAA2B,OAAO,IAAI,8BAA8B;AAE1E,MAAM,YAAY;AAIlB,IAAI,CAAC,UAAU,wBAAwB,GAAG;AACxC,YAAU,wBAAwB,IAAI,IAAI,kBAAA;AAC5C;AAEA,MAAM,eAAe,UAAU,wBAAwB;AAUvD,SAAS,cAAiB,OAA6C;AACrE,SAAO,OAAQ,MAAqB,SAAS;AAC/C;AAEA,SAAS,mBAAmB,SAAiC;AAC3D,QAAM,uBAAuB;AAC7B,MAAI,OAAO,qBAAqB,iBAAiB,YAAY;AAC3D,WAAO,qBAAqB,aAAA;AAAA,EAC9B;AACA,QAAM,QAAQ,QAAQ,IAAI,YAAY;AACtC,SAAO,QAAQ,CAAC,KAAK,IAAI,CAAA;AAC3B;AAEA,SAAS,0BAA0B,UAAoB,OAAsB;AAC3E,MAAI,SAAS,IAAI;AACf;AAAA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WAAA;AACd,SAAOC,gBAAiB,OAAO,wBAAwB,MAAM,GAAG,MAAM;AACxE;AAKO,SAAS,aAAa,QAA+C;AAC1E,QAAM,QAAQ,WAAA;AACd,SAAOC,eAAgB,OAAO,EAAE,MAAM,SAAS,GAAG,QAAQ;AAC5D;AAEO,SAAS,cAAc;AAC5B,QAAM,QAAQ,WAAA;AACd,SAAO,MAAM;AACf;AAGO,SAAS,kBACd,QACgD;AAChD,SAAOC,oBAAqB,WAAA,GAAc,MAAM;AAClD;"}
1
+ {"version":3,"file":"request-response.js","sources":["../../src/request-response.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks'\n\nimport {\n H3Event,\n clearSession as h3_clearSession,\n deleteCookie as h3_deleteCookie,\n getRequestHost as h3_getRequestHost,\n getRequestIP as h3_getRequestIP,\n getRequestProtocol as h3_getRequestProtocol,\n getRequestURL as h3_getRequestURL,\n getSession as h3_getSession,\n getValidatedQuery as h3_getValidatedQuery,\n parseCookies as h3_parseCookies,\n sanitizeStatusCode as h3_sanitizeStatusCode,\n sanitizeStatusMessage as h3_sanitizeStatusMessage,\n sealSession as h3_sealSession,\n setCookie as h3_setCookie,\n toResponse as h3_toResponse,\n unsealSession as h3_unsealSession,\n updateSession as h3_updateSession,\n useSession as h3_useSession,\n} from 'h3-v2'\nimport type {\n RequestHeaderMap,\n RequestHeaderName,\n ResponseHeaderMap,\n ResponseHeaderName,\n TypedHeaders,\n} from 'fetchdts'\n\nimport type { CookieSerializeOptions } from 'cookie-es'\nimport type {\n Session,\n SessionConfig,\n SessionData,\n SessionManager,\n SessionUpdate,\n} from './session'\nimport type { StandardSchemaV1 } from '@standard-schema/spec'\nimport type { RequestHandler } from './request-handler'\n\ninterface StartEvent {\n h3Event: H3Event\n}\n\n// Use a global symbol to ensure the same AsyncLocalStorage instance is shared\n// across different bundles that may each bundle this module.\nconst GLOBAL_EVENT_STORAGE_KEY = Symbol.for('tanstack-start:event-storage')\n\nconst globalObj = globalThis as typeof globalThis & {\n [GLOBAL_EVENT_STORAGE_KEY]?: AsyncLocalStorage<StartEvent>\n}\n\nif (!globalObj[GLOBAL_EVENT_STORAGE_KEY]) {\n globalObj[GLOBAL_EVENT_STORAGE_KEY] = new AsyncLocalStorage<StartEvent>()\n}\n\nconst eventStorage = globalObj[GLOBAL_EVENT_STORAGE_KEY]\n\nexport type { ResponseHeaderName, RequestHeaderName }\n\ntype HeadersWithGetSetCookie = Headers & {\n getSetCookie?: () => Array<string>\n}\n\ntype MaybePromise<T> = T | Promise<T>\n\nfunction isPromiseLike<T>(value: MaybePromise<T>): value is Promise<T> {\n return typeof (value as Promise<T>).then === 'function'\n}\n\nfunction getSetCookieValues(headers: Headers): Array<string> {\n const headersWithSetCookie = headers as HeadersWithGetSetCookie\n if (typeof headersWithSetCookie.getSetCookie === 'function') {\n return headersWithSetCookie.getSetCookie()\n }\n const value = headers.get('set-cookie')\n return value ? [value] : []\n}\n\nfunction mergeEventResponseHeaders(response: Response, event: H3Event): void {\n if (response.ok) {\n return\n }\n\n const eventSetCookies = getSetCookieValues(event.res.headers)\n if (eventSetCookies.length === 0) {\n return\n }\n\n const responseSetCookies = getSetCookieValues(response.headers)\n response.headers.delete('set-cookie')\n for (const cookie of responseSetCookies) {\n response.headers.append('set-cookie', cookie)\n }\n for (const cookie of eventSetCookies) {\n response.headers.append('set-cookie', cookie)\n }\n}\n\nfunction attachResponseHeaders<T>(\n value: MaybePromise<T>,\n event: H3Event,\n): MaybePromise<T> {\n if (isPromiseLike(value)) {\n return value.then((resolved) => {\n if (resolved instanceof Response) {\n mergeEventResponseHeaders(resolved, event)\n }\n return resolved\n })\n }\n\n if (value instanceof Response) {\n mergeEventResponseHeaders(value, event)\n }\n\n return value\n}\n\nexport function requestHandler<TRegister = unknown>(\n handler: RequestHandler<TRegister>,\n) {\n return (request: Request, requestOpts: any): Promise<Response> | Response => {\n const h3Event = new H3Event(request)\n\n const response = eventStorage.run({ h3Event }, () =>\n handler(request, requestOpts),\n )\n return h3_toResponse(attachResponseHeaders(response, h3Event), h3Event)\n }\n}\n\nfunction getH3Event() {\n const event = eventStorage.getStore()\n if (!event) {\n throw new Error(\n `No StartEvent found in AsyncLocalStorage. Make sure you are using the function within the server runtime.`,\n )\n }\n return event.h3Event\n}\n\nexport function getRequest(): Request {\n const event = getH3Event()\n return event.req\n}\n\nexport function getRequestHeaders(): TypedHeaders<RequestHeaderMap> {\n // TODO `as any` not needed when fetchdts is updated\n return getH3Event().req.headers as any\n}\n\nexport function getRequestHeader(name: RequestHeaderName): string | undefined {\n return getRequestHeaders().get(name) || undefined\n}\n\nexport function getRequestIP(opts?: {\n /**\n * Use the X-Forwarded-For HTTP header set by proxies.\n *\n * Note: Make sure that this header can be trusted (your application running behind a CDN or reverse proxy) before enabling.\n */\n xForwardedFor?: boolean\n}) {\n return h3_getRequestIP(getH3Event(), opts)\n}\n\n/**\n * Get the request hostname.\n *\n * If `xForwardedHost` is `true`, it will use the `x-forwarded-host` header if it exists.\n *\n * If no host header is found, it will default to \"localhost\".\n */\nexport function getRequestHost(opts?: { xForwardedHost?: boolean }) {\n return h3_getRequestHost(getH3Event(), opts)\n}\n\n/**\n * Get the full incoming request URL.\n *\n * If `xForwardedHost` is `true`, it will use the `x-forwarded-host` header if it exists.\n *\n * If `xForwardedProto` is `false`, it will not use the `x-forwarded-proto` header.\n */\nexport function getRequestUrl(opts?: {\n xForwardedHost?: boolean\n xForwardedProto?: boolean\n}) {\n return h3_getRequestURL(getH3Event(), opts)\n}\n\n/**\n * Get the request protocol.\n *\n * If `x-forwarded-proto` header is set to \"https\", it will return \"https\". You can disable this behavior by setting `xForwardedProto` to `false`.\n *\n * If protocol cannot be determined, it will default to \"http\".\n */\nexport function getRequestProtocol(opts?: {\n xForwardedProto?: boolean\n}): 'http' | 'https' | (string & {}) {\n return h3_getRequestProtocol(getH3Event(), opts)\n}\n\nexport function setResponseHeaders(\n headers: TypedHeaders<ResponseHeaderMap>,\n): void {\n const event = getH3Event()\n for (const [name, value] of Object.entries(headers)) {\n event.res.headers.set(name, value)\n }\n}\n\nexport function getResponseHeaders(): TypedHeaders<ResponseHeaderMap> {\n const event = getH3Event()\n return event.res.headers\n}\n\nexport function getResponseHeader(\n name: ResponseHeaderName,\n): string | undefined {\n const event = getH3Event()\n return event.res.headers.get(name) || undefined\n}\n\nexport function setResponseHeader(\n name: ResponseHeaderName,\n value: string | Array<string>,\n): void {\n const event = getH3Event()\n if (Array.isArray(value)) {\n event.res.headers.delete(name)\n for (const valueItem of value) {\n event.res.headers.append(name, valueItem)\n }\n } else {\n event.res.headers.set(name, value)\n }\n}\nexport function removeResponseHeader(name: ResponseHeaderName): void {\n const event = getH3Event()\n event.res.headers.delete(name)\n}\n\nexport function clearResponseHeaders(\n headerNames?: Array<ResponseHeaderName>,\n): void {\n const event = getH3Event()\n // If headerNames is provided, clear only those headers\n if (headerNames && headerNames.length > 0) {\n for (const name of headerNames) {\n event.res.headers.delete(name)\n }\n // Otherwise, clear all headers\n } else {\n for (const name of event.res.headers.keys()) {\n event.res.headers.delete(name)\n }\n }\n}\n\nexport function getResponseStatus(): number {\n return getH3Event().res.status || 200\n}\n\nexport function setResponseStatus(code?: number, text?: string): void {\n const event = getH3Event()\n if (code) {\n event.res.status = h3_sanitizeStatusCode(code, event.res.status)\n }\n if (text) {\n event.res.statusText = h3_sanitizeStatusMessage(text)\n }\n}\n\n/**\n * Parse the request to get HTTP Cookie header string and return an object of all cookie name-value pairs.\n * @returns Object of cookie name-value pairs\n * ```ts\n * const cookies = getCookies()\n * ```\n */\nexport function getCookies(): Record<string, string> {\n const event = getH3Event()\n return h3_parseCookies(event)\n}\n\n/**\n * Get a cookie value by name.\n * @param name Name of the cookie to get\n * @returns {*} Value of the cookie (String or undefined)\n * ```ts\n * const authorization = getCookie('Authorization')\n * ```\n */\nexport function getCookie(name: string): string | undefined {\n return getCookies()[name] || undefined\n}\n\n/**\n * Set a cookie value by name.\n * @param name Name of the cookie to set\n * @param value Value of the cookie to set\n * @param options {CookieSerializeOptions} Options for serializing the cookie\n * ```ts\n * setCookie('Authorization', '1234567')\n * ```\n */\nexport function setCookie(\n name: string,\n value: string,\n options?: CookieSerializeOptions,\n): void {\n const event = getH3Event()\n h3_setCookie(event, name, value, options)\n}\n\n/**\n * Remove a cookie by name.\n * @param name Name of the cookie to delete\n * @param serializeOptions {CookieSerializeOptions} Cookie options\n * ```ts\n * deleteCookie('SessionId')\n * ```\n */\nexport function deleteCookie(\n name: string,\n options?: CookieSerializeOptions,\n): void {\n const event = getH3Event()\n h3_deleteCookie(event, name, options)\n}\n\nfunction getDefaultSessionConfig(config: SessionConfig): SessionConfig {\n return {\n name: 'start',\n ...config,\n }\n}\n\n/**\n * Create a session manager for the current request.\n */\nexport function useSession<TSessionData extends SessionData = SessionData>(\n config: SessionConfig,\n): Promise<SessionManager<TSessionData>> {\n const event = getH3Event()\n return h3_useSession(event, getDefaultSessionConfig(config))\n}\n/**\n * Get the session for the current request\n */\nexport function getSession<TSessionData extends SessionData = SessionData>(\n config: SessionConfig,\n): Promise<Session<TSessionData>> {\n const event = getH3Event()\n return h3_getSession(event, getDefaultSessionConfig(config))\n}\n\n/**\n * Update the session data for the current request.\n */\nexport function updateSession<TSessionData extends SessionData = SessionData>(\n config: SessionConfig,\n update?: SessionUpdate<TSessionData>,\n): Promise<Session<TSessionData>> {\n const event = getH3Event()\n return h3_updateSession(event, getDefaultSessionConfig(config), update)\n}\n\n/**\n * Encrypt and sign the session data for the current request.\n */\nexport function sealSession(config: SessionConfig): Promise<string> {\n const event = getH3Event()\n return h3_sealSession(event, getDefaultSessionConfig(config))\n}\n/**\n * Decrypt and verify the session data for the current request.\n */\nexport function unsealSession(\n config: SessionConfig,\n sealed: string,\n): Promise<Partial<Session>> {\n const event = getH3Event()\n return h3_unsealSession(event, getDefaultSessionConfig(config), sealed)\n}\n\n/**\n * Clear the session data for the current request.\n */\nexport function clearSession(config: Partial<SessionConfig>): Promise<void> {\n const event = getH3Event()\n return h3_clearSession(event, { name: 'start', ...config })\n}\n\nexport function getResponse() {\n const event = getH3Event()\n return event.res\n}\n\n// not public API (yet)\nexport function getValidatedQuery<TSchema extends StandardSchemaV1>(\n schema: StandardSchemaV1,\n): Promise<StandardSchemaV1.InferOutput<TSchema>> {\n return h3_getValidatedQuery(getH3Event(), schema)\n}\n"],"names":["h3_toResponse","h3_getRequestIP","h3_getRequestHost","h3_getRequestURL","h3_getRequestProtocol","h3_sanitizeStatusCode","h3_sanitizeStatusMessage","h3_parseCookies","h3_setCookie","h3_deleteCookie","h3_useSession","h3_getSession","h3_updateSession","h3_sealSession","h3_unsealSession","h3_clearSession","h3_getValidatedQuery"],"mappings":";;AA+CA,MAAM,2BAA2B,uBAAO,IAAI,8BAA8B;AAE1E,MAAM,YAAY;AAIlB,IAAI,CAAC,UAAU,wBAAwB,GAAG;AACxC,YAAU,wBAAwB,IAAI,IAAI,kBAAA;AAC5C;AAEA,MAAM,eAAe,UAAU,wBAAwB;AAUvD,SAAS,cAAiB,OAA6C;AACrE,SAAO,OAAQ,MAAqB,SAAS;AAC/C;AAEA,SAAS,mBAAmB,SAAiC;AAC3D,QAAM,uBAAuB;AAC7B,MAAI,OAAO,qBAAqB,iBAAiB,YAAY;AAC3D,WAAO,qBAAqB,aAAA;AAAA,EAC9B;AACA,QAAM,QAAQ,QAAQ,IAAI,YAAY;AACtC,SAAO,QAAQ,CAAC,KAAK,IAAI,CAAA;AAC3B;AAEA,SAAS,0BAA0B,UAAoB,OAAsB;AAC3E,MAAI,SAAS,IAAI;AACf;AAAA,EACF;AAEA,QAAM,kBAAkB,mBAAmB,MAAM,IAAI,OAAO;AAC5D,MAAI,gBAAgB,WAAW,GAAG;AAChC;AAAA,EACF;AAEA,QAAM,qBAAqB,mBAAmB,SAAS,OAAO;AAC9D,WAAS,QAAQ,OAAO,YAAY;AACpC,aAAW,UAAU,oBAAoB;AACvC,aAAS,QAAQ,OAAO,cAAc,MAAM;AAAA,EAC9C;AACA,aAAW,UAAU,iBAAiB;AACpC,aA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AqB,WAAA,GAAc,MAAM;AAClD;"}
@@ -1 +1 @@
1
- {"version":3,"file":"router-manifest.js","sources":["../../src/router-manifest.ts"],"sourcesContent":["import { buildDevStylesUrl, rootRouteId } from '@tanstack/router-core'\nimport type { AnyRoute, RouterManagedTag } from '@tanstack/router-core'\n\n// Pre-computed constant for dev styles URL\nconst ROUTER_BASEPATH = process.env.TSS_ROUTER_BASEPATH || '/'\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 *\n * @param matchedRoutes - In dev mode, the matched routes are used to build\n * the dev styles URL for route-scoped CSS collection.\n */\nexport async function getStartManifest(\n matchedRoutes?: ReadonlyArray<AnyRoute>,\n) {\n const { tsrStartManifest } = await import('tanstack-start-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 // Inject dev styles link in dev mode\n if (process.env.TSS_DEV_SERVER === 'true' && matchedRoutes) {\n const matchedRouteIds = matchedRoutes.map((route) => route.id)\n rootRoute.assets.push({\n tag: 'link',\n attrs: {\n rel: 'stylesheet',\n href: buildDevStylesUrl(ROUTER_BASEPATH, matchedRouteIds),\n 'data-tanstack-router-dev-styles': 'true',\n },\n })\n }\n\n let script = `import('${startManifest.clientEntry}')`\n if (process.env.TSS_DEV_SERVER === 'true') {\n const { injectedHeadScripts } = await import(\n 'tanstack-start-injected-head-scripts:v'\n )\n if (injectedHeadScripts) {\n script = `${injectedHeadScripts + ';'}${script}`\n }\n }\n rootRoute.assets.push({\n tag: 'script',\n attrs: {\n type: 'module',\n async: true,\n },\n children: script,\n })\n\n const manifest = {\n routes: Object.fromEntries(\n Object.entries(startManifest.routes).flatMap(([k, v]) => {\n const result = {} as {\n preloads?: Array<string>\n assets?: Array<RouterManagedTag>\n }\n let hasData = false\n if (v.preloads && v.preloads.length > 0) {\n result['preloads'] = v.preloads\n hasData = true\n }\n if (v.assets && v.assets.length > 0) {\n result['assets'] = v.assets\n hasData = true\n }\n if (!hasData) {\n return []\n }\n return [[k, result]]\n }),\n ),\n }\n\n // Strip out anything that isn't needed for the client\n return manifest\n}\n"],"names":[],"mappings":";AAIA,MAAM,kBAAkB,QAAQ,IAAI,uBAAuB;AAW3D,eAAsB,iBACpB,eACA;AACA,QAAM,EAAE,iBAAA,IAAqB,MAAM,OAAO,2BAA2B;AACrE,QAAM,gBAAgB,iBAAA;AAEtB,QAAM,YAAa,cAAc,OAAO,WAAW,IACjD,cAAc,OAAO,WAAW,KAAK,CAAA;AAEvC,YAAU,SAAS,UAAU,UAAU,CAAA;AAGvC,MAAI,QAAQ,IAAI,mBAAmB,UAAU,eAAe;AAC1D,UAAM,kBAAkB,cAAc,IAAI,CAAC,UAAU,MAAM,EAAE;AAC7D,cAAU,OAAO,KAAK;AAAA,MACpB,KAAK;AAAA,MACL,OAAO;AAAA,QACL,KAAK;AAAA,QACL,MAAM,kBAAkB,iBAAiB,eAAe;AAAA,QACxD,mCAAmC;AAAA,MAAA;AAAA,IACrC,CACD;AAAA,EACH;AAEA,MAAI,SAAS,WAAW,cAAc,WAAW;AACjD,MAAI,QAAQ,IAAI,mBAAmB,QAAQ;AACzC,UAAM,EAAE,oBAAA,IAAwB,MAAM,OACpC,wCACF;AACA,QAAI,qBAAqB;AACvB,eAAS,GAAG,sBAAsB,GAAG,GAAG,MAAM;AAAA,IAChD;AAAA,EACF;AACA,YAAU,OAAO,KAAK;AAAA,IACpB,KAAK;AAAA,IACL,OAAO;AAAA,MACL,MAAM;AAAA,MACN,OAAO;AAAA,IAAA;AAAA,IAET,UAAU;AAAA,EAAA,CACX;AAED,QAAM,WAAW;AAAA,IACf,QAAQ,OAAO;AAAA,MACb,OAAO,QAAQ,cAAc,MAAM,EAAE,QAAQ,CAAC,CAAC,GAAG,CAAC,MAAM;AACvD,cAAM,SAAS,CAAA;AAIf,YAAI,UAAU;AACd,YAAI,EAAE,YAAY,EAAE,SAAS,SAAS,GAAG;AACvC,iBAAO,UAAU,IAAI,EAAE;AACvB,oBAAU;AAAA,QACZ;AACA,YAAI,EAAE,UAAU,EAAE,OAAO,SAAS,GAAG;AACnC,iBAAO,QAAQ,IAAI,EAAE;AACrB,oBAAU;AAAA,QACZ;AACA,YAAI,CAAC,SAAS;AACZ,iBAAO,CAAA;AAAA,QACT;AACA,eAAO,CAAC,CAAC,GAAG,MAAM,CAAC;AAAA,MACrB,CAAC;AAAA,IAAA;AAAA,EACH;AAIF,SAAO;AACT;"}
1
+ {"version":3,"file":"router-manifest.js","sources":["../../src/router-manifest.ts"],"sourcesContent":["import { buildDevStylesUrl, rootRouteId } from '@tanstack/router-core'\nimport type { AnyRoute, RouterManagedTag } from '@tanstack/router-core'\n\n// Pre-computed constant for dev styles URL\nconst ROUTER_BASEPATH = process.env.TSS_ROUTER_BASEPATH || '/'\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 *\n * @param matchedRoutes - In dev mode, the matched routes are used to build\n * the dev styles URL for route-scoped CSS collection.\n */\nexport async function getStartManifest(\n matchedRoutes?: ReadonlyArray<AnyRoute>,\n) {\n const { tsrStartManifest } = await import('tanstack-start-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 // Inject dev styles link in dev mode\n if (process.env.TSS_DEV_SERVER === 'true' && matchedRoutes) {\n const matchedRouteIds = matchedRoutes.map((route) => route.id)\n rootRoute.assets.push({\n tag: 'link',\n attrs: {\n rel: 'stylesheet',\n href: buildDevStylesUrl(ROUTER_BASEPATH, matchedRouteIds),\n 'data-tanstack-router-dev-styles': 'true',\n },\n })\n }\n\n let script = `import('${startManifest.clientEntry}')`\n if (process.env.TSS_DEV_SERVER === 'true') {\n const { injectedHeadScripts } =\n await import('tanstack-start-injected-head-scripts:v')\n if (injectedHeadScripts) {\n script = `${injectedHeadScripts + ';'}${script}`\n }\n }\n rootRoute.assets.push({\n tag: 'script',\n attrs: {\n type: 'module',\n async: true,\n },\n children: script,\n })\n\n const manifest = {\n routes: Object.fromEntries(\n Object.entries(startManifest.routes).flatMap(([k, v]) => {\n const result = {} as {\n preloads?: Array<string>\n assets?: Array<RouterManagedTag>\n }\n let hasData = false\n if (v.preloads && v.preloads.length > 0) {\n result['preloads'] = v.preloads\n hasData = true\n }\n if (v.assets && v.assets.length > 0) {\n result['assets'] = v.assets\n hasData = true\n }\n if (!hasData) {\n return []\n }\n return [[k, result]]\n }),\n ),\n }\n\n // Strip out anything that isn't needed for the client\n return manifest\n}\n"],"names":[],"mappings":";AAIA,MAAM,kBAAkB,QAAQ,IAAI,uBAAuB;AAW3D,eAAsB,iBACpB,eACA;AACA,QAAM,EAAE,iBAAA,IAAqB,MAAM,OAAO,2BAA2B;AACrE,QAAM,gBAAgB,iBAAA;AAEtB,QAAM,YAAa,cAAc,OAAO,WAAW,IACjD,cAAc,OAAO,WAAW,KAAK,CAAA;AAEvC,YAAU,SAAS,UAAU,UAAU,CAAA;AAGvC,MAAI,QAAQ,IAAI,mBAAmB,UAAU,eAAe;AAC1D,UAAM,kBAAkB,cAAc,IAAI,CAAC,UAAU,MAAM,EAAE;AAC7D,cAAU,OAAO,KAAK;AAAA,MACpB,KAAK;AAAA,MACL,OAAO;AAAA,QACL,KAAK;AAAA,QACL,MAAM,kBAAkB,iBAAiB,eAAe;AAAA,QACxD,mCAAmC;AAAA,MAAA;AAAA,IACrC,CACD;AAAA,EACH;AAEA,MAAI,SAAS,WAAW,cAAc,WAAW;AACjD,MAAI,QAAQ,IAAI,mBAAmB,QAAQ;AACzC,UAAM,EAAE,oBAAA,IACN,MAAM,OAAO,wCAAwC;AACvD,QAAI,qBAAqB;AACvB,eAAS,GAAG,sBAAsB,GAAG,GAAG,MAAM;AAAA,IAChD;AAAA,EACF;AACA,YAAU,OAAO,KAAK;AAAA,IACpB,KAAK;AAAA,IACL,OAAO;AAAA,MACL,MAAM;AAAA,MACN,OAAO;AAAA,IAAA;AAAA,IAET,UAAU;AAAA,EAAA,CACX;AAED,QAAM,WAAW;AAAA,IACf,QAAQ,OAAO;AAAA,MACb,OAAO,QAAQ,cAAc,MAAM,EAAE,QAAQ,CAAC,CAAC,GAAG,CAAC,MAAM;AACvD,cAAM,SAAS,CAAA;AAIf,YAAI,UAAU;AACd,YAAI,EAAE,YAAY,EAAE,SAAS,SAAS,GAAG;AACvC,iBAAO,UAAU,IAAI,EAAE;AACvB,oBAAU;AAAA,QACZ;AACA,YAAI,EAAE,UAAU,EAAE,OAAO,SAAS,GAAG;AACnC,iBAAO,QAAQ,IAAI,EAAE;AACrB,oBAAU;AAAA,QACZ;AACA,YAAI,CAAC,SAAS;AACZ,iBAAO,CAAA;AAAA,QACT;AACA,eAAO,CAAC,CAAC,GAAG,MAAM,CAAC;AAAA,MACrB,CAAC;AAAA,IAAA;AAAA,EACH;AAIF,SAAO;AACT;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/start-server-core",
3
- "version": "1.151.2",
3
+ "version": "1.151.6",
4
4
  "description": "Modern and scalable routing for React applications",
5
5
  "author": "Tanner Linsley",
6
6
  "license": "MIT",
@@ -64,9 +64,9 @@
64
64
  "seroval": "^1.4.1",
65
65
  "tiny-invariant": "^1.3.3",
66
66
  "@tanstack/history": "1.151.1",
67
- "@tanstack/router-core": "1.151.2",
68
- "@tanstack/start-storage-context": "1.151.2",
69
- "@tanstack/start-client-core": "1.151.2"
67
+ "@tanstack/start-client-core": "1.151.6",
68
+ "@tanstack/router-core": "1.151.6",
69
+ "@tanstack/start-storage-context": "1.151.6"
70
70
  },
71
71
  "devDependencies": {
72
72
  "@standard-schema/spec": "^1.0.0",
@@ -12,6 +12,7 @@ import {
12
12
  } from '@tanstack/router-core'
13
13
  import {
14
14
  attachRouterServerSsrUtils,
15
+ getNormalizedURL,
15
16
  getOrigin,
16
17
  } from '@tanstack/router-core/ssr/server'
17
18
  import { runWithStartContext } from '@tanstack/start-storage-context'
@@ -216,8 +217,9 @@ export function createStartHandler<TRegister = Register>(
216
217
  let cbWillCleanup = false as boolean
217
218
 
218
219
  try {
219
- const url = new URL(request.url)
220
- const href = url.href.replace(url.origin, '')
220
+ // normalizing and sanitizing the pathname here for server, so we always deal with the same format during SSR.
221
+ const url = getNormalizedURL(request.url)
222
+ const href = url.pathname + url.search + url.hash
221
223
  const origin = getOrigin(request)
222
224
 
223
225
  const entries = await getEntries()
@@ -39,9 +39,8 @@ export async function getStartManifest(
39
39
 
40
40
  let script = `import('${startManifest.clientEntry}')`
41
41
  if (process.env.TSS_DEV_SERVER === 'true') {
42
- const { injectedHeadScripts } = await import(
43
- 'tanstack-start-injected-head-scripts:v'
44
- )
42
+ const { injectedHeadScripts } =
43
+ await import('tanstack-start-injected-head-scripts:v')
45
44
  if (injectedHeadScripts) {
46
45
  script = `${injectedHeadScripts + ';'}${script}`
47
46
  }