@analogjs/router 3.0.0-beta.2 → 3.0.0-beta.20

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.
@@ -7,7 +7,12 @@ 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
9
  import { AsyncLocalStorage } from "node:async_hooks";
10
+ import * as h3 from "h3";
10
11
  import { eventHandler, getRouterParam, readBody } from "h3";
12
+ import { IncomingMessage, ServerResponse } from "node:http";
13
+ import { Socket } from "node:net";
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
@@ -965,35 +970,397 @@ function renderStream(rootComponent, config, platformProviders = []) {
965
970
  };
966
971
  }
967
972
  //#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
973
+ //#region node_modules/.pnpm/ofetch@2.0.0-alpha.3/node_modules/ofetch/dist/index.mjs
974
+ /**
975
+ * Joins the given base URL and path, ensuring that there is only one slash between them.
976
+ */
977
+ function joinURL(base, path) {
978
+ if (!base || base === "/") return path || "/";
979
+ if (!path || path === "/") return base || "/";
980
+ const baseHasTrailing = base[base.length - 1] === "/";
981
+ const pathHasLeading = path[0] === "/";
982
+ if (baseHasTrailing && pathHasLeading) return base + path.slice(1);
983
+ if (!baseHasTrailing && !pathHasLeading) return `${base}/${path}`;
984
+ return base + path;
985
+ }
986
+ /**
987
+ * Adds the base path to the input path, if it is not already present.
988
+ */
989
+ function withBase(input = "", base = "") {
990
+ if (!base || base === "/") return input;
991
+ const _base = withoutTrailingSlash(base);
992
+ if (input.startsWith(_base)) return input;
993
+ return joinURL(_base, input);
994
+ }
995
+ function withoutTrailingSlash(path) {
996
+ if (!path || path === "/") return "/";
997
+ return path[path.length - 1] === "/" ? path.slice(0, -1) : path;
998
+ }
999
+ /**
1000
+ * Returns the URL with the given query parameters. If a query parameter is undefined, it is omitted.
1001
+ */
1002
+ function withQuery(input, query) {
1003
+ if (!query || Object.keys(query).length === 0) return input;
1004
+ const searchIndex = input.indexOf("?");
1005
+ if (searchIndex === -1) {
1006
+ const normalizedQuery = Object.entries(query).filter(([, value]) => value !== void 0).flatMap(([key, value]) => {
1007
+ if (Array.isArray(value)) return value.map((item) => [key, normalizeQueryValue(item)]);
1008
+ return [[key, normalizeQueryValue(value)]];
1009
+ });
1010
+ const queryString$1 = new URLSearchParams(normalizedQuery).toString();
1011
+ return queryString$1 ? `${input}?${queryString$1}` : input;
1012
+ }
1013
+ const searchParams = new URLSearchParams(input.slice(searchIndex + 1));
1014
+ const base = input.slice(0, searchIndex);
1015
+ for (const [key, value] of Object.entries(query)) if (value === void 0) searchParams.delete(key);
1016
+ else if (Array.isArray(value)) for (const item of value) searchParams.append(key, normalizeQueryValue(item));
1017
+ else searchParams.set(key, normalizeQueryValue(value));
1018
+ const queryString = searchParams.toString();
1019
+ return queryString ? `${base}?${queryString}` : base;
1020
+ }
1021
+ function normalizeQueryValue(value) {
1022
+ if (value === null) return "";
1023
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
1024
+ if (typeof value === "object") return JSON.stringify(value);
1025
+ return String(value);
1026
+ }
1027
+ var FetchError = class extends Error {
1028
+ constructor(message, opts) {
1029
+ super(message, opts);
1030
+ this.name = "FetchError";
1031
+ if (opts?.cause && !this.cause) this.cause = opts.cause;
1032
+ }
1033
+ };
1034
+ function createFetchError(ctx) {
1035
+ const errorMessage = ctx.error?.message || ctx.error?.toString() || "";
1036
+ const method = ctx.request?.method || ctx.options?.method || "GET";
1037
+ const url = ctx.request?.url || String(ctx.request) || "/";
1038
+ 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);
1039
+ for (const key of [
1040
+ "request",
1041
+ "options",
1042
+ "response"
1043
+ ]) Object.defineProperty(fetchError, key, { get() {
1044
+ return ctx[key];
1045
+ } });
1046
+ for (const [key, refKey] of [
1047
+ ["data", "_data"],
1048
+ ["status", "status"],
1049
+ ["statusCode", "status"],
1050
+ ["statusText", "statusText"],
1051
+ ["statusMessage", "statusText"]
1052
+ ]) Object.defineProperty(fetchError, key, { get() {
1053
+ return ctx.response && ctx.response[refKey];
1054
+ } });
1055
+ return fetchError;
1056
+ }
1057
+ var payloadMethods = new Set(Object.freeze([
1058
+ "PATCH",
1059
+ "POST",
1060
+ "PUT",
1061
+ "DELETE"
1062
+ ]));
1063
+ function isPayloadMethod(method = "GET") {
1064
+ return payloadMethods.has(method.toUpperCase());
1065
+ }
1066
+ function isJSONSerializable(value) {
1067
+ if (value === void 0) return false;
1068
+ const t = typeof value;
1069
+ if (t === "string" || t === "number" || t === "boolean" || t === null) return true;
1070
+ if (t !== "object") return false;
1071
+ if (Array.isArray(value)) return true;
1072
+ if (value.buffer) return false;
1073
+ if (value instanceof FormData || value instanceof URLSearchParams) return false;
1074
+ return value.constructor && value.constructor.name === "Object" || typeof value.toJSON === "function";
1075
+ }
1076
+ var textTypes = /* @__PURE__ */ new Set([
1077
+ "image/svg",
1078
+ "application/xml",
1079
+ "application/xhtml",
1080
+ "application/html"
1081
+ ]);
1082
+ var JSON_RE = /^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;
1083
+ function detectResponseType(_contentType = "") {
1084
+ if (!_contentType) return "json";
1085
+ const contentType = _contentType.split(";").shift() || "";
1086
+ if (JSON_RE.test(contentType)) return "json";
1087
+ if (contentType === "text/event-stream") return "stream";
1088
+ if (textTypes.has(contentType) || contentType.startsWith("text/")) return "text";
1089
+ return "blob";
1090
+ }
1091
+ function resolveFetchOptions(request, input, defaults, Headers$1) {
1092
+ const headers = mergeHeaders(input?.headers ?? request?.headers, defaults?.headers, Headers$1);
1093
+ let query;
1094
+ if (defaults?.query || defaults?.params || input?.params || input?.query) query = {
1095
+ ...defaults?.params,
1096
+ ...defaults?.query,
1097
+ ...input?.params,
1098
+ ...input?.query
1099
+ };
1100
+ return {
1101
+ ...defaults,
1102
+ ...input,
1103
+ query,
1104
+ params: query,
1105
+ headers
1106
+ };
1107
+ }
1108
+ function mergeHeaders(input, defaults, Headers$1) {
1109
+ if (!defaults) return new Headers$1(input);
1110
+ const headers = new Headers$1(defaults);
1111
+ if (input) for (const [key, value] of Symbol.iterator in input || Array.isArray(input) ? input : new Headers$1(input)) headers.set(key, value);
1112
+ return headers;
1113
+ }
1114
+ async function callHooks(context, hooks) {
1115
+ if (hooks) if (Array.isArray(hooks)) for (const hook of hooks) await hook(context);
1116
+ else await hooks(context);
1117
+ }
1118
+ var retryStatusCodes = /* @__PURE__ */ new Set([
1119
+ 408,
1120
+ 409,
1121
+ 425,
1122
+ 429,
1123
+ 500,
1124
+ 502,
1125
+ 503,
1126
+ 504
1127
+ ]);
1128
+ var nullBodyResponses = /* @__PURE__ */ new Set([
1129
+ 101,
1130
+ 204,
1131
+ 205,
1132
+ 304
1133
+ ]);
1134
+ function createFetch(globalOptions = {}) {
1135
+ const { fetch: fetch$1 = globalThis.fetch } = globalOptions;
1136
+ async function onError(context) {
1137
+ const isAbort = context.error && context.error.name === "AbortError" && !context.options.timeout || false;
1138
+ if (context.options.retry !== false && !isAbort) {
1139
+ let retries;
1140
+ if (typeof context.options.retry === "number") retries = context.options.retry;
1141
+ else retries = isPayloadMethod(context.options.method) ? 0 : 1;
1142
+ const responseCode = context.response && context.response.status || 500;
1143
+ if (retries > 0 && (Array.isArray(context.options.retryStatusCodes) ? context.options.retryStatusCodes.includes(responseCode) : retryStatusCodes.has(responseCode))) {
1144
+ const retryDelay = typeof context.options.retryDelay === "function" ? context.options.retryDelay(context) : context.options.retryDelay || 0;
1145
+ if (retryDelay > 0) await new Promise((resolve) => setTimeout(resolve, retryDelay));
1146
+ return $fetchRaw(context.request, {
1147
+ ...context.options,
1148
+ retry: retries - 1
1149
+ });
1150
+ }
1151
+ }
1152
+ const error = createFetchError(context);
1153
+ if (Error.captureStackTrace) Error.captureStackTrace(error, $fetchRaw);
1154
+ throw error;
1155
+ }
1156
+ const $fetchRaw = async function $fetchRaw$1(_request, _options = {}) {
1157
+ const context = {
1158
+ request: _request,
1159
+ options: resolveFetchOptions(_request, _options, globalOptions.defaults, Headers),
1160
+ response: void 0,
1161
+ error: void 0
1162
+ };
1163
+ if (context.options.method) context.options.method = context.options.method.toUpperCase();
1164
+ if (context.options.onRequest) await callHooks(context, context.options.onRequest);
1165
+ if (typeof context.request === "string") {
1166
+ if (context.options.baseURL) context.request = withBase(context.request, context.options.baseURL);
1167
+ if (context.options.query) {
1168
+ context.request = withQuery(context.request, context.options.query);
1169
+ delete context.options.query;
1170
+ }
1171
+ if ("query" in context.options) delete context.options.query;
1172
+ if ("params" in context.options) delete context.options.params;
1173
+ }
1174
+ if (context.options.body && isPayloadMethod(context.options.method)) {
1175
+ if (isJSONSerializable(context.options.body)) {
1176
+ const contentType = context.options.headers.get("content-type");
1177
+ 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);
1178
+ context.options.headers = new Headers(context.options.headers || {});
1179
+ if (!contentType) context.options.headers.set("content-type", "application/json");
1180
+ if (!context.options.headers.has("accept")) context.options.headers.set("accept", "application/json");
1181
+ } else if ("pipeTo" in context.options.body && typeof context.options.body.pipeTo === "function" || typeof context.options.body.pipe === "function") {
1182
+ if (!("duplex" in context.options)) context.options.duplex = "half";
1183
+ }
1184
+ }
1185
+ 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);
1186
+ try {
1187
+ context.response = await fetch$1(context.request, context.options);
1188
+ } catch (error) {
1189
+ context.error = error;
1190
+ if (context.options.onRequestError) await callHooks(context, context.options.onRequestError);
1191
+ return await onError(context);
1192
+ }
1193
+ if ((context.response.body || context.response._bodyInit) && !nullBodyResponses.has(context.response.status) && context.options.method !== "HEAD") {
1194
+ const responseType = (context.options.parseResponse ? "json" : context.options.responseType) || detectResponseType(context.response.headers.get("content-type") || "");
1195
+ switch (responseType) {
1196
+ case "json": {
1197
+ const data = await context.response.text();
1198
+ if (data) {
1199
+ const parseFunction = context.options.parseResponse || JSON.parse;
1200
+ context.response._data = parseFunction(data);
1201
+ }
1202
+ break;
1203
+ }
1204
+ case "stream":
1205
+ context.response._data = context.response.body || context.response._bodyInit;
1206
+ break;
1207
+ default: context.response._data = await context.response[responseType]();
1208
+ }
1209
+ }
1210
+ if (context.options.onResponse) await callHooks(context, context.options.onResponse);
1211
+ if (!context.options.ignoreResponseError && context.response.status >= 400 && context.response.status < 600) {
1212
+ if (context.options.onResponseError) await callHooks(context, context.options.onResponseError);
1213
+ return await onError(context);
1214
+ }
1215
+ return context.response;
1216
+ };
1217
+ const $fetch$1 = async function $fetch$2(request, options) {
1218
+ return (await $fetchRaw(request, options))._data;
1219
+ };
1220
+ $fetch$1.raw = $fetchRaw;
1221
+ $fetch$1.native = (...args) => fetch$1(...args);
1222
+ $fetch$1.create = (defaultOptions = {}, customGlobalOptions = {}) => createFetch({
1223
+ ...globalOptions,
1224
+ ...customGlobalOptions,
1225
+ defaults: {
1226
+ ...globalOptions.defaults,
1227
+ ...customGlobalOptions.defaults,
1228
+ ...defaultOptions
1229
+ }
978
1230
  });
979
- return ref;
1231
+ return $fetch$1;
980
1232
  }
981
- function normalizeArgs(arg1, arg2) {
982
- if (typeof arg1 === "function") return {
983
- config: {},
984
- handler: arg1
1233
+ var $fetch = createFetch({ fetch: globalThis.fetch ? (...args) => globalThis.fetch(...args) : () => Promise.reject(/* @__PURE__ */ new Error("[ofetch] global.fetch is not supported!")) });
1234
+ //#endregion
1235
+ //#region node_modules/.pnpm/radix3@1.1.2/node_modules/radix3/dist/index.mjs
1236
+ var NODE_TYPES = {
1237
+ NORMAL: 0,
1238
+ WILDCARD: 1,
1239
+ PLACEHOLDER: 2
1240
+ };
1241
+ function createRouter(options = {}) {
1242
+ const ctx = {
1243
+ options,
1244
+ rootNode: createRadixNode(),
1245
+ staticRoutesMap: {}
985
1246
  };
986
- if (isStandardSchema(arg1)) return {
987
- config: { input: arg1 },
988
- handler: arg2
1247
+ const normalizeTrailingSlash = (p) => options.strictTrailingSlash ? p : p.replace(/\/$/, "") || "/";
1248
+ if (options.routes) for (const path in options.routes) insert(ctx, normalizeTrailingSlash(path), options.routes[path]);
1249
+ return {
1250
+ ctx,
1251
+ lookup: (path) => lookup(ctx, normalizeTrailingSlash(path)),
1252
+ insert: (path, data) => insert(ctx, normalizeTrailingSlash(path), data),
1253
+ remove: (path) => remove(ctx, normalizeTrailingSlash(path))
989
1254
  };
1255
+ }
1256
+ function lookup(ctx, path) {
1257
+ const staticPathNode = ctx.staticRoutesMap[path];
1258
+ if (staticPathNode) return staticPathNode.data;
1259
+ const sections = path.split("/");
1260
+ const params = {};
1261
+ let paramsFound = false;
1262
+ let wildcardNode = null;
1263
+ let node = ctx.rootNode;
1264
+ let wildCardParam = null;
1265
+ for (let i = 0; i < sections.length; i++) {
1266
+ const section = sections[i];
1267
+ if (node.wildcardChildNode !== null) {
1268
+ wildcardNode = node.wildcardChildNode;
1269
+ wildCardParam = sections.slice(i).join("/");
1270
+ }
1271
+ const nextNode = node.children.get(section);
1272
+ if (nextNode === void 0) {
1273
+ if (node && node.placeholderChildren.length > 1) {
1274
+ const remaining = sections.length - i;
1275
+ node = node.placeholderChildren.find((c) => c.maxDepth === remaining) || null;
1276
+ } else node = node.placeholderChildren[0] || null;
1277
+ if (!node) break;
1278
+ if (node.paramName) params[node.paramName] = section;
1279
+ paramsFound = true;
1280
+ } else node = nextNode;
1281
+ }
1282
+ if ((node === null || node.data === null) && wildcardNode !== null) {
1283
+ node = wildcardNode;
1284
+ params[node.paramName || "_"] = wildCardParam;
1285
+ paramsFound = true;
1286
+ }
1287
+ if (!node) return null;
1288
+ if (paramsFound) return {
1289
+ ...node.data,
1290
+ params: paramsFound ? params : void 0
1291
+ };
1292
+ return node.data;
1293
+ }
1294
+ function insert(ctx, path, data) {
1295
+ let isStaticRoute = true;
1296
+ const sections = path.split("/");
1297
+ let node = ctx.rootNode;
1298
+ let _unnamedPlaceholderCtr = 0;
1299
+ const matchedNodes = [node];
1300
+ for (const section of sections) {
1301
+ let childNode;
1302
+ if (childNode = node.children.get(section)) node = childNode;
1303
+ else {
1304
+ const type = getNodeType(section);
1305
+ childNode = createRadixNode({
1306
+ type,
1307
+ parent: node
1308
+ });
1309
+ node.children.set(section, childNode);
1310
+ if (type === NODE_TYPES.PLACEHOLDER) {
1311
+ childNode.paramName = section === "*" ? `_${_unnamedPlaceholderCtr++}` : section.slice(1);
1312
+ node.placeholderChildren.push(childNode);
1313
+ isStaticRoute = false;
1314
+ } else if (type === NODE_TYPES.WILDCARD) {
1315
+ node.wildcardChildNode = childNode;
1316
+ childNode.paramName = section.slice(3) || "_";
1317
+ isStaticRoute = false;
1318
+ }
1319
+ matchedNodes.push(childNode);
1320
+ node = childNode;
1321
+ }
1322
+ }
1323
+ for (const [depth, node2] of matchedNodes.entries()) node2.maxDepth = Math.max(matchedNodes.length - depth, node2.maxDepth || 0);
1324
+ node.data = data;
1325
+ if (isStaticRoute === true) ctx.staticRoutesMap[path] = node;
1326
+ return node;
1327
+ }
1328
+ function remove(ctx, path) {
1329
+ let success = false;
1330
+ const sections = path.split("/");
1331
+ let node = ctx.rootNode;
1332
+ for (const section of sections) {
1333
+ node = node.children.get(section);
1334
+ if (!node) return success;
1335
+ }
1336
+ if (node.data) {
1337
+ const lastSection = sections.at(-1) || "";
1338
+ node.data = null;
1339
+ if (Object.keys(node.children).length === 0 && node.parent) {
1340
+ node.parent.children.delete(lastSection);
1341
+ node.parent.wildcardChildNode = null;
1342
+ node.parent.placeholderChildren = [];
1343
+ }
1344
+ success = true;
1345
+ }
1346
+ return success;
1347
+ }
1348
+ function createRadixNode(options = {}) {
990
1349
  return {
991
- config: arg1 ?? {},
992
- handler: arg2
1350
+ type: options.type || NODE_TYPES.NORMAL,
1351
+ maxDepth: 0,
1352
+ parent: options.parent || null,
1353
+ children: /* @__PURE__ */ new Map(),
1354
+ data: options.data || null,
1355
+ paramName: options.paramName || null,
1356
+ wildcardChildNode: null,
1357
+ placeholderChildren: []
993
1358
  };
994
1359
  }
995
- function isStandardSchema(value) {
996
- return typeof value === "object" && value !== null && "~standard" in value;
1360
+ function getNodeType(str) {
1361
+ if (str.startsWith("**")) return NODE_TYPES.WILDCARD;
1362
+ if (str[0] === ":" || str === "*") return NODE_TYPES.PLACEHOLDER;
1363
+ return NODE_TYPES.NORMAL;
997
1364
  }
998
1365
  //#endregion
999
1366
  //#region packages/router/server/src/server-fn/app-injector.ts
@@ -1030,6 +1397,262 @@ async function createServerFnAppInjector(configOrProviders = []) {
1030
1397
  return (await createApplication(config, { platformRef: platformServer() })).injector;
1031
1398
  }
1032
1399
  //#endregion
1400
+ //#region packages/router/server/src/server-manifest.ts
1401
+ /**
1402
+ * Filled in at build time by the platform's server build, the same way the
1403
+ * router plugin fills in `ANALOG_ROUTE_FILES`. Empty without it.
1404
+ */
1405
+ var ANALOG_SERVER_MANIFEST = {};
1406
+ //#endregion
1407
+ //#region packages/router/server/src/request-handler.ts
1408
+ var SERVER_FN_PREFIX = "/_analog/fn/";
1409
+ /**
1410
+ * Handles Analog's requests: server functions and page endpoints, then SSR
1411
+ * for GET requests outside the API prefix. Static client files are the
1412
+ * host's job; serve them first, without an index fallback, or SSR answers
1413
+ * asset URLs.
1414
+ */
1415
+ function createAnalogRequestHandler(options = {}) {
1416
+ const manifest = serverManifest();
1417
+ const apiPrefix = `/${manifest.apiPrefix}/`;
1418
+ const pageEndpointPrefix = `${apiPrefix}_analog/pages/`;
1419
+ const pageRoutes = createRouter({ routes: Object.fromEntries(Object.entries(manifest.pageEndpoints).map(([route, importEndpoint]) => [route, { importEndpoint }])) });
1420
+ const appInjector = Promise.all([manifest.config(), ...manifest.serverFnModules.map((load) => load())]).then(([config]) => createServerFnAppInjector(config));
1421
+ appInjector.catch(() => void 0);
1422
+ async function route(request, url, context) {
1423
+ if (url.pathname.startsWith(SERVER_FN_PREFIX)) return callServerFn(url.pathname.slice(12), request, context, await appInjector);
1424
+ if (url.pathname.startsWith(pageEndpointPrefix)) {
1425
+ const match = pageRoutes.lookup(url.pathname);
1426
+ return match ? callPageEndpoint(match, request, url, context, serverFetch(baseUrl(context))) : null;
1427
+ }
1428
+ if (request.method === "GET" && !url.pathname.startsWith(apiPrefix)) return renderPage(manifest, url, context, serverFetch(baseUrl(context)));
1429
+ return null;
1430
+ }
1431
+ const handle = async (request, context) => {
1432
+ const url = new URL(request.url);
1433
+ if (context) return route(request, url, context);
1434
+ const created = nodeContext(request, url);
1435
+ const response = await route(request, url, created);
1436
+ return response && withResponseHeaders(response, created.res);
1437
+ };
1438
+ /**
1439
+ * An ofetch instance for page endpoints' `fetch` and the router's SSR
1440
+ * interceptor, which records responses in TransferState. Same-origin
1441
+ * requests run in-process, as on Nitro, so they never go to the host named
1442
+ * by the client's `Host` header.
1443
+ */
1444
+ function serverFetch(origin) {
1445
+ return $fetch.create({ baseURL: origin }, { fetch: async (input, init) => {
1446
+ const request = new Request(input, init);
1447
+ if (new URL(request.url).origin !== origin) return fetch(request);
1448
+ return await handle(request) ?? await options.fetch?.(request) ?? new Response(null, { status: 404 });
1449
+ } });
1450
+ }
1451
+ return handle;
1452
+ }
1453
+ /** The origin `BASE_URL` holds, so absolute URLs built from it stay in-process. */
1454
+ function baseUrl(context) {
1455
+ return getBaseUrl(context.req);
1456
+ }
1457
+ function serverManifest() {
1458
+ if (!ANALOG_SERVER_MANIFEST.render) throw new Error("[@analogjs/router] createAnalogRequestHandler() needs the server build from `analog({ server })`, which fills in the server manifest.");
1459
+ return ANALOG_SERVER_MANIFEST;
1460
+ }
1461
+ async function callServerFn(id, request, context, parent) {
1462
+ let input;
1463
+ if (request.method !== "GET") {
1464
+ const text = await request.text();
1465
+ try {
1466
+ input = text ? JSON.parse(text) : void 0;
1467
+ } catch {
1468
+ return Response.json({ message: "Malformed request body" }, { status: 400 });
1469
+ }
1470
+ }
1471
+ const { status, body, headers } = await dispatchServerFn(id, input, { node: context }, {
1472
+ parent,
1473
+ method: request.method
1474
+ });
1475
+ const responseHeaders = new Headers();
1476
+ for (const [key, value] of Object.entries(headers ?? {})) for (const item of [value].flat()) responseHeaders.append(key, item);
1477
+ return Response.json(body ?? null, {
1478
+ status,
1479
+ headers: responseHeaders
1480
+ });
1481
+ }
1482
+ async function callPageEndpoint(match, request, url, context, fetch) {
1483
+ const event = pageEndpointEvent(request, url, context);
1484
+ event.context.params = match.params ?? {};
1485
+ const endpoint = await match.importEndpoint();
1486
+ const result = await (request.method === "GET" ? endpoint.load : endpoint.action)?.({
1487
+ params: event.context.params,
1488
+ req: context.req,
1489
+ res: context.res,
1490
+ fetch,
1491
+ event
1492
+ });
1493
+ return result instanceof Response ? result : Response.json(result ?? {}, { status: context.res.statusCode });
1494
+ }
1495
+ /**
1496
+ * Page endpoints receive an h3 event, backed by the `Request` so it is the
1497
+ * one body source: h3 v1 reads `event.web.request`, h3 v2 wraps the request.
1498
+ */
1499
+ function pageEndpointEvent(request, url, context) {
1500
+ if ("createEvent" in h3) {
1501
+ const event = h3.createEvent(context.req, context.res);
1502
+ event.web = {
1503
+ request,
1504
+ url
1505
+ };
1506
+ return event;
1507
+ }
1508
+ const { H3Event } = h3;
1509
+ return new H3Event(request);
1510
+ }
1511
+ async function renderPage(manifest, url, context, fetch) {
1512
+ const path = `${url.pathname}${url.search}`;
1513
+ const req = context.req;
1514
+ req.originalUrl ??= path;
1515
+ const html = await (await manifest.render())(path, await manifest.template(path), {
1516
+ req,
1517
+ res: context.res,
1518
+ fetch
1519
+ });
1520
+ return new Response(html, {
1521
+ status: context.res.statusCode,
1522
+ headers: { "content-type": "text/html; charset=utf-8" }
1523
+ });
1524
+ }
1525
+ /**
1526
+ * A Node request/response pair for a bare `Request`, carrying what Analog
1527
+ * reads: method, URL, headers and protocol. The same approach as h3's web
1528
+ * adapter; it needs `node:http` (Node, Bun, Deno).
1529
+ */
1530
+ function nodeContext(request, url) {
1531
+ const socket = new Socket();
1532
+ Object.defineProperty(socket, "encrypted", { value: url.protocol === "https:" });
1533
+ const req = new IncomingMessage(socket);
1534
+ const path = `${url.pathname}${url.search}`;
1535
+ req.method = request.method;
1536
+ req.url = path;
1537
+ Object.assign(req, { originalUrl: path });
1538
+ req.headers = {
1539
+ host: url.host,
1540
+ ...Object.fromEntries(request.headers)
1541
+ };
1542
+ return {
1543
+ req,
1544
+ res: new ServerResponse(req)
1545
+ };
1546
+ }
1547
+ /** Headers the app set on the created response, under Analog's own. */
1548
+ function withResponseHeaders(response, res) {
1549
+ const headers = new Headers();
1550
+ for (const [key, value] of Object.entries(res.getHeaders())) for (const item of [value ?? []].flat()) headers.append(key, String(item));
1551
+ response.headers.forEach((value, key) => {
1552
+ if (key !== "set-cookie") headers.set(key, value);
1553
+ });
1554
+ for (const cookie of response.headers.getSetCookie()) headers.append("set-cookie", cookie);
1555
+ return new Response(response.body, {
1556
+ status: response.status,
1557
+ statusText: response.statusText,
1558
+ headers
1559
+ });
1560
+ }
1561
+ //#endregion
1562
+ //#region packages/router/server/src/node-handler.ts
1563
+ /**
1564
+ * The Node adapter for `createAnalogRequestHandler()`: converts the request,
1565
+ * writes Analog's `Response`, and calls `next` when Analog returns `null`.
1566
+ */
1567
+ function createAnalogHandler(options = {}) {
1568
+ const handleAnalogRequest = createAnalogRequestHandler(options);
1569
+ return (req, res, next) => {
1570
+ Promise.resolve(req).then((req) => handleAnalogRequest(toRequest(req), {
1571
+ req,
1572
+ res
1573
+ })).then((response) => response ? writeResponse(response, res) : next()).catch(next);
1574
+ };
1575
+ }
1576
+ function toRequest(req) {
1577
+ const protocol = req.socket.encrypted ? "https" : "http";
1578
+ const path = req.originalUrl ?? req.url ?? "/";
1579
+ const url = new URL(path, `${protocol}://${req.headers.host ?? "localhost"}`);
1580
+ const headers = new Headers();
1581
+ for (const [key, value] of Object.entries(req.headers)) for (const item of [value ?? []].flat()) headers.append(key, item);
1582
+ const hasBody = req.method !== "GET" && req.method !== "HEAD";
1583
+ return new Request(url, {
1584
+ method: req.method,
1585
+ headers,
1586
+ body: hasBody ? requestBody(req) : void 0,
1587
+ duplex: "half"
1588
+ });
1589
+ }
1590
+ /**
1591
+ * Hosts whose body parsers run first keep the original bytes on `rawBody`
1592
+ * (NestJS with `rawBody: true`). Otherwise the stream is read lazily, so a
1593
+ * request passed on with `next()` keeps its body.
1594
+ */
1595
+ function requestBody(req) {
1596
+ const rawBody = req.rawBody;
1597
+ if (rawBody) return new Uint8Array(rawBody);
1598
+ let reader;
1599
+ return new ReadableStream({
1600
+ async pull(controller) {
1601
+ 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.");
1602
+ reader ??= Readable.toWeb(req).getReader();
1603
+ const { done, value } = await reader.read();
1604
+ if (done) controller.close();
1605
+ else controller.enqueue(value);
1606
+ },
1607
+ cancel: (reason) => reader?.cancel(reason)
1608
+ }, { highWaterMark: 0 });
1609
+ }
1610
+ /** Keeps headers the app already set on `res`; cookies are appended. */
1611
+ async function writeResponse(response, res) {
1612
+ res.statusCode = response.status;
1613
+ response.headers.forEach((value, key) => {
1614
+ if (key !== "set-cookie") res.setHeader(key, value);
1615
+ });
1616
+ const cookies = response.headers.getSetCookie();
1617
+ if (cookies.length) res.appendHeader("set-cookie", cookies);
1618
+ if (!response.body) {
1619
+ res.end();
1620
+ return;
1621
+ }
1622
+ await pipeline(Readable.fromWeb(response.body), res);
1623
+ }
1624
+ //#endregion
1625
+ //#region packages/router/server/src/server-fn/server-fn.ts
1626
+ function serverFn(arg1, arg2) {
1627
+ const { config, handler } = normalizeArgs(arg1, arg2);
1628
+ if (config.method === "GET" && config.input) throw new Error("[analog] a serverFn with `input` must use POST; GET is reserved for input-less reads.");
1629
+ const ref = createServerFnRef(config);
1630
+ serverFnRegistry.set(ref.id, {
1631
+ id: ref.id,
1632
+ method: ref.method,
1633
+ config,
1634
+ handler
1635
+ });
1636
+ return ref;
1637
+ }
1638
+ function normalizeArgs(arg1, arg2) {
1639
+ if (typeof arg1 === "function") return {
1640
+ config: {},
1641
+ handler: arg1
1642
+ };
1643
+ if (isStandardSchema(arg1)) return {
1644
+ config: { input: arg1 },
1645
+ handler: arg2
1646
+ };
1647
+ return {
1648
+ config: arg1 ?? {},
1649
+ handler: arg2
1650
+ };
1651
+ }
1652
+ function isStandardSchema(value) {
1653
+ return typeof value === "object" && value !== null && "~standard" in value;
1654
+ }
1655
+ //#endregion
1033
1656
  //#region packages/router/server/src/server-fn/event-handler.ts
1034
1657
  /**
1035
1658
  * The h3 request/response layer for the server-function dispatch route.
@@ -1071,6 +1694,6 @@ async function handleServerFnRequest(event, appInjector) {
1071
1694
  return body;
1072
1695
  }
1073
1696
  //#endregion
1074
- export { SERVER_FN_ALLOWED_ORIGINS, SERVER_FN_INTERCEPTORS, createServerFnAppInjector, createServerFnEventHandler, dispatchServerFn, handleServerFnRequest, isServerFnOriginAllowed, provideServerContext, provideServerFns, render, renderStream, runInterceptors, serverFn, serverFnRegistry, withAllowedOrigins, withServerFnInterceptors };
1697
+ 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
1698
 
1076
1699
  //# sourceMappingURL=analogjs-router-server.mjs.map