@analogjs/router 2.8.0-beta.1 → 2.8.0-beta.11

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 (28) hide show
  1. package/fesm2022/analogjs-router-debug.page-MFY2u07E.mjs +119 -0
  2. package/fesm2022/analogjs-router-debug.page-MFY2u07E.mjs.map +1 -0
  3. package/fesm2022/analogjs-router-i18n.mjs +82 -210
  4. package/fesm2022/analogjs-router-i18n.mjs.map +1 -1
  5. package/fesm2022/analogjs-router-routes-L2tt-0ms.mjs +263 -0
  6. package/fesm2022/analogjs-router-routes-L2tt-0ms.mjs.map +1 -0
  7. package/fesm2022/analogjs-router-server-actions.mjs +240 -294
  8. package/fesm2022/analogjs-router-server-actions.mjs.map +1 -1
  9. package/fesm2022/analogjs-router-server.mjs +387 -832
  10. package/fesm2022/analogjs-router-server.mjs.map +1 -1
  11. package/fesm2022/analogjs-router-tanstack-query-server.mjs +35 -85
  12. package/fesm2022/analogjs-router-tanstack-query-server.mjs.map +1 -1
  13. package/fesm2022/analogjs-router-tanstack-query.mjs +79 -127
  14. package/fesm2022/analogjs-router-tanstack-query.mjs.map +1 -1
  15. package/fesm2022/analogjs-router-tokens.mjs +14 -19
  16. package/fesm2022/analogjs-router-tokens.mjs.map +1 -1
  17. package/fesm2022/analogjs-router.mjs +777 -1187
  18. package/fesm2022/analogjs-router.mjs.map +1 -1
  19. package/package.json +2 -2
  20. package/types/analogjs-router-i18n.d.ts +55 -24
  21. package/types/analogjs-router-server-actions.d.ts +179 -90
  22. package/types/analogjs-router-server.d.ts +76 -116
  23. package/types/analogjs-router-tanstack-query-server.d.ts +33 -37
  24. package/types/analogjs-router-tanstack-query.d.ts +19 -24
  25. package/types/analogjs-router-tokens.d.ts +18 -22
  26. package/types/analogjs-router.d.ts +271 -251
  27. package/fesm2022/analogjs-router-debug.page-COcFkgRu.mjs +0 -91
  28. package/fesm2022/analogjs-router-debug.page-COcFkgRu.mjs.map +0 -1
@@ -1,532 +1,289 @@
1
- import { InjectionToken, Injector, runInInjectionContext, ɵresetCompiledComponents as _resetCompiledComponents, enableProdMode } from '@angular/core';
2
- import { ɵSERVER_CONTEXT as _SERVER_CONTEXT, renderApplication, platformServer, INITIAL_CONFIG, ɵrenderInternal as _renderInternal, provideServerRendering } from '@angular/platform-server';
3
- import { REQUEST, RESPONSE, BASE_URL, LOCALE } from '@analogjs/router/tokens';
4
- import { SERVER_FN_DISPATCHER, createServerFnRef } from '@analogjs/router';
5
- import { HttpErrorResponse } from '@angular/common/http';
6
- import { bootstrapApplication, createApplication } from '@angular/platform-browser';
7
- import { AsyncLocalStorage } from 'node:async_hooks';
8
- import { eventHandler, getRouterParam, readBody } from 'h3';
9
-
10
- /**
11
- * Server-side registry of server functions, keyed by id. A `.server.ts` module
12
- * populates it as a side effect of `serverFn(...)` running at import time; the
13
- * Nitro dispatch route imports those modules to fill it, then looks up by id.
14
- */
15
- const serverFnRegistry = new Map();
16
-
17
- const SERVER_FN_INTERCEPTORS = new InjectionToken('SERVER_FN_INTERCEPTORS');
18
- /** `withServerFnInterceptors([...])` — registers the chain (DI, ordered). */
1
+ import { InjectionToken, Injector, enableProdMode, runInInjectionContext, ɵresetCompiledComponents } from "@angular/core";
2
+ import { INITIAL_CONFIG, platformServer, provideServerRendering, renderApplication, ɵSERVER_CONTEXT, ɵrenderInternal } from "@angular/platform-server";
3
+ import { BASE_URL, LOCALE, REQUEST, RESPONSE } from "@analogjs/router/tokens";
4
+ import { SERVER_FN_DISPATCHER, createServerFnRef } from "@analogjs/router";
5
+ import { HttpErrorResponse } from "@angular/common/http";
6
+ import { bootstrapApplication, createApplication } from "@angular/platform-browser";
7
+ import { AsyncLocalStorage } from "node:async_hooks";
8
+ import { eventHandler, getRouterParam, readBody } from "h3";
9
+ const serverFnRegistry = /* @__PURE__ */ new Map();
10
+ const SERVER_FN_INTERCEPTORS = new InjectionToken("SERVER_FN_INTERCEPTORS");
19
11
  function withServerFnInterceptors(interceptors) {
20
- return {
21
- providers: interceptors.map((fn) => ({
22
- provide: SERVER_FN_INTERCEPTORS,
23
- useValue: fn,
24
- multi: true,
25
- })),
26
- };
27
- }
28
- /** `provideServerFns(withServerFnInterceptors(...))` — mirrors provideHttpClient. */
12
+ return { providers: interceptors.map((fn) => ({
13
+ provide: SERVER_FN_INTERCEPTORS,
14
+ useValue: fn,
15
+ multi: true
16
+ })) };
17
+ }
29
18
  function provideServerFns(...features) {
30
- return features.flatMap((f) => f.providers);
19
+ return features.flatMap((f) => f.providers);
31
20
  }
32
21
  function makeCtx(input, context) {
33
- return {
34
- input,
35
- context,
36
- with(patch) {
37
- return makeCtx(input, { ...context, ...patch });
38
- },
39
- };
40
- }
41
- /**
42
- * Run the interceptor chain, then the handler, threading the context.
43
- *
44
- * `runInCtx` re-establishes the DI injection context around each interceptor
45
- * and the handler individually. This is what keeps `inject()` working in a
46
- * handler even when an upstream interceptor `await`s before calling `next`
47
- * (which would otherwise resume outside Angular's synchronous injection
48
- * context). It defaults to a pass-through for non-DI callers/tests.
49
- */
50
- async function runInterceptors(interceptors, input, handler, runInCtx = (fn) => fn()) {
51
- let i = -1;
52
- const dispatch = async (ctx) => {
53
- i += 1;
54
- if (i < interceptors.length) {
55
- return runInCtx(() => interceptors[i](ctx, dispatch));
56
- }
57
- return runInCtx(() => handler(ctx.input, ctx.context));
58
- };
59
- return dispatch(makeCtx(input, {}));
22
+ return {
23
+ input,
24
+ context,
25
+ with(patch) {
26
+ return makeCtx(input, {
27
+ ...context,
28
+ ...patch
29
+ });
30
+ }
31
+ };
60
32
  }
61
-
62
- /**
63
- * Same-origin enforcement for the server-function HTTP transport.
64
- *
65
- * Server functions are same-origin RPC: a client proxy only ever calls the
66
- * relative `/_analog/fn/:id` URL of its own app. A cross-origin page must not be
67
- * able to invoke them against a logged-in user (a CSRF-shaped attack), so the
68
- * transport rejects browser requests whose origin is not the app's own — out of
69
- * the box, with no per-app configuration.
70
- *
71
- * The signals used (`Sec-Fetch-Site`, `Origin`) are added by the browser and
72
- * cannot be forged by a cross-origin page's `fetch`. Non-browser callers (curl,
73
- * server-to-server, SSR in-process) send neither, so they are unaffected: the
74
- * guard blocks the cross-origin browser attack it is meant to, and nothing else.
75
- */
76
- /**
77
- * Origins permitted beyond the app's own, registered through DI:
78
- * `provideServerFns(withAllowedOrigins([...]))`. Empty by default — the
79
- * transport is same-origin unless an app opts out explicitly.
80
- */
81
- const SERVER_FN_ALLOWED_ORIGINS = new InjectionToken('SERVER_FN_ALLOWED_ORIGINS');
82
- /**
83
- * `withAllowedOrigins([...])` — permit cross-origin browser calls from the
84
- * listed origins, or pass `'*'` to disable the same-origin guard entirely.
85
- * Server functions are frequently cookie-authenticated, so this is an explicit
86
- * opt-out of CSRF protection: allow-list the exact origins you control.
87
- */
33
+ async function runInterceptors(interceptors, input, handler, runInCtx = (fn) => fn()) {
34
+ let i = -1;
35
+ const dispatch = async (ctx) => {
36
+ i += 1;
37
+ if (i < interceptors.length) return runInCtx(() => interceptors[i](ctx, dispatch));
38
+ return runInCtx(() => handler(ctx.input, ctx.context));
39
+ };
40
+ return dispatch(makeCtx(input, {}));
41
+ }
42
+ const SERVER_FN_ALLOWED_ORIGINS = new InjectionToken("SERVER_FN_ALLOWED_ORIGINS");
88
43
  function withAllowedOrigins(origins) {
89
- return {
90
- providers: origins.map((origin) => ({
91
- provide: SERVER_FN_ALLOWED_ORIGINS,
92
- useValue: origin,
93
- multi: true,
94
- })),
95
- };
44
+ return { providers: origins.map((origin) => ({
45
+ provide: SERVER_FN_ALLOWED_ORIGINS,
46
+ useValue: origin,
47
+ multi: true
48
+ })) };
96
49
  }
97
50
  function firstHeader(value) {
98
- return Array.isArray(value) ? value[0] : value;
99
- }
100
- /**
101
- * Whether an HTTP request to a server function may proceed.
102
- *
103
- * Allowed when the request is same-origin, carries no browser-origin signal at
104
- * all (a non-browser client, or a same-origin GET that omits `Origin`), or its
105
- * `Origin` is listed in `allowedOrigins`. Passing `'*'` in `allowedOrigins`
106
- * disables the check — the explicit opt-in to cross-origin access.
107
- *
108
- * `Sec-Fetch-Site` is the authoritative signal when present: `same-origin` and
109
- * `none` (a direct navigation, not a cross-site fetch) pass; `same-site` and
110
- * `cross-site` require an explicit `allowedOrigins` entry. When the header is
111
- * absent (older browsers, some proxies) the `Origin` host is compared to the
112
- * request host as a fallback.
113
- */
51
+ return Array.isArray(value) ? value[0] : value;
52
+ }
114
53
  function isServerFnOriginAllowed(headers, allowedOrigins = []) {
115
- if (allowedOrigins.includes('*')) {
116
- return true;
117
- }
118
- const origin = firstHeader(headers['origin']);
119
- const originAllowlisted = origin !== undefined && allowedOrigins.includes(origin);
120
- const site = firstHeader(headers['sec-fetch-site']);
121
- if (site) {
122
- if (site === 'same-origin' || site === 'none') {
123
- return true;
124
- }
125
- // same-site / cross-site: only when the origin is explicitly permitted.
126
- return originAllowlisted;
127
- }
128
- // No `Sec-Fetch-Site`: fall back to comparing the `Origin` host to the host.
129
- if (!origin) {
130
- // Non-browser client, or a same-origin GET with no `Origin` — not the
131
- // cross-origin browser request this guard exists to reject.
132
- return true;
133
- }
134
- if (originAllowlisted) {
135
- return true;
136
- }
137
- const host = firstHeader(headers['x-forwarded-host']) ?? firstHeader(headers['host']);
138
- if (!host) {
139
- return false;
140
- }
141
- try {
142
- return new URL(origin).host === host;
143
- }
144
- catch {
145
- return false;
146
- }
54
+ if (allowedOrigins.includes("*")) return true;
55
+ const origin = firstHeader(headers["origin"]);
56
+ const originAllowlisted = origin !== void 0 && allowedOrigins.includes(origin);
57
+ const site = firstHeader(headers["sec-fetch-site"]);
58
+ if (site) {
59
+ if (site === "same-origin" || site === "none") return true;
60
+ return originAllowlisted;
61
+ }
62
+ if (!origin) return true;
63
+ if (originAllowlisted) return true;
64
+ const host = firstHeader(headers["x-forwarded-host"]) ?? firstHeader(headers["host"]);
65
+ if (!host) return false;
66
+ try {
67
+ return new URL(origin).host === host;
68
+ } catch {
69
+ return false;
70
+ }
147
71
  }
148
-
149
- /**
150
- * Server-side dispatch for a server function call.
151
- *
152
- * 1. reject cross-origin browser calls (403), unless allow-listed — HTTP
153
- * transport only (in-process callers omit `method` and are exempt)
154
- * 2. look up the function by id
155
- * 3. enforce the configured HTTP method (405 on mismatch)
156
- * 4. require a JSON body on input-bearing calls (415 otherwise)
157
- * 5. validate `input` against the Standard-Schema (4xx on failure)
158
- * 6. build a per-request injector (REQUEST/RESPONSE + app providers)
159
- * 7. run the interceptor chain, then the handler, re-entering
160
- * `runInInjectionContext` at every hop so `inject()` works even after an
161
- * interceptor `await`s before calling `next`
162
- * 8. a `Response` returned by an interceptor/handler (`fail`/`redirect`)
163
- * short-circuits with its status AND headers
164
- *
165
- * `options.method` is the request's HTTP method; when provided it is enforced
166
- * against the function's configured method AND it turns on the same-origin
167
- * guard. Transports (the generated Nitro handler) always pass it; trusted
168
- * in-process callers may omit it, which also exempts them from the origin guard.
169
- */
170
72
  async function dispatchServerFn(id, rawInput, event, options = {}) {
171
- const { parent, providers = [], method, allowedOrigins = [] } = options;
172
- const headers = (event.node.req.headers ?? {});
173
- // Same-origin guard runs first — before we even confirm the function exists —
174
- // so a cross-origin page cannot probe which ids are registered. Gated on
175
- // `method` so only HTTP-transport calls are checked; in-process callers omit
176
- // it. The signals (`Origin`/`Sec-Fetch-Site`) are browser-set and unforgeable.
177
- if (method) {
178
- const allowed = [
179
- ...allowedOrigins,
180
- ...(parent?.get(SERVER_FN_ALLOWED_ORIGINS, []) ?? []),
181
- ];
182
- if (!isServerFnOriginAllowed(headers, allowed)) {
183
- return {
184
- status: 403,
185
- body: { message: 'Cross-origin server function call rejected' },
186
- };
187
- }
188
- }
189
- const def = serverFnRegistry.get(id);
190
- if (!def) {
191
- return { status: 404, body: { message: `Unknown server function: ${id}` } };
192
- }
193
- // Enforce the transport method: a GET-only read must not be POSTable, and an
194
- // input-bearing POST must not be reachable via GET.
195
- if (method && method.toUpperCase() !== def.method) {
196
- return {
197
- status: 405,
198
- body: { message: `Method ${method} not allowed for ${id}` },
199
- headers: { Allow: def.method },
200
- };
201
- }
202
- // Input travels as a JSON body. Reject anything else before decoding, so a
203
- // form post from a cross-origin page (which cannot set a JSON content type
204
- // without a CORS preflight) never reaches a handler. HTTP transport only.
205
- if (method && def.method === 'POST' && !isJsonContentType(headers)) {
206
- return {
207
- status: 415,
208
- body: { message: 'Server functions accept an application/json body' },
209
- };
210
- }
211
- let input = rawInput;
212
- if (def.config.input) {
213
- const result = await def.config.input['~standard'].validate(rawInput);
214
- if ('issues' in result && result.issues) {
215
- return { status: 400, body: { errors: result.issues } };
216
- }
217
- input = result.value;
218
- }
219
- // Child of the app injector: only the request tokens are per-request; app
220
- // services + interceptors resolve up the parent chain. All four are provided
221
- // here so a handler resolves them the same way it would inside a component
222
- // during SSR, whether it was reached over HTTP or in-process.
223
- const req = event.node.req;
224
- const locale = detectLocale(req);
225
- const injector = Injector.create({
226
- parent,
227
- providers: [
228
- { provide: REQUEST, useValue: event.node.req },
229
- { provide: RESPONSE, useValue: event.node.res },
230
- { provide: BASE_URL, useValue: getBaseUrl(req) },
231
- ...(locale ? [{ provide: LOCALE, useValue: locale }] : []),
232
- ...providers,
233
- ],
234
- });
235
- // Re-enter the injection context at each hop rather than wrapping the whole
236
- // chain once: an interceptor that awaits before `next` would otherwise run the
237
- // handler outside the context and break `inject()`.
238
- const runInCtx = (fn) => runInInjectionContext(injector, fn);
239
- const interceptors = injector.get(SERVER_FN_INTERCEPTORS, []);
240
- const outcome = await runInterceptors(interceptors, input, def.handler, runInCtx);
241
- if (outcome instanceof Response) {
242
- const text = await outcome.text();
243
- const body = text ? safeJson(text) : null;
244
- const headers = {};
245
- outcome.headers.forEach((value, key) => {
246
- if (key.toLowerCase() !== 'set-cookie') {
247
- headers[key] = value;
248
- }
249
- });
250
- // `Headers.forEach` yields cookies comma-joined into a single value, which
251
- // is not a valid way to send more than one; `getSetCookie` keeps them apart.
252
- const setCookie = outcome.headers.getSetCookie?.() ?? [];
253
- if (setCookie.length) {
254
- headers['set-cookie'] = setCookie;
255
- }
256
- return {
257
- status: outcome.status,
258
- body,
259
- headers: Object.keys(headers).length ? headers : undefined,
260
- };
261
- }
262
- return { status: 200, body: outcome };
73
+ const { parent, providers = [], method, allowedOrigins = [] } = options;
74
+ const headers = event.node.req.headers ?? {};
75
+ if (method) {
76
+ if (!isServerFnOriginAllowed(headers, [...allowedOrigins, ...parent?.get(SERVER_FN_ALLOWED_ORIGINS, []) ?? []])) return {
77
+ status: 403,
78
+ body: { message: "Cross-origin server function call rejected" }
79
+ };
80
+ }
81
+ const def = serverFnRegistry.get(id);
82
+ if (!def) return {
83
+ status: 404,
84
+ body: { message: `Unknown server function: ${id}` }
85
+ };
86
+ if (method && method.toUpperCase() !== def.method) return {
87
+ status: 405,
88
+ body: { message: `Method ${method} not allowed for ${id}` },
89
+ headers: { Allow: def.method }
90
+ };
91
+ if (method && def.method === "POST" && !isJsonContentType(headers)) return {
92
+ status: 415,
93
+ body: { message: "Server functions accept an application/json body" }
94
+ };
95
+ let input = rawInput;
96
+ if (def.config.input) {
97
+ const result = await def.config.input["~standard"].validate(rawInput);
98
+ if ("issues" in result && result.issues) return {
99
+ status: 400,
100
+ body: { errors: result.issues }
101
+ };
102
+ input = result.value;
103
+ }
104
+ const req = event.node.req;
105
+ const locale = detectLocale(req);
106
+ const injector = Injector.create({
107
+ parent,
108
+ providers: [
109
+ {
110
+ provide: REQUEST,
111
+ useValue: event.node.req
112
+ },
113
+ {
114
+ provide: RESPONSE,
115
+ useValue: event.node.res
116
+ },
117
+ {
118
+ provide: BASE_URL,
119
+ useValue: getBaseUrl(req)
120
+ },
121
+ ...locale ? [{
122
+ provide: LOCALE,
123
+ useValue: locale
124
+ }] : [],
125
+ ...providers
126
+ ]
127
+ });
128
+ const runInCtx = (fn) => runInInjectionContext(injector, fn);
129
+ const outcome = await runInterceptors(injector.get(SERVER_FN_INTERCEPTORS, []), input, def.handler, runInCtx);
130
+ if (outcome instanceof Response) {
131
+ const text = await outcome.text();
132
+ const body = text ? safeJson(text) : null;
133
+ const headers = {};
134
+ outcome.headers.forEach((value, key) => {
135
+ if (key.toLowerCase() !== "set-cookie") headers[key] = value;
136
+ });
137
+ const setCookie = outcome.headers.getSetCookie?.() ?? [];
138
+ if (setCookie.length) headers["set-cookie"] = setCookie;
139
+ return {
140
+ status: outcome.status,
141
+ body,
142
+ headers: Object.keys(headers).length ? headers : void 0
143
+ };
144
+ }
145
+ return {
146
+ status: 200,
147
+ body: outcome
148
+ };
263
149
  }
264
150
  function isJsonContentType(headers) {
265
- const contentType = headers['content-type'];
266
- const value = Array.isArray(contentType) ? contentType[0] : contentType;
267
- if (!value) {
268
- return false;
269
- }
270
- const mediaType = value.split(';')[0].trim().toLowerCase();
271
- return mediaType === 'application/json' || mediaType.endsWith('+json');
151
+ const contentType = headers["content-type"];
152
+ const value = Array.isArray(contentType) ? contentType[0] : contentType;
153
+ if (!value) return false;
154
+ const mediaType = value.split(";")[0].trim().toLowerCase();
155
+ return mediaType === "application/json" || mediaType.endsWith("+json");
272
156
  }
273
157
  function safeJson(text) {
274
- try {
275
- return JSON.parse(text);
276
- }
277
- catch {
278
- return text;
279
- }
158
+ try {
159
+ return JSON.parse(text);
160
+ } catch {
161
+ return text;
162
+ }
280
163
  }
281
-
282
- /**
283
- * The in-process transport used during SSR. `ServerFnClient` picks this up from
284
- * DI and calls the handler directly instead of issuing an HTTP request back
285
- * into the app — the render and the handler already share a process and a
286
- * request, so the round-trip only adds latency (and would need an absolute URL).
287
- *
288
- * `method` is deliberately not passed to `dispatchServerFn`: this is a trusted
289
- * in-process caller, so the HTTP-transport-only checks (same-origin, method
290
- * enforcement, content type) do not apply. Validation and the interceptor chain
291
- * still run, so an SSR call behaves like a browser call in every other respect.
292
- *
293
- * A non-2xx result is thrown as an `HttpErrorResponse` so the failure surfaces
294
- * on `resource.error()` exactly as it does in the browser.
295
- */
296
164
  function createServerFnDispatcher(req, res) {
297
- const event = { node: { req, res } };
298
- return async (fn, input, injector) => {
299
- const { status, body } = await dispatchServerFn(fn.id, input, event, {
300
- parent: injector,
301
- });
302
- if (status < 200 || status > 299) {
303
- throw new HttpErrorResponse({ status, error: body, url: fn.url });
304
- }
305
- return body;
306
- };
165
+ const event = { node: {
166
+ req,
167
+ res
168
+ } };
169
+ return async (fn, input, injector) => {
170
+ const { status, body } = await dispatchServerFn(fn.id, input, event, { parent: injector });
171
+ if (status < 200 || status > 299) throw new HttpErrorResponse({
172
+ status,
173
+ error: body,
174
+ url: fn.url
175
+ });
176
+ return body;
177
+ };
178
+ }
179
+ function provideServerContext({ req, res }) {
180
+ const baseUrl = getBaseUrl(req);
181
+ const locale = typeof ANALOG_I18N_FIXED_LOCALE !== "undefined" && ANALOG_I18N_FIXED_LOCALE || detectLocale(req);
182
+ if (import.meta.env?.DEV) ɵresetCompiledComponents();
183
+ return [
184
+ {
185
+ provide: ɵSERVER_CONTEXT,
186
+ useValue: "ssr-analog"
187
+ },
188
+ {
189
+ provide: REQUEST,
190
+ useValue: req
191
+ },
192
+ {
193
+ provide: RESPONSE,
194
+ useValue: res
195
+ },
196
+ {
197
+ provide: BASE_URL,
198
+ useValue: baseUrl
199
+ },
200
+ {
201
+ provide: SERVER_FN_DISPATCHER,
202
+ useValue: createServerFnDispatcher(req, res)
203
+ },
204
+ ...locale ? [{
205
+ provide: LOCALE,
206
+ useValue: locale
207
+ }] : []
208
+ ];
307
209
  }
308
-
309
- function provideServerContext({ req, res, }) {
310
- const baseUrl = getBaseUrl(req);
311
- const locale = detectLocale(req);
312
- // Optional chaining: a Nitro-bundled caller has no `import.meta.env` at all.
313
- if (import.meta.env?.DEV) {
314
- _resetCompiledComponents();
315
- }
316
- return [
317
- { provide: _SERVER_CONTEXT, useValue: 'ssr-analog' },
318
- { provide: REQUEST, useValue: req },
319
- { provide: RESPONSE, useValue: res },
320
- { provide: BASE_URL, useValue: baseUrl },
321
- // Server functions called while rendering run in-process, in this injector.
322
- {
323
- provide: SERVER_FN_DISPATCHER,
324
- useValue: createServerFnDispatcher(req, res),
325
- },
326
- ...(locale ? [{ provide: LOCALE, useValue: locale }] : []),
327
- ];
328
- }
329
- /**
330
- * Detects the locale from the request URL path prefix or Accept-Language header.
331
- * URL prefix takes priority (e.g. /fr/about -> 'fr').
332
- */
333
210
  function detectLocale(req) {
334
- const url = req.originalUrl || req.url || '';
335
- const localeFromUrl = extractLocaleFromUrl(url);
336
- if (localeFromUrl) {
337
- return localeFromUrl;
338
- }
339
- return parseAcceptLanguage(req.headers['accept-language']);
211
+ const localeFromUrl = extractLocaleFromUrl(req.originalUrl || req.url || "");
212
+ if (localeFromUrl) return localeFromUrl;
213
+ return parseAcceptLanguage(req.headers["accept-language"]);
340
214
  }
341
- /**
342
- * Extracts a locale from the first URL path segment if it matches
343
- * a BCP 47-like pattern (e.g. 'en', 'en-US', 'zh-Hans-CN').
344
- */
345
215
  function extractLocaleFromUrl(url) {
346
- const pathname = url.split('?')[0];
347
- const segments = pathname.split('/').filter(Boolean);
348
- if (segments.length === 0) {
349
- return undefined;
350
- }
351
- const firstSegment = segments[0];
352
- // Match BCP 47 language tags: 2-letter language code with optional region/script
353
- // e.g. 'en', 'en-US', 'zh-Hans', 'zh-Hans-CN'
354
- if (/^[a-z]{2}(-[a-zA-Z]{2,4})?(-[a-zA-Z]{2}|\d{3})?$/.test(firstSegment)) {
355
- return firstSegment;
356
- }
357
- return undefined;
216
+ const segments = url.split("?")[0].split("/").filter(Boolean);
217
+ if (segments.length === 0) return;
218
+ const firstSegment = segments[0];
219
+ if (/^[a-z]{2}(-[a-zA-Z]{2,4})?(-[a-zA-Z]{2}|\d{3})?$/.test(firstSegment)) return firstSegment;
358
220
  }
359
- /**
360
- * Parses the Accept-Language header and returns the most preferred language.
361
- */
362
221
  function parseAcceptLanguage(header) {
363
- if (!header) {
364
- return undefined;
365
- }
366
- const locales = header
367
- .split(',')
368
- .map((part) => {
369
- const [locale, qPart] = part.trim().split(';');
370
- const q = qPart ? parseFloat(qPart.replace('q=', '')) : 1;
371
- return { locale: locale.trim(), q };
372
- })
373
- .sort((a, b) => b.q - a.q);
374
- return locales[0]?.locale || undefined;
222
+ if (!header) return;
223
+ return header.split(",").map((part) => {
224
+ const [locale, qPart] = part.trim().split(";");
225
+ const q = qPart ? parseFloat(qPart.replace("q=", "")) : 1;
226
+ return {
227
+ locale: locale.trim(),
228
+ q
229
+ };
230
+ }).sort((a, b) => b.q - a.q)[0]?.locale || void 0;
375
231
  }
376
232
  function getBaseUrl(req) {
377
- const protocol = getRequestProtocol(req);
378
- const { headers } = req;
379
- // Node's `IncomingMessage` has no `originalUrl`, and a server function
380
- // endpoint is reached with a plain request, so fall back before dereferencing.
381
- const originalUrl = req.originalUrl || req.url || '/';
382
- const parsedUrl = new URL('', `${protocol}://${headers.host}${originalUrl.endsWith('/')
383
- ? originalUrl.substring(0, originalUrl.length - 1)
384
- : originalUrl}`);
385
- const baseUrl = parsedUrl.origin;
386
- return baseUrl;
233
+ const protocol = getRequestProtocol(req);
234
+ const { headers } = req;
235
+ const originalUrl = req.originalUrl || req.url || "/";
236
+ return new URL("", `${protocol}://${headers.host}${originalUrl.endsWith("/") ? originalUrl.substring(0, originalUrl.length - 1) : originalUrl}`).origin;
387
237
  }
388
238
  function getRequestProtocol(req, opts = {}) {
389
- if (opts.xForwardedProto !== false &&
390
- req.headers['x-forwarded-proto'] === 'https') {
391
- return 'https';
392
- }
393
- return req.connection?.encrypted ? 'https' : 'http';
239
+ if (opts.xForwardedProto !== false && req.headers["x-forwarded-proto"] === "https") return "https";
240
+ return req.connection?.encrypted ? "https" : "http";
394
241
  }
395
-
396
- /**
397
- * Nulls `def.tView` on every component definition that Angular has
398
- * compiled in this process. Angular caches the result of `consts()` on
399
- * `def.tView` — that factory is where `$localize` tagged templates are
400
- * evaluated — so without this reset the first rendered locale would be
401
- * frozen into the cache for the process lifetime.
402
- *
403
- * The set on `globalThis.__ngComponentDefs` is populated by a Vite
404
- * transform in `@analogjs/platform` that patches `@angular/core`'s
405
- * `getComponentId()` to mirror every compiled component definition to
406
- * a global Set, bypassing the `ngServerMode` guard that normally
407
- * prevents registration on the server.
408
- */
409
242
  function resetComponentDefTViews() {
410
- const defs = globalThis.__ngComponentDefs;
411
- if (!defs)
412
- return;
413
- for (const def of defs) {
414
- def.tView = null;
415
- }
243
+ if (typeof ANALOG_I18N_FIXED_LOCALE !== "undefined" && ANALOG_I18N_FIXED_LOCALE) return;
244
+ const defs = globalThis.__ngComponentDefs;
245
+ if (!defs) return;
246
+ for (const def of defs) def.tView = null;
416
247
  }
417
-
418
- // Optional chaining: the server-function dispatch endpoint imports this entry
419
- // from a Nitro bundle, where `import.meta.env` is not defined at all.
420
- if (import.meta.env?.PROD) {
421
- enableProdMode();
422
- }
423
- /**
424
- * Returns a function that accepts the navigation URL,
425
- * the root HTML, and server context.
426
- *
427
- * @param rootComponent
428
- * @param config
429
- * @param platformProviders
430
- * @returns Promise<string | Reponse>
431
- */
248
+ if (import.meta.env?.PROD) enableProdMode();
432
249
  function render(rootComponent, config, platformProviders = []) {
433
- function bootstrap(context) {
434
- return bootstrapApplication(rootComponent, config, context);
435
- }
436
- return async function render(url, document, serverContext) {
437
- resetComponentDefTViews();
438
- const html = await renderApplication(bootstrap, {
439
- document,
440
- url,
441
- platformProviders: [
442
- provideServerContext(serverContext),
443
- platformProviders,
444
- ],
445
- });
446
- return html;
447
- };
250
+ function bootstrap(context) {
251
+ return bootstrapApplication(rootComponent, config, context);
252
+ }
253
+ return async function render(url, document, serverContext) {
254
+ resetComponentDefTViews();
255
+ return await renderApplication(bootstrap, {
256
+ document,
257
+ url,
258
+ platformProviders: [provideServerContext(serverContext), platformProviders]
259
+ });
260
+ };
448
261
  }
449
-
450
- /**
451
- * Pure string helpers for slicing a fully rendered SSR document into the parts
452
- * the streaming renderer flushes: the shell up to `<body>`, the authoritative
453
- * `<body>` inner HTML for the tail, and the authoritative `<head>` inner HTML
454
- * for the finalize-time head reconcile. Extracted from `render-stream` so they
455
- * can be unit tested without driving the platform.
456
- */
457
- /** Byte offset just after the opening `<body>` tag, or 0 if none. */
458
262
  function afterBodyOpen(html) {
459
- const m = /<body[^>]*>/i.exec(html);
460
- return m ? m.index + m[0].length : 0;
263
+ const m = /<body[^>]*>/i.exec(html);
264
+ return m ? m.index + m[0].length : 0;
461
265
  }
462
- /** Inner HTML of `<body>` from a fully rendered document string. */
463
266
  function bodyInner(html) {
464
- const start = afterBodyOpen(html);
465
- const end = html.lastIndexOf('</body>');
466
- return html.slice(start, end > -1 ? end : html.length);
267
+ const start = afterBodyOpen(html);
268
+ const end = html.lastIndexOf("</body>");
269
+ return html.slice(start, end > -1 ? end : html.length);
467
270
  }
468
- /** Inner HTML of `<head>` from a fully rendered document string. */
469
271
  function headInner(html) {
470
- const open = /<head[^>]*>/i.exec(html);
471
- if (!open)
472
- return '';
473
- const start = open.index + open[0].length;
474
- const end = html.indexOf('</head>', start);
475
- return html.slice(start, end > -1 ? end : start);
272
+ const open = /<head[^>]*>/i.exec(html);
273
+ if (!open) return "";
274
+ const start = open.index + open[0].length;
275
+ const end = html.indexOf("</head>", start);
276
+ return html.slice(start, end > -1 ? end : start);
476
277
  }
477
-
478
- /**
479
- * Per-request decisions about whether the streaming renderer should fall back
480
- * to a buffered render. Extracted from `render-stream` so they can be unit
481
- * tested without driving the platform.
482
- */
483
- /**
484
- * User agents that receive a fully buffered render (with a resolved `<head>`)
485
- * instead of the streamed shell. Streaming flushes the head before the app has
486
- * set a dynamic title/meta and reconciles it via a finalize script; a crawler
487
- * that does not run that script would index the shell's static head. Mirrors
488
- * Nuxt's bot bypass — streaming targets interactive clients, bots get the
489
- * buffered path whose head is byte-identical to the classic `render()`.
490
- */
491
278
  const SSR_BOT_RE = /bot|crawl|spider|slurp|mediapartners|facebookexternalhit|embedly|quora link preview|outbrain|pinterest|vkshare|w3c_validator|whatsapp|telegrambot|lighthouse|google-inspectiontool|headlesschrome|bingpreview/i;
492
279
  function isLikelyBot(serverContext) {
493
- const ua = serverContext?.req?.headers?.['user-agent'];
494
- return typeof ua === 'string' && SSR_BOT_RE.test(ua);
495
- }
496
- /**
497
- * Whether streaming is disabled for this request by a `streaming: false` route
498
- * rule. The platform plugin translates that rule into an `x-analog-no-streaming`
499
- * response header (mirroring how `ssr: false` becomes `x-analog-no-ssr`); when
500
- * present, `renderStream` produces the buffered `render()` output for this
501
- * route instead of streaming.
502
- */
280
+ const ua = serverContext?.req?.headers?.["user-agent"];
281
+ return typeof ua === "string" && SSR_BOT_RE.test(ua);
282
+ }
503
283
  function streamingDisabledByRoute(serverContext) {
504
- return serverContext?.res?.getHeader?.('x-analog-no-streaming') === 'true';
284
+ return serverContext?.res?.getHeader?.("x-analog-no-streaming") === "true";
505
285
  }
506
-
507
- /**
508
- * Tiny client runtime for progressive streaming SSR — EXPERIMENTAL.
509
- *
510
- * `renderStream` streams the document in three parts:
511
- * 1. the head + this runtime + an empty `<div data-analog-stream>` region;
512
- * 2. each `@defer` block, as it resolves on the server, as a
513
- * `<template data-analog-defer="ID">…</template>` followed by a call to
514
- * `window.__analogPaint("ID")` — this runtime paints the block into the
515
- * streaming region immediately, so content appears progressively and out
516
- * of document order;
517
- * 3. the authoritative document tail: the app's resolved `<head>` in a
518
- * `<template data-analog-head>` and the hydration-annotated body in a
519
- * `<template data-analog-authoritative>`, followed by
520
- * `window.__analogReconcileHead()` + `window.__analogFinalize()`. The head
521
- * is reconciled first (a dynamically-set `<title>`/meta is applied to the
522
- * live document, since the streamed shell head was flushed before the app
523
- * ran), then the body is swapped to the exact document Angular's
524
- * incremental hydration expects.
525
- *
526
- * Emitted into the document by `renderStream`. Exported as a string so it can
527
- * be injected verbatim and unit-tested against a DOM.
528
- */
529
- const DEFER_RECONCILE_RUNTIME = /* js */ `
286
+ const DEFER_RECONCILE_RUNTIME = `
530
287
  (function () {
531
288
  function region() {
532
289
  return document.querySelector('[data-analog-stream]');
@@ -594,372 +351,170 @@ const DEFER_RECONCILE_RUNTIME = /* js */ `
594
351
  };
595
352
  })();
596
353
  `;
597
-
598
- /**
599
- * Progressive streaming SSR renderer — EXPERIMENTAL.
600
- *
601
- * Returns a `ReadableStream<Uint8Array>` that flushes bytes DURING the render,
602
- * not after it:
603
- * 1. the document head + a client reconcile runtime are flushed immediately,
604
- * before the app has finished rendering, so the browser starts fetching
605
- * assets right away;
606
- * 2. each `@defer (hydrate …)` block's content is flushed the moment it
607
- * resolves on the server — out of document order — while later blocks are
608
- * still pending (proven: a slow block does not hold back an early one);
609
- * 3. once the app is stable, the authoritative, fully hydration-annotated
610
- * document is flushed as the tail. This is byte-identical to a buffered
611
- * `renderApplication`, and is what Angular's incremental hydration runs
612
- * against on the client.
613
- *
614
- * Unlike a buffered renderer, this drives the platform directly
615
- * (`platformServer` + `bootstrapApplication` + `ɵrenderInternal`) so it can
616
- * interleave flushes with rendering. Angular's hydration annotation is
617
- * whole-document (the root's `ngh` index references every `@defer` container),
618
- * so the authoritative hydration payload is necessarily the tail: RENDERING
619
- * streams progressively, and hydration begins once the tail arrives.
620
- *
621
- * Depends on an upstream Angular per-block resolution hook exposed on two
622
- * globals (see {@link SsrStreamingGlobals}). When the primitive is absent,
623
- * `renderStream` degrades to a single buffered chunk so behaviour matches the
624
- * classic `render()` path, which is unchanged and remains the default.
625
- */
626
- // Optional chaining: the server-function dispatch endpoint imports this entry
627
- // from a Nitro bundle, where `import.meta.env` is not defined at all.
628
- if (import.meta.env?.PROD) {
629
- enableProdMode();
630
- }
354
+ if (import.meta.env?.PROD) enableProdMode();
631
355
  function streamingPrimitiveAvailable() {
632
- const g = globalThis;
633
- return (typeof g.__analogSsrInternals?.collectNativeNodesInLContainer === 'function');
634
- }
635
- /**
636
- * Per-render capture handlers live in async-local storage, not a single shared
637
- * global slot, so concurrent renders in one process do not clobber each other.
638
- * `globalThis.__analogSsrDeferCapture` is a stable dispatcher installed once; it
639
- * routes each resolved `@defer` block to the handler of the render whose async
640
- * context it fired in. A block that resolves outside any render (no store) is a
641
- * no-op.
642
- */
356
+ return typeof globalThis.__analogSsrInternals?.collectNativeNodesInLContainer === "function";
357
+ }
643
358
  const captureStore = new AsyncLocalStorage();
644
359
  function installCaptureDispatcher() {
645
- const g = globalThis;
646
- if (g.__analogSsrDeferCapture?.__analogDispatcher)
647
- return;
648
- const dispatch = ((ev) => {
649
- captureStore.getStore()?.(ev);
650
- });
651
- dispatch.__analogDispatcher = true;
652
- g.__analogSsrDeferCapture = dispatch;
360
+ const g = globalThis;
361
+ if (g.__analogSsrDeferCapture?.__analogDispatcher) return;
362
+ const dispatch = ((ev) => {
363
+ captureStore.getStore()?.(ev);
364
+ });
365
+ dispatch.__analogDispatcher = true;
366
+ g.__analogSsrDeferCapture = dispatch;
653
367
  }
654
368
  let warnedMissingPrimitive = false;
655
369
  function warnMissingPrimitiveOnce() {
656
- if (warnedMissingPrimitive || !import.meta.env?.DEV)
657
- return;
658
- warnedMissingPrimitive = true;
659
- console.warn('[@analogjs/router] renderStream: the streaming hook was not found on ' +
660
- '@angular/core, so rendering falls back to buffered. Enable ' +
661
- '`experimental.streaming` in your Analog config; if it already is, your ' +
662
- 'installed Angular version may be incompatible with the streaming patch.');
663
- }
664
- /**
665
- * Serialize a `@defer` block's live domino subtree to HTML. Called a macrotask
666
- * after the block resolves, by which point change detection has filled in the
667
- * block's interpolations.
668
- */
370
+ if (warnedMissingPrimitive || !import.meta.env?.DEV) return;
371
+ warnedMissingPrimitive = true;
372
+ console.warn("[@analogjs/router] renderStream: the streaming hook was not found on @angular/core, so rendering falls back to buffered. Enable `experimental.streaming` in your Analog config; if it already is, your installed Angular version may be incompatible with the streaming patch.");
373
+ }
669
374
  function serializeLContainerHtml(lContainer) {
670
- const g = globalThis;
671
- const collect = g.__analogSsrInternals?.collectNativeNodesInLContainer;
672
- if (!collect)
673
- return '';
674
- const nodes = [];
675
- collect(lContainer, nodes);
676
- let html = '';
677
- for (const n of nodes)
678
- html += n?.outerHTML ?? n?.data ?? n?.nodeValue ?? '';
679
- return html;
680
- }
681
- /** Destroy the platform on a macrotask, matching `renderApplication`. */
375
+ const collect = globalThis.__analogSsrInternals?.collectNativeNodesInLContainer;
376
+ if (!collect) return "";
377
+ const nodes = [];
378
+ collect(lContainer, nodes);
379
+ let html = "";
380
+ for (const n of nodes) html += n?.outerHTML ?? n?.data ?? n?.nodeValue ?? "";
381
+ return html;
382
+ }
682
383
  function asyncDestroyPlatform(platformRef) {
683
- return new Promise((resolve) => {
684
- setTimeout(() => {
685
- platformRef.destroy();
686
- resolve();
687
- }, 0);
688
- });
384
+ return new Promise((resolve) => {
385
+ setTimeout(() => {
386
+ platformRef.destroy();
387
+ resolve();
388
+ }, 0);
389
+ });
689
390
  }
690
- /**
691
- * Returns a function that renders a URL to a `ReadableStream<Uint8Array>`.
692
- *
693
- * Usage in main.server.ts:
694
- * ```ts
695
- * import { renderStream } from '@analogjs/router/server';
696
- * export default renderStream(App, config);
697
- * ```
698
- */
699
391
  function renderStream(rootComponent, config, platformProviders = []) {
700
- function bootstrap(context) {
701
- return bootstrapApplication(rootComponent, config, context);
702
- }
703
- return async function renderStream(url, document, serverContext) {
704
- // Reset before every render — both the buffered fallback below and the
705
- // streaming path — so a prior render's locale/consts are not frozen for the
706
- // process lifetime (parity with render.ts).
707
- resetComponentDefTViews();
708
- // Fall back to a single buffered chunk so output matches the classic path
709
- // for:
710
- // - crawlers, which may not run the finalize script that reconciles a
711
- // dynamic <head>, so they get a buffered render with a resolved head;
712
- // - routes with a `streaming: false` rule (opt out per route);
713
- // - a missing streaming primitive.
714
- const primitiveAvailable = streamingPrimitiveAvailable();
715
- const bot = isLikelyBot(serverContext);
716
- const routeDisabled = streamingDisabledByRoute(serverContext);
717
- if (bot || routeDisabled || !primitiveAvailable) {
718
- // Warn only when the primitive is genuinely absent — the bot and
719
- // route-opt-out paths fall back to buffered by design, not by degradation.
720
- if (!bot && !routeDisabled && !primitiveAvailable) {
721
- warnMissingPrimitiveOnce();
722
- }
723
- const html = await renderApplication((context) => bootstrapApplication(rootComponent, config, context), {
724
- document,
725
- url,
726
- platformProviders: [
727
- provideServerContext(serverContext),
728
- platformProviders,
729
- ],
730
- });
731
- return new ReadableStream({
732
- start(controller) {
733
- controller.enqueue(new TextEncoder().encode(html));
734
- controller.close();
735
- },
736
- });
737
- }
738
- installCaptureDispatcher();
739
- const encoder = new TextEncoder();
740
- // The stream is returned immediately; `start` fills it as the render
741
- // progresses, so the consumer receives the head, then each @defer block the
742
- // moment it resolves, then the authoritative tail — true streaming.
743
- return new ReadableStream({
744
- async start(controller) {
745
- const enqueue = (s) => controller.enqueue(encoder.encode(s));
746
- // The capture handler fires once per @defer block as it resolves. The
747
- // block's DOM is not filled until the next change-detection tick, so we
748
- // serialize + flush it a macrotask later — flushing DURING the render.
749
- // It is scoped to this render via async-local storage (see
750
- // installCaptureDispatcher) so concurrent renders never cross-talk.
751
- let blockIndex = 0;
752
- let capturing = true;
753
- const seen = new Set();
754
- const pendingFlushes = [];
755
- const onBlockResolved = (ev) => {
756
- // A block can reach `Complete` more than once during a render; only
757
- // stream each container once. Also ignore any resolution that fires
758
- // after the render has moved on to serializing the authoritative tail.
759
- if (!capturing || seen.has(ev.lContainer))
760
- return;
761
- seen.add(ev.lContainer);
762
- const id = `s${blockIndex++}`;
763
- pendingFlushes.push(new Promise((resolve) => {
764
- setTimeout(() => {
765
- const html = serializeLContainerHtml(ev.lContainer);
766
- enqueue(`<template data-analog-defer="${id}">${html}</template>` +
767
- `<script>window.__analogPaint&&window.__analogPaint(${JSON.stringify(id)})</script>`);
768
- resolve();
769
- }, 0);
770
- }));
771
- };
772
- // Run the whole render inside the async-local context so every
773
- // change-detection tick and @defer resolution it schedules routes back
774
- // to THIS render's handler.
775
- await captureStore.run(onBlockResolved, async () => {
776
- const platformRef = platformServer([
777
- { provide: INITIAL_CONFIG, useValue: { document, url } },
778
- provideServerContext(serverContext),
779
- platformProviders,
780
- ]);
781
- // 1. Flush the head + reconcile runtime immediately (before the app is
782
- // rendered), then open the live streaming region.
783
- enqueue(document.slice(0, afterBodyOpen(document)) +
784
- `<script>${DEFER_RECONCILE_RUNTIME}</script>` +
785
- `<div data-analog-stream></div>`);
786
- let appRef;
787
- let errored = false;
788
- try {
789
- // 2. Bootstrap + render. Blocks resolve out of order during this
790
- // phase and flush via the capture handler above.
791
- appRef = await bootstrap({ platformRef });
792
- await appRef.whenStable();
793
- await Promise.all(pendingFlushes);
794
- // Stop capturing before serializing the tail so late resolutions
795
- // triggered by the hydration pass are not streamed as extra blocks.
796
- capturing = false;
797
- // 3. Flush the authoritative, fully hydration-annotated document as
798
- // the tail. Carried in <template>s (their inert `ng-state`
799
- // script survives). The app's resolved <head> ships alongside so
800
- // a dynamically-set title/meta — set during render, after the
801
- // shell head was already flushed — is reconciled onto the live
802
- // document before the runtime swaps in the body and hydration
803
- // boots.
804
- const authoritative = await _renderInternal(platformRef, appRef);
805
- enqueue(`<template data-analog-head>${headInner(authoritative)}</template>` +
806
- `<template data-analog-authoritative>${bodyInner(authoritative)}</template>` +
807
- `<script>window.__analogReconcileHead&&window.__analogReconcileHead();` +
808
- `window.__analogFinalize&&window.__analogFinalize()</script>` +
809
- `</body></html>`);
810
- }
811
- catch (err) {
812
- // The head + runtime were already flushed, so the status/headers are
813
- // committed; error the stream (a no-op silent close would hand the
814
- // client a truncated, non-hydratable 200) and log with block context.
815
- errored = true;
816
- console.error(`[@analogjs/router] renderStream failed for ${url} after ` +
817
- `${blockIndex} block(s); response truncated.`, err);
818
- controller.error(err);
819
- }
820
- finally {
821
- await asyncDestroyPlatform(platformRef);
822
- if (!errored)
823
- controller.close();
824
- }
825
- });
826
- },
827
- });
828
- };
392
+ function bootstrap(context) {
393
+ return bootstrapApplication(rootComponent, config, context);
394
+ }
395
+ return async function renderStream(url, document, serverContext) {
396
+ resetComponentDefTViews();
397
+ const primitiveAvailable = streamingPrimitiveAvailable();
398
+ const bot = isLikelyBot(serverContext);
399
+ const routeDisabled = streamingDisabledByRoute(serverContext);
400
+ if (bot || routeDisabled || !primitiveAvailable) {
401
+ if (!bot && !routeDisabled && !primitiveAvailable) warnMissingPrimitiveOnce();
402
+ const html = await renderApplication((context) => bootstrapApplication(rootComponent, config, context), {
403
+ document,
404
+ url,
405
+ platformProviders: [provideServerContext(serverContext), platformProviders]
406
+ });
407
+ return new ReadableStream({ start(controller) {
408
+ controller.enqueue(new TextEncoder().encode(html));
409
+ controller.close();
410
+ } });
411
+ }
412
+ installCaptureDispatcher();
413
+ const encoder = new TextEncoder();
414
+ return new ReadableStream({ async start(controller) {
415
+ const enqueue = (s) => controller.enqueue(encoder.encode(s));
416
+ let blockIndex = 0;
417
+ let capturing = true;
418
+ const seen = /* @__PURE__ */ new Set();
419
+ const pendingFlushes = [];
420
+ const onBlockResolved = (ev) => {
421
+ if (!capturing || seen.has(ev.lContainer)) return;
422
+ seen.add(ev.lContainer);
423
+ const id = `s${blockIndex++}`;
424
+ pendingFlushes.push(new Promise((resolve) => {
425
+ setTimeout(() => {
426
+ const html = serializeLContainerHtml(ev.lContainer);
427
+ enqueue(`<template data-analog-defer="${id}">${html}</template><script>window.__analogPaint&&window.__analogPaint(${JSON.stringify(id)})<\/script>`);
428
+ resolve();
429
+ }, 0);
430
+ }));
431
+ };
432
+ await captureStore.run(onBlockResolved, async () => {
433
+ const platformRef = platformServer([
434
+ {
435
+ provide: INITIAL_CONFIG,
436
+ useValue: {
437
+ document,
438
+ url
439
+ }
440
+ },
441
+ provideServerContext(serverContext),
442
+ platformProviders
443
+ ]);
444
+ enqueue(document.slice(0, afterBodyOpen(document)) + `<script>${DEFER_RECONCILE_RUNTIME}<\/script><div data-analog-stream></div>`);
445
+ let appRef;
446
+ let errored = false;
447
+ try {
448
+ appRef = await bootstrap({ platformRef });
449
+ await appRef.whenStable();
450
+ await Promise.all(pendingFlushes);
451
+ capturing = false;
452
+ const authoritative = await ɵrenderInternal(platformRef, appRef);
453
+ enqueue(`<template data-analog-head>${headInner(authoritative)}</template><template data-analog-authoritative>${bodyInner(authoritative)}</template><script>window.__analogReconcileHead&&window.__analogReconcileHead();window.__analogFinalize&&window.__analogFinalize()<\/script></body></html>`);
454
+ } catch (err) {
455
+ errored = true;
456
+ console.error(`[@analogjs/router] renderStream failed for ${url} after ${blockIndex} block(s); response truncated.`, err);
457
+ controller.error(err);
458
+ } finally {
459
+ await asyncDestroyPlatform(platformRef);
460
+ if (!errored) controller.close();
461
+ }
462
+ });
463
+ } });
464
+ };
829
465
  }
830
-
831
466
  function serverFn(arg1, arg2) {
832
- const { config, handler } = normalizeArgs(arg1, arg2);
833
- // GET is reserved for input-less reads; an input schema requires POST (the
834
- // input travels in the body, not the query). Build transforms reject this too.
835
- if (config.method === 'GET' && config.input) {
836
- throw new Error('[analog] a serverFn with `input` must use POST; GET is reserved for input-less reads.');
837
- }
838
- // `createServerFnRef` throws if the build-derived id is missing, so `ref.id`
839
- // is the authoritative route key here.
840
- const ref = createServerFnRef(config);
841
- serverFnRegistry.set(ref.id, {
842
- id: ref.id,
843
- method: ref.method,
844
- config,
845
- handler,
846
- });
847
- return ref;
467
+ const { config, handler } = normalizeArgs(arg1, arg2);
468
+ if (config.method === "GET" && config.input) throw new Error("[analog] a serverFn with `input` must use POST; GET is reserved for input-less reads.");
469
+ const ref = createServerFnRef(config);
470
+ serverFnRegistry.set(ref.id, {
471
+ id: ref.id,
472
+ method: ref.method,
473
+ config,
474
+ handler
475
+ });
476
+ return ref;
848
477
  }
849
478
  function normalizeArgs(arg1, arg2) {
850
- // serverFn(handler) — input-less GET.
851
- if (typeof arg1 === 'function') {
852
- return {
853
- config: {},
854
- handler: arg1,
855
- };
856
- }
857
- // serverFn(schema, handler) — a Standard Schema ⇒ POST + input.
858
- if (isStandardSchema(arg1)) {
859
- return {
860
- config: { input: arg1 },
861
- handler: arg2,
862
- };
863
- }
864
- // serverFn(config, handler) — explicit config object.
865
- return {
866
- config: arg1 ?? {},
867
- handler: arg2,
868
- };
479
+ if (typeof arg1 === "function") return {
480
+ config: {},
481
+ handler: arg1
482
+ };
483
+ if (isStandardSchema(arg1)) return {
484
+ config: { input: arg1 },
485
+ handler: arg2
486
+ };
487
+ return {
488
+ config: arg1 ?? {},
489
+ handler: arg2
490
+ };
869
491
  }
870
492
  function isStandardSchema(value) {
871
- return typeof value === 'object' && value !== null && '~standard' in value;
493
+ return typeof value === "object" && value !== null && "~standard" in value;
872
494
  }
873
-
874
- /**
875
- * Builds the parent injector the server-function dispatch endpoint runs handlers
876
- * against, over HTTP.
877
- *
878
- * A plain `Injector.create({ providers })` resolves explicitly-listed providers
879
- * but not tree-shakeable `providedIn: 'root'` services — those attach to a
880
- * *bootstrapped* application's root injector, which `Injector.create` is not.
881
- * So the in-process SSR leg (whose parent is the app's own bootstrapped
882
- * injector) resolved `root` services while the HTTP leg did not — the same
883
- * handler could work while rendering and fail when called from the browser.
884
- *
885
- * Bootstrapping a real application on the server platform closes that gap: the
886
- * returned `appRef.injector` is a root environment injector, so both listed
887
- * providers and `providedIn: 'root'` services resolve, matching SSR.
888
- *
889
- * The generated endpoint passes the app's own server `ApplicationConfig` (the
890
- * one `main.server.ts` renders with), so a handler sees exactly the DI the app
891
- * configured — services, tokens, and interceptors alike — with no second
892
- * provider list to keep in sync. No root component is bootstrapped
893
- * (`createApplication`, not `bootstrapApplication`), so nothing renders, no
894
- * change detection runs, and the router registers but never navigates. It is a
895
- * DI container with the app's providers, built once and reused for the process,
896
- * with only `REQUEST`/`RESPONSE` rebuilt per call in the child.
897
- *
898
- * A bare provider array is also accepted (direct callers and tests without an
899
- * app config); it is wrapped with `provideServerRendering` so the server tokens
900
- * resolve the same way.
901
- */
902
495
  async function createServerFnAppInjector(configOrProviders = []) {
903
- const config = Array.isArray(configOrProviders)
904
- ? { providers: [provideServerRendering(), ...configOrProviders] }
905
- : configOrProviders;
906
- const appRef = await createApplication(config, {
907
- platformRef: platformServer(),
908
- });
909
- return appRef.injector;
496
+ return (await createApplication(Array.isArray(configOrProviders) ? { providers: [provideServerRendering(), ...configOrProviders] } : configOrProviders, { platformRef: platformServer() })).injector;
910
497
  }
911
-
912
- /**
913
- * The h3 request/response layer for the server-function dispatch route.
914
- *
915
- * `createServerFnAppInjector` bootstraps the parent injector once; this wraps
916
- * that in the `/_analog/fn/:id` handler the Nitro build registers. Kept as a
917
- * runtime function (rather than inlined into the generated module) so the
918
- * transport behaviour — body decoding, the malformed-body contract, and header
919
- * propagation — is unit-tested directly instead of by matching generated source.
920
- *
921
- * `appInjector` may be a promise: the generated module bootstraps the app at
922
- * import time and passes the pending injector, which is awaited on first request
923
- * and resolved instantly thereafter.
924
- */
925
498
  function createServerFnEventHandler(appInjector) {
926
- return eventHandler((event) => handleServerFnRequest(event, appInjector));
499
+ return eventHandler((event) => handleServerFnRequest(event, appInjector));
927
500
  }
928
- /**
929
- * Decode a server-function request, dispatch it, and write the result to the
930
- * h3 response. Same-origin, method, content-type, validation, and interceptors
931
- * are enforced inside `dispatchServerFn`; this owns only the h3 I/O around it.
932
- */
933
501
  async function handleServerFnRequest(event, appInjector) {
934
- const id = getRouterParam(event, 'id') ?? '';
935
- // h3 parses the body before dispatch gets a say, and its parse error is an
936
- // HTML/500-shaped response rather than the JSON contract callers expect.
937
- let input;
938
- if (event.method !== 'GET') {
939
- try {
940
- input = await readBody(event);
941
- }
942
- catch {
943
- event.node.res.statusCode = 400;
944
- return { message: 'Malformed request body' };
945
- }
946
- }
947
- const { status, body, headers } = await dispatchServerFn(id, input, event, {
948
- parent: await appInjector,
949
- method: event.method,
950
- });
951
- event.node.res.statusCode = status;
952
- if (headers) {
953
- for (const [key, value] of Object.entries(headers)) {
954
- event.node.res.setHeader(key, value);
955
- }
956
- }
957
- return body;
502
+ const id = getRouterParam(event, "id") ?? "";
503
+ let input;
504
+ if (event.method !== "GET") try {
505
+ input = await readBody(event);
506
+ } catch {
507
+ event.node.res.statusCode = 400;
508
+ return { message: "Malformed request body" };
509
+ }
510
+ const { status, body, headers } = await dispatchServerFn(id, input, event, {
511
+ parent: await appInjector,
512
+ method: event.method
513
+ });
514
+ event.node.res.statusCode = status;
515
+ if (headers) for (const [key, value] of Object.entries(headers)) event.node.res.setHeader(key, value);
516
+ return body;
958
517
  }
959
-
960
- /**
961
- * Generated bundle index. Do not edit.
962
- */
963
-
964
518
  export { SERVER_FN_ALLOWED_ORIGINS, SERVER_FN_INTERCEPTORS, createServerFnAppInjector, createServerFnEventHandler, dispatchServerFn, handleServerFnRequest, isServerFnOriginAllowed, provideServerContext, provideServerFns, render, renderStream, runInterceptors, serverFn, serverFnRegistry, withAllowedOrigins, withServerFnInterceptors };
965
- //# sourceMappingURL=analogjs-router-server.mjs.map
519
+
520
+ //# sourceMappingURL=analogjs-router-server.mjs.map