@analogjs/router 3.0.0-alpha.91 → 3.0.0-alpha.92

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.
@@ -1,11 +1,296 @@
1
1
  import { BASE_URL as BASE_URL$1, INTERNAL_FETCH, LOCALE as LOCALE$1, REQUEST as REQUEST$1, RESPONSE as RESPONSE$1 } from "./analogjs-router-tokens.mjs";
2
2
  import { InjectionToken, Injector, enableProdMode, runInInjectionContext } from "@angular/core";
3
+ import { HttpErrorResponse } from "@angular/common/http";
3
4
  import { bootstrapApplication, createApplication } from "@angular/platform-browser";
4
5
  import { BASE_URL, LOCALE, REQUEST, RESPONSE } from "@analogjs/router/tokens";
5
- import { eventHandler, getRouterParam, readBody } from "nitro/h3";
6
+ import { eventHandler, getRouterParam, readBody } from "h3";
6
7
  import { INITIAL_CONFIG, platformServer, provideServerRendering, renderApplication, ɵSERVER_CONTEXT, ɵrenderInternal } from "@angular/platform-server";
8
+ import { SERVER_FN_DISPATCHER, createServerFnRef } from "@analogjs/router";
7
9
  import { AsyncLocalStorage } from "node:async_hooks";
8
- import { createServerFnRef } from "@analogjs/router";
10
+ //#region packages/router/server/src/server-fn/registry.ts
11
+ /**
12
+ * Server-side registry of server functions, keyed by id. A `.server.ts` module
13
+ * populates it as a side effect of `serverFn(...)` running at import time; the
14
+ * Nitro dispatch route imports those modules to fill it, then looks up by id.
15
+ */
16
+ var serverFnRegistry = /* @__PURE__ */ new Map();
17
+ //#endregion
18
+ //#region packages/router/server/src/server-fn/node-context.ts
19
+ /**
20
+ * Dispatch provides the Node request and response through `REQUEST` and
21
+ * `RESPONSE`, which are typed as Node primitives, so server functions only run
22
+ * on a Node runtime. h3 leaves `node` undefined on other runtimes. Calls made
23
+ * in-process while rendering may have no response.
24
+ */
25
+ function assertNodeContext(event) {
26
+ const node = event.node;
27
+ if (!node?.req) throw new Error("@analogjs/router: server functions require a Node runtime.");
28
+ return node;
29
+ }
30
+ //#endregion
31
+ //#region packages/router/server/src/server-fn/interceptors.ts
32
+ var SERVER_FN_INTERCEPTORS = new InjectionToken("SERVER_FN_INTERCEPTORS");
33
+ /** `withServerFnInterceptors([...])` — registers the chain (DI, ordered). */
34
+ function withServerFnInterceptors(interceptors) {
35
+ return { providers: interceptors.map((fn) => ({
36
+ provide: SERVER_FN_INTERCEPTORS,
37
+ useValue: fn,
38
+ multi: true
39
+ })) };
40
+ }
41
+ /** `provideServerFns(withServerFnInterceptors(...))` — mirrors provideHttpClient. */
42
+ function provideServerFns(...features) {
43
+ return features.flatMap((f) => f.providers);
44
+ }
45
+ function makeCtx(input, context) {
46
+ return {
47
+ input,
48
+ context,
49
+ with(patch) {
50
+ return makeCtx(input, {
51
+ ...context,
52
+ ...patch
53
+ });
54
+ }
55
+ };
56
+ }
57
+ /**
58
+ * Run the interceptor chain, then the handler, threading the context.
59
+ *
60
+ * `runInCtx` re-establishes the DI injection context around each interceptor
61
+ * and the handler individually. This is what keeps `inject()` working in a
62
+ * handler even when an upstream interceptor `await`s before calling `next`
63
+ * (which would otherwise resume outside Angular's synchronous injection
64
+ * context). It defaults to a pass-through for non-DI callers/tests.
65
+ */
66
+ async function runInterceptors(interceptors, input, handler, runInCtx = (fn) => fn()) {
67
+ let i = -1;
68
+ const dispatch = async (ctx) => {
69
+ i += 1;
70
+ if (i < interceptors.length) return runInCtx(() => interceptors[i](ctx, dispatch));
71
+ return runInCtx(() => handler(ctx.input, ctx.context));
72
+ };
73
+ return dispatch(makeCtx(input, {}));
74
+ }
75
+ //#endregion
76
+ //#region packages/router/server/src/server-fn/same-origin.ts
77
+ /**
78
+ * Same-origin enforcement for the server-function HTTP transport.
79
+ *
80
+ * Server functions are same-origin RPC: a client proxy only ever calls the
81
+ * relative `/_analog/fn/:id` URL of its own app. A cross-origin page must not be
82
+ * able to invoke them against a logged-in user (a CSRF-shaped attack), so the
83
+ * transport rejects browser requests whose origin is not the app's own — out of
84
+ * the box, with no per-app configuration.
85
+ *
86
+ * The signals used (`Sec-Fetch-Site`, `Origin`) are added by the browser and
87
+ * cannot be forged by a cross-origin page's `fetch`. Non-browser callers (curl,
88
+ * server-to-server, SSR in-process) send neither, so they are unaffected: the
89
+ * guard blocks the cross-origin browser attack it is meant to, and nothing else.
90
+ */
91
+ /**
92
+ * Origins permitted beyond the app's own, registered through DI:
93
+ * `provideServerFns(withAllowedOrigins([...]))`. Empty by default — the
94
+ * transport is same-origin unless an app opts out explicitly.
95
+ */
96
+ var SERVER_FN_ALLOWED_ORIGINS = new InjectionToken("SERVER_FN_ALLOWED_ORIGINS");
97
+ /**
98
+ * `withAllowedOrigins([...])` — permit cross-origin browser calls from the
99
+ * listed origins, or pass `'*'` to disable the same-origin guard entirely.
100
+ * Server functions are frequently cookie-authenticated, so this is an explicit
101
+ * opt-out of CSRF protection: allow-list the exact origins you control.
102
+ */
103
+ function withAllowedOrigins(origins) {
104
+ return { providers: origins.map((origin) => ({
105
+ provide: SERVER_FN_ALLOWED_ORIGINS,
106
+ useValue: origin,
107
+ multi: true
108
+ })) };
109
+ }
110
+ function firstHeader(value) {
111
+ return Array.isArray(value) ? value[0] : value;
112
+ }
113
+ /**
114
+ * Whether an HTTP request to a server function may proceed.
115
+ *
116
+ * Allowed when the request is same-origin, carries no browser-origin signal at
117
+ * all (a non-browser client, or a same-origin GET that omits `Origin`), or its
118
+ * `Origin` is listed in `allowedOrigins`. Passing `'*'` in `allowedOrigins`
119
+ * disables the check — the explicit opt-in to cross-origin access.
120
+ *
121
+ * `Sec-Fetch-Site` is the authoritative signal when present: `same-origin` and
122
+ * `none` (a direct navigation, not a cross-site fetch) pass; `same-site` and
123
+ * `cross-site` require an explicit `allowedOrigins` entry. When the header is
124
+ * absent (older browsers, some proxies) the `Origin` host is compared to the
125
+ * request host as a fallback.
126
+ */
127
+ function isServerFnOriginAllowed(headers, allowedOrigins = []) {
128
+ if (allowedOrigins.includes("*")) return true;
129
+ const origin = firstHeader(headers["origin"]);
130
+ const originAllowlisted = origin !== void 0 && allowedOrigins.includes(origin);
131
+ const site = firstHeader(headers["sec-fetch-site"]);
132
+ if (site) {
133
+ if (site === "same-origin" || site === "none") return true;
134
+ return originAllowlisted;
135
+ }
136
+ if (!origin) return true;
137
+ if (originAllowlisted) return true;
138
+ const host = firstHeader(headers["x-forwarded-host"]) ?? firstHeader(headers["host"]);
139
+ if (!host) return false;
140
+ try {
141
+ return new URL(origin).host === host;
142
+ } catch {
143
+ return false;
144
+ }
145
+ }
146
+ //#endregion
147
+ //#region packages/router/server/src/server-fn/dispatch.ts
148
+ /**
149
+ * Server-side dispatch for a server function call.
150
+ *
151
+ * 1. reject cross-origin browser calls (403), unless allow-listed — HTTP
152
+ * transport only (in-process callers omit `method` and are exempt)
153
+ * 2. look up the function by id
154
+ * 3. enforce the configured HTTP method (405 on mismatch)
155
+ * 4. require a JSON body on input-bearing calls (415 otherwise)
156
+ * 5. validate `input` against the Standard-Schema (4xx on failure)
157
+ * 6. build a per-request injector (REQUEST/RESPONSE + app providers)
158
+ * 7. run the interceptor chain, then the handler, re-entering
159
+ * `runInInjectionContext` at every hop so `inject()` works even after an
160
+ * interceptor `await`s before calling `next`
161
+ * 8. a `Response` returned by an interceptor/handler (`fail`/`redirect`)
162
+ * short-circuits with its status AND headers
163
+ *
164
+ * `options.method` is the request's HTTP method; when provided it is enforced
165
+ * against the function's configured method AND it turns on the same-origin
166
+ * guard. Transports (the generated Nitro handler) always pass it; trusted
167
+ * in-process callers may omit it, which also exempts them from the origin guard.
168
+ */
169
+ async function dispatchServerFn(id, rawInput, event, options = {}) {
170
+ const { parent, providers = [], method, allowedOrigins = [] } = options;
171
+ const node = assertNodeContext(event);
172
+ const headers = node.req.headers ?? {};
173
+ if (method) {
174
+ if (!isServerFnOriginAllowed(headers, [...allowedOrigins, ...parent?.get(SERVER_FN_ALLOWED_ORIGINS, []) ?? []])) return {
175
+ status: 403,
176
+ body: { message: "Cross-origin server function call rejected" }
177
+ };
178
+ }
179
+ const def = serverFnRegistry.get(id);
180
+ if (!def) return {
181
+ status: 404,
182
+ body: { message: `Unknown server function: ${id}` }
183
+ };
184
+ if (method && method.toUpperCase() !== def.method) return {
185
+ status: 405,
186
+ body: { message: `Method ${method} not allowed for ${id}` },
187
+ headers: { Allow: def.method }
188
+ };
189
+ if (method && def.method === "POST" && !isJsonContentType(headers)) return {
190
+ status: 415,
191
+ body: { message: "Server functions accept an application/json body" }
192
+ };
193
+ let input = rawInput;
194
+ if (def.config.input) {
195
+ const result = await def.config.input["~standard"].validate(rawInput);
196
+ if ("issues" in result && result.issues) return {
197
+ status: 400,
198
+ body: { errors: result.issues }
199
+ };
200
+ input = result.value;
201
+ }
202
+ const req = node.req;
203
+ const locale = detectLocale(req);
204
+ const injector = Injector.create({
205
+ parent,
206
+ providers: [
207
+ {
208
+ provide: REQUEST,
209
+ useValue: node.req
210
+ },
211
+ {
212
+ provide: RESPONSE,
213
+ useValue: node.res
214
+ },
215
+ {
216
+ provide: BASE_URL,
217
+ useValue: getBaseUrl(req)
218
+ },
219
+ ...locale ? [{
220
+ provide: LOCALE,
221
+ useValue: locale
222
+ }] : [],
223
+ ...providers
224
+ ]
225
+ });
226
+ const runInCtx = (fn) => runInInjectionContext(injector, fn);
227
+ const outcome = await runInterceptors(injector.get(SERVER_FN_INTERCEPTORS, []), input, def.handler, runInCtx);
228
+ if (outcome instanceof Response) {
229
+ const text = await outcome.text();
230
+ const body = text ? safeJson(text) : null;
231
+ const headers = {};
232
+ outcome.headers.forEach((value, key) => {
233
+ if (key.toLowerCase() !== "set-cookie") headers[key] = value;
234
+ });
235
+ const setCookie = outcome.headers.getSetCookie?.() ?? [];
236
+ if (setCookie.length) headers["set-cookie"] = setCookie;
237
+ return {
238
+ status: outcome.status,
239
+ body,
240
+ headers: Object.keys(headers).length ? headers : void 0
241
+ };
242
+ }
243
+ return {
244
+ status: 200,
245
+ body: outcome
246
+ };
247
+ }
248
+ function isJsonContentType(headers) {
249
+ const contentType = headers["content-type"];
250
+ const value = Array.isArray(contentType) ? contentType[0] : contentType;
251
+ if (!value) return false;
252
+ const mediaType = value.split(";")[0].trim().toLowerCase();
253
+ return mediaType === "application/json" || mediaType.endsWith("+json");
254
+ }
255
+ function safeJson(text) {
256
+ try {
257
+ return JSON.parse(text);
258
+ } catch {
259
+ return text;
260
+ }
261
+ }
262
+ //#endregion
263
+ //#region packages/router/server/src/server-fn/ssr-dispatcher.ts
264
+ /**
265
+ * The in-process transport used during SSR. `ServerFnClient` picks this up from
266
+ * DI and calls the handler directly instead of issuing an HTTP request back
267
+ * into the app — the render and the handler already share a process and a
268
+ * request, so the round-trip only adds latency (and would need an absolute URL).
269
+ *
270
+ * `method` is deliberately not passed to `dispatchServerFn`: this is a trusted
271
+ * in-process caller, so the HTTP-transport-only checks (same-origin, method
272
+ * enforcement, content type) do not apply. Validation and the interceptor chain
273
+ * still run, so an SSR call behaves like a browser call in every other respect.
274
+ *
275
+ * A non-2xx result is thrown as an `HttpErrorResponse` so the failure surfaces
276
+ * on `resource.error()` exactly as it does in the browser.
277
+ */
278
+ function createServerFnDispatcher(req, res) {
279
+ const event = { node: {
280
+ req,
281
+ res
282
+ } };
283
+ return async (fn, input, injector) => {
284
+ const { status, body } = await dispatchServerFn(fn.id, input, event, { parent: injector });
285
+ if (status < 200 || status > 299) throw new HttpErrorResponse({
286
+ status,
287
+ error: body,
288
+ url: fn.url
289
+ });
290
+ return body;
291
+ };
292
+ }
293
+ //#endregion
9
294
  //#region packages/router/server/src/provide-server-context.ts
10
295
  function getHeaderValue(value) {
11
296
  return Array.isArray(value) ? value[0] : value;
@@ -18,7 +303,7 @@ function getRequestHeader(req, name) {
18
303
  }
19
304
  function provideServerContext({ req, res, fetch }) {
20
305
  const baseUrl = getBaseUrl(req);
21
- const locale = detectLocale(req);
306
+ const locale = typeof ANALOG_I18N_FIXED_LOCALE !== "undefined" && ANALOG_I18N_FIXED_LOCALE || detectLocale(req);
22
307
  return [
23
308
  {
24
309
  provide: ɵSERVER_CONTEXT,
@@ -40,6 +325,10 @@ function provideServerContext({ req, res, fetch }) {
40
325
  provide: INTERNAL_FETCH,
41
326
  useValue: fetch
42
327
  },
328
+ {
329
+ provide: SERVER_FN_DISPATCHER,
330
+ useValue: createServerFnDispatcher(req, res)
331
+ },
43
332
  ...locale ? [{
44
333
  provide: LOCALE$1,
45
334
  useValue: locale
@@ -188,10 +477,11 @@ function isLikelyBot(serverContext) {
188
477
  * rule. The platform plugin translates that rule into an `x-analog-no-streaming`
189
478
  * response header (mirroring how `ssr: false` becomes `x-analog-no-ssr`); when
190
479
  * present, `renderStream` produces the buffered `render()` output for this
191
- * route instead of streaming.
480
+ * route instead of streaming. On Nitro v3, which renders without a Node
481
+ * response, the header is forwarded on the request instead.
192
482
  */
193
483
  function streamingDisabledByRoute(serverContext) {
194
- return serverContext?.res?.getHeader?.("x-analog-no-streaming") === "true";
484
+ return serverContext?.res?.getHeader?.("x-analog-no-streaming") === "true" || serverContext?.req?.headers?.["x-analog-no-streaming"] === "true";
195
485
  }
196
486
  //#endregion
197
487
  //#region packages/router/server/src/defer-reconcile-runtime.ts
@@ -445,14 +735,6 @@ function renderStream(rootComponent, config, platformProviders = []) {
445
735
  };
446
736
  }
447
737
  //#endregion
448
- //#region packages/router/server/src/server-fn/registry.ts
449
- /**
450
- * Server-side registry of server functions, keyed by id. A `.server.ts` module
451
- * populates it as a side effect of `serverFn(...)` running at import time; the
452
- * Nitro dispatch route imports those modules to fill it, then looks up by id.
453
- */
454
- var serverFnRegistry = /* @__PURE__ */ new Map();
455
- //#endregion
456
738
  //#region packages/router/server/src/server-fn/server-fn.ts
457
739
  function serverFn(arg1, arg2) {
458
740
  const { config, handler } = normalizeArgs(arg1, arg2);
@@ -517,250 +799,6 @@ async function createServerFnAppInjector(configOrProviders = []) {
517
799
  return (await createApplication(Array.isArray(configOrProviders) ? { providers: [provideServerRendering(), ...configOrProviders] } : configOrProviders, { platformRef: platformServer() })).injector;
518
800
  }
519
801
  //#endregion
520
- //#region packages/router/server/src/server-fn/node-context.ts
521
- /**
522
- * Dispatch provides the Node request and response through `REQUEST` and
523
- * `RESPONSE`, which are typed as Node primitives, so server functions only run
524
- * on a Node runtime. h3 leaves `node` undefined on other runtimes.
525
- */
526
- function assertNodeContext(event) {
527
- const node = event.node;
528
- if (!node?.req || !node.res) throw new Error("@analogjs/router: server functions require a Node runtime.");
529
- return node;
530
- }
531
- //#endregion
532
- //#region packages/router/server/src/server-fn/interceptors.ts
533
- var SERVER_FN_INTERCEPTORS = new InjectionToken("SERVER_FN_INTERCEPTORS");
534
- /** `withServerFnInterceptors([...])` — registers the chain (DI, ordered). */
535
- function withServerFnInterceptors(interceptors) {
536
- return { providers: interceptors.map((fn) => ({
537
- provide: SERVER_FN_INTERCEPTORS,
538
- useValue: fn,
539
- multi: true
540
- })) };
541
- }
542
- /** `provideServerFns(withServerFnInterceptors(...))` — mirrors provideHttpClient. */
543
- function provideServerFns(...features) {
544
- return features.flatMap((f) => f.providers);
545
- }
546
- function makeCtx(input, context) {
547
- return {
548
- input,
549
- context,
550
- with(patch) {
551
- return makeCtx(input, {
552
- ...context,
553
- ...patch
554
- });
555
- }
556
- };
557
- }
558
- /**
559
- * Run the interceptor chain, then the handler, threading the context.
560
- *
561
- * `runInCtx` re-establishes the DI injection context around each interceptor
562
- * and the handler individually. This is what keeps `inject()` working in a
563
- * handler even when an upstream interceptor `await`s before calling `next`
564
- * (which would otherwise resume outside Angular's synchronous injection
565
- * context). It defaults to a pass-through for non-DI callers/tests.
566
- */
567
- async function runInterceptors(interceptors, input, handler, runInCtx = (fn) => fn()) {
568
- let i = -1;
569
- const dispatch = async (ctx) => {
570
- i += 1;
571
- if (i < interceptors.length) return runInCtx(() => interceptors[i](ctx, dispatch));
572
- return runInCtx(() => handler(ctx.input, ctx.context));
573
- };
574
- return dispatch(makeCtx(input, {}));
575
- }
576
- //#endregion
577
- //#region packages/router/server/src/server-fn/same-origin.ts
578
- /**
579
- * Same-origin enforcement for the server-function HTTP transport.
580
- *
581
- * Server functions are same-origin RPC: a client proxy only ever calls the
582
- * relative `/_analog/fn/:id` URL of its own app. A cross-origin page must not be
583
- * able to invoke them against a logged-in user (a CSRF-shaped attack), so the
584
- * transport rejects browser requests whose origin is not the app's own — out of
585
- * the box, with no per-app configuration.
586
- *
587
- * The signals used (`Sec-Fetch-Site`, `Origin`) are added by the browser and
588
- * cannot be forged by a cross-origin page's `fetch`. Non-browser callers (curl,
589
- * server-to-server, SSR in-process) send neither, so they are unaffected: the
590
- * guard blocks the cross-origin browser attack it is meant to, and nothing else.
591
- */
592
- /**
593
- * Origins permitted beyond the app's own, registered through DI:
594
- * `provideServerFns(withAllowedOrigins([...]))`. Empty by default — the
595
- * transport is same-origin unless an app opts out explicitly.
596
- */
597
- var SERVER_FN_ALLOWED_ORIGINS = new InjectionToken("SERVER_FN_ALLOWED_ORIGINS");
598
- /**
599
- * `withAllowedOrigins([...])` — permit cross-origin browser calls from the
600
- * listed origins, or pass `'*'` to disable the same-origin guard entirely.
601
- * Server functions are frequently cookie-authenticated, so this is an explicit
602
- * opt-out of CSRF protection: allow-list the exact origins you control.
603
- */
604
- function withAllowedOrigins(origins) {
605
- return { providers: origins.map((origin) => ({
606
- provide: SERVER_FN_ALLOWED_ORIGINS,
607
- useValue: origin,
608
- multi: true
609
- })) };
610
- }
611
- function firstHeader(value) {
612
- return Array.isArray(value) ? value[0] : value;
613
- }
614
- /**
615
- * Whether an HTTP request to a server function may proceed.
616
- *
617
- * Allowed when the request is same-origin, carries no browser-origin signal at
618
- * all (a non-browser client, or a same-origin GET that omits `Origin`), or its
619
- * `Origin` is listed in `allowedOrigins`. Passing `'*'` in `allowedOrigins`
620
- * disables the check — the explicit opt-in to cross-origin access.
621
- *
622
- * `Sec-Fetch-Site` is the authoritative signal when present: `same-origin` and
623
- * `none` (a direct navigation, not a cross-site fetch) pass; `same-site` and
624
- * `cross-site` require an explicit `allowedOrigins` entry. When the header is
625
- * absent (older browsers, some proxies) the `Origin` host is compared to the
626
- * request host as a fallback.
627
- */
628
- function isServerFnOriginAllowed(headers, allowedOrigins = []) {
629
- if (allowedOrigins.includes("*")) return true;
630
- const origin = firstHeader(headers["origin"]);
631
- const originAllowlisted = origin !== void 0 && allowedOrigins.includes(origin);
632
- const site = firstHeader(headers["sec-fetch-site"]);
633
- if (site) {
634
- if (site === "same-origin" || site === "none") return true;
635
- return originAllowlisted;
636
- }
637
- if (!origin) return true;
638
- if (originAllowlisted) return true;
639
- const host = firstHeader(headers["x-forwarded-host"]) ?? firstHeader(headers["host"]);
640
- if (!host) return false;
641
- try {
642
- return new URL(origin).host === host;
643
- } catch {
644
- return false;
645
- }
646
- }
647
- //#endregion
648
- //#region packages/router/server/src/server-fn/dispatch.ts
649
- /**
650
- * Server-side dispatch for a server function call.
651
- *
652
- * 1. reject cross-origin browser calls (403), unless allow-listed — HTTP
653
- * transport only (in-process callers omit `method` and are exempt)
654
- * 2. look up the function by id
655
- * 3. enforce the configured HTTP method (405 on mismatch)
656
- * 4. require a JSON body on input-bearing calls (415 otherwise)
657
- * 5. validate `input` against the Standard-Schema (4xx on failure)
658
- * 6. build a per-request injector (REQUEST/RESPONSE + app providers)
659
- * 7. run the interceptor chain, then the handler, re-entering
660
- * `runInInjectionContext` at every hop so `inject()` works even after an
661
- * interceptor `await`s before calling `next`
662
- * 8. a `Response` returned by an interceptor/handler (`fail`/`redirect`)
663
- * short-circuits with its status AND headers
664
- *
665
- * `options.method` is the request's HTTP method; when provided it is enforced
666
- * against the function's configured method AND it turns on the same-origin
667
- * guard. Transports (the generated Nitro handler) always pass it; trusted
668
- * in-process callers may omit it, which also exempts them from the origin guard.
669
- */
670
- async function dispatchServerFn(id, rawInput, event, options = {}) {
671
- const { parent, providers = [], method, allowedOrigins = [] } = options;
672
- const node = assertNodeContext(event);
673
- const headers = node.req.headers ?? {};
674
- if (method) {
675
- if (!isServerFnOriginAllowed(headers, [...allowedOrigins, ...parent?.get(SERVER_FN_ALLOWED_ORIGINS, []) ?? []])) return {
676
- status: 403,
677
- body: { message: "Cross-origin server function call rejected" }
678
- };
679
- }
680
- const def = serverFnRegistry.get(id);
681
- if (!def) return {
682
- status: 404,
683
- body: { message: `Unknown server function: ${id}` }
684
- };
685
- if (method && method.toUpperCase() !== def.method) return {
686
- status: 405,
687
- body: { message: `Method ${method} not allowed for ${id}` },
688
- headers: { Allow: def.method }
689
- };
690
- if (method && def.method === "POST" && !isJsonContentType(headers)) return {
691
- status: 415,
692
- body: { message: "Server functions accept an application/json body" }
693
- };
694
- let input = rawInput;
695
- if (def.config.input) {
696
- const result = await def.config.input["~standard"].validate(rawInput);
697
- if ("issues" in result && result.issues) return {
698
- status: 400,
699
- body: { errors: result.issues }
700
- };
701
- input = result.value;
702
- }
703
- const req = node.req;
704
- const locale = detectLocale(req);
705
- const injector = Injector.create({
706
- parent,
707
- providers: [
708
- {
709
- provide: REQUEST,
710
- useValue: node.req
711
- },
712
- {
713
- provide: RESPONSE,
714
- useValue: node.res
715
- },
716
- {
717
- provide: BASE_URL,
718
- useValue: getBaseUrl(req)
719
- },
720
- ...locale ? [{
721
- provide: LOCALE,
722
- useValue: locale
723
- }] : [],
724
- ...providers
725
- ]
726
- });
727
- const runInCtx = (fn) => runInInjectionContext(injector, fn);
728
- const outcome = await runInterceptors(injector.get(SERVER_FN_INTERCEPTORS, []), input, def.handler, runInCtx);
729
- if (outcome instanceof Response) {
730
- const text = await outcome.text();
731
- const body = text ? safeJson(text) : null;
732
- const headers = {};
733
- outcome.headers.forEach((value, key) => {
734
- if (key.toLowerCase() !== "set-cookie") headers[key] = value;
735
- });
736
- const setCookie = outcome.headers.getSetCookie?.() ?? [];
737
- if (setCookie.length) headers["set-cookie"] = setCookie;
738
- return {
739
- status: outcome.status,
740
- body,
741
- headers: Object.keys(headers).length ? headers : void 0
742
- };
743
- }
744
- return {
745
- status: 200,
746
- body: outcome
747
- };
748
- }
749
- function isJsonContentType(headers) {
750
- const contentType = headers["content-type"];
751
- const value = Array.isArray(contentType) ? contentType[0] : contentType;
752
- if (!value) return false;
753
- const mediaType = value.split(";")[0].trim().toLowerCase();
754
- return mediaType === "application/json" || mediaType.endsWith("+json");
755
- }
756
- function safeJson(text) {
757
- try {
758
- return JSON.parse(text);
759
- } catch {
760
- return text;
761
- }
762
- }
763
- //#endregion
764
802
  //#region packages/router/server/src/server-fn/event-handler.ts
765
803
  /**
766
804
  * The h3 request/response layer for the server-function dispatch route.