@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
package/README.md CHANGED
@@ -1,25 +1,26 @@
1
1
  # @loozo/angular-launch
2
2
 
3
- Typed server functions for Angular applications built with [`@loozo/angular-router`](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.4/packages/angular-router/README.md). You define queries and mutations in an `rpc.ts` file next to a route, and call them from that route's pages and resolvers through a generated, fully typed client.
3
+ Typed server functions for Angular applications built with [`@loozo/angular-router`](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.6/packages/angular-router/README.md). You define queries, mutations, streams and channels in an `rpc.ts` file next to a route, and call them from that route's pages and resolvers through a generated, fully typed client.
4
4
 
5
5
  Calls go through Angular's `HttpClient`. In the browser they're ordinary HTTP requests. During server rendering they run in-process with the current request's context, and hydration reuses their responses through Angular's transfer cache. Errors you declare on a procedure come back typed on the client.
6
6
 
7
7
  Use it when you want typed reads and writes between an Angular SSR app and its own server, without maintaining a separate API layer.
8
8
 
9
- **Status:** experimental. MIT license. It currently covers queries, mutations, guards and declared errors, with optional [TanStack Query](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.4/packages/angular-launch/tanstack-query/README.md) options and keys. There's no builder or watch mode yet, and no subscriptions, optimistic updates, automatic invalidation or storage adapters.
9
+ **Status:** experimental. MIT license. It currently covers queries, mutations, streams (over server-sent events), channels (over websockets, on the built Node server), middleware, declared errors and redirect and not-found outcomes, with optional [TanStack Query](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.6/packages/angular-launch/tanstack-query/README.md) options and keys, and Angular builders that generate before `ng build` and while `ng serve` runs. There are no storage adapters, and optimistic updates and invalidation come from TanStack Query through the integration.
10
10
 
11
11
  ## Requirements
12
12
 
13
- - Angular 22 with SSR: `@angular/core` and `@angular/common` `^22.0.0` and `rxjs` `^7.8.2` (the peer dependencies), plus `@angular/router`, `@angular/ssr` and `@angular/platform-server` as in the example. Tested with Angular 22.2.2.
13
+ - Angular 22 with SSR: `@angular/core`, `@angular/common` and `@angular/router` `^22.0.0` and `rxjs` `^7.8.2` (the peer dependencies), plus `@angular/ssr` and `@angular/platform-server` as in the example. Tested with Angular 22.2.2.
14
+ - `@angular/build` `~22.2.0`, for the builders. The range is narrow on purpose: the application builder's options schema is Angular's own at the version Launch was built against, so an option added in a later Angular minor is rejected until Launch is rebuilt against that minor. Launch follows the router's [Angular version policy](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.6/packages/angular-router/README.md#angular-versions) and releases in lockstep with it.
14
15
  - `@loozo/angular-router` at exactly the version Launch pins in its `peerDependencies`, as a dependency of your app. Launch generation writes the router's files too, through an internal router entry point, so the two must match; the exact peer dependency enforces that.
15
16
  - TypeScript 6 with strict checking. Generation rejects a tsconfig where any of `noImplicitAny`, `strictNullChecks`, `strictFunctionTypes`, `strictBindCallApply`, `strictPropertyInitialization`, `strictBuiltinIteratorReturn`, `noImplicitThis` or `useUnknownInCatchVariables` is off, or where `noCheck` is on. `"strict": true` is enough unless a flag is explicitly turned off, including in an extended config. Generation never edits your tsconfig.
16
17
  - A `package.json` with a `name` in the application directory. The name is part of the generated app identity.
17
- - Optionally, `@tanstack/angular-query` `^5.0.0-rc.5` for the [TanStack Query integration](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.4/packages/angular-launch/tanstack-query/README.md).
18
+ - Optionally, `@tanstack/angular-query` `^5.0.0-rc.5` for the [TanStack Query integration](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.6/packages/angular-launch/tanstack-query/README.md).
18
19
 
19
20
  Install both packages:
20
21
 
21
22
  ```sh
22
- pnpm add @loozo/angular-launch @loozo/angular-router@0.0.6
23
+ pnpm add @loozo/angular-launch @loozo/angular-router@0.0.8
23
24
  ```
24
25
 
25
26
  ## How it fits together
@@ -42,7 +43,7 @@ generated/
42
43
  ├── routes.generated.ts router: routes for provideRouter
43
44
  ├── destinations.generated.ts router
44
45
  ├── context.generated.d.ts registers your context type
45
- └── server.generated.ts createContext, handleRequest, provideServer
46
+ └── server.generated.ts createContext, handleRequest, handleUpgrade, provideServer
46
47
  ```
47
48
 
48
49
  Generation writes a `route.generated.ts` and an `rpc.generated.ts` beside every route that has a page or descendants with pages, with or without a local group; the tree shows only the ones for `todos`. Redirect routes, and parents left with only redirects below them, get neither.
@@ -51,11 +52,11 @@ The route tree is the router's. An `rpc.ts` belongs to the route declared in the
51
52
 
52
53
  ## Setup
53
54
 
54
- The [todos example](https://github.com/theo-matzavinos/loozo/tree/angular-launch@0.0.4/examples/angular-launch) is a complete app, and the snippets below are simplified from it. `db` and `sessions` stand for your own server-only modules: the example uses a test cookie instead of sessions, and its in-memory `db.todos.listForUser` also takes a test-only delay flag.
55
+ The [todos example](https://github.com/theo-matzavinos/loozo/tree/angular-launch@0.0.6/examples/angular-launch) is a complete app, and the snippets below are simplified from it. `db` and `sessions` stand for your own server-only modules: the example uses a test cookie instead of sessions, and its in-memory `db.todos.listForUser` also takes a test-only delay flag.
55
56
 
56
57
  ### 1. Define the context
57
58
 
58
- One file anywhere in your app's TypeScript sources default-exports `defineContext`. It runs once per live server request and its return value is what every handler and guard receives as `context`:
59
+ One file anywhere in your app's TypeScript sources default-exports `defineContext`. It runs once per live server request and its return value is the `context` every middleware and handler starts from:
59
60
 
60
61
  ```ts
61
62
  // src/context.ts
@@ -76,52 +77,55 @@ Generation registers the awaited return type, so `Context` from `@loozo/angular-
76
77
 
77
78
  ```ts
78
79
  // src/routes/+authenticated/todos/rpc.ts
79
- import { defineRpc, mutation, query } from "@loozo/angular-launch/server";
80
- import { isSignedIn, requireUser } from "../../../auth.server";
80
+ import { defineRpc } from "@loozo/angular-launch/server";
81
+ import { signedIn } from "../../../auth.server";
81
82
  import { idSchema, titleSchema } from "../../../todo-input.server";
82
83
 
83
84
  export default defineRpc(
84
85
  "todos",
85
- {
86
+ ({ query, mutation }) => ({
86
87
  list: query({
87
- handler: ({ context }) => context.db.todos.listForUser(requireUser(context).id),
88
+ handler: ({ context }) => context.db.todos.listForUser(context.user.id),
88
89
  }),
89
90
  add: mutation({
90
91
  input: titleSchema,
91
- handler: ({ input, context }) =>
92
- context.db.todos.addForUser(requireUser(context).id, input.title),
92
+ handler: ({ input, context }) => context.db.todos.addForUser(context.user.id, input.title),
93
93
  }),
94
- },
95
- { canActivate: [isSignedIn] },
94
+ }),
95
+ { use: [signedIn] },
96
96
  );
97
97
  ```
98
98
 
99
- ### 3. Generate
100
-
101
- Generation is a Node function. The example calls it from a small script:
102
-
103
- ```js
104
- // generate.mjs
105
- import { generate } from "@loozo/angular-launch/generation";
99
+ `signedIn` is a [middleware](#middleware) that refuses calls without a user and narrows `context.user` for the handlers.
106
100
 
107
- await generate(import.meta.dirname, {
108
- tsconfig: "tsconfig.app.json",
109
- scanDirectories: ["src/routes"],
110
- outDirectory: "generated",
111
- check: process.argv.includes("--check"),
112
- });
113
- ```
101
+ ### 3. Generate
114
102
 
115
- Run it before the Angular build. Launch apps use Angular's own `@angular/build:application` builder, not the router's companion builders, which don't accept Launch files:
103
+ Generation runs inside two Angular builders that replace your project's `build` and `serve` builders. Both run Angular's official builders (`@angular/build:application` and `@angular/build:dev-server`) after generating, so everything else about your build stays the same. Use them instead of the router's builders, which don't accept Launch files. In `angular.json`:
116
104
 
117
105
  ```json
118
- "scripts": {
119
- "generate": "node generate.mjs",
120
- "build": "pnpm generate && ng build"
106
+ "build": {
107
+ "builder": "@loozo/angular-launch:application",
108
+ "options": {
109
+ "tsconfig": "tsconfig.app.json",
110
+ "scanDirectories": ["src/routes"],
111
+ "outDirectory": "generated",
112
+ "browser": "src/main.ts",
113
+ "server": "src/main.server.ts",
114
+ "ssr": { "entry": "src/server.ts" },
115
+ "outputMode": "server",
116
+ "tsConfig": "tsconfig.app.json"
117
+ },
118
+ "configurations": { "check": { "check": true } }
119
+ },
120
+ "serve": {
121
+ "builder": "@loozo/angular-launch:serve",
122
+ "options": { "buildTarget": "my-app:build" }
121
123
  }
122
124
  ```
123
125
 
124
- Include the generated files, declarations included, in your app tsconfig: `"include": ["src/**/*.ts", "generated/**/*.ts"]`. See [Generation](#generation) for the options and what gets written.
126
+ `ng build` and `ng serve` then generate first, and `ng serve` regenerates as you edit. `ng run my-app:build:check` verifies the generated files without writing them, for CI. `tsconfig` is the TypeScript config generation reads; `tsConfig` is Angular's own compilation config. They can be the same file.
127
+
128
+ Include the generated files, declarations included, in your app tsconfig: `"include": ["src/**/*.ts", "generated/**/*.ts"]`. See [Builders](#builders) for the builder options and [Generation](#generation) for what gets written.
125
129
 
126
130
  ### 4. Wire the browser and server apps
127
131
 
@@ -140,6 +144,8 @@ export const config: ApplicationConfig = {
140
144
  };
141
145
  ```
142
146
 
147
+ To have pages follow a procedure's [`redirect()` and `notFound()`](#redirects-and-not-found), add [`rpcNavigationErrors`](#navigating-on-outcomes) to `provideRouter`.
148
+
143
149
  The server config adds the generated `provideServer()`, after `provideHttpClient()`:
144
150
 
145
151
  ```ts
@@ -155,7 +161,7 @@ export const serverConfig = mergeApplicationConfig(config, {
155
161
  });
156
162
  ```
157
163
 
158
- Wrap the server bootstrap in `finishLaunchRendering`. If an RPC is called during prerendering, where there's no live request, this makes the build fail instead of producing a broken page:
164
+ Wrap the server bootstrap in `finishLaunchRendering`. If an RPC fails while Angular prerenders a page, this makes the build fail instead of producing a broken page (see [Prerendering](#prerendering)):
159
165
 
160
166
  ```ts
161
167
  // src/main.server.ts
@@ -171,7 +177,7 @@ export default async function bootstrap(context: BootstrapContext) {
171
177
  }
172
178
  ```
173
179
 
174
- In the server entry, let `handleRequest` answer RPC requests (it returns `null` for anything else), and render pages with a request scope from `createContext`. This is the Express server that Angular's SSR setup generates, with Launch added:
180
+ In the server entry, let `handleRequest` answer RPC requests (it returns `null` for anything else), and render pages with a request scope from `createContext`. Give `handleRequest` and Angular the same `allowedHosts` list (see [Hosts](#hosts)), and give the web request a signal that aborts when the client goes away (see [Aborted requests](#aborted-requests)). This is the Express server that Angular's SSR setup generates, with Launch added:
175
181
 
176
182
  ```ts
177
183
  // src/server.ts
@@ -183,19 +189,32 @@ import {
183
189
  isMainModule,
184
190
  writeResponseToNodeResponse,
185
191
  } from "@angular/ssr/node";
192
+ import { createUpgradeHandler } from "@loozo/angular-launch/node";
186
193
  import express from "express";
187
- import { createContext, handleRequest } from "../generated/server.generated";
194
+ import { createContext, handleRequest, handleUpgrade } from "../generated/server.generated";
188
195
 
189
196
  const browser = join(import.meta.dirname, "../browser");
190
- const angular = new AngularNodeAppEngine();
197
+ // An explicit list stops Angular reading NG_ALLOWED_HOSTS, so read it here.
198
+ const allowedHosts = (process.env["NG_ALLOWED_HOSTS"] ?? "localhost").split(",");
199
+ const angular = new AngularNodeAppEngine({ allowedHosts });
191
200
  const app = express();
192
201
 
193
202
  app.use(express.static(browser, { maxAge: "1y", index: false, redirect: false }));
194
203
 
195
204
  app.use(async (request, response, next) => {
196
205
  try {
197
- const web = createWebRequestFromNodeRequest(request);
198
- const rpc = await handleRequest(web);
206
+ // Angular's helper only aborts while the body is still arriving; abort on a closed response.
207
+ const closed = new AbortController();
208
+
209
+ response.once("close", () => {
210
+ if (!response.writableFinished) {
211
+ closed.abort();
212
+ }
213
+ });
214
+
215
+ const native = createWebRequestFromNodeRequest(request);
216
+ const web = new Request(native, { signal: AbortSignal.any([native.signal, closed.signal]) });
217
+ const rpc = await handleRequest(web, { allowedHosts });
199
218
 
200
219
  if (rpc) {
201
220
  await writeResponseToNodeResponse(rpc, response);
@@ -218,57 +237,192 @@ app.use(async (request, response, next) => {
218
237
  }
219
238
  });
220
239
 
240
+ // Channels arrive as websocket upgrades, which Express never sees.
241
+ const upgrade = createUpgradeHandler((request) => handleUpgrade(request, { allowedHosts }));
242
+
221
243
  if (isMainModule(import.meta.url)) {
222
244
  const port = process.env["PORT"] || 4000;
223
-
224
- app.listen(port, (error) => {
245
+ const server = app.listen(port, (error) => {
225
246
  if (error) {
226
247
  throw error;
227
248
  }
228
249
 
229
250
  console.log(`Listening on http://localhost:${port}`);
230
251
  });
252
+
253
+ server.on("upgrade", upgrade);
231
254
  }
232
255
 
233
256
  export const reqHandler = createNodeRequestHandler(app);
234
257
  ```
235
258
 
236
- Angular's dev server and build use the exported `reqHandler`; `listen` only runs when you start the built server yourself (see [Deploying](#deploying)). The server must serve the `browser` build output itself: Angular's engine doesn't serve script or style files. Express isn't required; see [Other server frameworks](#other-server-frameworks).
259
+ Angular's dev server and build use the exported `reqHandler`; `listen` only runs when you start the built server yourself (see [Deploying](#deploying)). The server must serve the `browser` build output itself: Angular's engine doesn't serve script or style files. Express isn't required; see [Other server frameworks](#other-server-frameworks). The upgrade handler only matters if you define [channels](#channels); see [Channels on Node](#channels-on-node).
237
260
 
238
261
  Always pass `scope.request` together with `scope`, not your original request. The scope ties the context to the request Angular renders; if they don't match, RPC calls during rendering fail with `INTERNAL` and a server log entry. This catches wiring mistakes only; it doesn't check your authentication.
239
262
 
240
263
  ## Defining RPCs
241
264
 
242
- `defineRpc(namespace, procedures, options?)` declares a group. Each procedure is a `query` (a read) or a `mutation` (a write):
265
+ `defineRpc(namespace, build, options?)` declares a group. `build` receives the `query` (a read), `mutation` (a write), `stream` (a read that sends values while it runs) and `channel` (a conversation over a websocket) builders and returns the group's procedures:
243
266
 
244
267
  ```ts
245
- query({ input?, canActivate?, errors?, handler });
246
- mutation({ input?, canActivate?, errors?, handler });
268
+ defineRpc(
269
+ "todos",
270
+ ({ query, mutation, stream }) => ({
271
+ list: query({ input?, use?, errors?, handler }),
272
+ add: mutation({ input?, use?, errors?, handler }),
273
+ watch: stream({ input?, use?, errors?, handler }),
274
+ }),
275
+ { use? },
276
+ );
247
277
  ```
248
278
 
249
- The handler receives `{ context, input, errors }` and returns a value or a promise.
279
+ The handler receives `{ context, input, errors, request, signal, response }` and returns a value or a promise; a [stream's](#streams) returns an async iterable. It can also throw a [declared error](#declared-errors) or an [outcome](#redirects-and-not-found). `request` is the request the call runs in: the RPC request over HTTP, the page request during server rendering, or a cookie-less `GET` of the page's URL while Angular [prerenders](#prerendering) it. `signal` aborts when the caller goes away; see [Calling RPCs](#calling-rpcs). `response` sets cookies and headers; see [Cookies and headers](#cookies-and-headers).
250
280
 
251
281
  - **Namespaces and procedure names** are literal ASCII identifiers. `__proto__` is not allowed; `constructor` and `toString` are fine. One `defineRpc` per route, and each namespace is unique across the app because it names the group's URL.
252
- - **Inputs** are [Standard Schema](https://standardschema.dev) V1 schemas, from any library or written by hand. Validation can be async and can transform the value: callers pass the schema's input type, and guards and handlers receive its output. The `input` schema must have a concrete type without `undefined` or `null` branches, though its caller input type may be a union such as `Schema<string | number, …>`. Omit `input` for a procedure without input.
253
- - **Guards** return `boolean` or `Promise<boolean>`; `false` fails the call with `FORBIDDEN`. Group guards (in `defineRpc` options) get `{ context, request }`; procedure guards also get the validated `input`. Guards are never inherited through the route tree. A call runs input validation, then the group's guards, then the procedure's guards, then the handler.
254
- - Guards don't narrow types. Use an ordinary function to narrow, such as the example's `requireUser`:
282
+ - **The callback** is read without running it: an arrow function that destructures any of `query`, `mutation` and `stream` without renaming, returning a parenthesized object literal in which each procedure is a direct `query(...)`, `mutation(...)` or `stream(...)` call with inline options.
283
+ - **Inputs** are [Standard Schema](https://standardschema.dev) V1 schemas, from any library or written by hand. Validation can be async and can transform the value: callers pass the schema's input type, and procedure middleware and handlers receive its output. The `input` schema must have a concrete type without `undefined` or `null` branches, though its caller input type may be a union such as `Schema<string | number, …>`. Omit `input` for a procedure without input.
284
+
285
+ Availability isn't authorization: anyone who can reach your server can call any procedure, so protect every group and procedure that needs it with middleware. Route params aren't passed to procedures automatically; pass what you need as input and validate it.
286
+
287
+ ### Middleware
288
+
289
+ Middleware runs around a call to refuse it, add typed values to its context, or wrap the rest of it:
255
290
 
256
291
  ```ts
257
292
  // src/auth.server.ts
258
- import type { Context, Guard } from "@loozo/angular-launch/server";
259
-
260
- export const isSignedIn: Guard = ({ context }) => context.user !== null;
293
+ import { forbidden, middleware } from "@loozo/angular-launch/server";
261
294
 
262
- export function requireUser(context: Context): { id: string } {
295
+ export const signedIn = middleware(async ({ context, next }) => {
263
296
  if (context.user === null) {
264
- throw new Error("User required");
297
+ throw forbidden();
265
298
  }
266
299
 
267
- return context.user;
268
- }
300
+ return next({ user: context.user }); // later middleware and handlers see a non-null user
301
+ });
302
+ ```
303
+
304
+ List middleware in the group's `use` to run it for every procedure in the group, or in a procedure's `use` to run it for that procedure. A call runs, in order:
305
+
306
+ 1. the group's middleware, with no input;
307
+ 2. input validation;
308
+ 3. the procedure's middleware, with the validated input;
309
+ 4. the handler.
310
+
311
+ So a caller that group middleware refuses gets `FORBIDDEN` even when its input is invalid, and can't probe your schemas.
312
+
313
+ - **`next()`** continues the call. `next(values)` also merges `values` into the context by spread, so the context must be a plain object: a class instance would lose its prototype. An addition is a single object type with required keys, since a missing optional value would leave the earlier one in place, and a union could hide such a key in one of its members. Write a value that may be missing as `next({ user: maybeUser })` with a type such as `User | null`, and alternatives as a union value, such as `next({ session: a | b })`. Every `next(...)` in a middleware adds the same keys, so `next({ user: null })` in one branch and `next()` in another is a type error. A value that differs per branch goes in one `next()` call with a union-typed value, such as `next({ user: preview ? null : context.user })` or a variable typed `User | null`. The context is read-only at the top level, so `context.user = null` is a type error: add and replace values through `next()`, where later middleware and handlers see their types. A middleware must call `next` exactly once and return its result; calling it twice or returning anything else fails the call with `INTERNAL`.
314
+ - **Wrapping:** `next()` rejects when anything after it throws, declared errors included, so a middleware can time, log or run the rest of the call in a transaction that rolls back:
315
+
316
+ ```ts
317
+ export const timing = middleware(async ({ next }) => {
318
+ const start = performance.now();
319
+
320
+ try {
321
+ return await next();
322
+ } finally {
323
+ console.log(`RPC took ${(performance.now() - start).toFixed(1)} ms`);
324
+ }
325
+ });
326
+ ```
327
+
328
+ - **Refusing:** `throw forbidden()` fails the call with `FORBIDDEN`, and `throw notFound()` or `throw redirect(to)` answer it with that [outcome](#redirects-and-not-found); a handler can throw them too. Any other exception fails the call with `INTERNAL`. Declared errors belong to handlers.
329
+ - **Needs:** a middleware without an annotation needs your `Context` and accepts any input, so it fits anywhere. Annotate its argument with `MiddlewareArgs<Needs, Input>` to require values that earlier middleware adds, or an input shape:
330
+
331
+ ```ts
332
+ export const ownTodo = middleware(
333
+ async ({ context, input, next }: MiddlewareArgs<{ user: User; db: Db }, { id: string }>) => {
334
+ const todo = await context.db.todos.findForUser(context.user.id, input.id);
335
+
336
+ if (todo === null) {
337
+ throw forbidden();
338
+ }
339
+
340
+ return next({ todo });
341
+ },
342
+ );
343
+ ```
344
+
345
+ Each `use` entry must accept the context and input accumulated before it, and the error lands on the entry that doesn't (`… is not assignable to type 'never'`). Group middleware gets no input, so a middleware that needs input only fits on a procedure.
346
+
347
+ - **Server rendering:** middleware runs for every call, also during server rendering, where `request` is the page request: usually a `GET` navigation with `Sec-Fetch-Site: none` or `cross-site`. Request-shaped checks, such as on the method or `Sec-Fetch-Site`, misfire there, which is why Launch's own [cross-origin check](#cross-origin-requests) isn't middleware and runs over HTTP only.
348
+ - There's no dedupe: middleware listed in both the group and a procedure runs twice. Middleware isn't inherited through the route tree.
349
+ - **Known limits:**
350
+ - Casting an addition to `object` or `{}`, or deliberately widening a middleware's result type, hides the keys it adds, so the context type no longer matches what runs.
351
+ - Only the top level of the context is read-only. Writing to a nested object, such as `context.session.user = null`, can still invalidate a narrowing nested inside it.
352
+ - Separate `next({ user: null })` and `next({ user: context.user })` calls don't infer `User | null` when `context.user` is a `User`; write the single-call form above.
353
+
354
+ ### Cookies and headers
355
+
356
+ Middleware and handlers set cookies and headers through `response`:
357
+
358
+ ```ts
359
+ login: mutation({
360
+ input: credentialsSchema,
361
+ errors: { WRONG_CREDENTIALS: { status: 401, message: "Wrong email or password", data: nullSchema } },
362
+ handler: async ({ input, context, response, errors }) => {
363
+ const session = await context.sessions.signIn(input.email, input.password);
364
+
365
+ if (session === null) {
366
+ throw errors.WRONG_CREDENTIALS(null);
367
+ }
368
+
369
+ // Defaults: Path=/; HttpOnly; Secure; SameSite=Lax
370
+ response.setCookie("session", session.token, { maxAge: 60 * 60 * 24 * 30 });
371
+
372
+ return { user: session.userId };
373
+ },
374
+ }),
375
+ logout: mutation({
376
+ handler: async ({ context, response }) => {
377
+ await context.sessions.end(context.sessionToken);
378
+ response.deleteCookie("session");
379
+
380
+ return null;
381
+ },
382
+ }),
269
383
  ```
270
384
 
271
- Availability isn't authorization: anyone who can reach your server can call any procedure, so every group and procedure needs its own guards. Route params aren't passed to procedures automatically; pass what you need as input and validate it.
385
+ - **`response.setCookie(name, value, options?)`** adds a `Set-Cookie` header. Options are `path` (default `/`), `domain`, `maxAge` in whole seconds, `expires`, `httpOnly` (default `true`), `secure` (default `true`) and `sameSite` (`"lax"` by default, `"strict"` or `"none"`, which needs `secure`). Browsers keep `Secure` cookies from `http://localhost`, so the defaults work in development; a plain-HTTP deployment on another hostname needs `secure: false`. Values aren't encoded for you: encode anything outside printable ASCII, or with spaces, `"`, `,`, `;` or `\`, first. An invalid name, value or option throws a `TypeError`, which fails the call with `INTERNAL`.
386
+ - **`response.deleteCookie(name, options?)`** expires a cookie. Pass the `path`, `domain` and security options it was set with, or the browser keeps it.
387
+ - **`response.headers`** is a `Headers` object for the RPC response. Launch's own headers (`Content-Type`, `Cache-Control`, `Vary`, `X-Content-Type-Options`) replace any you set, and the status comes from the call's outcome, never from `response`. Use `setCookie` for cookies: a `Set-Cookie` header written here is dropped during server rendering like any other header.
388
+ - **Every outcome** carries them, failures included: a cookie set before a declared error, `forbidden()` or an `INTERNAL` failure is still sent. What a cookie records has usually happened by then, such as a session a middleware refreshed before the handler failed. So set a cookie after the steps that make it true, as `login` above does: a failure before that sends none.
389
+ - **During server rendering**, cookies go on the page response, including a redirect Angular answers with, and headers are dropped, since a page's headers mustn't depend on which queries it ran. Angular copies the page's headers once the app is first stable, so only calls that settle before then send their cookies: those from guards, resolvers and rendering do, while a call made later, such as one awaited in a `BEFORE_APP_SERIALIZED` hook, still runs but its cookies are lost. Hydration reuses transferred results without calling the server, so the page response is the only chance to send such a cookie. Every call in a render gets the same context, created from the page request's cookies, so a cookie one call sets isn't visible to later calls; see the session example below. A failed initial navigation, such as a resolver whose RPC fails, makes `angular.handle` return `null`, and the cookies set during that render are lost with the page. Handle the failure in the route if they matter, so the page renders and carries them.
390
+ - **When they're sent:** once the call settled, or for a [stream](#streams) once its handler returned its iterable. After that, setting a cookie throws and header changes are ignored, so a wrapping middleware can add a header after `await next()` for queries and mutations, and it's ignored for streams:
391
+
392
+ ```ts
393
+ export const timing = middleware(async ({ next, response }) => {
394
+ const start = performance.now();
395
+
396
+ try {
397
+ return await next();
398
+ } finally {
399
+ response.headers.append("server-timing", `rpc;dur=${(performance.now() - start).toFixed(1)}`);
400
+ }
401
+ });
402
+ ```
403
+
404
+ A middleware can refresh a session cookie for every call in its group, during server rendering too. Every call in a render gets the same context, and each RPC request its own, so a cell in the context makes the refresh run once per page or RPC request instead of once per call:
405
+
406
+ ```ts
407
+ // The context factory returns `refresh: { pending: null as Promise<string> | null }` too.
408
+ export const session = middleware(async ({ context, response, next }) => {
409
+ const current = await context.sessions.read(context.sessionToken);
410
+
411
+ // Calls in one render share the context: only the first refreshes.
412
+ if (current !== null && current.expiresSoon && context.refresh.pending === null) {
413
+ context.refresh.pending = context.sessions.extend(current);
414
+ response.setCookie("session", await context.refresh.pending, {
415
+ maxAge: 60 * 60 * 24 * 30,
416
+ });
417
+ }
418
+
419
+ return next({ user: current?.user ?? null });
420
+ });
421
+ ```
422
+
423
+ Concurrent RPC requests from the browser each have their own context, so each can still refresh. Your session store has to accept that, with a sliding expiry or by keeping the old token valid for a short while. That also keeps the session usable when a refreshed cookie never arrives, as after a failed render.
424
+
425
+ There's no cookie reader: your context parses the request's `Cookie` header, as in the [example](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.6/examples/angular-launch/src/context.ts).
272
426
 
273
427
  ### JSON values
274
428
 
@@ -285,7 +439,7 @@ complete: mutation({
285
439
  NOT_FOUND: { status: 404, message: "Todo does not exist", data: idSchema },
286
440
  },
287
441
  handler: async ({ input, context, errors }) => {
288
- const todo = await context.db.todos.completeForUser(requireUser(context).id, input.id);
442
+ const todo = await context.db.todos.completeForUser(context.user.id, input.id);
289
443
 
290
444
  if (todo === null) {
291
445
  throw errors.NOT_FOUND({ id: input.id });
@@ -300,12 +454,12 @@ Each error needs an identifier code, an integer literal `status` from 400 to 599
300
454
 
301
455
  Launch itself uses four codes, which you can't declare:
302
456
 
303
- | Code | Status | When |
304
- | --------------- | ------ | ----------------------------------------------------------------------------------- |
305
- | `INVALID_INPUT` | 400 | The request is malformed, or its input failed schema validation |
306
- | `FORBIDDEN` | 403 | A guard returned `false`, or a mutation was called during server rendering |
307
- | `RPC_NOT_FOUND` | 404 | No such procedure |
308
- | `INTERNAL` | 500 | Anything else: an unexpected exception, an invalid error payload, a non-JSON result |
457
+ | Code | Status | When |
458
+ | --------------- | ------ | --------------------------------------------------------------------------------------------------------------------------- |
459
+ | `INVALID_INPUT` | 400 | The request is malformed, or its input failed schema validation |
460
+ | `FORBIDDEN` | 403 | `forbidden()` was thrown, the request wasn't proven same-origin, or a mutation or stream was called during server rendering |
461
+ | `RPC_NOT_FOUND` | 404 | No such procedure |
462
+ | `INTERNAL` | 500 | Anything else: an unexpected exception, an invalid error payload, a non-JSON result |
309
463
 
310
464
  `INTERNAL` never exposes details to the client; they go to the server log. Your own `NOT_FOUND` is fine, but `__proto__` can't be an error code.
311
465
 
@@ -323,6 +477,132 @@ try {
323
477
  }
324
478
  ```
325
479
 
480
+ ### Redirects and not found
481
+
482
+ A page that can't be shown, because the visitor must sign in first or the thing it shows doesn't exist, is answered with an outcome from `@loozo/angular-launch/server` instead of an error code. Middleware and handlers throw them:
483
+
484
+ ```ts
485
+ // src/auth.server.ts
486
+ import { createUrl } from "@loozo/angular-router";
487
+ import { middleware, redirect } from "@loozo/angular-launch/server";
488
+ import signIn from "./routes/sign-in/route";
489
+
490
+ // For reads that pages load while navigating.
491
+ export const signInFirst = middleware(async ({ context, next }) => {
492
+ if (context.user === null) {
493
+ throw redirect(createUrl(signIn, {}));
494
+ }
495
+
496
+ return next({ user: context.user });
497
+ });
498
+ ```
499
+
500
+ ```ts
501
+ import { notFound } from "@loozo/angular-launch/server";
502
+
503
+ get: query({
504
+ input: idSchema,
505
+ handler: async ({ input, context }) => {
506
+ const todo = await context.db.todos.findForUser(context.user.id, input.id);
507
+
508
+ // Another user's todo is missing too.
509
+ if (todo === null) {
510
+ throw notFound();
511
+ }
512
+
513
+ return todo;
514
+ },
515
+ }),
516
+ ```
517
+
518
+ - **`redirect(to)`** takes a root-relative app URL, such as `createUrl` builds. `redirect("https://…")` is a type error, and a URL that leaves the app, such as `//example.com`, throws a `TypeError`. An external redirect, such as to an OAuth provider, is data your page acts on.
519
+ - **On the wire** a redirect is a 303 with `{ "redirect": { "to": "/sign-in" } }` and no `Location` header, so `fetch` hands it to the client instead of following it, and not-found is a 404 with `{ "notFound": null }`. Only status 200 is a result: a handler that returns `{ redirect: { to } }` returns data.
520
+ - **On the client** the call rejects with `RpcRedirect` (with its `to`) or `RpcNotFound` from `@loozo/angular-launch`. They aren't `RpcError`s, so `isError` is false for them. Nothing navigates for you, except in a guard or resolver with [`rpcNavigationErrors`](#navigating-on-outcomes).
521
+ - **Not-found isn't `RPC_NOT_FOUND`**, which means no such procedure, and it doesn't take a declared `NOT_FOUND` code. Use `notFound()` when the page can't be shown, and a declared error when the page handles the case itself, as the example's `complete` does.
522
+
523
+ ### Streams
524
+
525
+ A stream sends values while it runs, such as a list that changes or an answer that's still being written. Its handler returns an async iterable, usually written as an `async function*`:
526
+
527
+ ```ts
528
+ export default defineRpc(
529
+ "live",
530
+ ({ stream }) => ({
531
+ watch: stream({
532
+ handler: async function* ({ context, signal }) {
533
+ yield* context.db.todos.watchForUser(context.user.id, signal);
534
+ },
535
+ }),
536
+ }),
537
+ { use: [signedIn] },
538
+ );
539
+ ```
540
+
541
+ Write the handler as `handler: async function* (…) { … }`: generation doesn't accept method shorthand (`async *handler() { … }`). A stream takes the same `input`, `use` and `errors` options as a query. It's a read, and it doesn't run during server rendering (see [Calling streams](#calling-streams)).
542
+
543
+ - **Values** must be strict JSON, like results, and each reaches the caller as soon as it's yielded. A value that isn't ends the stream with `INTERNAL`. The handler returns nothing: returning a value is a type error.
544
+ - **Yield the current state first.** A caller that reconnects starts a new call and the handler starts over, so a stream of snapshots loses nothing across a reconnect, while a stream of changes loses those made in between.
545
+ - **Middleware** runs once per stream, before the handler, with one context. `next()` settles when the stream ends: it resolves when the handler finishes or the caller goes away, and rejects when the handler throws. Wrapping middleware therefore spans the whole stream; one that opens a transaction keeps it open as long as the stream runs. Nothing is checked again while the stream runs, so a handler that must notice a revoked session checks before each value.
546
+ - **Cookies and headers** are sent with the stream's response, which starts once the handler returned its iterable. Set them in middleware before `next()`, or in a handler that isn't a generator, before it returns one: an `async function*` handler's body runs after the response started, so setting a cookie there throws and ends the stream with `INTERNAL`. See [Cookies and headers](#cookies-and-headers).
547
+ - **Failures** before the handler returns its iterable, such as a refusing middleware or invalid input, are ordinary responses with their status, as for a query. After that the response has started: a declared error, an outcome or any other exception ends the stream with that error. An `async function*` handler's body only runs once the response has started, so outcomes it throws arrive as an `error` event, such as `{"status":404,"notFound":null}`.
548
+ - **Cancellation:** when the caller stops reading or goes away, the handler's `signal` aborts and the generator is asked to return, which runs its `finally` blocks once it next yields. A generator waiting on something that ignores the signal finishes that wait first, and middleware's `next()` resolves only once the generator has returned. Hosts cancel a response body when its client goes away while it's being sent, but a client that leaves earlier, while the context or middleware still run, is noticed only through the request's signal. Keep the server entry's [abort wiring](#aborted-requests), or such a stream runs until it ends by itself.
549
+
550
+ A stream is called with a `POST` like any procedure. Its response is `text/event-stream`: one `value` event per value, then one `end` or `error` event, and a `: keep-alive` comment every 15 seconds so proxies don't close an idle connection. Every `data` line is strict JSON:
551
+
552
+ ```text
553
+ event: value
554
+ data: [{"id":"1","title":"Review todos","completed":false}]
555
+
556
+ event: error
557
+ data: {"status":404,"error":{"code":"NOT_FOUND","message":"Todo does not exist","data":{"id":"1"}}}
558
+ ```
559
+
560
+ ### Channels
561
+
562
+ A channel is a stream that also listens: the caller sends messages while the handler yields values, over one websocket. Use it for a conversation, such as a chat or an editor that sends edits and gets the document back. Its options are a stream's plus a required `message` schema, and its handler also receives `messages`:
563
+
564
+ ```ts
565
+ export default defineRpc(
566
+ "live",
567
+ ({ channel }) => ({
568
+ // The user's todos now, then again after each title the caller sends is added.
569
+ add: channel({
570
+ message: titleSchema,
571
+ handler: async function* ({ context, messages }) {
572
+ yield await context.db.todos.snapshotForUser(context.user.id);
573
+
574
+ for await (const { title } of messages) {
575
+ await context.db.todos.addForUser(context.user.id, title);
576
+ yield await context.db.todos.snapshotForUser(context.user.id);
577
+ }
578
+ },
579
+ }),
580
+ }),
581
+ { use: [signedIn] },
582
+ );
583
+ ```
584
+
585
+ Everything in [Streams](#streams) applies: values are strict JSON, the handler is written `handler: async function* (…)`, yields the current state first and returns nothing, middleware runs once and its `next()` settles when the channel ends, cookies must be set before the handler returns its iterable, and the handler's `signal` aborts and its generator is returned when the caller goes away. `input`, if any, is read once, when the channel opens; `message` follows the same concrete-type rule as `input`, and its caller input type is what the client's `send` takes. Channels don't run during server rendering: they fail with `FORBIDDEN` before any middleware.
586
+
587
+ - **Messages** are validated with `message` as the handler reads them, in the order they arrived. A message that fails validation ends the call with `INVALID_INPUT` and the schema's issues, also when the handler catches the error. `messages` has one consumer: a second iterator throws. It ends when the caller closes the channel, after the messages already received, so a handler waiting on it returns normally; its `signal` aborts at the same time.
588
+ - **Flow control** keeps both sides bounded. The server sends at most 256 values the caller hasn't read, and the caller at most 32 messages the handler hasn't read; each side grants more as it reads half its window. A caller that stops reading pauses the handler at its `yield` (it returns at once if the caller then leaves), and a handler that stops reading `messages` makes the caller's `send` wait. The server also stops pulling values while the socket buffers more than 1 MiB of unsent data, checking every 50 ms. Throughput is about 256 values per network round trip.
589
+ - **Failures** before the handler returns its iterable, such as a refusing middleware, invalid input or a missing procedure (`RPC_NOT_FOUND`), still upgrade the socket, which receives the failure and closes, so the client sees the procedure's own error. Host, shape and [origin](#cross-origin-requests) checks happen earlier, before a context exists, and are refused with a plain HTTP response as for any RPC; a browser doesn't expose that response, so the client sees only a `TypeError`. The server log says why.
590
+ - **Input rides in the URL** (`?input=…`), so it's limited by the server's header size: Node refuses headers over 16 KiB with 431, which the client sees as a `TypeError`. Send large data as messages.
591
+ - **Ending:** once the handler ends, the server sends the end or the error and closes. A message the caller sends while that's on its way is dropped.
592
+
593
+ A channel is a `GET /_rpc/<namespace>/<procedure>?input=<encoded strict JSON>` upgraded to a websocket by the generated `handleUpgrade`; `handleRequest` answers a channel's path with `RPC_NOT_FOUND`, and `handleUpgrade` answers any other procedure the same way. Every frame is strict JSON text:
594
+
595
+ ```text
596
+ caller → server {"message":{"title":"Buy milk"}} one message
597
+ {"ready":128} "I've read 128 more values"
598
+ server → caller {"value":[{"id":"1","title":"Buy milk","completed":false}]}
599
+ {"ready":16} "the handler read 16 more messages"
600
+ {"end":null}, or a failure such as {"status":410,"error":{"code":"GONE","message":"Gone","data":null}}
601
+ then the server closes with 1000
602
+ ```
603
+
604
+ A binary or malformed frame, a message beyond the caller's credit, or a grant for more values than were sent ends the call with `INVALID_INPUT` without issues. Failure frames are exactly a stream's `error` event data.
605
+
326
606
  ## Calling RPCs
327
607
 
328
608
  Each route that has a page or descendants with pages gets an `rpc.generated.ts` with `injectRpc()`, even without its own group; redirect routes don't. Call it in an injection context:
@@ -348,7 +628,7 @@ export default class Todos {
348
628
  }
349
629
  ```
350
630
 
351
- Every call returns a promise. Procedures with input take the input first and options second; procedures without input take only options:
631
+ Every query and mutation call returns a promise; [streams](#calling-streams) return an async iterable and [channels](#calling-channels) an open channel, and both can be followed as signals with [`connect()`](#following-streams-and-channels-with-connect). Procedures with input take the input first and options second; procedures without input take only options:
352
632
 
353
633
  ```ts
354
634
  await rpc.todos.list();
@@ -356,12 +636,12 @@ await rpc.todos.list({ signal, transferCache: false });
356
636
  await rpc.todos.add({ title }, { signal });
357
637
  ```
358
638
 
359
- | Option | Effect |
360
- | --------------- | ----------------------------------------------------------------------------------------------------------------------- |
361
- | `signal` | Abort the HTTP request; the call rejects with an `AbortError`. The server may still finish the work, including a write. |
362
- | `transferCache` | Queries default to `true`. Mutations only accept `false` and never use the transfer cache. |
639
+ | Option | Effect |
640
+ | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
641
+ | `signal` | Abort the HTTP request; the call rejects with an `AbortError`. The server's middleware and handler see their `signal` abort, but aborting is advisory: work that ignores it finishes, and a write may already have committed. |
642
+ | `transferCache` | Queries default to `true`. Mutations only accept `false` and never use the transfer cache. |
363
643
 
364
- `isError(error)` is true only for errors returned by that exact procedure, and narrows them to its declared errors plus the four framework codes. Network failures and aborts are not `RpcError`s. For a type, use `ClientRpcError<typeof group.procedures.complete>` from `@loozo/angular-launch`. Each callable also has a literal `kind` of `"query"` or `"mutation"`.
644
+ `isError(error)` is true only for errors returned by that exact procedure, and narrows them to its declared errors plus the four framework codes. Network failures, aborts and the [outcomes](#redirects-and-not-found) `RpcRedirect` and `RpcNotFound` are not `RpcError`s. For a type, use `ClientRpcError<typeof group.procedures.complete>` from `@loozo/angular-launch`. Each callable also has a literal `kind` of `"query"`, `"mutation"`, `"stream"` or `"channel"`.
365
645
 
366
646
  Route resolvers can call RPCs too, which is how a page gets its data during SSR:
367
647
 
@@ -381,13 +661,155 @@ export default defineRoute("todos", {
381
661
 
382
662
  `Client<typeof group>` from `@loozo/angular-launch` gives you the client type for a group, for example to type a result: `Awaited<ReturnType<Client<typeof group>["list"]>>`. Import the group with `import type` so server code stays out of the browser bundle.
383
663
 
664
+ ### Navigating on outcomes
665
+
666
+ `rpcNavigationErrors({ notFound })` from `@loozo/angular-launch` is a navigation error handler for Angular's `withNavigationErrorHandler`:
667
+
668
+ ```ts
669
+ // src/config.ts
670
+ import { provideRouter, withNavigationErrorHandler } from "@angular/router";
671
+ import { rpcNavigationErrors } from "@loozo/angular-launch";
672
+ import { createUrl } from "@loozo/angular-router";
673
+ import notFound from "./routes/not-found/route";
674
+
675
+ provideRouter(
676
+ routes,
677
+ withNavigationErrorHandler(rpcNavigationErrors({ notFound: createUrl(notFound, {}) })),
678
+ );
679
+ ```
680
+
681
+ When a guard or resolver's call rejects with `RpcRedirect`, the navigation goes to its `to` instead; during server rendering Angular answers the page request with a 302 to it. When it rejects with `RpcNotFound`, the `notFound` page is rendered while the address bar keeps the requested URL; during server rendering the page is answered with status 404. Other errors are left to Angular.
682
+
683
+ - Only navigation acts on outcomes. A call from a component, a click handler or a TanStack query just rejects.
684
+ - Angular takes one navigation error handler. If your app has its own, call the function `rpcNavigationErrors` returns from it, inside that handler's injection context, and return its result.
685
+ - The 404 needs the route's `RenderMode.Server`. While Angular prerenders a page, an outcome fails the build instead; see [Prerendering](#prerendering).
686
+
687
+ ### Calling streams
688
+
689
+ In a component, follow a stream with [`connect()`](#following-streams-and-channels-with-connect), which handles rendering, reconnecting on input changes and cleanup. Underneath, a stream's callable returns an async iterable instead of a promise, and takes only `signal` as an option:
690
+
691
+ ```ts
692
+ for await (const todos of rpc.live.watch({ signal })) {
693
+ this.todos.set(todos);
694
+ }
695
+ ```
696
+
697
+ Each iteration sends a new request; leaving the loop early or aborting `signal` closes it. Iteration:
698
+
699
+ - ends after the stream's last value;
700
+ - throws an `RpcError` that the callable's `isError` recognizes, for a framework or declared error, and an `RpcRedirect` or `RpcNotFound` for an outcome, whether the stream was refused or ended with it;
701
+ - throws an `AbortError` when `signal` aborts;
702
+ - throws a `TypeError` when the connection fails or closes before the stream ended.
703
+
704
+ Nothing reconnects for you. To reconnect, iterate again, typically after a `TypeError` and a pause; retrying doesn't help after an `RpcError`. Each reconnect is a new call with a fresh context, and the stream starts over from the handler's first value.
705
+
706
+ Streams use the browser's `fetch`, not `HttpClient`, so HTTP interceptors don't see them. An `HttpClient` request keeps the app from becoming stable until it completes and keeps its whole response in memory, which an open stream would do for as long as it runs. Cookies are sent as for any same-origin request.
707
+
708
+ Streams don't run during server rendering: there, iterating one fails at once with `FORBIDDEN`, before any middleware runs. Render the page from a query, then follow the stream in the browser; an open stream doesn't keep the app from becoming stable.
709
+
710
+ TanStack Query options aren't generated for streams; see the [TanStack Query guide](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.6/packages/angular-launch/tanstack-query/README.md#limitations).
711
+
712
+ ### Calling channels
713
+
714
+ A channel's callable opens the websocket at once and returns the channel: iterate it for the handler's values and `send` messages to it. It takes only `signal` as an option:
715
+
716
+ ```ts
717
+ const adding = rpc.live.add({ signal });
718
+
719
+ const sending = (async () => {
720
+ for (const title of titles) {
721
+ await adding.send({ title }); // typed by the channel's message schema
722
+ }
723
+ })();
724
+
725
+ for await (const todos of adding) {
726
+ this.todos.set(todos); // typed by what the handler yields
727
+ }
728
+ ```
729
+
730
+ - **Read while you send.** Each side's window fills when the other stops reading: the server stops at 256 values you haven't read, and `send` waits once 32 messages are unread on the server. So read in a loop that runs alongside your sends, as above. Awaiting a batch of sends before reading stalls for good once both windows fill: with a handler that yields once per message, `for (const title of thousandTitles) await adding.send({ title })` followed by the read loop never gets to the loop. Its sends stop after about 290: 256 values wait unread, so the handler stops at its next `yield` and reads no more messages, and the next 32 wait unread on the server. [`connect()`](#following-streams-and-channels-with-connect) always reads, so it can't stall this way.
731
+ - **`send`** resolves once the message is handed to the socket. Messages sent before the socket opens, or while the server has no room, wait in order. It rejects with the channel's closing error if the channel closes first (an `AbortError` after `signal` aborts, a `TypeError` after the channel ended or the connection closed), with a `TypeError` once the channel is closed, and with a `TypeError` for a message that isn't strict JSON.
732
+ - **Iteration** works like a stream's: it ends after the handler's last value, throws the callable's own `RpcError` or an `RpcRedirect` or `RpcNotFound` for a failure, an `AbortError` when `signal` aborts and a `TypeError` when the connection closes early, the server refused the handshake or sent a malformed frame. Values that arrive before you read them are kept, up to the server's window; aborting `signal` drops the ones not read yet, also after the handler ended. Reads may overlap: each settles in order. A channel has one iterator: iterating it twice throws. Leaving the loop early, as `break` does, or aborting `signal` closes the socket, and the handler sees its `messages` end and its `signal` abort.
733
+ - **Nothing reconnects for you,** and each call is new: a new context, the handler's first value again.
734
+
735
+ Channels use the browser's `WebSocket`, with the URL resolved against the page as `ws:` or `wss:`, and send the page's cookies. HTTP interceptors don't see them, and an open channel doesn't keep the app from becoming stable. During server rendering a channel fails at once with `FORBIDDEN`, without connecting. TanStack Query options aren't generated for channels.
736
+
737
+ ### Following streams and channels with `connect()`
738
+
739
+ A stream's or channel's callable also has `connect()`, which follows it as signals. Call it in an injection context, such as a field initializer:
740
+
741
+ ```ts
742
+ @Component({
743
+ template: `
744
+ <ul>
745
+ @for (todo of todos.value(); track todo.id) {
746
+ <li>{{ todo.title }}</li>
747
+ }
748
+ </ul>
749
+ @if (todos.status() === "failed") {
750
+ <p>Lost the live list. <button (click)="todos.reconnect()">Reconnect</button></p>
751
+ }
752
+ <form (submit)="add($event, title)">
753
+ <input #title required maxlength="200" />
754
+ <button [disabled]="adding.status() !== 'open'">Add</button>
755
+ </form>
756
+ `,
757
+ })
758
+ export default class Live {
759
+ readonly #rpc = injectRpc();
760
+ readonly #route = injectRoute();
761
+ // The server renders the resolver's list; after hydration the stream follows it.
762
+ protected readonly todos = this.#rpc.live.watch.connect({
763
+ initial: () => this.#route.data().todos,
764
+ });
765
+ protected readonly adding = this.#rpc.live.add.connect({ initial: () => null });
766
+
767
+ protected async add(event: SubmitEvent, input: HTMLInputElement): Promise<void> {
768
+ event.preventDefault();
769
+
770
+ try {
771
+ await this.adding.send({ title: input.value.trim() });
772
+ input.value = "";
773
+ } catch {
774
+ // adding.status() and adding.error() say why.
775
+ }
776
+ }
777
+ }
778
+ ```
779
+
780
+ The options are:
781
+
782
+ | Option | Effect |
783
+ | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
784
+ | `input` | Read reactively. A change closes the connection and opens a new one; `undefined` keeps it closed with status `"idle"`. Required for a procedure with input, returning its input. A procedure without input connects by default; a function returning `null` connects and `undefined` keeps it closed. |
785
+ | `initial` | The value until the first value arrives, read reactively until then; also what the server renders. |
786
+ | `reduce` | Optional. `(state, value) => state` folds each value into the state, starting from `initial()` for each new call. Without it, the state is the latest value. |
787
+
788
+ It returns a connection:
789
+
790
+ | Member | Meaning |
791
+ | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
792
+ | `value` | A signal of the state. It's kept through failures and reconnects until a value from the new call replaces it. |
793
+ | `status` | A signal of `"idle"` (no input, or on the server), `"connecting"`, `"open"`, `"ended"` (the handler ended) or `"failed"`. |
794
+ | `error` | A signal of what failed it while `"failed"`: the procedure's `RpcError` (narrow it with the callable's `isError`), an `RpcRedirect` or `RpcNotFound`, a `TypeError` for a lost or refused connection, or the `Error` `reduce` threw (anything else it throws becomes an `Error` with it as `cause`); `undefined` otherwise. |
795
+ | `reconnect()` | After `"ended"` or `"failed"`, opens a new call, starting from the handler's first value. Does nothing otherwise. |
796
+ | `send()` | Channels only. Waits while connecting and for the server's room while open, and resolves once the message is handed to the socket. Rejects with a `TypeError` while idle, ended or failed; with the same error `error()` shows when the connection fails while it waits, also when `reduce` throws; and with an `AbortError` when Launch closes the call first, for a new input, `reconnect()` or the injection context's destruction. |
797
+
798
+ On the server it never connects: `status` is `"idle"` and `value` is `initial()`. In the browser it connects after the next render. It doesn't use `HttpClient` or Angular's pending tasks, so an open connection never keeps the app from becoming stable, and destroying the injection context closes it. It reads every value as it arrives, so channel sends never stall the way they can [when you iterate yourself](#calling-channels).
799
+
800
+ - A failed connection keeps showing the last value; show `status()` or `error()` next to it so the page doesn't look current.
801
+ - Every change of `input` reconnects, without a debounce.
802
+ - The first render shows `initial()`, also after hydration, until the first value arrives.
803
+ - `reduce` runs untracked and must be pure; what it throws fails the connection.
804
+ - A `send` you don't await or catch surfaces its rejection as an unhandled rejection.
805
+
384
806
  ### With TanStack Query
385
807
 
386
- With the `tanstackQuery` generation option, each `rpc.generated.ts` also exports `injectQueries()`: typed query and mutation options and keys for the same groups, for `@tanstack/angular-query`. See the [TanStack Query guide](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.4/packages/angular-launch/tanstack-query/README.md) for setup, keys, invalidation and hydration.
808
+ With the `tanstackQuery` generation option, each `rpc.generated.ts` also exports `injectQueries()`: typed query and mutation options and keys for the same groups, for `@tanstack/angular-query`. See the [TanStack Query guide](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.6/packages/angular-launch/tanstack-query/README.md) for setup, keys, invalidation, optimistic updates and hydration.
387
809
 
388
810
  ## Server rendering and hydration
389
811
 
390
- During server rendering, calls run directly on the server with the context created for that page request. Queries are stored in Angular's HTTP transfer cache, so hydration reuses the responses instead of calling the server again. After the app is stable, calls are ordinary HTTP requests, each with a fresh context. Opt a query out with `{ transferCache: false }`. Queries run through [TanStack Query](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.4/packages/angular-launch/tanstack-query/README.md) opt out and are transferred by TanStack instead.
812
+ During server rendering, calls run directly on the server with the context created for that page request. Queries are stored in Angular's HTTP transfer cache, so hydration reuses the responses instead of calling the server again. After the app is stable, calls are ordinary HTTP requests, each with a fresh context. Opt a query out with `{ transferCache: false }`. Queries run through [TanStack Query](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.6/packages/angular-launch/tanstack-query/README.md) opt out and are transferred by TanStack instead.
391
813
 
392
814
  The reuse has limits, all of them Angular's transfer cache behaving as designed:
393
815
 
@@ -395,12 +817,46 @@ The reuse has limits, all of them Angular's transfer cache behaving as designed:
395
817
  - The cache serves calls made before the app first becomes stable. RPCs called later, for example from a `@defer` block that hydrates on interaction or when it enters the viewport, go over HTTP.
396
818
  - Launch relies on your app's transfer cache settings. `withNoHttpTransferCache()`, or a `withHttpTransferCacheOptions` `filter` that rejects `/_rpc/` requests, turns reuse off without any error, and every query runs again in the browser.
397
819
 
398
- Mutations are refused during server rendering with `FORBIDDEN`, before validation, guards or the handler run. Rendering should only read.
820
+ Outcomes in a guard or resolver become a 302 or a 404 page with [`rpcNavigationErrors`](#navigating-on-outcomes), and both have caveats:
821
+
822
+ - A server-rendered not-found page calls the procedure again over HTTP during hydration, because only successes transfer, so its handler runs twice. A redirect doesn't: the browser follows the 302.
823
+ - Any other failure of a guard or resolver during server rendering, such as `FORBIDDEN`, `INTERNAL`, a declared error, or an outcome without `rpcNavigationErrors`, fails the initial navigation. Angular then renders no page and `angular.handle` returns `null`, so your server's fallback answers, such as the example's plain 404, without the cookies calls set during the render. Handle such errors in the route if the page should show something, or throw an outcome instead.
824
+
825
+ Mutations are refused during server rendering with `FORBIDDEN`, before any middleware, validation or the handler runs. Rendering should only read. Streams are refused the same way, since they don't finish; see [Calling streams](#calling-streams).
399
826
 
400
- RPCs need a live request. Prerendering a page that calls an RPC fails the build (with `finishLaunchRendering` in place); static pages that don't call RPCs prerender normally. Blocking initial navigation (`withEnabledBlockingInitialNavigation`) combined with a root resolver that calls an RPC isn't supported.
827
+ Middleware and handlers run during server rendering too, with the page request as `request`. Their `signal` aborts when the page request aborts, or when `HttpClient` unsubscribes from the call before it settled. Cookies they set go on the page response through Angular's `RESPONSE_INIT`, and headers are dropped; see [Cookies and headers](#cookies-and-headers).
401
828
 
402
829
  Transferred responses end up in the HTML. Only return data that the user may see, and serve personalized pages with `Cache-Control: private, no-store`.
403
830
 
831
+ ### Prerendering
832
+
833
+ A page Angular prerenders at build time can call queries:
834
+
835
+ ```ts
836
+ // src/rendering.ts
837
+ export const rendering: ServerRoute[] = [
838
+ { path: "about", renderMode: RenderMode.Prerender },
839
+ { path: "**", renderMode: RenderMode.Server },
840
+ ];
841
+ ```
842
+
843
+ Angular prerenders without a request, so Launch creates the page's context from a cookie-less `GET` of the page's URL, and every call in that render shares it. A prerendered page shows what an anonymous visitor would see: middleware that needs a signed-in user refuses, and that fails the build.
844
+
845
+ Every call made while prerendering must succeed. With [`finishLaunchRendering`](#4-wire-the-browser-and-server-apps) in place, the build fails and names the call when one answers with anything but a result: a declared error, a framework code (such as `FORBIDDEN` from middleware, or for a mutation or stream), `notFound()` or `redirect()`. It also fails when a call sets a cookie, since a prerendered page is a file with no response to carry it, and when the context factory throws. Without it, Angular can write the page with the failure rendered into it, or skip the page and still report success.
846
+
847
+ Launch checks once the app is first stable, which covers calls from guards, resolvers and rendering. That's the last point where a render can still fail: Angular runs `BEFORE_APP_SERIALIZED` hooks afterwards and only logs their errors. So a call made later, such as one awaited in such a hook, isn't checked, and the page is written whether it fails or sets a cookie. Don't make Launch calls there.
848
+
849
+ The results reach the browser inside the page, as during server rendering: through Angular's transfer cache, or TanStack's hydration. Loading the page makes no RPC. Every call after that, such as a refetch, an invalidation or a client-side navigation to the page, is an ordinary HTTP request to your server, with the visitor's own context. So:
850
+
851
+ - Queries on a prerendered page should answer the same for everyone. One that reads the user shows the anonymous answer in the HTML, then the visitor's after its next call.
852
+ - Everything a prerendered call returns is in a file served to every visitor.
853
+ - The app still needs its server. A static deployment (`outputMode: "static"`) can't answer `/_rpc/`, so there, a client-side navigation to a prerendered page that calls an RPC fails.
854
+ - The context factory runs at build time, once per prerendered page, in Angular's prerender workers, so whatever it uses, such as a database, must be reachable from the build. The request's URL has the page's path on a local origin Angular picks, such as `http://localhost:<port>`; don't build absolute links from it.
855
+ - `ng serve` renders prerendered routes on every request the same way, with the anonymous context whatever cookies the browser sends.
856
+ - Angular's prerender timeout doesn't reach handlers: their `signal` aborts when the render's application is destroyed, or when `HttpClient` unsubscribes from the call.
857
+
858
+ Blocking initial navigation (`withEnabledBlockingInitialNavigation`) combined with a root resolver that calls an RPC isn't supported: Angular runs that resolver while it discovers routes, also without a request, so Launch runs the call there with an anonymous context too.
859
+
404
860
  ## Deploying
405
861
 
406
862
  With `outputMode: "server"`, `ng build` writes the browser files and a bundled server:
@@ -417,24 +873,131 @@ Copy `dist/<app>` to the host and start the server with Node:
417
873
  PORT=8080 NG_ALLOWED_HOSTS=example.com node dist/<app>/server/server.mjs
418
874
  ```
419
875
 
420
- The server bundle includes your dependencies by default, so the host doesn't need `node_modules`. `AngularNodeAppEngine` reads two environment variables:
421
-
422
- | Variable | Effect |
423
- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
424
- | `NG_ALLOWED_HOSTS` | Comma-separated hostnames allowed to render pages, in addition to `security.allowedHosts` in `angular.json`. Pages for other hosts get a 400. |
425
- | `NG_TRUST_PROXY_HEADERS` | Comma-separated `Forwarded` and `X-Forwarded-*` headers that Angular should trust. Set it only behind a proxy that overwrites those headers. Off by default. |
876
+ The server bundle includes your dependencies by default, so the host doesn't need `node_modules`. The server reads two environment variables:
426
877
 
427
- The host check covers page rendering only. `handleRequest` runs before Angular and answers RPC requests for any host.
878
+ | Variable | Effect |
879
+ | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
880
+ | `NG_ALLOWED_HOSTS` | Comma-separated hostnames allowed for pages and RPCs. The server entry above reads it and passes the list to both; it defaults to `localhost` there. Other hosts get a 400. |
881
+ | `NG_TRUST_PROXY_HEADERS` | Read by `AngularNodeAppEngine`: comma-separated `Forwarded` and `X-Forwarded-*` headers that Angular should trust. Set it only behind a proxy that overwrites those headers. Off by default. |
428
882
 
429
883
  Launch calls `/_rpc/<namespace>/<procedure>` from the root of the domain, even when the app has a different `<base href>`. If the app is served under a path prefix, route `/_rpc/` to the same server.
430
884
 
431
885
  Browser tabs opened before a deploy keep calling the procedures they were built with. After you rename a namespace or procedure, or change an input schema, those calls fail with `RPC_NOT_FOUND` or `INVALID_INPUT` until the page reloads. The same applies while old and new servers run side by side during a rolling deploy.
432
886
 
433
- Launch has been verified on Node only.
887
+ Launch has been verified on Node, and with a platform-neutral server build (below) on Deno and Cloudflare's workerd, run locally. Streams have been verified on Node, under `ng serve` and on Deno. Channels have been verified on the built Node server in Chromium, Firefox and WebKit; `ng serve` doesn't forward websocket upgrades to them yet, so under the dev server a channel fails with a `TypeError`.
888
+
889
+ ### Streams behind proxies
890
+
891
+ Stream responses carry `Cache-Control: private, no-store, no-transform` and `X-Accel-Buffering: no`, which tell compression middleware that honors `no-transform` and buffering proxies such as nginx to pass them through as they're written. Go's reverse proxy, which Tailscale Serve uses, passes `text/event-stream` responses through as they're written anyway. Each open stream holds a connection: over HTTP/1.1, browsers open at most 6 per origin, so several open streams can hold up other requests. Over HTTP/2, usually with HTTPS, they share one connection.
892
+
893
+ ### Channels on Node
894
+
895
+ Channels arrive as websocket upgrades, which Node hands to the HTTP server's `upgrade` listeners instead of its request handler. `createUpgradeHandler` from `@loozo/angular-launch/node` turns the generated `handleUpgrade` into such a listener. Create it once, at your server module's top level, and attach it to the server that serves the app: with Express, the server `app.listen()` returns, as in the [server entry](#4-wire-the-browser-and-server-apps); with plain Node:
896
+
897
+ ```ts
898
+ // src/server.ts
899
+ import { createServer } from "node:http";
900
+ import { createUpgradeHandler } from "@loozo/angular-launch/node";
901
+ import { handleUpgrade } from "../generated/server.generated";
902
+
903
+ const upgrade = createUpgradeHandler((request) => handleUpgrade(request, { allowedHosts }));
904
+
905
+ if (isMainModule(import.meta.url)) {
906
+ const server = createServer(reqHandler).listen(port);
907
+
908
+ server.on("upgrade", upgrade);
909
+ }
910
+ ```
911
+
912
+ Pass `handleUpgrade` the same `allowedHosts` and `origins` as `handleRequest`: it checks [hosts](#hosts) and [origins](#cross-origin-requests) the same way, before a context exists. The listener builds a web `Request` from the upgrade (the protocol from the socket, the host from `Host`; like Angular's default, it trusts no proxy headers), writes refusals to the socket as plain HTTP responses, and accepts the rest with [`ws`](https://github.com/websockets/ws), with the call's headers and cookies on the `101`. Upgrades outside `/_rpc/` are left to the server's other `upgrade` listeners. It pings each open socket every 15 seconds and drops one that doesn't answer, and closes a socket whose message is over `maxPayload` bytes with 1009, which the client sees as a `TypeError`:
913
+
914
+ ```ts
915
+ createUpgradeHandler((request) => handleUpgrade(request, { allowedHosts }), {
916
+ maxPayload: 64 * 1024, // defaults to 1 MiB
917
+ });
918
+ ```
919
+
920
+ - **Memory:** an open channel holds at most about 1 MiB of unsent values plus 32 unread messages of up to `maxPayload` each. How many channels may be open at once is up to your host or proxy.
921
+ - **Leaving early:** a client that leaves while the context or middleware still run ends the call before its handler starts when its browser closes the connection (Chromium and WebKit do); Firefox's leaving isn't noticed until the upgrade is accepted, when the socket closes at once.
922
+ - **HTTP/2:** Node's `http2` server doesn't accept websockets over HTTP/2 (RFC 8441) by default. Browsers then open the channel over HTTP/1.1, so serve that too.
923
+ - **Other frameworks:** the listener needs the Node `upgrade` event. Express and plain Node give it as shown; Hono's `@hono/node-server` needs its own upgrade wiring, which isn't covered here.
924
+
925
+ ### Hosts
926
+
927
+ `handleRequest` checks the hostname of the request URL before anything else, matching `allowedHosts` the way Angular does: exactly, `*.example.com` for subdomains only, or `*` for any host. RPCs for other hosts get a plain-text 400 `Host not allowed`, as Angular answers pages, and the hostname is logged. An empty list refuses every RPC.
928
+
929
+ Passing `allowedHosts` to `AngularNodeAppEngine` replaces its own read of `NG_ALLOWED_HOSTS`, which is why the server entry reads the variable itself. `security.allowedHosts` in `angular.json` still applies to pages only: Angular builds it into an internal manifest that `handleRequest` can't read, so list RPC hosts in the server entry. Under `ng serve`, Vite's host check covers `/_rpc/` as well.
930
+
931
+ ### Cross-origin requests
932
+
933
+ `handleRequest` answers only RPCs it can prove come from the app's own origin. The rest get `FORBIDDEN` (403), logged with the reason, before a context is created:
934
+
935
+ 1. An `Origin` listed in `origins` passes.
936
+ 2. Otherwise, if the request has `Sec-Fetch-Site`, it must be `same-origin`. `same-site` (a sibling subdomain), `cross-site` and `none` are refused.
937
+ 3. Otherwise, if it has `Origin`, that must equal the request URL's origin.
938
+ 4. A request with neither header is refused. There's no `Referer` fallback and no opt-out.
939
+
940
+ Launch's browser client always sends one of the two headers. curl, scripts, Node's `fetch` and server-to-server callers send neither, so they must send `Origin` with the app's origin. Browsers send `Sec-Fetch-Site` only to HTTPS and `localhost`, so a plain-HTTP deployment on any other hostname relies on `Origin` matching the request URL. Behind a proxy that rewrites `Host`, that URL isn't the public one, and those calls are refused until you list the public origin:
941
+
942
+ ```ts
943
+ const rpc = await handleRequest(web, { allowedHosts, origins: ["https://app.example.com"] });
944
+ ```
945
+
946
+ List a sibling site's origin the same way to let it call. Only HTTP requests are checked: calls made during server rendering carry the page request, whose `Sec-Fetch-Site` is `cross-site` or `none` on an ordinary navigation, and run without these checks.
947
+
948
+ ### Other runtimes
949
+
950
+ `ng build` can also write a server bundle that doesn't depend on Node, for edge and serverless platforms: set `"platform": "neutral"` in the build target's `ssr` option, next to `entry`. Launch's server code uses only web `Request` and `Response`, so only your server entry changes:
951
+
952
+ ```ts
953
+ // src/server.ts
954
+ import { AngularAppEngine, createRequestHandler } from "@angular/ssr";
955
+ import { createContext, handleRequest } from "../generated/server.generated";
956
+
957
+ const allowedHosts = ["app.example.com"];
958
+ const angular = new AngularAppEngine({ allowedHosts });
959
+
960
+ export const reqHandler = createRequestHandler(async (request: Request) => {
961
+ const rpc = await handleRequest(request, { allowedHosts });
962
+
963
+ if (rpc) {
964
+ return rpc;
965
+ }
966
+
967
+ const scope = await createContext(request);
968
+ const page = await angular.handle(scope.request, scope);
969
+
970
+ return page ?? new Response("Not found", { status: 404 });
971
+ });
972
+ ```
973
+
974
+ - Import from `@angular/ssr`, not `@angular/ssr/node`. `AngularAppEngine` doesn't read `NG_ALLOWED_HOSTS` or `NG_TRUST_PROXY_HEADERS`: pass `allowedHosts`, and `trustProxyHeaders` if you're behind a proxy (it's off by default), to its constructor, and the same hosts to `handleRequest`. List them in the entry as above, or read them from your platform's configuration.
975
+ - The bundle neither serves the `browser` files nor starts a server. Point your platform's static hosting at `dist/<app>/browser` and its request handler at the exported `reqHandler`.
976
+ - Nothing polyfills Node modules for you, so your context, handlers and their dependencies must run on the platform. In-memory state lasts only as long as the platform keeps an instance alive.
977
+ - `handleUpgrade` takes a web `Request` and runs a channel on any standard `WebSocket` the platform accepts, sending `headers` on its `101` response, but it hasn't been verified on Deno or workerd, and neither has workerd's `bufferedAmount`, which the server's flow control reads.
978
+
979
+ ### Aborted requests
980
+
981
+ Launch passes `request.signal` on to middleware and handlers as `signal`. Angular's `createWebRequestFromNodeRequest` gives a signal that only aborts while the request body is still arriving, so by the time an RPC handler runs, a client that disconnects no longer aborts it. That's why the server entry above links a signal that aborts when the Node response closes before it finished:
982
+
983
+ ```ts
984
+ const closed = new AbortController();
985
+
986
+ response.once("close", () => {
987
+ if (!response.writableFinished) {
988
+ closed.abort();
989
+ }
990
+ });
991
+
992
+ const native = createWebRequestFromNodeRequest(request);
993
+ const web = new Request(native, { signal: AbortSignal.any([native.signal, closed.signal]) });
994
+ ```
995
+
996
+ Pass `web` to both `handleRequest` and `createContext`, so page renders get the same signal. Without this wiring everything works, but query and mutation handlers never see an abort over HTTP, and a [stream](#streams) whose client left before it started runs until it ends by itself. A stream that's already being sent stops either way, since Angular's helper cancels its body when the response closes.
434
997
 
435
998
  ### Other server frameworks
436
999
 
437
- `handleRequest` and `createContext` take a web `Request`, so any framework that gives you one works. `AngularNodeAppEngine` also accepts a web `Request`, and keeps the environment variables above. With [Hono](https://hono.dev) on Node:
1000
+ `handleRequest` and `createContext` take a web `Request`, so any framework that gives you one works. `AngularNodeAppEngine` also accepts a web `Request`. With [Hono](https://hono.dev) on Node:
438
1001
 
439
1002
  ```ts
440
1003
  // src/server.ts
@@ -447,13 +1010,15 @@ import { Hono } from "hono";
447
1010
  import { createContext, handleRequest } from "../generated/server.generated";
448
1011
 
449
1012
  const browser = fileURLToPath(new URL("../browser", import.meta.url));
450
- const angular = new AngularNodeAppEngine();
1013
+ // An explicit list stops Angular reading NG_ALLOWED_HOSTS, so read it here.
1014
+ const allowedHosts = (process.env["NG_ALLOWED_HOSTS"] ?? "localhost").split(",");
1015
+ const angular = new AngularNodeAppEngine({ allowedHosts });
451
1016
  const app = new Hono();
452
1017
 
453
1018
  app.use("*", serveStatic({ root: browser }));
454
1019
 
455
1020
  app.all("*", async (c) => {
456
- const rpc = await handleRequest(c.req.raw);
1021
+ const rpc = await handleRequest(c.req.raw, { allowedHosts });
457
1022
 
458
1023
  if (rpc) {
459
1024
  return rpc;
@@ -476,10 +1041,12 @@ if (isMainModule(import.meta.url)) {
476
1041
  export const reqHandler = createRequestHandler(app.fetch);
477
1042
  ```
478
1043
 
479
- Export the handler as `reqHandler`; Angular's dev server and build don't look for a default export. Under `ng serve`, `serveStatic` logs that the `browser` directory doesn't exist. That's expected: the dev server serves those files itself.
1044
+ Export the handler as `reqHandler`; Angular's dev server and build don't look for a default export. [Channels](#channels-on-node) need their own upgrade wiring with Hono, which isn't covered here. Whether `@hono/node-server` aborts `c.req.raw.signal` when a client disconnects is unverified, so don't rely on handlers seeing an abort there. Under `ng serve`, `serveStatic` logs that the `browser` directory doesn't exist. That's expected: the dev server serves those files itself.
480
1045
 
481
1046
  ## Generation
482
1047
 
1048
+ The [builders](#builders) run generation for you. Underneath, it's a Node function you can also call from your own tools:
1049
+
483
1050
  ```ts
484
1051
  generate(workspace: string, options: GenerationOptions, stopped?: () => boolean): Promise<void>;
485
1052
  ```
@@ -489,7 +1056,7 @@ generate(workspace: string, options: GenerationOptions, stopped?: () => boolean)
489
1056
  | `tsconfig` | `string` | Your app tsconfig, relative to `workspace` |
490
1057
  | `scanDirectories` | `string[]` | Exactly one route directory, relative to the tsconfig's directory |
491
1058
  | `outDirectory` | `string` | Where the app-wide generated files go, relative to `workspace` |
492
- | `tanstackQuery` | `boolean` | Also generate `injectQueries()`; see [TanStack Query](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.4/packages/angular-launch/tanstack-query/README.md) |
1059
+ | `tanstackQuery` | `boolean` | Also generate `injectQueries()`; see [TanStack Query](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.6/packages/angular-launch/tanstack-query/README.md) |
493
1060
  | `check` | `boolean` | Verify generated files without writing them; fails if anything is out of date |
494
1061
 
495
1062
  `workspace` is the absolute path of the application directory (the one with its `package.json`). The tsconfig, scan directory and output directory must all be inside it. `stopped` lets a caller cancel: if it returns `true` before writing starts, nothing is written.
@@ -500,7 +1067,7 @@ Generation reads your source without running it. It writes the router's files pl
500
1067
  | --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
501
1068
  | `rpc.generated.ts` beside each route | `injectRpc()` with the route's own and ancestor groups, plus `injectQueries()` with `tanstackQuery`; none for redirect routes |
502
1069
  | `<outDirectory>/context.generated.d.ts` | Registers your context type |
503
- | `<outDirectory>/server.generated.ts` | `createContext`, `handleRequest`, `provideServer`, the registry |
1070
+ | `<outDirectory>/server.generated.ts` | `createContext`, `handleRequest`, `handleUpgrade`, `provideServer`, the registry |
504
1071
 
505
1072
  Each file starts with an ownership marker comment. Generation only replaces or removes files with those exact names and markers, fails rather than overwrite an unmarked file or a symlink in their place, and removes stale ones. Unchanged files aren't rewritten. Everything is validated before anything is written, so a run that fails validation changes nothing. Files are then written one at a time, with no rollback: a write error partway through, such as an unwritable file, or an interrupted run can leave some files updated and others not. The next successful run repairs them.
506
1073
 
@@ -508,12 +1075,35 @@ Before writing, generation type-checks the generated files, your route and RPC d
508
1075
 
509
1076
  Generated browser code contains only names, kinds and error metadata, never your schemas, handlers or context. Keep server-only modules out of anything a page imports at runtime; the example names them `*.server.ts`.
510
1077
 
511
- `server.generated.ts` binds Launch's internal `createRequestScope`, `handleRpc` and `provideLaunchServer` to your app. It imports them from `@loozo/angular-launch/_server`, an entry point for generated code only that isn't public API and can change in any release; use the generated functions instead. The app identity comes from the `package.json` name, the generation tsconfig's path within the app, and the context file's path and contents, so moving the whole app directory doesn't change it.
1078
+ `server.generated.ts` binds Launch's internal `createRequestScope`, `handleRpc`, `handleChannelUpgrade` and `provideLaunchServer` to your app. It imports them from `@loozo/angular-launch/_server`, an entry point for generated code only that isn't public API and can change in any release; use the generated functions instead. The app identity comes from the `package.json` name, the generation tsconfig's path within the app, and the context file's path and contents, so moving the whole app directory doesn't change it.
512
1079
 
513
- RPC URLs are `/_rpc/<namespace>/<procedure>`, so they change only when you rename a namespace or procedure. Moving an `rpc.ts` or the generation tsconfig doesn't change them. The example doesn't commit generated files: it regenerates before every build, and `node generate.mjs --check` verifies them without writing.
1080
+ RPC URLs are `/_rpc/<namespace>/<procedure>`, so they change only when you rename a namespace or procedure. Moving an `rpc.ts` or the generation tsconfig doesn't change them. The example doesn't commit generated files: every build regenerates them, and its `check` configuration (`ng run todos:build:check`) verifies them without writing.
514
1081
 
515
1082
  `@loozo/angular-launch/generation` is Node-only.
516
1083
 
1084
+ ### Builders
1085
+
1086
+ #### `@loozo/angular-launch:application`
1087
+
1088
+ All `@angular/build:application` options, plus the generation options above (`tsconfig`, `scanDirectories`, `outDirectory`, `tanstackQuery` and `check`, which default to `false`). It takes those out and passes every other option through unchanged.
1089
+
1090
+ The builder runs generation once, then the official application build. Invalid options stop the build before generation starts. Generation errors, including drift with `check: true`, are logged and fail the build before the Angular build runs. `watch: true` is rejected; use the serve builder for watching.
1091
+
1092
+ #### `@loozo/angular-launch:serve`
1093
+
1094
+ All `@angular/build:dev-server` options, set in `angular.json` or on the command line (`ng serve --port 4300`), plus:
1095
+
1096
+ | Option | Type | Default | Description |
1097
+ | ------------- | ----------------- | -------- | ---------------------------------------------------------------------------------------- |
1098
+ | `buildTarget` | `string` | required | A target that uses `@loozo/angular-launch:application`. Generation options come from it. |
1099
+ | `poll` | `number \| false` | `1000` | The dev server's file-watch polling interval in milliseconds, or `false` for no default. |
1100
+
1101
+ Invalid options stop the serve builder before it generates anything, and so does an invalid build target. The build target must not resolve `check: true`, because serving always writes generated files. The initial generation must succeed before the dev server starts; if it fails, the error is logged and the builder reports a failed build.
1102
+
1103
+ The builder then watches the scan directory and the context file, wherever the last generation found it, and regenerates when files are added, changed or removed there. A pass starts once changes have been quiet for 150 ms, so saving several files at once or renaming a directory runs one pass. Passes run one at a time; changes during a pass cause one more. A failed pass is logged and the server keeps running; the next change retries. When it starts watching a context file outside the scan directory, it runs one more pass once that watch is live, so an edit made while the file was being found isn't lost. A plain rename of the context file is followed, but a move that passes through a missing or broken context, such as delete-then-create or a file that's broken at its new path, is picked up only on the next change in the scan directory or a restart. Other files, such as a module your context imports, don't trigger generation; Angular's build still checks them.
1104
+
1105
+ Polling is on by default because Angular 22.2.2's native file watcher misses edits to files inside a renamed directory, which leaves the dev server serving stale output. It costs some idle CPU. Set `"poll": false` in the serve target to go back to native file events; Angular's own configuration then applies, including a `poll` on the build target. A positive number overrides the build target's `poll`; `0` is rejected. On the command line, `--poll` accepts milliseconds only. `poll` configures Angular's dev-server watcher; Launch's own watcher uses native file events.
1106
+
517
1107
  ### Generation sessions
518
1108
 
519
1109
  `generate` starts from scratch on every call. A long-running tool that regenerates repeatedly (for example, after file changes) can create a session instead, which reuses compiler work between calls:
@@ -541,27 +1131,30 @@ The options are fixed when the session is created. Edits inside the app, includi
541
1131
 
542
1132
  ## Limitations
543
1133
 
544
- - No Angular builder or watch mode for Launch yet; run generation yourself before `ng build` or `ng serve`.
545
- - No subscriptions, optimistic updates or automatic invalidation. Beyond hydration, the only query cache is TanStack Query's, through the optional [integration](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.4/packages/angular-launch/tanstack-query/README.md#limitations), which has its own limitations.
1134
+ - Streams and channels don't reconnect or resume on their own (`connect()` reconnects when asked or when its input changes), and HTTP interceptors don't see them. Channels carry strict JSON text only, one call per socket, with no acknowledgements, and don't run under `ng serve` yet.
1135
+ - Beyond hydration, the only query cache is TanStack Query's, through the optional [integration](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.6/packages/angular-launch/tanstack-query/README.md#limitations), which has its own limitations. Optimistic updates and invalidation are TanStack's too, as its guide [shows](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.6/packages/angular-launch/tanstack-query/README.md#optimistic-updates); Launch adds no helpers for them. Without it, nothing is invalidated for you.
546
1136
  - No storage adapters; persistence is your handler's job.
547
- - No production authentication, CSRF, CORS or caching policy. You provide those.
548
- - Server work isn't cancelled when the client aborts, and nothing is rolled back.
1137
+ - No production authentication, CORS or caching policy. You provide those. Cross-origin RPCs are refused (see [Cross-origin requests](#cross-origin-requests)); there's no CSRF token scheme.
1138
+ - No cookie reader, and no success status other than 200. During server rendering, a cookie set by one call isn't visible to later calls in the same render, a failed initial navigation loses the render's cookies, and headers are dropped.
1139
+ - Aborting is advisory: handlers get a `signal`, but work that ignores it finishes, a write may already have committed, and nothing is rolled back.
1140
+ - Middleware is server-side only: there's no client middleware (use an Angular HTTP interceptor), and no dedupe of middleware listed twice.
1141
+ - Redirects are root-relative only, and outcomes act only in navigation, through `rpcNavigationErrors`. Nothing maps `FORBIDDEN` to a page.
549
1142
  - One RPC group per route, and one context per application.
550
1143
 
551
1144
  ## Further reading
552
1145
 
553
- - [TanStack Query](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.4/packages/angular-launch/tanstack-query/README.md): the optional query and mutation integration
554
- - [`specs/angular-launch.md`](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.4/specs/angular-launch.md): design and full contract
555
- - [`examples/angular-launch`](https://github.com/theo-matzavinos/loozo/tree/angular-launch@0.0.4/examples/angular-launch): the todos app. Its cookie identity and in-memory database are test fixtures, not security or deployment guidance.
556
- - [`@loozo/angular-router`](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.4/packages/angular-router/README.md): routes, codecs and navigation
1146
+ - [TanStack Query](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.6/packages/angular-launch/tanstack-query/README.md): the optional query and mutation integration
1147
+ - [`specs/angular-launch.md`](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.6/specs/angular-launch.md): design and full contract
1148
+ - [`examples/angular-launch`](https://github.com/theo-matzavinos/loozo/tree/angular-launch@0.0.6/examples/angular-launch): the todos app. Its cookie identity and in-memory database are test fixtures, not security or deployment guidance.
1149
+ - [`@loozo/angular-router`](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.6/packages/angular-router/README.md): routes, codecs and navigation
557
1150
 
558
1151
  ## Developing this package
559
1152
 
560
1153
  ```sh
561
- pnpm run build # tsc
1154
+ pnpm run build # builder schemas, then tsc
562
1155
  pnpm run typecheck
563
1156
  pnpm run test # node --test
564
1157
  node tests/packed.mjs /absolute/new-directory # packed consumer check; directory must not exist
565
1158
  ```
566
1159
 
567
- The packed check keeps its consumer, pnpm store and temporary files inside the directory you pass.
1160
+ The packed check keeps its consumer, pnpm store and temporary files inside the directory you pass. The build regenerates the builder schemas in `schemas/` from the installed `@angular/build`; `tests/schema.test.mjs` fails when a committed schema is stale.