@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.
- package/fesm2022/analogjs-router-debug.page-MFY2u07E.mjs +119 -0
- package/fesm2022/analogjs-router-debug.page-MFY2u07E.mjs.map +1 -0
- package/fesm2022/analogjs-router-i18n.mjs +82 -210
- package/fesm2022/analogjs-router-i18n.mjs.map +1 -1
- package/fesm2022/analogjs-router-routes-L2tt-0ms.mjs +263 -0
- package/fesm2022/analogjs-router-routes-L2tt-0ms.mjs.map +1 -0
- package/fesm2022/analogjs-router-server-actions.mjs +240 -294
- package/fesm2022/analogjs-router-server-actions.mjs.map +1 -1
- package/fesm2022/analogjs-router-server.mjs +387 -832
- package/fesm2022/analogjs-router-server.mjs.map +1 -1
- package/fesm2022/analogjs-router-tanstack-query-server.mjs +35 -85
- package/fesm2022/analogjs-router-tanstack-query-server.mjs.map +1 -1
- package/fesm2022/analogjs-router-tanstack-query.mjs +79 -127
- package/fesm2022/analogjs-router-tanstack-query.mjs.map +1 -1
- package/fesm2022/analogjs-router-tokens.mjs +14 -19
- package/fesm2022/analogjs-router-tokens.mjs.map +1 -1
- package/fesm2022/analogjs-router.mjs +777 -1187
- package/fesm2022/analogjs-router.mjs.map +1 -1
- package/package.json +2 -2
- package/types/analogjs-router-i18n.d.ts +55 -24
- package/types/analogjs-router-server-actions.d.ts +179 -90
- package/types/analogjs-router-server.d.ts +76 -116
- package/types/analogjs-router-tanstack-query-server.d.ts +33 -37
- package/types/analogjs-router-tanstack-query.d.ts +19 -24
- package/types/analogjs-router-tokens.d.ts +18 -22
- package/types/analogjs-router.d.ts +271 -251
- package/fesm2022/analogjs-router-debug.page-COcFkgRu.mjs +0 -91
- package/fesm2022/analogjs-router-debug.page-COcFkgRu.mjs.map +0 -1
|
@@ -1,532 +1,289 @@
|
|
|
1
|
-
import { InjectionToken, Injector, runInInjectionContext, ɵresetCompiledComponents
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { SERVER_FN_DISPATCHER, createServerFnRef } from
|
|
5
|
-
import { HttpErrorResponse } from
|
|
6
|
-
import { bootstrapApplication, createApplication } from
|
|
7
|
-
import { AsyncLocalStorage } from
|
|
8
|
-
import { eventHandler, getRouterParam, readBody } from
|
|
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
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
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
|
-
|
|
19
|
+
return features.flatMap((f) => f.providers);
|
|
31
20
|
}
|
|
32
21
|
function makeCtx(input, context) {
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
|
|
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
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
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
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
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
|
-
|
|
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
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
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
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
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
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
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
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
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
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
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
|
-
|
|
335
|
-
|
|
336
|
-
|
|
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
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
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
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
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
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
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
|
-
|
|
390
|
-
|
|
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
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
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
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
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
|
-
|
|
460
|
-
|
|
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
|
-
|
|
465
|
-
|
|
466
|
-
|
|
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
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
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
|
-
|
|
494
|
-
|
|
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
|
-
|
|
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
|
-
|
|
633
|
-
|
|
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
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
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
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
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
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
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
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
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
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
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
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
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
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
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
|
-
|
|
519
|
+
|
|
520
|
+
//# sourceMappingURL=analogjs-router-server.mjs.map
|