@analogjs/router 3.0.0-beta.4 → 3.0.0-beta.41

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