@tanstack/start-server-core 1.142.3 → 1.142.4

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.
@@ -6,6 +6,48 @@ if (!globalObj[GLOBAL_EVENT_STORAGE_KEY]) {
6
6
  globalObj[GLOBAL_EVENT_STORAGE_KEY] = new AsyncLocalStorage();
7
7
  }
8
8
  const eventStorage = globalObj[GLOBAL_EVENT_STORAGE_KEY];
9
+ function isPromiseLike(value) {
10
+ return typeof value.then === "function";
11
+ }
12
+ function getSetCookieValues(headers) {
13
+ const headersWithSetCookie = headers;
14
+ if (typeof headersWithSetCookie.getSetCookie === "function") {
15
+ return headersWithSetCookie.getSetCookie();
16
+ }
17
+ const value = headers.get("set-cookie");
18
+ return value ? [value] : [];
19
+ }
20
+ function mergeEventResponseHeaders(response, event) {
21
+ if (response.ok) {
22
+ return;
23
+ }
24
+ const eventSetCookies = getSetCookieValues(event.res.headers);
25
+ if (eventSetCookies.length === 0) {
26
+ return;
27
+ }
28
+ const responseSetCookies = getSetCookieValues(response.headers);
29
+ response.headers.delete("set-cookie");
30
+ for (const cookie of responseSetCookies) {
31
+ response.headers.append("set-cookie", cookie);
32
+ }
33
+ for (const cookie of eventSetCookies) {
34
+ response.headers.append("set-cookie", cookie);
35
+ }
36
+ }
37
+ function attachResponseHeaders(value, event) {
38
+ if (isPromiseLike(value)) {
39
+ return value.then((resolved) => {
40
+ if (resolved instanceof Response) {
41
+ mergeEventResponseHeaders(resolved, event);
42
+ }
43
+ return resolved;
44
+ });
45
+ }
46
+ if (value instanceof Response) {
47
+ mergeEventResponseHeaders(value, event);
48
+ }
49
+ return value;
50
+ }
9
51
  function requestHandler(handler) {
10
52
  return (request, requestOpts) => {
11
53
  const h3Event = new H3Event(request);
@@ -13,7 +55,7 @@ function requestHandler(handler) {
13
55
  { h3Event },
14
56
  () => handler(request, requestOpts)
15
57
  );
16
- return toResponse(response, h3Event);
58
+ return toResponse(attachResponseHeaders(response, h3Event), h3Event);
17
59
  };
18
60
  }
19
61
  function getH3Event() {
@@ -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\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(response, 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;AAIhD,SAAS,eACd,SACA;AACA,SAAO,CAAC,SAAkB,gBAAmD;AAC3E,UAAM,UAAU,IAAI,QAAQ,OAAO;AAEnC,UAAM,WAAW,aAAa;AAAA,MAAI,EAAE,QAAA;AAAA,MAAW,MAC7C,QAAQ,SAAS,WAAW;AAAA,IAAA;AAE9B,WAAOA,WAAc,UAAU,OAAO;AAAA,EACxC;AACF;AAEA,SAAS,aAAa;AACpB,QAAM,QAAQ,aAAa,SAAA;AAC3B,MAAI,CAAC,OAAO;AACV,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAAA,EAEJ;AACA,SAAO,MAAM;AACf;AAEO,SAAS,aAAsB;AACpC,QAAM,QAAQ,WAAA;AACd,SAAO,MAAM;AACf;AAEO,SAAS,oBAAoD;AAElE,SAAO,WAAA,EAAa,IAAI;AAC1B;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,wBAAwB,MAAM,CAAC;AAC9D;AAIO,SAAS,cACd,QACA,QAC2B;AAC3B,QAAM,QAAQ,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,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,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,a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,QAAQ,WAAA;AACd,SAAO,MAAM;AACf;AAGO,SAAS,kBACd,QACgD;AAChD,SAAOC,oBAAqB,WAAA,GAAc,MAAM;AAClD;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/start-server-core",
3
- "version": "1.142.3",
3
+ "version": "1.142.4",
4
4
  "description": "Modern and scalable routing for React applications",
5
5
  "author": "Tanner Linsley",
6
6
  "license": "MIT",
@@ -60,13 +60,13 @@
60
60
  "node": ">=22.12.0"
61
61
  },
62
62
  "dependencies": {
63
- "h3-v2": "npm:h3@2.0.1-rc.2",
63
+ "h3-v2": "npm:h3@2.0.1-rc.6",
64
64
  "seroval": "^1.4.1",
65
65
  "tiny-invariant": "^1.3.3",
66
- "@tanstack/router-core": "1.141.8",
67
66
  "@tanstack/history": "1.141.0",
68
- "@tanstack/start-storage-context": "1.142.1",
69
- "@tanstack/start-client-core": "1.142.1"
67
+ "@tanstack/router-core": "1.141.8",
68
+ "@tanstack/start-client-core": "1.142.1",
69
+ "@tanstack/start-storage-context": "1.142.1"
70
70
  },
71
71
  "devDependencies": {
72
72
  "@standard-schema/spec": "^1.0.0",
@@ -59,6 +59,65 @@ const eventStorage = globalObj[GLOBAL_EVENT_STORAGE_KEY]
59
59
 
60
60
  export type { ResponseHeaderName, RequestHeaderName }
61
61
 
62
+ type HeadersWithGetSetCookie = Headers & {
63
+ getSetCookie?: () => Array<string>
64
+ }
65
+
66
+ type MaybePromise<T> = T | Promise<T>
67
+
68
+ function isPromiseLike<T>(value: MaybePromise<T>): value is Promise<T> {
69
+ return typeof (value as Promise<T>).then === 'function'
70
+ }
71
+
72
+ function getSetCookieValues(headers: Headers): Array<string> {
73
+ const headersWithSetCookie = headers as HeadersWithGetSetCookie
74
+ if (typeof headersWithSetCookie.getSetCookie === 'function') {
75
+ return headersWithSetCookie.getSetCookie()
76
+ }
77
+ const value = headers.get('set-cookie')
78
+ return value ? [value] : []
79
+ }
80
+
81
+ function mergeEventResponseHeaders(response: Response, event: H3Event): void {
82
+ if (response.ok) {
83
+ return
84
+ }
85
+
86
+ const eventSetCookies = getSetCookieValues(event.res.headers)
87
+ if (eventSetCookies.length === 0) {
88
+ return
89
+ }
90
+
91
+ const responseSetCookies = getSetCookieValues(response.headers)
92
+ response.headers.delete('set-cookie')
93
+ for (const cookie of responseSetCookies) {
94
+ response.headers.append('set-cookie', cookie)
95
+ }
96
+ for (const cookie of eventSetCookies) {
97
+ response.headers.append('set-cookie', cookie)
98
+ }
99
+ }
100
+
101
+ function attachResponseHeaders<T>(
102
+ value: MaybePromise<T>,
103
+ event: H3Event,
104
+ ): MaybePromise<T> {
105
+ if (isPromiseLike(value)) {
106
+ return value.then((resolved) => {
107
+ if (resolved instanceof Response) {
108
+ mergeEventResponseHeaders(resolved, event)
109
+ }
110
+ return resolved
111
+ })
112
+ }
113
+
114
+ if (value instanceof Response) {
115
+ mergeEventResponseHeaders(value, event)
116
+ }
117
+
118
+ return value
119
+ }
120
+
62
121
  export function requestHandler<TRegister = unknown>(
63
122
  handler: RequestHandler<TRegister>,
64
123
  ) {
@@ -68,7 +127,7 @@ export function requestHandler<TRegister = unknown>(
68
127
  const response = eventStorage.run({ h3Event }, () =>
69
128
  handler(request, requestOpts),
70
129
  )
71
- return h3_toResponse(response, h3Event)
130
+ return h3_toResponse(attachResponseHeaders(response, h3Event), h3Event)
72
131
  }
73
132
  }
74
133