@tanstack/start-server-core 1.142.1 → 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.
- package/dist/esm/request-response.d.ts +5 -1
- package/dist/esm/request-response.js +44 -2
- package/dist/esm/request-response.js.map +1 -1
- package/dist/esm/server-functions-handler.js +8 -8
- package/dist/esm/server-functions-handler.js.map +1 -1
- package/package.json +4 -4
- package/src/request-response.ts +61 -4
- package/src/server-functions-handler.ts +8 -8
|
@@ -115,5 +115,9 @@ export declare function unsealSession(config: SessionConfig, sealed: string): Pr
|
|
|
115
115
|
* Clear the session data for the current request.
|
|
116
116
|
*/
|
|
117
117
|
export declare function clearSession(config: Partial<SessionConfig>): Promise<void>;
|
|
118
|
-
export declare function getResponse():
|
|
118
|
+
export declare function getResponse(): {
|
|
119
|
+
status?: number;
|
|
120
|
+
statusText?: string;
|
|
121
|
+
get headers(): Headers;
|
|
122
|
+
};
|
|
119
123
|
export declare function getValidatedQuery<TSchema extends StandardSchemaV1>(schema: StandardSchemaV1): Promise<StandardSchemaV1.InferOutput<TSchema>>;
|
|
@@ -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() {
|
|
@@ -147,7 +189,7 @@ function clearSession(config) {
|
|
|
147
189
|
}
|
|
148
190
|
function getResponse() {
|
|
149
191
|
const event = getH3Event();
|
|
150
|
-
return event
|
|
192
|
+
return event.res;
|
|
151
193
|
}
|
|
152
194
|
function getValidatedQuery(schema) {
|
|
153
195
|
return getValidatedQuery$1(getH3Event(), schema);
|
|
@@ -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\n// not public API\nexport function getResponse() {\n const event = getH3Event()\n // @ts-expect-error accessing internal symbol\n return event[Symbol.for('h3.internal.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;A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QAAQ,WAAA;AACd,SAAOC,cAAe,OAAO,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;AAGO,SAAS,cAAc;AAC5B,QAAM,QAAQ,WAAA;AAEd,SAAO,MAAM,OAAO,IAAI,uBAAuB,CAAC;AAClD;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,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AO,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;"}
|
|
@@ -136,8 +136,8 @@ const handleServerAction = async ({
|
|
|
136
136
|
return new Response(
|
|
137
137
|
nonStreamingBody ? JSON.stringify(nonStreamingBody) : void 0,
|
|
138
138
|
{
|
|
139
|
-
status: response2
|
|
140
|
-
statusText: response2
|
|
139
|
+
status: response2.status,
|
|
140
|
+
statusText: response2.statusText,
|
|
141
141
|
headers: {
|
|
142
142
|
"Content-Type": "application/json",
|
|
143
143
|
[X_TSS_SERIALIZED]: "true"
|
|
@@ -163,8 +163,8 @@ const handleServerAction = async ({
|
|
|
163
163
|
}
|
|
164
164
|
});
|
|
165
165
|
return new Response(stream, {
|
|
166
|
-
status: response2
|
|
167
|
-
statusText: response2
|
|
166
|
+
status: response2.status,
|
|
167
|
+
statusText: response2.statusText,
|
|
168
168
|
headers: {
|
|
169
169
|
"Content-Type": "application/x-ndjson",
|
|
170
170
|
[X_TSS_SERIALIZED]: "true"
|
|
@@ -172,8 +172,8 @@ const handleServerAction = async ({
|
|
|
172
172
|
});
|
|
173
173
|
}
|
|
174
174
|
return new Response(void 0, {
|
|
175
|
-
status: response2
|
|
176
|
-
statusText: response2
|
|
175
|
+
status: response2.status,
|
|
176
|
+
statusText: response2.statusText
|
|
177
177
|
});
|
|
178
178
|
} catch (error) {
|
|
179
179
|
if (error instanceof Response) {
|
|
@@ -197,8 +197,8 @@ const handleServerAction = async ({
|
|
|
197
197
|
);
|
|
198
198
|
const response2 = getResponse();
|
|
199
199
|
return new Response(serializedError, {
|
|
200
|
-
status: response2
|
|
201
|
-
statusText: response2
|
|
200
|
+
status: response2.status ?? 500,
|
|
201
|
+
statusText: response2.statusText,
|
|
202
202
|
headers: {
|
|
203
203
|
"Content-Type": "application/json",
|
|
204
204
|
[X_TSS_SERIALIZED]: "true"
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-functions-handler.js","sources":["../../src/server-functions-handler.ts"],"sourcesContent":["import { isNotFound } from '@tanstack/router-core'\nimport invariant from 'tiny-invariant'\nimport {\n TSS_FORMDATA_CONTEXT,\n X_TSS_RAW_RESPONSE,\n X_TSS_SERIALIZED,\n getDefaultSerovalPlugins,\n} from '@tanstack/start-client-core'\nimport { fromJSON, toCrossJSONAsync, toCrossJSONStream } from 'seroval'\nimport { getResponse } from './request-response'\nimport { getServerFnById } from './getServerFnById'\n\nlet regex: RegExp | undefined = undefined\n\nexport const handleServerAction = async ({\n request,\n context,\n}: {\n request: Request\n context: any\n}) => {\n const controller = new AbortController()\n const signal = controller.signal\n const abort = () => controller.abort()\n request.signal.addEventListener('abort', abort)\n\n if (regex === undefined) {\n regex = new RegExp(`${process.env.TSS_SERVER_FN_BASE}([^/?#]+)`)\n }\n\n const method = request.method\n const url = new URL(request.url, 'http://localhost:3000')\n // extract the serverFnId from the url as host/_serverFn/:serverFnId\n // Define a regex to match the path and extract the :thing part\n\n // Execute the regex\n const match = url.pathname.match(regex)\n const serverFnId = match ? match[1] : null\n const search = Object.fromEntries(url.searchParams.entries()) as {\n payload?: any\n createServerFn?: boolean\n }\n\n const isCreateServerFn = 'createServerFn' in search\n\n if (typeof serverFnId !== 'string') {\n throw new Error('Invalid server action param for serverFnId: ' + serverFnId)\n }\n\n const action = await getServerFnById(serverFnId, { fromClient: true })\n\n // Known FormData 'Content-Type' header values\n const formDataContentTypes = [\n 'multipart/form-data',\n 'application/x-www-form-urlencoded',\n ]\n\n const contentType = request.headers.get('Content-Type')\n const serovalPlugins = getDefaultSerovalPlugins()\n\n function parsePayload(payload: any) {\n const parsedPayload = fromJSON(payload, { plugins: serovalPlugins })\n return parsedPayload as any\n }\n\n const response = await (async () => {\n try {\n let result = await (async () => {\n // FormData\n if (\n formDataContentTypes.some(\n (type) => contentType && contentType.includes(type),\n )\n ) {\n // We don't support GET requests with FormData payloads... that seems impossible\n invariant(\n method.toLowerCase() !== 'get',\n 'GET requests with FormData payloads are not supported',\n )\n const formData = await request.formData()\n const serializedContext = formData.get(TSS_FORMDATA_CONTEXT)\n formData.delete(TSS_FORMDATA_CONTEXT)\n\n const params = {\n context,\n data: formData,\n }\n if (typeof serializedContext === 'string') {\n try {\n const parsedContext = JSON.parse(serializedContext)\n const deserializedContext = fromJSON(parsedContext, {\n plugins: serovalPlugins,\n })\n if (\n typeof deserializedContext === 'object' &&\n deserializedContext\n ) {\n params.context = { ...context, ...deserializedContext }\n }\n } catch {}\n }\n\n return await action(params, signal)\n }\n\n // Get requests use the query string\n if (method.toLowerCase() === 'get') {\n invariant(\n isCreateServerFn,\n 'expected GET request to originate from createServerFn',\n )\n // By default the payload is the search params\n let payload: any = search.payload\n // If there's a payload, we should try to parse it\n payload = payload ? parsePayload(JSON.parse(payload)) : {}\n payload.context = { ...context, ...payload.context }\n // Send it through!\n return await action(payload, signal)\n }\n\n if (method.toLowerCase() !== 'post') {\n throw new Error('expected POST method')\n }\n\n let jsonPayload\n if (contentType?.includes('application/json')) {\n jsonPayload = await request.json()\n }\n\n // If this POST request was created by createServerFn,\n // its payload will be the only argument\n if (isCreateServerFn) {\n const payload = jsonPayload ? parsePayload(jsonPayload) : {}\n payload.context = { ...payload.context, ...context }\n return await action(payload, signal)\n }\n\n // Otherwise, we'll spread the payload. Need to\n // support `use server` functions that take multiple\n // arguments.\n return await action(...jsonPayload)\n })()\n\n // Any time we get a Response back, we should just\n // return it immediately.\n if (result.result instanceof Response) {\n result.result.headers.set(X_TSS_RAW_RESPONSE, 'true')\n return result.result\n }\n\n // If this is a non createServerFn request, we need to\n // pull out the result from the result object\n if (!isCreateServerFn) {\n result = result.result\n\n // The result might again be a response,\n // and if it is, return it.\n if (result instanceof Response) {\n return result\n }\n }\n\n // TODO: RSCs Where are we getting this package?\n // if (isValidElement(result)) {\n // const { renderToPipeableStream } = await import(\n // // @ts-expect-error\n // 'react-server-dom/server'\n // )\n\n // const pipeableStream = renderToPipeableStream(result)\n\n // setHeaders(event, {\n // 'Content-Type': 'text/x-component',\n // } as any)\n\n // sendStream(event, response)\n // event._handled = true\n\n // return new Response(null, { status: 200 })\n // }\n\n if (isNotFound(result)) {\n return isNotFoundResponse(result)\n }\n\n const response = getResponse()\n let nonStreamingBody: any = undefined\n\n if (result !== undefined) {\n // first run without the stream in case `result` does not need streaming\n let done = false as boolean\n const callbacks: {\n onParse: (value: any) => void\n onDone: () => void\n onError: (error: any) => void\n } = {\n onParse: (value) => {\n nonStreamingBody = value\n },\n onDone: () => {\n done = true\n },\n onError: (error) => {\n throw error\n },\n }\n toCrossJSONStream(result, {\n refs: new Map(),\n plugins: serovalPlugins,\n onParse(value) {\n callbacks.onParse(value)\n },\n onDone() {\n callbacks.onDone()\n },\n onError: (error) => {\n callbacks.onError(error)\n },\n })\n if (done) {\n return new Response(\n nonStreamingBody ? JSON.stringify(nonStreamingBody) : undefined,\n {\n status: response?.status,\n statusText: response?.statusText,\n headers: {\n 'Content-Type': 'application/json',\n [X_TSS_SERIALIZED]: 'true',\n },\n },\n )\n }\n\n // not done yet, we need to stream\n const encoder = new TextEncoder()\n const stream = new ReadableStream({\n start(controller) {\n callbacks.onParse = (value) =>\n controller.enqueue(encoder.encode(JSON.stringify(value) + '\\n'))\n callbacks.onDone = () => {\n try {\n controller.close()\n } catch (error) {\n controller.error(error)\n }\n }\n callbacks.onError = (error) => controller.error(error)\n // stream the initial body\n if (nonStreamingBody !== undefined) {\n callbacks.onParse(nonStreamingBody)\n }\n },\n })\n return new Response(stream, {\n status: response?.status,\n statusText: response?.statusText,\n headers: {\n 'Content-Type': 'application/x-ndjson',\n [X_TSS_SERIALIZED]: 'true',\n },\n })\n }\n\n return new Response(undefined, {\n status: response?.status,\n statusText: response?.statusText,\n })\n } catch (error: any) {\n if (error instanceof Response) {\n return error\n }\n // else if (\n // isPlainObject(error) &&\n // 'result' in error &&\n // error.result instanceof Response\n // ) {\n // return error.result\n // }\n\n // Currently this server-side context has no idea how to\n // build final URLs, so we need to defer that to the client.\n // The client will check for __redirect and __notFound keys,\n // and if they exist, it will handle them appropriately.\n\n if (isNotFound(error)) {\n return isNotFoundResponse(error)\n }\n\n console.info()\n console.info('Server Fn Error!')\n console.info()\n console.error(error)\n console.info()\n\n const serializedError = JSON.stringify(\n await Promise.resolve(\n toCrossJSONAsync(error, {\n refs: new Map(),\n plugins: serovalPlugins,\n }),\n ),\n )\n const response = getResponse()\n return new Response(serializedError, {\n status: response?.status ?? 500,\n statusText: response?.statusText,\n headers: {\n 'Content-Type': 'application/json',\n [X_TSS_SERIALIZED]: 'true',\n },\n })\n }\n })()\n\n request.signal.removeEventListener('abort', abort)\n\n return response\n}\n\nfunction isNotFoundResponse(error: any) {\n const { headers, ...rest } = error\n\n return new Response(JSON.stringify(rest), {\n status: 404,\n headers: {\n 'Content-Type': 'application/json',\n ...(headers || {}),\n },\n })\n}\n"],"names":["response","controller"],"mappings":";;;;;;AAYA,IAAI,QAA4B;AAEzB,MAAM,qBAAqB,OAAO;AAAA,EACvC;AAAA,EACA;AACF,MAGM;AACJ,QAAM,aAAa,IAAI,gBAAA;AACvB,QAAM,SAAS,WAAW;AAC1B,QAAM,QAAQ,MAAM,WAAW,MAAA;AAC/B,UAAQ,OAAO,iBAAiB,SAAS,KAAK;AAE9C,MAAI,UAAU,QAAW;AACvB,YAAQ,IAAI,OAAO,GAAG,QAAQ,IAAI,kBAAkB,WAAW;AAAA,EACjE;AAEA,QAAM,SAAS,QAAQ;AACvB,QAAM,MAAM,IAAI,IAAI,QAAQ,KAAK,uBAAuB;AAKxD,QAAM,QAAQ,IAAI,SAAS,MAAM,KAAK;AACtC,QAAM,aAAa,QAAQ,MAAM,CAAC,IAAI;AACtC,QAAM,SAAS,OAAO,YAAY,IAAI,aAAa,SAAS;AAK5D,QAAM,mBAAmB,oBAAoB;AAE7C,MAAI,OAAO,eAAe,UAAU;AACl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mBAAmB,KAAK;AAAA,MACjC;AAEA,cAAQ,KAAA;AACR,cAAQ,KAAK,kBAAkB;AAC/B,cAAQ,KAAA;AACR,cAAQ,MAAM,KAAK;AACnB,cAAQ,KAAA;AAER,YAAM,kBAAkB,KAAK;AAAA,QAC3B,MAAM,QAAQ;AAAA,UACZ,iBAAiB,OAAO;AAAA,YACtB,0BAAU,IAAA;AAAA,YACV,SAAS;AAAA,UAAA,CACV;AAAA,QAAA;AAAA,MACH;AAEF,YAAMA,YAAW,YAAA;AACjB,aAAO,IAAI,SAAS,iBAAiB;AAAA,QACnC,QAAQA,WAAU,UAAU;AAAA,QAC5B,YAAYA,WAAU;AAAA,QACtB,SAAS;AAAA,UACP,gBAAgB;AAAA,UAChB,CAAC,gBAAgB,GAAG;AAAA,QAAA;AAAA,MACtB,CACD;AAAA,IACH;AAAA,EACF,GAAA;AAEA,UAAQ,OAAO,oBAAoB,SAAS,KAAK;AAEjD,SAAO;AACT;AAEA,SAAS,mBAAmB,OAAY;AACtC,QAAM,EAAE,SAAS,GAAG,KAAA,IAAS;AAE7B,SAAO,IAAI,SAAS,KAAK,UAAU,IAAI,GAAG;AAAA,IACxC,QAAQ;AAAA,IACR,SAAS;AAAA,MACP,gBAAgB;AAAA,MAChB,GAAI,WAAW,CAAA;AAAA,IAAC;AAAA,EAClB,CACD;AACH;"}
|
|
1
|
+
{"version":3,"file":"server-functions-handler.js","sources":["../../src/server-functions-handler.ts"],"sourcesContent":["import { isNotFound } from '@tanstack/router-core'\nimport invariant from 'tiny-invariant'\nimport {\n TSS_FORMDATA_CONTEXT,\n X_TSS_RAW_RESPONSE,\n X_TSS_SERIALIZED,\n getDefaultSerovalPlugins,\n} from '@tanstack/start-client-core'\nimport { fromJSON, toCrossJSONAsync, toCrossJSONStream } from 'seroval'\nimport { getResponse } from './request-response'\nimport { getServerFnById } from './getServerFnById'\n\nlet regex: RegExp | undefined = undefined\n\nexport const handleServerAction = async ({\n request,\n context,\n}: {\n request: Request\n context: any\n}) => {\n const controller = new AbortController()\n const signal = controller.signal\n const abort = () => controller.abort()\n request.signal.addEventListener('abort', abort)\n\n if (regex === undefined) {\n regex = new RegExp(`${process.env.TSS_SERVER_FN_BASE}([^/?#]+)`)\n }\n\n const method = request.method\n const url = new URL(request.url, 'http://localhost:3000')\n // extract the serverFnId from the url as host/_serverFn/:serverFnId\n // Define a regex to match the path and extract the :thing part\n\n // Execute the regex\n const match = url.pathname.match(regex)\n const serverFnId = match ? match[1] : null\n const search = Object.fromEntries(url.searchParams.entries()) as {\n payload?: any\n createServerFn?: boolean\n }\n\n const isCreateServerFn = 'createServerFn' in search\n\n if (typeof serverFnId !== 'string') {\n throw new Error('Invalid server action param for serverFnId: ' + serverFnId)\n }\n\n const action = await getServerFnById(serverFnId, { fromClient: true })\n\n // Known FormData 'Content-Type' header values\n const formDataContentTypes = [\n 'multipart/form-data',\n 'application/x-www-form-urlencoded',\n ]\n\n const contentType = request.headers.get('Content-Type')\n const serovalPlugins = getDefaultSerovalPlugins()\n\n function parsePayload(payload: any) {\n const parsedPayload = fromJSON(payload, { plugins: serovalPlugins })\n return parsedPayload as any\n }\n\n const response = await (async () => {\n try {\n let result = await (async () => {\n // FormData\n if (\n formDataContentTypes.some(\n (type) => contentType && contentType.includes(type),\n )\n ) {\n // We don't support GET requests with FormData payloads... that seems impossible\n invariant(\n method.toLowerCase() !== 'get',\n 'GET requests with FormData payloads are not supported',\n )\n const formData = await request.formData()\n const serializedContext = formData.get(TSS_FORMDATA_CONTEXT)\n formData.delete(TSS_FORMDATA_CONTEXT)\n\n const params = {\n context,\n data: formData,\n }\n if (typeof serializedContext === 'string') {\n try {\n const parsedContext = JSON.parse(serializedContext)\n const deserializedContext = fromJSON(parsedContext, {\n plugins: serovalPlugins,\n })\n if (\n typeof deserializedContext === 'object' &&\n deserializedContext\n ) {\n params.context = { ...context, ...deserializedContext }\n }\n } catch {}\n }\n\n return await action(params, signal)\n }\n\n // Get requests use the query string\n if (method.toLowerCase() === 'get') {\n invariant(\n isCreateServerFn,\n 'expected GET request to originate from createServerFn',\n )\n // By default the payload is the search params\n let payload: any = search.payload\n // If there's a payload, we should try to parse it\n payload = payload ? parsePayload(JSON.parse(payload)) : {}\n payload.context = { ...context, ...payload.context }\n // Send it through!\n return await action(payload, signal)\n }\n\n if (method.toLowerCase() !== 'post') {\n throw new Error('expected POST method')\n }\n\n let jsonPayload\n if (contentType?.includes('application/json')) {\n jsonPayload = await request.json()\n }\n\n // If this POST request was created by createServerFn,\n // its payload will be the only argument\n if (isCreateServerFn) {\n const payload = jsonPayload ? parsePayload(jsonPayload) : {}\n payload.context = { ...payload.context, ...context }\n return await action(payload, signal)\n }\n\n // Otherwise, we'll spread the payload. Need to\n // support `use server` functions that take multiple\n // arguments.\n return await action(...jsonPayload)\n })()\n\n // Any time we get a Response back, we should just\n // return it immediately.\n if (result.result instanceof Response) {\n result.result.headers.set(X_TSS_RAW_RESPONSE, 'true')\n return result.result\n }\n\n // If this is a non createServerFn request, we need to\n // pull out the result from the result object\n if (!isCreateServerFn) {\n result = result.result\n\n // The result might again be a response,\n // and if it is, return it.\n if (result instanceof Response) {\n return result\n }\n }\n\n // TODO: RSCs Where are we getting this package?\n // if (isValidElement(result)) {\n // const { renderToPipeableStream } = await import(\n // // @ts-expect-error\n // 'react-server-dom/server'\n // )\n\n // const pipeableStream = renderToPipeableStream(result)\n\n // setHeaders(event, {\n // 'Content-Type': 'text/x-component',\n // } as any)\n\n // sendStream(event, response)\n // event._handled = true\n\n // return new Response(null, { status: 200 })\n // }\n\n if (isNotFound(result)) {\n return isNotFoundResponse(result)\n }\n\n const response = getResponse()\n let nonStreamingBody: any = undefined\n\n if (result !== undefined) {\n // first run without the stream in case `result` does not need streaming\n let done = false as boolean\n const callbacks: {\n onParse: (value: any) => void\n onDone: () => void\n onError: (error: any) => void\n } = {\n onParse: (value) => {\n nonStreamingBody = value\n },\n onDone: () => {\n done = true\n },\n onError: (error) => {\n throw error\n },\n }\n toCrossJSONStream(result, {\n refs: new Map(),\n plugins: serovalPlugins,\n onParse(value) {\n callbacks.onParse(value)\n },\n onDone() {\n callbacks.onDone()\n },\n onError: (error) => {\n callbacks.onError(error)\n },\n })\n if (done) {\n return new Response(\n nonStreamingBody ? JSON.stringify(nonStreamingBody) : undefined,\n {\n status: response.status,\n statusText: response.statusText,\n headers: {\n 'Content-Type': 'application/json',\n [X_TSS_SERIALIZED]: 'true',\n },\n },\n )\n }\n\n // not done yet, we need to stream\n const encoder = new TextEncoder()\n const stream = new ReadableStream({\n start(controller) {\n callbacks.onParse = (value) =>\n controller.enqueue(encoder.encode(JSON.stringify(value) + '\\n'))\n callbacks.onDone = () => {\n try {\n controller.close()\n } catch (error) {\n controller.error(error)\n }\n }\n callbacks.onError = (error) => controller.error(error)\n // stream the initial body\n if (nonStreamingBody !== undefined) {\n callbacks.onParse(nonStreamingBody)\n }\n },\n })\n return new Response(stream, {\n status: response.status,\n statusText: response.statusText,\n headers: {\n 'Content-Type': 'application/x-ndjson',\n [X_TSS_SERIALIZED]: 'true',\n },\n })\n }\n\n return new Response(undefined, {\n status: response.status,\n statusText: response.statusText,\n })\n } catch (error: any) {\n if (error instanceof Response) {\n return error\n }\n // else if (\n // isPlainObject(error) &&\n // 'result' in error &&\n // error.result instanceof Response\n // ) {\n // return error.result\n // }\n\n // Currently this server-side context has no idea how to\n // build final URLs, so we need to defer that to the client.\n // The client will check for __redirect and __notFound keys,\n // and if they exist, it will handle them appropriately.\n\n if (isNotFound(error)) {\n return isNotFoundResponse(error)\n }\n\n console.info()\n console.info('Server Fn Error!')\n console.info()\n console.error(error)\n console.info()\n\n const serializedError = JSON.stringify(\n await Promise.resolve(\n toCrossJSONAsync(error, {\n refs: new Map(),\n plugins: serovalPlugins,\n }),\n ),\n )\n const response = getResponse()\n return new Response(serializedError, {\n status: response.status ?? 500,\n statusText: response.statusText,\n headers: {\n 'Content-Type': 'application/json',\n [X_TSS_SERIALIZED]: 'true',\n },\n })\n }\n })()\n\n request.signal.removeEventListener('abort', abort)\n\n return response\n}\n\nfunction isNotFoundResponse(error: any) {\n const { headers, ...rest } = error\n\n return new Response(JSON.stringify(rest), {\n status: 404,\n headers: {\n 'Content-Type': 'application/json',\n ...(headers || {}),\n },\n })\n}\n"],"names":["response","controller"],"mappings":";;;;;;AAYA,IAAI,QAA4B;AAEzB,MAAM,qBAAqB,OAAO;AAAA,EACvC;AAAA,EACA;AACF,MAGM;AACJ,QAAM,aAAa,IAAI,gBAAA;AACvB,QAAM,SAAS,WAAW;AAC1B,QAAM,QAAQ,MAAM,WAAW,MAAA;AAC/B,UAAQ,OAAO,iBAAiB,SAAS,KAAK;AAE9C,MAAI,UAAU,QAAW;AACvB,YAAQ,IAAI,OAAO,GAAG,QAAQ,IAAI,kBAAkB,WAAW;AAAA,EACjE;AAEA,QAAM,SAAS,QAAQ;AACvB,QAAM,MAAM,IAAI,IAAI,QAAQ,KAAK,uBAAuB;AAKxD,QAAM,QAAQ,IAAI,SAAS,MAAM,KAAK;AACtC,QAAM,aAAa,QAAQ,MAAM,CAAC,IAAI;AACtC,QAAM,SAAS,OAAO,YAAY,IAAI,aAAa,SAAS;AAK5D,QAAM,mBAAmB,oBAAoB;AAE7C,MAAI,OAAO,eAAe,UAAU;AAClC,UAAM,IAAI,MAAM,iDAAiD,UAAU;AAAA,EAC7E;AAEA,QAAM,SAAS,MAAM,gBAAgB,YAAY,EAAE,YAAY,MAAM;AAGrE,QAAM,uBAAuB;AAAA,IAC3B;AAAA,IACA;AAAA,EAAA;AAGF,QAAM,cAAc,QAAQ,QAAQ,IAAI,cAAc;AACtD,QAAM,iBAAiB,yBAAA;AAEvB,WAAS,aAAa,SAAc;AAClC,UAAM,gBAAgB,SAAS,SAAS,EAAE,SAAS,gBAAgB;AACnE,WAAO;AAAA,EACT;AAEA,QAAM,WAAW,OAAO,YAAY;AAClC,QAAI;AACF,UAAI,SAAS,OAAO,YAAY;AAE9B,YACE,qBAAqB;AAAA,UACnB,CAAC,SAAS,eAAe,YAAY,S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C,gBAAgB,GAAG;AAAA,QAAA;AAAA,MACtB,CACD;AAAA,IACH;AAAA,EACF,GAAA;AAEA,UAAQ,OAAO,oBAAoB,SAAS,KAAK;AAEjD,SAAO;AACT;AAEA,SAAS,mBAAmB,OAAY;AACtC,QAAM,EAAE,SAAS,GAAG,KAAA,IAAS;AAE7B,SAAO,IAAI,SAAS,KAAK,UAAU,IAAI,GAAG;AAAA,IACxC,QAAQ;AAAA,IACR,SAAS;AAAA,MACP,gBAAgB;AAAA,MAChB,GAAI,WAAW,CAAA;AAAA,IAAC;AAAA,EAClB,CACD;AACH;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tanstack/start-server-core",
|
|
3
|
-
"version": "1.142.
|
|
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.
|
|
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/history": "1.141.0",
|
|
66
67
|
"@tanstack/router-core": "1.141.8",
|
|
67
68
|
"@tanstack/start-client-core": "1.142.1",
|
|
68
|
-
"@tanstack/start-storage-context": "1.142.1"
|
|
69
|
-
"@tanstack/history": "1.141.0"
|
|
69
|
+
"@tanstack/start-storage-context": "1.142.1"
|
|
70
70
|
},
|
|
71
71
|
"devDependencies": {
|
|
72
72
|
"@standard-schema/spec": "^1.0.0",
|
package/src/request-response.ts
CHANGED
|
@@ -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
|
|
|
@@ -337,11 +396,9 @@ export function clearSession(config: Partial<SessionConfig>): Promise<void> {
|
|
|
337
396
|
return h3_clearSession(event, { name: 'start', ...config })
|
|
338
397
|
}
|
|
339
398
|
|
|
340
|
-
// not public API
|
|
341
399
|
export function getResponse() {
|
|
342
400
|
const event = getH3Event()
|
|
343
|
-
|
|
344
|
-
return event[Symbol.for('h3.internal.event.res')]
|
|
401
|
+
return event.res
|
|
345
402
|
}
|
|
346
403
|
|
|
347
404
|
// not public API (yet)
|
|
@@ -221,8 +221,8 @@ export const handleServerAction = async ({
|
|
|
221
221
|
return new Response(
|
|
222
222
|
nonStreamingBody ? JSON.stringify(nonStreamingBody) : undefined,
|
|
223
223
|
{
|
|
224
|
-
status: response
|
|
225
|
-
statusText: response
|
|
224
|
+
status: response.status,
|
|
225
|
+
statusText: response.statusText,
|
|
226
226
|
headers: {
|
|
227
227
|
'Content-Type': 'application/json',
|
|
228
228
|
[X_TSS_SERIALIZED]: 'true',
|
|
@@ -252,8 +252,8 @@ export const handleServerAction = async ({
|
|
|
252
252
|
},
|
|
253
253
|
})
|
|
254
254
|
return new Response(stream, {
|
|
255
|
-
status: response
|
|
256
|
-
statusText: response
|
|
255
|
+
status: response.status,
|
|
256
|
+
statusText: response.statusText,
|
|
257
257
|
headers: {
|
|
258
258
|
'Content-Type': 'application/x-ndjson',
|
|
259
259
|
[X_TSS_SERIALIZED]: 'true',
|
|
@@ -262,8 +262,8 @@ export const handleServerAction = async ({
|
|
|
262
262
|
}
|
|
263
263
|
|
|
264
264
|
return new Response(undefined, {
|
|
265
|
-
status: response
|
|
266
|
-
statusText: response
|
|
265
|
+
status: response.status,
|
|
266
|
+
statusText: response.statusText,
|
|
267
267
|
})
|
|
268
268
|
} catch (error: any) {
|
|
269
269
|
if (error instanceof Response) {
|
|
@@ -302,8 +302,8 @@ export const handleServerAction = async ({
|
|
|
302
302
|
)
|
|
303
303
|
const response = getResponse()
|
|
304
304
|
return new Response(serializedError, {
|
|
305
|
-
status: response
|
|
306
|
-
statusText: response
|
|
305
|
+
status: response.status ?? 500,
|
|
306
|
+
statusText: response.statusText,
|
|
307
307
|
headers: {
|
|
308
308
|
'Content-Type': 'application/json',
|
|
309
309
|
[X_TSS_SERIALIZED]: 'true',
|