@loozo/angular-launch 0.0.4 → 0.0.6

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 (59) hide show
  1. package/README.md +695 -102
  2. package/builders/application.d.ts +4 -0
  3. package/builders/application.js +71 -0
  4. package/builders/options.d.ts +10 -0
  5. package/builders/options.js +64 -0
  6. package/builders/serve.d.ts +8 -0
  7. package/builders/serve.js +248 -0
  8. package/builders.json +15 -0
  9. package/channel.d.ts +53 -0
  10. package/channel.js +231 -0
  11. package/client.d.ts +59 -16
  12. package/client.js +3 -2
  13. package/connect.d.ts +201 -0
  14. package/connect.js +148 -0
  15. package/generated.d.ts +1 -1
  16. package/generated.js +86 -3
  17. package/generation/context-file.d.ts +2 -0
  18. package/generation/context-file.js +3 -0
  19. package/generation/index.js +77 -36
  20. package/index.d.ts +6 -1
  21. package/index.js +2 -0
  22. package/json.d.ts +9 -0
  23. package/json.js +24 -0
  24. package/navigation.d.ts +36 -0
  25. package/navigation.js +47 -0
  26. package/node/index.d.ts +57 -0
  27. package/node/index.js +175 -0
  28. package/outcomes.d.ts +55 -0
  29. package/outcomes.js +100 -0
  30. package/package.json +14 -4
  31. package/schemas/application.json +756 -0
  32. package/schemas/serve.json +153 -0
  33. package/server/backend.d.ts +42 -23
  34. package/server/backend.js +137 -47
  35. package/server/channel-messages.d.ts +54 -0
  36. package/server/channel-messages.js +84 -0
  37. package/server/channel-socket.d.ts +67 -0
  38. package/server/channel-socket.js +322 -0
  39. package/server/definitions.d.ts +463 -181
  40. package/server/definitions.js +90 -103
  41. package/server/dispatch.d.ts +99 -20
  42. package/server/dispatch.js +337 -89
  43. package/server/event-stream.d.ts +63 -0
  44. package/server/event-stream.js +173 -0
  45. package/server/generated.d.ts +1 -0
  46. package/server/generated.js +1 -0
  47. package/server/index.d.ts +6 -3
  48. package/server/index.js +2 -1
  49. package/server/outcomes.d.ts +75 -0
  50. package/server/outcomes.js +90 -0
  51. package/server/response-effects.d.ts +105 -0
  52. package/server/response-effects.js +78 -0
  53. package/server/upgrade.d.ts +58 -0
  54. package/server/upgrade.js +117 -0
  55. package/stream.d.ts +31 -0
  56. package/stream.js +159 -0
  57. package/tanstack-query/README.md +110 -22
  58. package/tanstack-query/generated.js +5 -2
  59. package/tanstack-query/queries.d.ts +8 -6
@@ -0,0 +1,153 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema",
3
+ "$comment": "Generated by scripts/builder-schemas.mjs from the @angular/build 22.2.2 dev-server schema plus the Launch options. Do not edit. The @angular/build schema portions are distributed under this license:\n\nThe MIT License\n\nCopyright (c) 2010-2026 Google LLC. https://angular.dev/license\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.",
4
+ "title": "Dev Server Target",
5
+ "description": "Dev Server target options for Build Facade.",
6
+ "type": "object",
7
+ "properties": {
8
+ "buildTarget": {
9
+ "type": "string",
10
+ "description": "A target using @loozo/angular-launch:application, as project:target[:configuration]. Launch options come from it.",
11
+ "pattern": "^[^:\\s]*:[^:\\s]*(:[^\\s]+)?$"
12
+ },
13
+ "port": {
14
+ "type": "number",
15
+ "description": "Port to listen on.",
16
+ "default": 4200
17
+ },
18
+ "host": {
19
+ "type": "string",
20
+ "description": "Host to listen on.",
21
+ "default": "localhost"
22
+ },
23
+ "proxyConfig": {
24
+ "type": "string",
25
+ "description": "Proxy configuration file. For more information, see https://angular.dev/tools/cli/serve#proxying-to-a-backend-server."
26
+ },
27
+ "ssl": {
28
+ "type": "boolean",
29
+ "description": "Serve using HTTPS.",
30
+ "default": false
31
+ },
32
+ "sslKey": {
33
+ "type": "string",
34
+ "description": "SSL key to use for serving HTTPS."
35
+ },
36
+ "sslCert": {
37
+ "type": "string",
38
+ "description": "SSL certificate to use for serving HTTPS."
39
+ },
40
+ "allowedHosts": {
41
+ "description": "The hosts that the development server will respond to. This option sets the Vite option of the same name. For further details: https://vite.dev/config/server-options.html#server-allowedhosts",
42
+ "default": [],
43
+ "oneOf": [
44
+ {
45
+ "type": "array",
46
+ "description": "A list of hosts that the development server will respond to.",
47
+ "items": {
48
+ "type": "string"
49
+ }
50
+ },
51
+ {
52
+ "type": "boolean",
53
+ "description": "Indicates that all hosts are allowed. This is not recommended and a security risk."
54
+ }
55
+ ]
56
+ },
57
+ "define": {
58
+ "description": "Defines global identifiers that will be replaced with a specified constant value when found in any JavaScript or TypeScript code including libraries. The value will be used directly. String values must be put in quotes. Identifiers within Angular metadata such as Component Decorators will not be replaced.",
59
+ "type": "object",
60
+ "additionalProperties": {
61
+ "type": "string"
62
+ }
63
+ },
64
+ "headers": {
65
+ "type": "object",
66
+ "description": "Custom HTTP headers to be added to all responses.",
67
+ "propertyNames": {
68
+ "pattern": "^[-_A-Za-z0-9]+$"
69
+ },
70
+ "additionalProperties": {
71
+ "type": "string"
72
+ }
73
+ },
74
+ "open": {
75
+ "type": "boolean",
76
+ "description": "Opens the url in default browser.",
77
+ "default": false,
78
+ "alias": "o"
79
+ },
80
+ "verbose": {
81
+ "type": "boolean",
82
+ "description": "Adds more details to output logging."
83
+ },
84
+ "liveReload": {
85
+ "type": "boolean",
86
+ "description": "Whether to reload the page on change, using live-reload.",
87
+ "default": true
88
+ },
89
+ "servePath": {
90
+ "type": "string",
91
+ "description": "The pathname where the application will be served."
92
+ },
93
+ "hmr": {
94
+ "type": "boolean",
95
+ "description": "Enable hot module replacement. Defaults to the value of 'liveReload'. Currently, only global and component stylesheets are supported."
96
+ },
97
+ "watch": {
98
+ "type": "boolean",
99
+ "description": "Rebuild on change.",
100
+ "default": true
101
+ },
102
+ "poll": {
103
+ "description": "Watch by polling every this many milliseconds. Defaults to 1000 when omitted. false adds no default, so Angular's own configuration applies, including a poll on the build target.",
104
+ "oneOf": [
105
+ {
106
+ "type": "number",
107
+ "exclusiveMinimum": 0
108
+ },
109
+ {
110
+ "const": false
111
+ }
112
+ ]
113
+ },
114
+ "inspect": {
115
+ "default": false,
116
+ "description": "Activate debugging inspector. This option only has an effect when 'SSR' or 'SSG' are enabled.",
117
+ "oneOf": [
118
+ {
119
+ "type": "string",
120
+ "description": "Activate the inspector on host and port in the format of `[[host:]port]`. See the security warning in https://nodejs.org/docs/latest-v22.x/api/cli.html#warning-binding-inspector-to-a-public-ipport-combination-is-insecure regarding the host parameter usage."
121
+ },
122
+ {
123
+ "type": "boolean"
124
+ }
125
+ ]
126
+ },
127
+ "prebundle": {
128
+ "description": "Enable and control the Vite-based development server's prebundling capabilities. To enable prebundling, the Angular CLI cache must also be enabled.",
129
+ "default": true,
130
+ "oneOf": [
131
+ {
132
+ "type": "boolean"
133
+ },
134
+ {
135
+ "type": "object",
136
+ "properties": {
137
+ "exclude": {
138
+ "description": "List of package imports that should not be prebundled by the development server. The packages will be bundled into the application code itself. Note: specifying `@foo/bar` marks all paths within the `@foo/bar` package as excluded, including sub-paths like `@foo/bar/baz`.",
139
+ "type": "array",
140
+ "items": {
141
+ "type": "string"
142
+ }
143
+ }
144
+ },
145
+ "additionalProperties": false,
146
+ "required": ["exclude"]
147
+ }
148
+ ]
149
+ }
150
+ },
151
+ "additionalProperties": false,
152
+ "required": ["buildTarget"]
153
+ }
@@ -10,21 +10,32 @@ import { type ApplicationBinding, type Registry } from "./dispatch.js";
10
10
  * after `provideHttpClient()`, instead of calling this.
11
11
  *
12
12
  * It replaces Angular's `HttpBackend` on the server. Calls from generated clients, and
13
- * any other request to `/_rpc/` on the current request's origin, are intercepted and
14
- * run in-process in `"rendering"` mode, so mutations are refused with `FORBIDDEN`. All
15
- * other requests, including ones to `/_rpc/` on another origin that don't come from a
16
- * generated client, go to Angular's `FetchBackend`.
17
- *
18
- * For intercepted calls, Angular's `REQUEST_CONTEXT` must be the {@link RequestScope}
19
- * created for Angular's `REQUEST`, or the calls fail with `INTERNAL`. A generated-client
20
- * call outside `/_rpc/` on the current request's origin fails with `INVALID_INPUT` with no
21
- * issues, as does any intercepted call with a query string, fragment, URL credentials, a
22
- * method other than `POST`, a non-JSON content type, its own `Authorization`,
23
- * `Proxy-Authorization` or `Cookie` header, or its own credentials setting.
24
- *
25
- * Without a live request, as during prerendering, calls from generated clients and
26
- * requests to a relative `/_rpc/` path fail and the fault is recorded for
27
- * {@link finishLaunchRendering}; other requests still go to `FetchBackend`.
13
+ * any other request to `/_rpc/` on the page's origin, are intercepted and run in-process
14
+ * in `"rendering"` mode, so mutations and streams are refused with `FORBIDDEN`. All other
15
+ * requests, including ones to `/_rpc/` on another origin that don't come from a generated
16
+ * client, go to Angular's `FetchBackend`.
17
+ *
18
+ * For intercepted calls during server rendering, Angular's `REQUEST_CONTEXT` must be the
19
+ * {@link RequestScope} created for Angular's `REQUEST`, or the calls fail with `INTERNAL`.
20
+ * A generated-client call outside `/_rpc/` on the page's origin fails with
21
+ * `INVALID_INPUT` with no issues, as does any intercepted call with a query string,
22
+ * fragment, URL credentials, a method other than `POST`, a non-JSON content type, its own
23
+ * `Authorization`, `Proxy-Authorization` or `Cookie` header, or its own credentials
24
+ * setting.
25
+ *
26
+ * Cookies an intercepted call sets are appended to `RESPONSE_INIT`'s headers when the
27
+ * call settles, whatever its outcome, so they reach the page response; its other headers
28
+ * are dropped. Angular copies those headers into the page response once the app is first
29
+ * stable, so cookies from a call that settles later, such as one awaited in a
30
+ * `BEFORE_APP_SERIALIZED` hook, are lost. Without `RESPONSE_INIT`, a call that set cookies
31
+ * fails with `INTERNAL`.
32
+ *
33
+ * Without `REQUEST`, as when Angular prerenders a page, the first intercepted call creates
34
+ * the render's context from a cookie-less `GET` of the page's URL, and every call in the
35
+ * render shares it. Its signal aborts when the application is destroyed. A call that
36
+ * doesn't answer 200, or sets a cookie, records a fault for
37
+ * {@link finishLaunchRendering}, as does a context factory that throws. Only faults
38
+ * recorded before the app is first stable fail the build.
28
39
  *
29
40
  * @param registry - The application's RPC groups.
30
41
  * @param application - The application binding.
@@ -32,14 +43,22 @@ import { type ApplicationBinding, type Registry } from "./dispatch.js";
32
43
  */
33
44
  export declare function provideLaunchServer(registry: Registry, application: ApplicationBinding): EnvironmentProviders;
34
45
  /**
35
- * Waits for the server application to become stable and fails the render if an RPC was
36
- * called without a live request.
46
+ * Waits for the server application to become stable and fails the render if a Launch call
47
+ * failed while Angular prerendered the page.
37
48
  *
38
49
  * @remarks
39
- * Angular's prerendering can swallow resolver errors and still report success. Return
40
- * this from your server bootstrap so a page that calls an RPC during prerendering fails
41
- * the build instead of producing a broken page. The application must include the
42
- * generated `provideServer()`.
50
+ * A prerendered page is written once and served to every visitor, so each Launch call it
51
+ * makes must answer 200 without setting a cookie; a mutation or stream is refused with
52
+ * `FORBIDDEN`, so it fails too. Angular's prerendering can swallow resolver errors and still
53
+ * report success, and a failed `injectQuery` only renders its error state, so return this
54
+ * from your server bootstrap to fail the build instead of producing a broken page. The
55
+ * application must include the generated `provideServer()`. Server-rendered pages are
56
+ * unaffected: their failures reach the caller as usual.
57
+ *
58
+ * It checks once the app is first stable, which covers calls from guards, resolvers and
59
+ * rendering. Angular runs `BEFORE_APP_SERIALIZED` hooks afterwards and only logs their
60
+ * errors, so a call made in one isn't checked and the page is still written; don't make
61
+ * Launch calls there.
43
62
  *
44
63
  * @example
45
64
  * ```ts
@@ -52,7 +71,7 @@ export declare function provideLaunchServer(registry: Registry, application: App
52
71
  *
53
72
  * @param app - The bootstrapped server application.
54
73
  * @returns The same application once it is stable.
55
- * @throws The recorded error when an RPC was called without a live request; the
56
- * application is destroyed first.
74
+ * @throws The first recorded fault, naming the call and its reply, the cookie or the
75
+ * context factory's error; the application is destroyed first.
57
76
  */
58
77
  export declare function finishLaunchRendering(app: ApplicationRef): Promise<ApplicationRef>;
package/server/backend.js CHANGED
@@ -1,8 +1,10 @@
1
- import { inject, InjectionToken, REQUEST, REQUEST_CONTEXT, makeEnvironmentProviders, } from "@angular/core";
1
+ import { DestroyRef, DOCUMENT, inject, InjectionToken, REQUEST, REQUEST_CONTEXT, RESPONSE_INIT, makeEnvironmentProviders, } from "@angular/core";
2
2
  import { FetchBackend, HttpBackend, HttpErrorResponse, HttpResponse } from "@angular/common/http";
3
3
  import { Observable } from "rxjs";
4
4
  import { RPC_CALL } from "../generated.js";
5
- import { dispatch, failure, invalidInput, isJsonMediaType, assertBoundScope, } from "./dispatch.js";
5
+ import { parseJson } from "../json.js";
6
+ import { dispatch, failure, invalidInput, isJsonMediaType, assertBoundScope, createRequestScope, } from "./dispatch.js";
7
+ import { createResponseEffects } from "./response-effects.js";
6
8
  const renderFaults = new InjectionToken("Launch render faults");
7
9
  /**
8
10
  * Provides the server-rendering transport that runs RPC calls in-process with the
@@ -14,21 +16,32 @@ const renderFaults = new InjectionToken("Launch render faults");
14
16
  * after `provideHttpClient()`, instead of calling this.
15
17
  *
16
18
  * It replaces Angular's `HttpBackend` on the server. Calls from generated clients, and
17
- * any other request to `/_rpc/` on the current request's origin, are intercepted and
18
- * run in-process in `"rendering"` mode, so mutations are refused with `FORBIDDEN`. All
19
- * other requests, including ones to `/_rpc/` on another origin that don't come from a
20
- * generated client, go to Angular's `FetchBackend`.
19
+ * any other request to `/_rpc/` on the page's origin, are intercepted and run in-process
20
+ * in `"rendering"` mode, so mutations and streams are refused with `FORBIDDEN`. All other
21
+ * requests, including ones to `/_rpc/` on another origin that don't come from a generated
22
+ * client, go to Angular's `FetchBackend`.
21
23
  *
22
- * For intercepted calls, Angular's `REQUEST_CONTEXT` must be the {@link RequestScope}
23
- * created for Angular's `REQUEST`, or the calls fail with `INTERNAL`. A generated-client
24
- * call outside `/_rpc/` on the current request's origin fails with `INVALID_INPUT` with no
25
- * issues, as does any intercepted call with a query string, fragment, URL credentials, a
26
- * method other than `POST`, a non-JSON content type, its own `Authorization`,
27
- * `Proxy-Authorization` or `Cookie` header, or its own credentials setting.
24
+ * For intercepted calls during server rendering, Angular's `REQUEST_CONTEXT` must be the
25
+ * {@link RequestScope} created for Angular's `REQUEST`, or the calls fail with `INTERNAL`.
26
+ * A generated-client call outside `/_rpc/` on the page's origin fails with
27
+ * `INVALID_INPUT` with no issues, as does any intercepted call with a query string,
28
+ * fragment, URL credentials, a method other than `POST`, a non-JSON content type, its own
29
+ * `Authorization`, `Proxy-Authorization` or `Cookie` header, or its own credentials
30
+ * setting.
28
31
  *
29
- * Without a live request, as during prerendering, calls from generated clients and
30
- * requests to a relative `/_rpc/` path fail and the fault is recorded for
31
- * {@link finishLaunchRendering}; other requests still go to `FetchBackend`.
32
+ * Cookies an intercepted call sets are appended to `RESPONSE_INIT`'s headers when the
33
+ * call settles, whatever its outcome, so they reach the page response; its other headers
34
+ * are dropped. Angular copies those headers into the page response once the app is first
35
+ * stable, so cookies from a call that settles later, such as one awaited in a
36
+ * `BEFORE_APP_SERIALIZED` hook, are lost. Without `RESPONSE_INIT`, a call that set cookies
37
+ * fails with `INTERNAL`.
38
+ *
39
+ * Without `REQUEST`, as when Angular prerenders a page, the first intercepted call creates
40
+ * the render's context from a cookie-less `GET` of the page's URL, and every call in the
41
+ * render shares it. Its signal aborts when the application is destroyed. A call that
42
+ * doesn't answer 200, or sets a cookie, records a fault for
43
+ * {@link finishLaunchRendering}, as does a context factory that throws. Only faults
44
+ * recorded before the app is first stable fail the build.
32
45
  *
33
46
  * @param registry - The application's RPC groups.
34
47
  * @param application - The application binding.
@@ -42,33 +55,41 @@ export function provideLaunchServer(registry, application) {
42
55
  useFactory: () => {
43
56
  const context = inject(REQUEST_CONTEXT);
44
57
  const nativeRequest = inject(REQUEST);
58
+ const responseInit = inject(RESPONSE_INIT, { optional: true });
45
59
  const fallback = inject(FetchBackend);
46
60
  const faults = inject(renderFaults);
61
+ const document = inject(DOCUMENT);
62
+ const destroyed = new AbortController();
63
+ let prerenderScope;
64
+ inject(DestroyRef).onDestroy(() => destroyed.abort());
65
+ // The first fault is the one the build reports.
66
+ function recordFault(message, cause) {
67
+ faults.fault ??= new Error(`Launch can't prerender this page: ${message}`, { cause });
68
+ }
47
69
  return {
48
70
  handle(request) {
49
71
  const marked = request.context.get(RPC_CALL);
50
- let target;
72
+ const prerendering = !(nativeRequest instanceof Request);
73
+ let page;
51
74
  if (nativeRequest instanceof Request) {
52
- target = new URL(request.urlWithParams, nativeRequest.url);
75
+ page = nativeRequest.url;
53
76
  }
54
77
  else {
55
- target = new URL(request.urlWithParams, "http://launch.invalid");
56
- const localRpc = target.origin === "http://launch.invalid" && target.pathname.startsWith("/_rpc/");
57
- if (!marked && !localRpc) {
58
- return fallback.handle(request);
59
- }
60
- const error = new Error("Launch RPC requires live request context; prerender RPC is unsupported");
61
- faults.unsupportedContext = error;
62
- return new Observable((subscriber) => subscriber.error(error));
78
+ page = document.location.href;
63
79
  }
64
- const ownOrigin = target.origin === new URL(nativeRequest.url).origin;
80
+ const target = new URL(request.urlWithParams, page);
81
+ const ownOrigin = target.origin === new URL(page).origin;
65
82
  const ownRpc = ownOrigin && target.pathname.startsWith("/_rpc/");
66
83
  if (!marked && !ownRpc) {
67
84
  return fallback.handle(request);
68
85
  }
69
86
  return new Observable((subscriber) => {
70
87
  function deliver(reply) {
71
- if (reply.status >= 400) {
88
+ if (prerendering && reply.status !== 200) {
89
+ recordFault(`${target.pathname} answered ${reply.status} ${JSON.stringify(reply.body)}`);
90
+ }
91
+ // Only 200 is a result: a redirect's 303 frame must not reach the caller as data.
92
+ if (reply.status !== 200) {
72
93
  subscriber.error(new HttpErrorResponse({
73
94
  status: reply.status,
74
95
  error: reply.body,
@@ -83,13 +104,17 @@ export function provideLaunchServer(registry, application) {
83
104
  }));
84
105
  subscriber.complete();
85
106
  }
86
- try {
87
- assertBoundScope(context, application, nativeRequest);
88
- }
89
- catch (error) {
90
- console.error("Launch SSR scope binding failed", error);
91
- deliver(failure("INTERNAL"));
92
- return;
107
+ let live;
108
+ if (nativeRequest instanceof Request) {
109
+ try {
110
+ assertBoundScope(context, application, nativeRequest);
111
+ live = { scope: context, request: nativeRequest };
112
+ }
113
+ catch (error) {
114
+ console.error("Launch SSR scope binding failed", error);
115
+ deliver(failure("INTERNAL"));
116
+ return;
117
+ }
93
118
  }
94
119
  const authOverride = request.headers.has("authorization") ||
95
120
  request.headers.has("proxy-authorization") ||
@@ -115,13 +140,72 @@ export function provideLaunchServer(registry, application) {
115
140
  deliver(invalidInput());
116
141
  return;
117
142
  }
118
- envelope = JSON.parse(body);
143
+ envelope = parseJson(body);
119
144
  }
120
145
  catch {
121
146
  deliver(invalidInput());
122
147
  return;
123
148
  }
124
- void dispatch(registry, target.pathname, envelope, context, application, nativeRequest, "rendering").then(deliver);
149
+ // Aborts when the page request does, or when HttpClient unsubscribes first.
150
+ const call = new AbortController();
151
+ const effects = createResponseEffects();
152
+ let settled = false;
153
+ async function run() {
154
+ let scope;
155
+ let pageRequest;
156
+ if (live) {
157
+ scope = live.scope;
158
+ pageRequest = live.request;
159
+ }
160
+ else {
161
+ prerenderScope ??= createRequestScope(application, new Request(page, { signal: destroyed.signal }));
162
+ try {
163
+ scope = await prerenderScope;
164
+ }
165
+ catch (error) {
166
+ recordFault("its context factory threw", error);
167
+ console.error("Launch prerender context creation failed", error);
168
+ deliver(failure("INTERNAL"));
169
+ return;
170
+ }
171
+ pageRequest = scope.request;
172
+ }
173
+ const reply = await dispatch(registry, target.pathname, envelope, scope, application, pageRequest, "rendering", AbortSignal.any([pageRequest.signal, call.signal]), effects);
174
+ settled = true;
175
+ effects.commit();
176
+ if (effects.cookies.length === 0) {
177
+ deliver(reply);
178
+ return;
179
+ }
180
+ // A prerendered page is a file: there's no response to put a cookie on.
181
+ if (prerendering) {
182
+ recordFault(`${target.pathname} set a cookie`);
183
+ deliver(reply);
184
+ return;
185
+ }
186
+ if (responseInit === null) {
187
+ console.error("Launch can't send cookies set during rendering without RESPONSE_INIT");
188
+ deliver(failure("INTERNAL"));
189
+ return;
190
+ }
191
+ // Angular builds the page response, and its redirects, from these headers. It
192
+ // creates them as Headers; keep that object for anyone holding it.
193
+ let headers = responseInit.headers;
194
+ if (!(headers instanceof Headers)) {
195
+ headers = new Headers(headers);
196
+ responseInit.headers = headers;
197
+ }
198
+ for (const cookie of effects.cookies) {
199
+ headers.append("set-cookie", cookie);
200
+ }
201
+ deliver(reply);
202
+ }
203
+ void run();
204
+ return () => {
205
+ if (!settled) {
206
+ call.abort(new DOMException("RPC call aborted", "AbortError"));
207
+ }
208
+ };
125
209
  });
126
210
  },
127
211
  };
@@ -130,14 +214,22 @@ export function provideLaunchServer(registry, application) {
130
214
  ]);
131
215
  }
132
216
  /**
133
- * Waits for the server application to become stable and fails the render if an RPC was
134
- * called without a live request.
217
+ * Waits for the server application to become stable and fails the render if a Launch call
218
+ * failed while Angular prerendered the page.
135
219
  *
136
220
  * @remarks
137
- * Angular's prerendering can swallow resolver errors and still report success. Return
138
- * this from your server bootstrap so a page that calls an RPC during prerendering fails
139
- * the build instead of producing a broken page. The application must include the
140
- * generated `provideServer()`.
221
+ * A prerendered page is written once and served to every visitor, so each Launch call it
222
+ * makes must answer 200 without setting a cookie; a mutation or stream is refused with
223
+ * `FORBIDDEN`, so it fails too. Angular's prerendering can swallow resolver errors and still
224
+ * report success, and a failed `injectQuery` only renders its error state, so return this
225
+ * from your server bootstrap to fail the build instead of producing a broken page. The
226
+ * application must include the generated `provideServer()`. Server-rendered pages are
227
+ * unaffected: their failures reach the caller as usual.
228
+ *
229
+ * It checks once the app is first stable, which covers calls from guards, resolvers and
230
+ * rendering. Angular runs `BEFORE_APP_SERIALIZED` hooks afterwards and only logs their
231
+ * errors, so a call made in one isn't checked and the page is still written; don't make
232
+ * Launch calls there.
141
233
  *
142
234
  * @example
143
235
  * ```ts
@@ -150,14 +242,12 @@ export function provideLaunchServer(registry, application) {
150
242
  *
151
243
  * @param app - The bootstrapped server application.
152
244
  * @returns The same application once it is stable.
153
- * @throws The recorded error when an RPC was called without a live request; the
154
- * application is destroyed first.
245
+ * @throws The first recorded fault, naming the call and its reply, the cookie or the
246
+ * context factory's error; the application is destroyed first.
155
247
  */
156
- // Native prerender can swallow resolver errors. Propagate only the unsupported
157
- // Launch context fault after native stability, without manufacturing a request.
158
248
  export async function finishLaunchRendering(app) {
159
249
  await app.whenStable();
160
- const fault = app.injector.get(renderFaults).unsupportedContext;
250
+ const fault = app.injector.get(renderFaults).fault;
161
251
  if (fault) {
162
252
  app.destroy();
163
253
  throw fault;
@@ -0,0 +1,54 @@
1
+ import { type InputIssue } from "../input-issues.js";
2
+ import type { Schema } from "./definitions.js";
3
+ /**
4
+ * Where a channel's handler reads its caller's messages from. Internal.
5
+ *
6
+ * @remarks
7
+ * The socket side of a channel creates it before the upgrade is accepted, so the handler can
8
+ * hold its `messages` from the start; messages arrive once the socket is accepted.
9
+ */
10
+ export interface ChannelInbox {
11
+ /**
12
+ * Takes the next unread message as received, before validation.
13
+ *
14
+ * @returns The message, or `done` once the caller closed the channel. Rejects with a
15
+ * {@link MessageRefused} after the caller broke the protocol.
16
+ */
17
+ next(): Promise<IteratorResult<unknown, undefined>>;
18
+ /**
19
+ * Ends the call with `INVALID_INPUT` and `issues`, for a message that failed validation.
20
+ *
21
+ * @param issues - The message schema's issues.
22
+ */
23
+ refuse(issues: readonly InputIssue[]): void;
24
+ }
25
+ /**
26
+ * Why a channel's messages ended: the caller sent a message that failed validation, or broke
27
+ * the protocol. Internal.
28
+ *
29
+ * @remarks
30
+ * `dispatch` answers it with `INVALID_INPUT` and its issues instead of logging it as an
31
+ * unexpected failure.
32
+ */
33
+ export declare class MessageRefused extends Error {
34
+ readonly issues: readonly InputIssue[];
35
+ /**
36
+ * Creates the refusal.
37
+ *
38
+ * @param issues - The message schema's issues; empty for a protocol violation.
39
+ */
40
+ constructor(issues: readonly InputIssue[]);
41
+ }
42
+ /**
43
+ * The `messages` a channel's handler receives: the inbox's messages, validated with `schema`
44
+ * as they're read, in arrival order.
45
+ *
46
+ * @remarks
47
+ * Internal. One consumer only: a second iterator throws a `TypeError`. A message that fails
48
+ * validation refuses the call through the inbox and throws a {@link MessageRefused}; after
49
+ * that, or after `return()`, iteration is done.
50
+ *
51
+ * @param inbox - Where the messages come from.
52
+ * @param schema - The channel's message schema.
53
+ */
54
+ export declare function channelMessages(inbox: ChannelInbox, schema: Schema): AsyncIterable<unknown>;
@@ -0,0 +1,84 @@
1
+ import { inputIssues } from "../input-issues.js";
2
+ /**
3
+ * Why a channel's messages ended: the caller sent a message that failed validation, or broke
4
+ * the protocol. Internal.
5
+ *
6
+ * @remarks
7
+ * `dispatch` answers it with `INVALID_INPUT` and its issues instead of logging it as an
8
+ * unexpected failure.
9
+ */
10
+ export class MessageRefused extends Error {
11
+ issues;
12
+ /**
13
+ * Creates the refusal.
14
+ *
15
+ * @param issues - The message schema's issues; empty for a protocol violation.
16
+ */
17
+ constructor(issues) {
18
+ super("Launch channel refused a message");
19
+ this.issues = issues;
20
+ this.name = "MessageRefused";
21
+ }
22
+ }
23
+ /**
24
+ * The `messages` a channel's handler receives: the inbox's messages, validated with `schema`
25
+ * as they're read, in arrival order.
26
+ *
27
+ * @remarks
28
+ * Internal. One consumer only: a second iterator throws a `TypeError`. A message that fails
29
+ * validation refuses the call through the inbox and throws a {@link MessageRefused}; after
30
+ * that, or after `return()`, iteration is done.
31
+ *
32
+ * @param inbox - Where the messages come from.
33
+ * @param schema - The channel's message schema.
34
+ */
35
+ export function channelMessages(inbox, schema) {
36
+ let taken = false;
37
+ let finished = false;
38
+ // Reads run one after another, so an asynchronous schema can't reorder messages.
39
+ let previous = Promise.resolve();
40
+ async function read() {
41
+ if (finished) {
42
+ return { done: true, value: undefined };
43
+ }
44
+ let received;
45
+ try {
46
+ received = await inbox.next();
47
+ }
48
+ catch (error) {
49
+ finished = true;
50
+ throw error;
51
+ }
52
+ if (received.done) {
53
+ finished = true;
54
+ return received;
55
+ }
56
+ const parsed = await schema["~standard"].validate(received.value);
57
+ if (parsed.issues) {
58
+ const issues = inputIssues(parsed.issues);
59
+ finished = true;
60
+ inbox.refuse(issues);
61
+ throw new MessageRefused(issues);
62
+ }
63
+ return { done: false, value: parsed.value };
64
+ }
65
+ return {
66
+ [Symbol.asyncIterator]() {
67
+ if (taken) {
68
+ throw new TypeError("A channel's messages have one consumer: iterate them once");
69
+ }
70
+ taken = true;
71
+ return {
72
+ next() {
73
+ const step = previous.then(read);
74
+ previous = step.catch(() => undefined);
75
+ return step;
76
+ },
77
+ async return() {
78
+ finished = true;
79
+ return { done: true, value: undefined };
80
+ },
81
+ };
82
+ },
83
+ };
84
+ }