@analogjs/router 3.0.0-beta.5 → 3.0.0-beta.50
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/fesm2022/analogjs-router-content.mjs +2 -2
- package/fesm2022/analogjs-router-content.mjs.map +1 -1
- package/fesm2022/analogjs-router-server-actions.mjs +18 -6
- package/fesm2022/analogjs-router-server-actions.mjs.map +1 -1
- package/fesm2022/analogjs-router-server.mjs +739 -39
- package/fesm2022/analogjs-router-server.mjs.map +1 -1
- package/fesm2022/analogjs-router-tanstack-query-server.mjs +24 -31
- package/fesm2022/analogjs-router-tanstack-query-server.mjs.map +1 -1
- package/fesm2022/analogjs-router-tanstack-query.mjs +14 -40
- package/fesm2022/analogjs-router-tanstack-query.mjs.map +1 -1
- package/fesm2022/analogjs-router.mjs +75 -21
- package/fesm2022/analogjs-router.mjs.map +1 -1
- package/fesm2022/debug.page.mjs +3 -3
- package/fesm2022/route-files.mjs +44 -16
- package/fesm2022/route-files.mjs.map +1 -1
- package/package.json +7 -6
- package/types/content/src/lib/markdown-helpers.d.ts +2 -1
- package/types/content/src/lib/routes.d.ts +2 -1
- package/types/server/actions/src/parse-request-data.d.ts +3 -0
- package/types/server/src/index.d.ts +2 -0
- package/types/server/src/node-handler.d.ts +8 -0
- package/types/server/src/request-handler.d.ts +30 -0
- package/types/server/src/server-fn/dispatch.d.ts +4 -2
- package/types/server/src/server-fn/event-handler.d.ts +3 -1
- package/types/server/src/server-fn/node-context.d.ts +14 -4
- package/types/server/src/server-fn/server-fn.d.ts +4 -4
- package/types/server/src/server-manifest.d.ts +26 -0
- package/types/server/src/utils/stream-request.d.ts +2 -0
- package/types/src/index.d.ts +1 -1
- package/types/src/lib/models.d.ts +14 -9
- package/types/src/lib/request-context.d.ts +5 -0
- package/types/src/lib/route-config.d.ts +1 -1
- package/types/src/lib/server-fn/inject-server-fn.d.ts +4 -4
- package/types/src/lib/server-fn/types.d.ts +1 -0
- package/types/src/lib/to-route.d.ts +53 -14
- package/types/tanstack-query/server/src/define-page-load-queries.d.ts +13 -10
- package/types/tanstack-query/server/src/index.d.ts +1 -2
- package/types/tanstack-query/src/index.d.ts +1 -1
- package/types/tanstack-query/src/provide-analog-query.d.ts +1 -3
- package/types/tanstack-query/src/server-query.d.ts +1 -1
- package/types/tanstack-query/server/src/provide-server-analog-query.d.ts +0 -2
- package/types/tanstack-query/src/provide-server-analog-query.d.ts +0 -2
|
@@ -6,8 +6,13 @@ import { bootstrapApplication, createApplication } from "@angular/platform-brows
|
|
|
6
6
|
import { BASE_URL, LOCALE, REQUEST, RESPONSE } from "@analogjs/router/tokens";
|
|
7
7
|
import { INITIAL_CONFIG, PlatformState, platformServer, provideServerRendering, renderApplication, ɵSERVER_CONTEXT, ɵrenderInternal } from "@angular/platform-server";
|
|
8
8
|
import { SERVER_FN_DISPATCHER, createServerFnRef } from "@analogjs/router";
|
|
9
|
+
import { IncomingMessage, ServerResponse } from "node:http";
|
|
10
|
+
import { Socket } from "node:net";
|
|
9
11
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
12
|
+
import * as h3 from "h3";
|
|
10
13
|
import { eventHandler, getRouterParam, readBody } from "h3";
|
|
14
|
+
import { Readable } from "node:stream";
|
|
15
|
+
import { pipeline } from "node:stream/promises";
|
|
11
16
|
//#region packages/router/server/src/server-fn/registry.ts
|
|
12
17
|
/**
|
|
13
18
|
* Server-side registry of server functions, keyed by id. A `.server.ts` module
|
|
@@ -19,15 +24,56 @@ var serverFnRegistry = /* @__PURE__ */ new Map();
|
|
|
19
24
|
//#region packages/router/server/src/server-fn/node-context.ts
|
|
20
25
|
/**
|
|
21
26
|
* Dispatch provides the Node request and response through `REQUEST` and
|
|
22
|
-
* `RESPONSE`, which are typed as Node primitives
|
|
23
|
-
*
|
|
24
|
-
* in-process while rendering may have no response.
|
|
27
|
+
* `RESPONSE`, which are typed as Node primitives. h3 leaves `node` undefined on
|
|
28
|
+
* other runtimes, where `nodeContext` creates them from the `Request`. Calls
|
|
29
|
+
* made in-process while rendering may have no response.
|
|
25
30
|
*/
|
|
26
31
|
function assertNodeContext(event) {
|
|
27
32
|
const node = event.node;
|
|
28
33
|
if (!node?.req) throw new Error("@analogjs/router: server functions require a Node runtime.");
|
|
29
34
|
return node;
|
|
30
35
|
}
|
|
36
|
+
/**
|
|
37
|
+
* A Node request/response pair for a bare `Request`, carrying what Analog
|
|
38
|
+
* reads: method, URL, headers and protocol, plus the `Request` and its abort
|
|
39
|
+
* `signal`. The same approach as h3's web adapter; it needs `node:http` (Node,
|
|
40
|
+
* Bun, Deno).
|
|
41
|
+
*/
|
|
42
|
+
function nodeContext(request, url) {
|
|
43
|
+
const socket = new Socket();
|
|
44
|
+
Object.defineProperty(socket, "encrypted", { value: url.protocol === "https:" });
|
|
45
|
+
const req = new IncomingMessage(socket);
|
|
46
|
+
const path = `${url.pathname}${url.search}`;
|
|
47
|
+
req.method = request.method;
|
|
48
|
+
req.url = path;
|
|
49
|
+
Object.assign(req, { originalUrl: path });
|
|
50
|
+
Object.defineProperties(req, {
|
|
51
|
+
signal: { value: request.signal },
|
|
52
|
+
request: { value: request }
|
|
53
|
+
});
|
|
54
|
+
req.headers = {
|
|
55
|
+
host: url.host,
|
|
56
|
+
...Object.fromEntries(request.headers)
|
|
57
|
+
};
|
|
58
|
+
return {
|
|
59
|
+
req,
|
|
60
|
+
res: new ServerResponse(req)
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
/** Headers the app set on the created response, under Analog's own. */
|
|
64
|
+
function withResponseHeaders(response, res) {
|
|
65
|
+
const headers = new Headers();
|
|
66
|
+
for (const [key, value] of Object.entries(res.getHeaders())) for (const item of [value ?? []].flat()) headers.append(key, String(item));
|
|
67
|
+
response.headers.forEach((value, key) => {
|
|
68
|
+
if (key !== "set-cookie") headers.set(key, value);
|
|
69
|
+
});
|
|
70
|
+
for (const cookie of response.headers.getSetCookie()) headers.append("set-cookie", cookie);
|
|
71
|
+
return new Response(response.body, {
|
|
72
|
+
status: response.status,
|
|
73
|
+
statusText: response.statusText,
|
|
74
|
+
headers
|
|
75
|
+
});
|
|
76
|
+
}
|
|
31
77
|
//#endregion
|
|
32
78
|
//#region packages/router/server/src/server-fn/interceptors.ts
|
|
33
79
|
var SERVER_FN_INTERCEPTORS = new InjectionToken("SERVER_FN_INTERCEPTORS");
|
|
@@ -154,7 +200,7 @@ function isServerFnOriginAllowed(headers, allowedOrigins = []) {
|
|
|
154
200
|
* 2. look up the function by id
|
|
155
201
|
* 3. enforce the configured HTTP method (405 on mismatch)
|
|
156
202
|
* 4. require a JSON body on input-bearing calls (415 otherwise)
|
|
157
|
-
* 5. validate `input` against the Standard-Schema (
|
|
203
|
+
* 5. validate `input` against the Standard-Schema (422 on failure)
|
|
158
204
|
* 6. build a per-request injector (REQUEST/RESPONSE + app providers)
|
|
159
205
|
* 7. run the interceptor chain, then the handler, re-entering
|
|
160
206
|
* `runInInjectionContext` at every hop so `inject()` works even after an
|
|
@@ -168,8 +214,12 @@ function isServerFnOriginAllowed(headers, allowedOrigins = []) {
|
|
|
168
214
|
* in-process callers may omit it, which also exempts them from the origin guard.
|
|
169
215
|
*/
|
|
170
216
|
async function dispatchServerFn(id, rawInput, event, options = {}) {
|
|
217
|
+
if (event.node?.req || !(event.req instanceof Request)) return dispatchInContext(id, rawInput, assertNodeContext(event), options);
|
|
218
|
+
const context = nodeContext(event.req, new URL(event.req.url));
|
|
219
|
+
return withContextHeaders(await dispatchInContext(id, rawInput, context, options), context.res);
|
|
220
|
+
}
|
|
221
|
+
async function dispatchInContext(id, rawInput, node, options) {
|
|
171
222
|
const { parent, providers = [], method, allowedOrigins = [] } = options;
|
|
172
|
-
const node = assertNodeContext(event);
|
|
173
223
|
const headers = node.req.headers ?? {};
|
|
174
224
|
if (method) {
|
|
175
225
|
if (!isServerFnOriginAllowed(headers, [...allowedOrigins, ...parent?.get(SERVER_FN_ALLOWED_ORIGINS, []) ?? []])) return {
|
|
@@ -195,7 +245,7 @@ async function dispatchServerFn(id, rawInput, event, options = {}) {
|
|
|
195
245
|
if (def.config.input) {
|
|
196
246
|
const result = await def.config.input["~standard"].validate(rawInput);
|
|
197
247
|
if ("issues" in result && result.issues) return {
|
|
198
|
-
status:
|
|
248
|
+
status: 422,
|
|
199
249
|
body: { errors: result.issues }
|
|
200
250
|
};
|
|
201
251
|
input = result.value;
|
|
@@ -225,7 +275,13 @@ async function dispatchServerFn(id, rawInput, event, options = {}) {
|
|
|
225
275
|
]
|
|
226
276
|
});
|
|
227
277
|
const runInCtx = (fn) => runInInjectionContext(injector, fn);
|
|
228
|
-
const
|
|
278
|
+
const interceptors = injector.get(SERVER_FN_INTERCEPTORS, []);
|
|
279
|
+
let outcome;
|
|
280
|
+
try {
|
|
281
|
+
outcome = await runInterceptors(interceptors, input, def.handler, runInCtx);
|
|
282
|
+
} finally {
|
|
283
|
+
injector.destroy();
|
|
284
|
+
}
|
|
229
285
|
if (outcome instanceof Response) {
|
|
230
286
|
const text = await outcome.text();
|
|
231
287
|
const body = text ? safeJson(text) : null;
|
|
@@ -246,6 +302,16 @@ async function dispatchServerFn(id, rawInput, event, options = {}) {
|
|
|
246
302
|
body: outcome
|
|
247
303
|
};
|
|
248
304
|
}
|
|
305
|
+
/** Headers set through `RESPONSE`, under those of a returned `Response`. */
|
|
306
|
+
function withContextHeaders(result, res) {
|
|
307
|
+
const headers = {};
|
|
308
|
+
for (const [key, value] of Object.entries(res.getHeaders())) if (value !== void 0) headers[key] = Array.isArray(value) ? value : String(value);
|
|
309
|
+
for (const [key, value] of Object.entries(result.headers ?? {})) headers[key] = key === "set-cookie" ? [headers[key] ?? [], value].flat() : value;
|
|
310
|
+
return Object.keys(headers).length ? {
|
|
311
|
+
...result,
|
|
312
|
+
headers
|
|
313
|
+
} : result;
|
|
314
|
+
}
|
|
249
315
|
function isJsonContentType(headers) {
|
|
250
316
|
const contentType = headers["content-type"];
|
|
251
317
|
const value = Array.isArray(contentType) ? contentType[0] : contentType;
|
|
@@ -514,6 +580,8 @@ function streamingDisabledByRoute(serverContext) {
|
|
|
514
580
|
if (serverContext?.streaming !== void 0) return !serverContext.streaming;
|
|
515
581
|
return serverContext?.res?.getHeader?.("x-analog-no-streaming") === "true" || serverContext?.req?.headers?.["x-analog-no-streaming"] === "true";
|
|
516
582
|
}
|
|
583
|
+
/** Marks the single-chunk stream of a buffered render, which is safe to cache. */
|
|
584
|
+
var BUFFERED_STREAM = Symbol.for("analog.bufferedStream");
|
|
517
585
|
//#endregion
|
|
518
586
|
//#region packages/router/server/src/defer-reconcile-runtime.ts
|
|
519
587
|
/**
|
|
@@ -909,10 +977,10 @@ function renderStream(rootComponent, config, platformProviders = []) {
|
|
|
909
977
|
platformProviders: [provideServerContext(serverContext), platformProviders]
|
|
910
978
|
});
|
|
911
979
|
navigation.throwIfFailed();
|
|
912
|
-
return new ReadableStream({ start(controller) {
|
|
980
|
+
return Object.assign(new ReadableStream({ start(controller) {
|
|
913
981
|
controller.enqueue(new TextEncoder().encode(html));
|
|
914
982
|
controller.close();
|
|
915
|
-
} });
|
|
983
|
+
} }), { [BUFFERED_STREAM]: true });
|
|
916
984
|
}
|
|
917
985
|
installCaptureDispatcher();
|
|
918
986
|
const platformRef = platformServer([
|
|
@@ -965,35 +1033,397 @@ function renderStream(rootComponent, config, platformProviders = []) {
|
|
|
965
1033
|
};
|
|
966
1034
|
}
|
|
967
1035
|
//#endregion
|
|
968
|
-
//#region
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
1036
|
+
//#region node_modules/.pnpm/ofetch@2.0.0-alpha.3/node_modules/ofetch/dist/index.mjs
|
|
1037
|
+
/**
|
|
1038
|
+
* Joins the given base URL and path, ensuring that there is only one slash between them.
|
|
1039
|
+
*/
|
|
1040
|
+
function joinURL(base, path) {
|
|
1041
|
+
if (!base || base === "/") return path || "/";
|
|
1042
|
+
if (!path || path === "/") return base || "/";
|
|
1043
|
+
const baseHasTrailing = base[base.length - 1] === "/";
|
|
1044
|
+
const pathHasLeading = path[0] === "/";
|
|
1045
|
+
if (baseHasTrailing && pathHasLeading) return base + path.slice(1);
|
|
1046
|
+
if (!baseHasTrailing && !pathHasLeading) return `${base}/${path}`;
|
|
1047
|
+
return base + path;
|
|
1048
|
+
}
|
|
1049
|
+
/**
|
|
1050
|
+
* Adds the base path to the input path, if it is not already present.
|
|
1051
|
+
*/
|
|
1052
|
+
function withBase(input = "", base = "") {
|
|
1053
|
+
if (!base || base === "/") return input;
|
|
1054
|
+
const _base = withoutTrailingSlash(base);
|
|
1055
|
+
if (input.startsWith(_base)) return input;
|
|
1056
|
+
return joinURL(_base, input);
|
|
1057
|
+
}
|
|
1058
|
+
function withoutTrailingSlash(path) {
|
|
1059
|
+
if (!path || path === "/") return "/";
|
|
1060
|
+
return path[path.length - 1] === "/" ? path.slice(0, -1) : path;
|
|
1061
|
+
}
|
|
1062
|
+
/**
|
|
1063
|
+
* Returns the URL with the given query parameters. If a query parameter is undefined, it is omitted.
|
|
1064
|
+
*/
|
|
1065
|
+
function withQuery(input, query) {
|
|
1066
|
+
if (!query || Object.keys(query).length === 0) return input;
|
|
1067
|
+
const searchIndex = input.indexOf("?");
|
|
1068
|
+
if (searchIndex === -1) {
|
|
1069
|
+
const normalizedQuery = Object.entries(query).filter(([, value]) => value !== void 0).flatMap(([key, value]) => {
|
|
1070
|
+
if (Array.isArray(value)) return value.map((item) => [key, normalizeQueryValue(item)]);
|
|
1071
|
+
return [[key, normalizeQueryValue(value)]];
|
|
1072
|
+
});
|
|
1073
|
+
const queryString$1 = new URLSearchParams(normalizedQuery).toString();
|
|
1074
|
+
return queryString$1 ? `${input}?${queryString$1}` : input;
|
|
1075
|
+
}
|
|
1076
|
+
const searchParams = new URLSearchParams(input.slice(searchIndex + 1));
|
|
1077
|
+
const base = input.slice(0, searchIndex);
|
|
1078
|
+
for (const [key, value] of Object.entries(query)) if (value === void 0) searchParams.delete(key);
|
|
1079
|
+
else if (Array.isArray(value)) for (const item of value) searchParams.append(key, normalizeQueryValue(item));
|
|
1080
|
+
else searchParams.set(key, normalizeQueryValue(value));
|
|
1081
|
+
const queryString = searchParams.toString();
|
|
1082
|
+
return queryString ? `${base}?${queryString}` : base;
|
|
1083
|
+
}
|
|
1084
|
+
function normalizeQueryValue(value) {
|
|
1085
|
+
if (value === null) return "";
|
|
1086
|
+
if (typeof value === "number" || typeof value === "boolean") return String(value);
|
|
1087
|
+
if (typeof value === "object") return JSON.stringify(value);
|
|
1088
|
+
return String(value);
|
|
1089
|
+
}
|
|
1090
|
+
var FetchError = class extends Error {
|
|
1091
|
+
constructor(message, opts) {
|
|
1092
|
+
super(message, opts);
|
|
1093
|
+
this.name = "FetchError";
|
|
1094
|
+
if (opts?.cause && !this.cause) this.cause = opts.cause;
|
|
1095
|
+
}
|
|
1096
|
+
};
|
|
1097
|
+
function createFetchError(ctx) {
|
|
1098
|
+
const errorMessage = ctx.error?.message || ctx.error?.toString() || "";
|
|
1099
|
+
const method = ctx.request?.method || ctx.options?.method || "GET";
|
|
1100
|
+
const url = ctx.request?.url || String(ctx.request) || "/";
|
|
1101
|
+
const fetchError = new FetchError(`${`[${method}] ${JSON.stringify(url)}`}: ${ctx.response ? `${ctx.response.status} ${ctx.response.statusText}` : "<no response>"}${errorMessage ? ` ${errorMessage}` : ""}`, ctx.error ? { cause: ctx.error } : void 0);
|
|
1102
|
+
for (const key of [
|
|
1103
|
+
"request",
|
|
1104
|
+
"options",
|
|
1105
|
+
"response"
|
|
1106
|
+
]) Object.defineProperty(fetchError, key, { get() {
|
|
1107
|
+
return ctx[key];
|
|
1108
|
+
} });
|
|
1109
|
+
for (const [key, refKey] of [
|
|
1110
|
+
["data", "_data"],
|
|
1111
|
+
["status", "status"],
|
|
1112
|
+
["statusCode", "status"],
|
|
1113
|
+
["statusText", "statusText"],
|
|
1114
|
+
["statusMessage", "statusText"]
|
|
1115
|
+
]) Object.defineProperty(fetchError, key, { get() {
|
|
1116
|
+
return ctx.response && ctx.response[refKey];
|
|
1117
|
+
} });
|
|
1118
|
+
return fetchError;
|
|
1119
|
+
}
|
|
1120
|
+
var payloadMethods = new Set(Object.freeze([
|
|
1121
|
+
"PATCH",
|
|
1122
|
+
"POST",
|
|
1123
|
+
"PUT",
|
|
1124
|
+
"DELETE"
|
|
1125
|
+
]));
|
|
1126
|
+
function isPayloadMethod(method = "GET") {
|
|
1127
|
+
return payloadMethods.has(method.toUpperCase());
|
|
1128
|
+
}
|
|
1129
|
+
function isJSONSerializable(value) {
|
|
1130
|
+
if (value === void 0) return false;
|
|
1131
|
+
const t = typeof value;
|
|
1132
|
+
if (t === "string" || t === "number" || t === "boolean" || t === null) return true;
|
|
1133
|
+
if (t !== "object") return false;
|
|
1134
|
+
if (Array.isArray(value)) return true;
|
|
1135
|
+
if (value.buffer) return false;
|
|
1136
|
+
if (value instanceof FormData || value instanceof URLSearchParams) return false;
|
|
1137
|
+
return value.constructor && value.constructor.name === "Object" || typeof value.toJSON === "function";
|
|
1138
|
+
}
|
|
1139
|
+
var textTypes = /* @__PURE__ */ new Set([
|
|
1140
|
+
"image/svg",
|
|
1141
|
+
"application/xml",
|
|
1142
|
+
"application/xhtml",
|
|
1143
|
+
"application/html"
|
|
1144
|
+
]);
|
|
1145
|
+
var JSON_RE = /^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;
|
|
1146
|
+
function detectResponseType(_contentType = "") {
|
|
1147
|
+
if (!_contentType) return "json";
|
|
1148
|
+
const contentType = _contentType.split(";").shift() || "";
|
|
1149
|
+
if (JSON_RE.test(contentType)) return "json";
|
|
1150
|
+
if (contentType === "text/event-stream") return "stream";
|
|
1151
|
+
if (textTypes.has(contentType) || contentType.startsWith("text/")) return "text";
|
|
1152
|
+
return "blob";
|
|
1153
|
+
}
|
|
1154
|
+
function resolveFetchOptions(request, input, defaults, Headers$1) {
|
|
1155
|
+
const headers = mergeHeaders(input?.headers ?? request?.headers, defaults?.headers, Headers$1);
|
|
1156
|
+
let query;
|
|
1157
|
+
if (defaults?.query || defaults?.params || input?.params || input?.query) query = {
|
|
1158
|
+
...defaults?.params,
|
|
1159
|
+
...defaults?.query,
|
|
1160
|
+
...input?.params,
|
|
1161
|
+
...input?.query
|
|
1162
|
+
};
|
|
1163
|
+
return {
|
|
1164
|
+
...defaults,
|
|
1165
|
+
...input,
|
|
1166
|
+
query,
|
|
1167
|
+
params: query,
|
|
1168
|
+
headers
|
|
1169
|
+
};
|
|
1170
|
+
}
|
|
1171
|
+
function mergeHeaders(input, defaults, Headers$1) {
|
|
1172
|
+
if (!defaults) return new Headers$1(input);
|
|
1173
|
+
const headers = new Headers$1(defaults);
|
|
1174
|
+
if (input) for (const [key, value] of Symbol.iterator in input || Array.isArray(input) ? input : new Headers$1(input)) headers.set(key, value);
|
|
1175
|
+
return headers;
|
|
1176
|
+
}
|
|
1177
|
+
async function callHooks(context, hooks) {
|
|
1178
|
+
if (hooks) if (Array.isArray(hooks)) for (const hook of hooks) await hook(context);
|
|
1179
|
+
else await hooks(context);
|
|
1180
|
+
}
|
|
1181
|
+
var retryStatusCodes = /* @__PURE__ */ new Set([
|
|
1182
|
+
408,
|
|
1183
|
+
409,
|
|
1184
|
+
425,
|
|
1185
|
+
429,
|
|
1186
|
+
500,
|
|
1187
|
+
502,
|
|
1188
|
+
503,
|
|
1189
|
+
504
|
|
1190
|
+
]);
|
|
1191
|
+
var nullBodyResponses = /* @__PURE__ */ new Set([
|
|
1192
|
+
101,
|
|
1193
|
+
204,
|
|
1194
|
+
205,
|
|
1195
|
+
304
|
|
1196
|
+
]);
|
|
1197
|
+
function createFetch(globalOptions = {}) {
|
|
1198
|
+
const { fetch: fetch$1 = globalThis.fetch } = globalOptions;
|
|
1199
|
+
async function onError(context) {
|
|
1200
|
+
const isAbort = context.error && context.error.name === "AbortError" && !context.options.timeout || false;
|
|
1201
|
+
if (context.options.retry !== false && !isAbort) {
|
|
1202
|
+
let retries;
|
|
1203
|
+
if (typeof context.options.retry === "number") retries = context.options.retry;
|
|
1204
|
+
else retries = isPayloadMethod(context.options.method) ? 0 : 1;
|
|
1205
|
+
const responseCode = context.response && context.response.status || 500;
|
|
1206
|
+
if (retries > 0 && (Array.isArray(context.options.retryStatusCodes) ? context.options.retryStatusCodes.includes(responseCode) : retryStatusCodes.has(responseCode))) {
|
|
1207
|
+
const retryDelay = typeof context.options.retryDelay === "function" ? context.options.retryDelay(context) : context.options.retryDelay || 0;
|
|
1208
|
+
if (retryDelay > 0) await new Promise((resolve) => setTimeout(resolve, retryDelay));
|
|
1209
|
+
return $fetchRaw(context.request, {
|
|
1210
|
+
...context.options,
|
|
1211
|
+
retry: retries - 1
|
|
1212
|
+
});
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
const error = createFetchError(context);
|
|
1216
|
+
if (Error.captureStackTrace) Error.captureStackTrace(error, $fetchRaw);
|
|
1217
|
+
throw error;
|
|
1218
|
+
}
|
|
1219
|
+
const $fetchRaw = async function $fetchRaw$1(_request, _options = {}) {
|
|
1220
|
+
const context = {
|
|
1221
|
+
request: _request,
|
|
1222
|
+
options: resolveFetchOptions(_request, _options, globalOptions.defaults, Headers),
|
|
1223
|
+
response: void 0,
|
|
1224
|
+
error: void 0
|
|
1225
|
+
};
|
|
1226
|
+
if (context.options.method) context.options.method = context.options.method.toUpperCase();
|
|
1227
|
+
if (context.options.onRequest) await callHooks(context, context.options.onRequest);
|
|
1228
|
+
if (typeof context.request === "string") {
|
|
1229
|
+
if (context.options.baseURL) context.request = withBase(context.request, context.options.baseURL);
|
|
1230
|
+
if (context.options.query) {
|
|
1231
|
+
context.request = withQuery(context.request, context.options.query);
|
|
1232
|
+
delete context.options.query;
|
|
1233
|
+
}
|
|
1234
|
+
if ("query" in context.options) delete context.options.query;
|
|
1235
|
+
if ("params" in context.options) delete context.options.params;
|
|
1236
|
+
}
|
|
1237
|
+
if (context.options.body && isPayloadMethod(context.options.method)) {
|
|
1238
|
+
if (isJSONSerializable(context.options.body)) {
|
|
1239
|
+
const contentType = context.options.headers.get("content-type");
|
|
1240
|
+
if (typeof context.options.body !== "string") context.options.body = contentType === "application/x-www-form-urlencoded" ? new URLSearchParams(context.options.body).toString() : JSON.stringify(context.options.body);
|
|
1241
|
+
context.options.headers = new Headers(context.options.headers || {});
|
|
1242
|
+
if (!contentType) context.options.headers.set("content-type", "application/json");
|
|
1243
|
+
if (!context.options.headers.has("accept")) context.options.headers.set("accept", "application/json");
|
|
1244
|
+
} else if ("pipeTo" in context.options.body && typeof context.options.body.pipeTo === "function" || typeof context.options.body.pipe === "function") {
|
|
1245
|
+
if (!("duplex" in context.options)) context.options.duplex = "half";
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
if (context.options.timeout) context.options.signal = context.options.signal ? AbortSignal.any([AbortSignal.timeout(context.options.timeout), context.options.signal]) : AbortSignal.timeout(context.options.timeout);
|
|
1249
|
+
try {
|
|
1250
|
+
context.response = await fetch$1(context.request, context.options);
|
|
1251
|
+
} catch (error) {
|
|
1252
|
+
context.error = error;
|
|
1253
|
+
if (context.options.onRequestError) await callHooks(context, context.options.onRequestError);
|
|
1254
|
+
return await onError(context);
|
|
1255
|
+
}
|
|
1256
|
+
if ((context.response.body || context.response._bodyInit) && !nullBodyResponses.has(context.response.status) && context.options.method !== "HEAD") {
|
|
1257
|
+
const responseType = (context.options.parseResponse ? "json" : context.options.responseType) || detectResponseType(context.response.headers.get("content-type") || "");
|
|
1258
|
+
switch (responseType) {
|
|
1259
|
+
case "json": {
|
|
1260
|
+
const data = await context.response.text();
|
|
1261
|
+
if (data) {
|
|
1262
|
+
const parseFunction = context.options.parseResponse || JSON.parse;
|
|
1263
|
+
context.response._data = parseFunction(data);
|
|
1264
|
+
}
|
|
1265
|
+
break;
|
|
1266
|
+
}
|
|
1267
|
+
case "stream":
|
|
1268
|
+
context.response._data = context.response.body || context.response._bodyInit;
|
|
1269
|
+
break;
|
|
1270
|
+
default: context.response._data = await context.response[responseType]();
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
if (context.options.onResponse) await callHooks(context, context.options.onResponse);
|
|
1274
|
+
if (!context.options.ignoreResponseError && context.response.status >= 400 && context.response.status < 600) {
|
|
1275
|
+
if (context.options.onResponseError) await callHooks(context, context.options.onResponseError);
|
|
1276
|
+
return await onError(context);
|
|
1277
|
+
}
|
|
1278
|
+
return context.response;
|
|
1279
|
+
};
|
|
1280
|
+
const $fetch$1 = async function $fetch$2(request, options) {
|
|
1281
|
+
return (await $fetchRaw(request, options))._data;
|
|
1282
|
+
};
|
|
1283
|
+
$fetch$1.raw = $fetchRaw;
|
|
1284
|
+
$fetch$1.native = (...args) => fetch$1(...args);
|
|
1285
|
+
$fetch$1.create = (defaultOptions = {}, customGlobalOptions = {}) => createFetch({
|
|
1286
|
+
...globalOptions,
|
|
1287
|
+
...customGlobalOptions,
|
|
1288
|
+
defaults: {
|
|
1289
|
+
...globalOptions.defaults,
|
|
1290
|
+
...customGlobalOptions.defaults,
|
|
1291
|
+
...defaultOptions
|
|
1292
|
+
}
|
|
978
1293
|
});
|
|
979
|
-
return
|
|
1294
|
+
return $fetch$1;
|
|
980
1295
|
}
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
1296
|
+
var $fetch = createFetch({ fetch: globalThis.fetch ? (...args) => globalThis.fetch(...args) : () => Promise.reject(/* @__PURE__ */ new Error("[ofetch] global.fetch is not supported!")) });
|
|
1297
|
+
//#endregion
|
|
1298
|
+
//#region node_modules/.pnpm/radix3@1.1.2/node_modules/radix3/dist/index.mjs
|
|
1299
|
+
var NODE_TYPES = {
|
|
1300
|
+
NORMAL: 0,
|
|
1301
|
+
WILDCARD: 1,
|
|
1302
|
+
PLACEHOLDER: 2
|
|
1303
|
+
};
|
|
1304
|
+
function createRouter(options = {}) {
|
|
1305
|
+
const ctx = {
|
|
1306
|
+
options,
|
|
1307
|
+
rootNode: createRadixNode(),
|
|
1308
|
+
staticRoutesMap: {}
|
|
985
1309
|
};
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
1310
|
+
const normalizeTrailingSlash = (p) => options.strictTrailingSlash ? p : p.replace(/\/$/, "") || "/";
|
|
1311
|
+
if (options.routes) for (const path in options.routes) insert(ctx, normalizeTrailingSlash(path), options.routes[path]);
|
|
1312
|
+
return {
|
|
1313
|
+
ctx,
|
|
1314
|
+
lookup: (path) => lookup(ctx, normalizeTrailingSlash(path)),
|
|
1315
|
+
insert: (path, data) => insert(ctx, normalizeTrailingSlash(path), data),
|
|
1316
|
+
remove: (path) => remove(ctx, normalizeTrailingSlash(path))
|
|
1317
|
+
};
|
|
1318
|
+
}
|
|
1319
|
+
function lookup(ctx, path) {
|
|
1320
|
+
const staticPathNode = ctx.staticRoutesMap[path];
|
|
1321
|
+
if (staticPathNode) return staticPathNode.data;
|
|
1322
|
+
const sections = path.split("/");
|
|
1323
|
+
const params = {};
|
|
1324
|
+
let paramsFound = false;
|
|
1325
|
+
let wildcardNode = null;
|
|
1326
|
+
let node = ctx.rootNode;
|
|
1327
|
+
let wildCardParam = null;
|
|
1328
|
+
for (let i = 0; i < sections.length; i++) {
|
|
1329
|
+
const section = sections[i];
|
|
1330
|
+
if (node.wildcardChildNode !== null) {
|
|
1331
|
+
wildcardNode = node.wildcardChildNode;
|
|
1332
|
+
wildCardParam = sections.slice(i).join("/");
|
|
1333
|
+
}
|
|
1334
|
+
const nextNode = node.children.get(section);
|
|
1335
|
+
if (nextNode === void 0) {
|
|
1336
|
+
if (node && node.placeholderChildren.length > 1) {
|
|
1337
|
+
const remaining = sections.length - i;
|
|
1338
|
+
node = node.placeholderChildren.find((c) => c.maxDepth === remaining) || null;
|
|
1339
|
+
} else node = node.placeholderChildren[0] || null;
|
|
1340
|
+
if (!node) break;
|
|
1341
|
+
if (node.paramName) params[node.paramName] = section;
|
|
1342
|
+
paramsFound = true;
|
|
1343
|
+
} else node = nextNode;
|
|
1344
|
+
}
|
|
1345
|
+
if ((node === null || node.data === null) && wildcardNode !== null) {
|
|
1346
|
+
node = wildcardNode;
|
|
1347
|
+
params[node.paramName || "_"] = wildCardParam;
|
|
1348
|
+
paramsFound = true;
|
|
1349
|
+
}
|
|
1350
|
+
if (!node) return null;
|
|
1351
|
+
if (paramsFound) return {
|
|
1352
|
+
...node.data,
|
|
1353
|
+
params: paramsFound ? params : void 0
|
|
989
1354
|
};
|
|
1355
|
+
return node.data;
|
|
1356
|
+
}
|
|
1357
|
+
function insert(ctx, path, data) {
|
|
1358
|
+
let isStaticRoute = true;
|
|
1359
|
+
const sections = path.split("/");
|
|
1360
|
+
let node = ctx.rootNode;
|
|
1361
|
+
let _unnamedPlaceholderCtr = 0;
|
|
1362
|
+
const matchedNodes = [node];
|
|
1363
|
+
for (const section of sections) {
|
|
1364
|
+
let childNode;
|
|
1365
|
+
if (childNode = node.children.get(section)) node = childNode;
|
|
1366
|
+
else {
|
|
1367
|
+
const type = getNodeType(section);
|
|
1368
|
+
childNode = createRadixNode({
|
|
1369
|
+
type,
|
|
1370
|
+
parent: node
|
|
1371
|
+
});
|
|
1372
|
+
node.children.set(section, childNode);
|
|
1373
|
+
if (type === NODE_TYPES.PLACEHOLDER) {
|
|
1374
|
+
childNode.paramName = section === "*" ? `_${_unnamedPlaceholderCtr++}` : section.slice(1);
|
|
1375
|
+
node.placeholderChildren.push(childNode);
|
|
1376
|
+
isStaticRoute = false;
|
|
1377
|
+
} else if (type === NODE_TYPES.WILDCARD) {
|
|
1378
|
+
node.wildcardChildNode = childNode;
|
|
1379
|
+
childNode.paramName = section.slice(3) || "_";
|
|
1380
|
+
isStaticRoute = false;
|
|
1381
|
+
}
|
|
1382
|
+
matchedNodes.push(childNode);
|
|
1383
|
+
node = childNode;
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
for (const [depth, node2] of matchedNodes.entries()) node2.maxDepth = Math.max(matchedNodes.length - depth, node2.maxDepth || 0);
|
|
1387
|
+
node.data = data;
|
|
1388
|
+
if (isStaticRoute === true) ctx.staticRoutesMap[path] = node;
|
|
1389
|
+
return node;
|
|
1390
|
+
}
|
|
1391
|
+
function remove(ctx, path) {
|
|
1392
|
+
let success = false;
|
|
1393
|
+
const sections = path.split("/");
|
|
1394
|
+
let node = ctx.rootNode;
|
|
1395
|
+
for (const section of sections) {
|
|
1396
|
+
node = node.children.get(section);
|
|
1397
|
+
if (!node) return success;
|
|
1398
|
+
}
|
|
1399
|
+
if (node.data) {
|
|
1400
|
+
const lastSection = sections.at(-1) || "";
|
|
1401
|
+
node.data = null;
|
|
1402
|
+
if (Object.keys(node.children).length === 0 && node.parent) {
|
|
1403
|
+
node.parent.children.delete(lastSection);
|
|
1404
|
+
node.parent.wildcardChildNode = null;
|
|
1405
|
+
node.parent.placeholderChildren = [];
|
|
1406
|
+
}
|
|
1407
|
+
success = true;
|
|
1408
|
+
}
|
|
1409
|
+
return success;
|
|
1410
|
+
}
|
|
1411
|
+
function createRadixNode(options = {}) {
|
|
990
1412
|
return {
|
|
991
|
-
|
|
992
|
-
|
|
1413
|
+
type: options.type || NODE_TYPES.NORMAL,
|
|
1414
|
+
maxDepth: 0,
|
|
1415
|
+
parent: options.parent || null,
|
|
1416
|
+
children: /* @__PURE__ */ new Map(),
|
|
1417
|
+
data: options.data || null,
|
|
1418
|
+
paramName: options.paramName || null,
|
|
1419
|
+
wildcardChildNode: null,
|
|
1420
|
+
placeholderChildren: []
|
|
993
1421
|
};
|
|
994
1422
|
}
|
|
995
|
-
function
|
|
996
|
-
|
|
1423
|
+
function getNodeType(str) {
|
|
1424
|
+
if (str.startsWith("**")) return NODE_TYPES.WILDCARD;
|
|
1425
|
+
if (str[0] === ":" || str === "*") return NODE_TYPES.PLACEHOLDER;
|
|
1426
|
+
return NODE_TYPES.NORMAL;
|
|
997
1427
|
}
|
|
998
1428
|
//#endregion
|
|
999
1429
|
//#region packages/router/server/src/server-fn/app-injector.ts
|
|
@@ -1053,24 +1483,294 @@ function createServerFnEventHandler(appInjector) {
|
|
|
1053
1483
|
* are enforced inside `dispatchServerFn`; this owns only the h3 I/O around it.
|
|
1054
1484
|
*/
|
|
1055
1485
|
async function handleServerFnRequest(event, appInjector) {
|
|
1056
|
-
const node = assertNodeContext(event);
|
|
1057
1486
|
const id = getRouterParam(event, "id") ?? "";
|
|
1487
|
+
if (!event.node?.req) return handleServerFnFetch(id, event.req, await appInjector);
|
|
1058
1488
|
let input;
|
|
1059
1489
|
if (event.method !== "GET") try {
|
|
1060
1490
|
input = await readBody(event);
|
|
1061
1491
|
} catch {
|
|
1062
|
-
|
|
1063
|
-
return { message: "Malformed request body" };
|
|
1492
|
+
return malformedBodyResponse();
|
|
1064
1493
|
}
|
|
1065
|
-
|
|
1494
|
+
return serverFnResponse(await dispatchServerFn(id, input, event, {
|
|
1066
1495
|
parent: await appInjector,
|
|
1067
1496
|
method: event.method
|
|
1497
|
+
}));
|
|
1498
|
+
}
|
|
1499
|
+
/** h3 v2 on fetch-native hosts (workerd, Bun, Deno) has a `Request` only. */
|
|
1500
|
+
async function handleServerFnFetch(id, request, parent) {
|
|
1501
|
+
const context = nodeContext(request, new URL(request.url));
|
|
1502
|
+
return withResponseHeaders(await callServerFn(id, request, context, parent), context.res);
|
|
1503
|
+
}
|
|
1504
|
+
async function callServerFn(id, request, context, parent) {
|
|
1505
|
+
let input;
|
|
1506
|
+
if (request.method !== "GET") {
|
|
1507
|
+
const text = await request.text();
|
|
1508
|
+
try {
|
|
1509
|
+
input = text ? JSON.parse(text) : void 0;
|
|
1510
|
+
} catch {
|
|
1511
|
+
return malformedBodyResponse();
|
|
1512
|
+
}
|
|
1513
|
+
}
|
|
1514
|
+
return serverFnResponse(await dispatchServerFn(id, input, { node: context }, {
|
|
1515
|
+
parent,
|
|
1516
|
+
method: request.method
|
|
1517
|
+
}));
|
|
1518
|
+
}
|
|
1519
|
+
function serverFnResponse({ status, body, headers }) {
|
|
1520
|
+
const responseHeaders = new Headers();
|
|
1521
|
+
for (const [key, value] of Object.entries(headers ?? {})) for (const item of [value].flat()) responseHeaders.append(key, item);
|
|
1522
|
+
if (isNullBodyStatus(status)) return new Response(null, {
|
|
1523
|
+
status,
|
|
1524
|
+
headers: responseHeaders
|
|
1525
|
+
});
|
|
1526
|
+
return Response.json(body ?? null, {
|
|
1527
|
+
status,
|
|
1528
|
+
headers: responseHeaders
|
|
1529
|
+
});
|
|
1530
|
+
}
|
|
1531
|
+
function malformedBodyResponse() {
|
|
1532
|
+
return Response.json({ message: "Malformed request body" }, { status: 400 });
|
|
1533
|
+
}
|
|
1534
|
+
function isNullBodyStatus(status) {
|
|
1535
|
+
return status === 204 || status === 205 || status === 304;
|
|
1536
|
+
}
|
|
1537
|
+
//#endregion
|
|
1538
|
+
//#region packages/router/server/src/server-manifest.ts
|
|
1539
|
+
/**
|
|
1540
|
+
* Filled in at build time by the platform's server build, the same way the
|
|
1541
|
+
* router plugin fills in `ANALOG_ROUTE_FILES`. Empty without it.
|
|
1542
|
+
*/
|
|
1543
|
+
var ANALOG_SERVER_MANIFEST = {};
|
|
1544
|
+
//#endregion
|
|
1545
|
+
//#region packages/router/server/src/request-handler.ts
|
|
1546
|
+
var SERVER_FN_PREFIX = "/_analog/fn/";
|
|
1547
|
+
/**
|
|
1548
|
+
* Handles Analog's requests: server functions and page endpoints, then SSR
|
|
1549
|
+
* for GET requests outside the API prefix. Static client files are the
|
|
1550
|
+
* host's job; serve them first, without an index fallback, or SSR answers
|
|
1551
|
+
* asset URLs.
|
|
1552
|
+
*/
|
|
1553
|
+
function createAnalogRequestHandler(options = {}) {
|
|
1554
|
+
const manifest = serverManifest();
|
|
1555
|
+
const apiPrefix = `/${manifest.apiPrefix}/`;
|
|
1556
|
+
const pageEndpointPrefix = `${apiPrefix}_analog/pages/`;
|
|
1557
|
+
const pageRoutes = createRouter({ routes: Object.fromEntries(Object.entries(manifest.pageEndpoints).map(([route, importEndpoint]) => [route, { importEndpoint }])) });
|
|
1558
|
+
const appInjector = Promise.all([manifest.config(), ...manifest.serverFnModules.map((load) => load())]).then(([config]) => createServerFnAppInjector(config));
|
|
1559
|
+
appInjector.catch(() => void 0);
|
|
1560
|
+
async function route(request, url, context) {
|
|
1561
|
+
if (url.pathname.startsWith(SERVER_FN_PREFIX)) return callServerFn(url.pathname.slice(12), request, context, await appInjector);
|
|
1562
|
+
if (url.pathname.startsWith(pageEndpointPrefix)) {
|
|
1563
|
+
const match = pageRoutes.lookup(url.pathname);
|
|
1564
|
+
return match ? callPageEndpoint(match, request, url, context, serverFetch(baseUrl(context))) : null;
|
|
1565
|
+
}
|
|
1566
|
+
if (request.method === "GET" && !url.pathname.startsWith(apiPrefix)) return renderPage(manifest, request, url, context, serverFetch(baseUrl(context)));
|
|
1567
|
+
return null;
|
|
1568
|
+
}
|
|
1569
|
+
const handle = async (request, context) => {
|
|
1570
|
+
const url = new URL(request.url);
|
|
1571
|
+
if (context) return route(request, url, context);
|
|
1572
|
+
const created = nodeContext(request, url);
|
|
1573
|
+
const response = await route(request, url, created);
|
|
1574
|
+
return response && withResponseHeaders(response, created.res);
|
|
1575
|
+
};
|
|
1576
|
+
/**
|
|
1577
|
+
* An ofetch instance for page endpoints' `fetch` and the router's SSR
|
|
1578
|
+
* interceptor, which records responses in TransferState. Same-origin
|
|
1579
|
+
* requests run in-process, as on Nitro, so they never go to the host named
|
|
1580
|
+
* by the client's `Host` header.
|
|
1581
|
+
*/
|
|
1582
|
+
function serverFetch(origin) {
|
|
1583
|
+
return $fetch.create({ baseURL: origin }, { fetch: async (input, init) => {
|
|
1584
|
+
const request = new Request(input, init);
|
|
1585
|
+
if (new URL(request.url).origin !== origin) return fetch(request);
|
|
1586
|
+
return await handle(request) ?? await options.fetch?.(request) ?? new Response(null, { status: 404 });
|
|
1587
|
+
} });
|
|
1588
|
+
}
|
|
1589
|
+
return handle;
|
|
1590
|
+
}
|
|
1591
|
+
/** The origin `BASE_URL` holds, so absolute URLs built from it stay in-process. */
|
|
1592
|
+
function baseUrl(context) {
|
|
1593
|
+
return getBaseUrl(context.req);
|
|
1594
|
+
}
|
|
1595
|
+
function serverManifest() {
|
|
1596
|
+
if (!ANALOG_SERVER_MANIFEST.render) throw new Error("[@analogjs/router] createAnalogRequestHandler() needs the server build from `analog({ server })`, which fills in the server manifest.");
|
|
1597
|
+
return ANALOG_SERVER_MANIFEST;
|
|
1598
|
+
}
|
|
1599
|
+
async function callPageEndpoint(match, request, url, context, fetch) {
|
|
1600
|
+
const event = pageEndpointEvent(request, url, context);
|
|
1601
|
+
event.context.params = match.params ?? {};
|
|
1602
|
+
const endpoint = await match.importEndpoint();
|
|
1603
|
+
const result = await (request.method === "GET" ? endpoint.load : endpoint.action)?.({
|
|
1604
|
+
params: event.context.params,
|
|
1605
|
+
req: context.req,
|
|
1606
|
+
res: context.res,
|
|
1607
|
+
fetch,
|
|
1608
|
+
event
|
|
1609
|
+
});
|
|
1610
|
+
return result instanceof Response ? result : Response.json(result ?? {}, { status: context.res.statusCode });
|
|
1611
|
+
}
|
|
1612
|
+
/**
|
|
1613
|
+
* Page endpoints receive an h3 event, backed by the `Request` so it is the
|
|
1614
|
+
* one body source: h3 v1 reads `event.web.request`, h3 v2 wraps the request.
|
|
1615
|
+
*/
|
|
1616
|
+
function pageEndpointEvent(request, url, context) {
|
|
1617
|
+
if ("createEvent" in h3) {
|
|
1618
|
+
const event = h3.createEvent(context.req, context.res);
|
|
1619
|
+
event.web = {
|
|
1620
|
+
request,
|
|
1621
|
+
url
|
|
1622
|
+
};
|
|
1623
|
+
return event;
|
|
1624
|
+
}
|
|
1625
|
+
const { H3Event } = h3;
|
|
1626
|
+
return new H3Event(request);
|
|
1627
|
+
}
|
|
1628
|
+
async function renderPage(manifest, request, url, context, fetch) {
|
|
1629
|
+
const signal = renderSignal(request, context.res);
|
|
1630
|
+
const path = `${url.pathname}${url.search}`;
|
|
1631
|
+
const req = context.req;
|
|
1632
|
+
req.originalUrl ??= path;
|
|
1633
|
+
const html = await (await manifest.render())(path, await manifest.template(path), {
|
|
1634
|
+
req,
|
|
1635
|
+
res: context.res,
|
|
1636
|
+
fetch,
|
|
1637
|
+
signal,
|
|
1638
|
+
renderErrorsAsHtml: true
|
|
1639
|
+
});
|
|
1640
|
+
const headers = new Headers({ "content-type": "text/html; charset=utf-8" });
|
|
1641
|
+
const status = context.res.statusCode;
|
|
1642
|
+
if ([
|
|
1643
|
+
204,
|
|
1644
|
+
205,
|
|
1645
|
+
304
|
|
1646
|
+
].includes(status)) {
|
|
1647
|
+
if (typeof html !== "string") await html.cancel();
|
|
1648
|
+
return new Response(null, {
|
|
1649
|
+
status,
|
|
1650
|
+
headers
|
|
1651
|
+
});
|
|
1652
|
+
}
|
|
1653
|
+
if (typeof html !== "string" && !(BUFFERED_STREAM in html)) {
|
|
1654
|
+
headers.set("content-encoding", "identity");
|
|
1655
|
+
headers.set("cache-control", "no-store, no-transform");
|
|
1656
|
+
}
|
|
1657
|
+
return new Response(html, {
|
|
1658
|
+
status,
|
|
1659
|
+
headers
|
|
1068
1660
|
});
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1661
|
+
}
|
|
1662
|
+
/**
|
|
1663
|
+
* Aborted when the client disconnects: fetch-native hosts abort the
|
|
1664
|
+
* `Request`, Node hosts close `res` before the response finishes.
|
|
1665
|
+
*/
|
|
1666
|
+
function renderSignal(request, res) {
|
|
1667
|
+
const closed = new AbortController();
|
|
1668
|
+
const abortIfUnfinished = () => {
|
|
1669
|
+
if (!res.writableEnded) closed.abort();
|
|
1670
|
+
};
|
|
1671
|
+
if (res.closed) abortIfUnfinished();
|
|
1672
|
+
else res.once("close", abortIfUnfinished);
|
|
1673
|
+
return AbortSignal.any([request.signal, closed.signal]);
|
|
1674
|
+
}
|
|
1675
|
+
//#endregion
|
|
1676
|
+
//#region packages/router/server/src/node-handler.ts
|
|
1677
|
+
/**
|
|
1678
|
+
* The Node adapter for `createAnalogRequestHandler()`: converts the request,
|
|
1679
|
+
* writes Analog's `Response`, and calls `next` when Analog returns `null`.
|
|
1680
|
+
*/
|
|
1681
|
+
function createAnalogHandler(options = {}) {
|
|
1682
|
+
const handleAnalogRequest = createAnalogRequestHandler(options);
|
|
1683
|
+
return (req, res, next) => {
|
|
1684
|
+
Promise.resolve(req).then((req) => handleAnalogRequest(toRequest(req), {
|
|
1685
|
+
req,
|
|
1686
|
+
res
|
|
1687
|
+
})).then((response) => response ? writeResponse(response, res) : next()).catch((error) => {
|
|
1688
|
+
if (!(res.closed && error.name === "AbortError")) next(error);
|
|
1689
|
+
});
|
|
1690
|
+
};
|
|
1691
|
+
}
|
|
1692
|
+
function toRequest(req) {
|
|
1693
|
+
const protocol = req.socket.encrypted ? "https" : "http";
|
|
1694
|
+
const path = req.originalUrl ?? req.url ?? "/";
|
|
1695
|
+
const url = new URL(path, `${protocol}://${req.headers.host ?? "localhost"}`);
|
|
1696
|
+
const headers = new Headers();
|
|
1697
|
+
for (const [key, value] of Object.entries(req.headers)) for (const item of [value ?? []].flat()) headers.append(key, item);
|
|
1698
|
+
const hasBody = req.method !== "GET" && req.method !== "HEAD";
|
|
1699
|
+
return new Request(url, {
|
|
1700
|
+
method: req.method,
|
|
1701
|
+
headers,
|
|
1702
|
+
body: hasBody ? requestBody(req) : void 0,
|
|
1703
|
+
duplex: "half"
|
|
1704
|
+
});
|
|
1705
|
+
}
|
|
1706
|
+
/**
|
|
1707
|
+
* Hosts whose body parsers run first keep the original bytes on `rawBody`
|
|
1708
|
+
* (NestJS with `rawBody: true`). Otherwise the stream is read lazily, so a
|
|
1709
|
+
* request passed on with `next()` keeps its body.
|
|
1710
|
+
*/
|
|
1711
|
+
function requestBody(req) {
|
|
1712
|
+
const rawBody = req.rawBody;
|
|
1713
|
+
if (rawBody) return new Uint8Array(rawBody);
|
|
1714
|
+
let reader;
|
|
1715
|
+
return new ReadableStream({
|
|
1716
|
+
async pull(controller) {
|
|
1717
|
+
if (!reader && req.readableEnded) throw new Error("[@analogjs/router] The request body was already read by another parser. Keep the raw body (NestJS: `rawBody: true`) or mount Analog before body parsers.");
|
|
1718
|
+
reader ??= Readable.toWeb(req).getReader();
|
|
1719
|
+
const { done, value } = await reader.read();
|
|
1720
|
+
if (done) controller.close();
|
|
1721
|
+
else controller.enqueue(value);
|
|
1722
|
+
},
|
|
1723
|
+
cancel: (reason) => reader?.cancel(reason)
|
|
1724
|
+
}, { highWaterMark: 0 });
|
|
1725
|
+
}
|
|
1726
|
+
/** Keeps headers the app already set on `res`; cookies are appended. */
|
|
1727
|
+
async function writeResponse(response, res) {
|
|
1728
|
+
res.statusCode = response.status;
|
|
1729
|
+
response.headers.forEach((value, key) => {
|
|
1730
|
+
if (key !== "set-cookie") res.setHeader(key, value);
|
|
1731
|
+
});
|
|
1732
|
+
const cookies = response.headers.getSetCookie();
|
|
1733
|
+
if (cookies.length) res.appendHeader("set-cookie", cookies);
|
|
1734
|
+
if (!response.body) {
|
|
1735
|
+
res.end();
|
|
1736
|
+
return;
|
|
1737
|
+
}
|
|
1738
|
+
await pipeline(Readable.fromWeb(response.body), res).catch((error) => {
|
|
1739
|
+
if (error.code !== "ERR_STREAM_PREMATURE_CLOSE") throw error;
|
|
1740
|
+
});
|
|
1741
|
+
}
|
|
1742
|
+
//#endregion
|
|
1743
|
+
//#region packages/router/server/src/server-fn/server-fn.ts
|
|
1744
|
+
function serverFn(arg1, arg2) {
|
|
1745
|
+
const { config, handler } = normalizeArgs(arg1, arg2);
|
|
1746
|
+
if (config.method === "GET" && config.input) throw new Error("[analog] a serverFn with `input` must use POST; GET is reserved for input-less reads.");
|
|
1747
|
+
const ref = createServerFnRef(config);
|
|
1748
|
+
serverFnRegistry.set(ref.id, {
|
|
1749
|
+
id: ref.id,
|
|
1750
|
+
method: ref.method,
|
|
1751
|
+
config,
|
|
1752
|
+
handler
|
|
1753
|
+
});
|
|
1754
|
+
return ref;
|
|
1755
|
+
}
|
|
1756
|
+
function normalizeArgs(arg1, arg2) {
|
|
1757
|
+
if (typeof arg1 === "function") return {
|
|
1758
|
+
config: {},
|
|
1759
|
+
handler: arg1
|
|
1760
|
+
};
|
|
1761
|
+
if (isStandardSchema(arg1)) return {
|
|
1762
|
+
config: { input: arg1 },
|
|
1763
|
+
handler: arg2
|
|
1764
|
+
};
|
|
1765
|
+
return {
|
|
1766
|
+
config: arg1 ?? {},
|
|
1767
|
+
handler: arg2
|
|
1768
|
+
};
|
|
1769
|
+
}
|
|
1770
|
+
function isStandardSchema(value) {
|
|
1771
|
+
return typeof value === "object" && value !== null && "~standard" in value;
|
|
1072
1772
|
}
|
|
1073
1773
|
//#endregion
|
|
1074
|
-
export { SERVER_FN_ALLOWED_ORIGINS, SERVER_FN_INTERCEPTORS, createServerFnAppInjector, createServerFnEventHandler, dispatchServerFn, handleServerFnRequest, isServerFnOriginAllowed, provideServerContext, provideServerFns, render, renderStream, runInterceptors, serverFn, serverFnRegistry, withAllowedOrigins, withServerFnInterceptors };
|
|
1774
|
+
export { SERVER_FN_ALLOWED_ORIGINS, SERVER_FN_INTERCEPTORS, createAnalogHandler, createAnalogRequestHandler, createServerFnAppInjector, createServerFnEventHandler, dispatchServerFn, handleServerFnRequest, isServerFnOriginAllowed, provideServerContext, provideServerFns, render, renderStream, runInterceptors, serverFn, serverFnRegistry, withAllowedOrigins, withServerFnInterceptors };
|
|
1075
1775
|
|
|
1076
1776
|
//# sourceMappingURL=analogjs-router-server.mjs.map
|