@loozo/angular-launch 0.0.5 → 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 (47) hide show
  1. package/README.md +463 -42
  2. package/channel.d.ts +53 -0
  3. package/channel.js +231 -0
  4. package/client.d.ts +50 -10
  5. package/connect.d.ts +201 -0
  6. package/connect.js +148 -0
  7. package/generated.d.ts +1 -1
  8. package/generated.js +86 -3
  9. package/generation/index.js +25 -9
  10. package/index.d.ts +6 -1
  11. package/index.js +2 -0
  12. package/json.d.ts +9 -0
  13. package/json.js +24 -0
  14. package/navigation.d.ts +36 -0
  15. package/navigation.js +47 -0
  16. package/node/index.d.ts +57 -0
  17. package/node/index.js +175 -0
  18. package/outcomes.d.ts +55 -0
  19. package/outcomes.js +100 -0
  20. package/package.json +9 -3
  21. package/server/backend.d.ts +42 -23
  22. package/server/backend.js +127 -48
  23. package/server/channel-messages.d.ts +54 -0
  24. package/server/channel-messages.js +84 -0
  25. package/server/channel-socket.d.ts +67 -0
  26. package/server/channel-socket.js +322 -0
  27. package/server/definitions.d.ts +152 -24
  28. package/server/definitions.js +13 -5
  29. package/server/dispatch.d.ts +62 -11
  30. package/server/dispatch.js +156 -36
  31. package/server/event-stream.d.ts +63 -0
  32. package/server/event-stream.js +173 -0
  33. package/server/generated.d.ts +1 -0
  34. package/server/generated.js +1 -0
  35. package/server/index.d.ts +4 -2
  36. package/server/index.js +1 -1
  37. package/server/outcomes.d.ts +51 -2
  38. package/server/outcomes.js +58 -4
  39. package/server/response-effects.d.ts +105 -0
  40. package/server/response-effects.js +78 -0
  41. package/server/upgrade.d.ts +58 -0
  42. package/server/upgrade.js +117 -0
  43. package/stream.d.ts +31 -0
  44. package/stream.js +159 -0
  45. package/tanstack-query/README.md +101 -9
  46. package/tanstack-query/generated.js +5 -2
  47. package/tanstack-query/queries.d.ts +8 -6
package/README.md CHANGED
@@ -1,26 +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.5/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, middleware and declared errors, with optional [TanStack Query](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.5/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 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.
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.
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.
15
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.
16
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.
17
17
  - A `package.json` with a `name` in the application directory. The name is part of the generated app identity.
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.5/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).
19
19
 
20
20
  Install both packages:
21
21
 
22
22
  ```sh
23
- pnpm add @loozo/angular-launch @loozo/angular-router@0.0.6
23
+ pnpm add @loozo/angular-launch @loozo/angular-router@0.0.8
24
24
  ```
25
25
 
26
26
  ## How it fits together
@@ -43,7 +43,7 @@ generated/
43
43
  ├── routes.generated.ts router: routes for provideRouter
44
44
  ├── destinations.generated.ts router
45
45
  ├── context.generated.d.ts registers your context type
46
- └── server.generated.ts createContext, handleRequest, provideServer
46
+ └── server.generated.ts createContext, handleRequest, handleUpgrade, provideServer
47
47
  ```
48
48
 
49
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.
@@ -52,7 +52,7 @@ The route tree is the router's. An `rpc.ts` belongs to the route declared in the
52
52
 
53
53
  ## Setup
54
54
 
55
- The [todos example](https://github.com/theo-matzavinos/loozo/tree/angular-launch@0.0.5/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.
56
56
 
57
57
  ### 1. Define the context
58
58
 
@@ -144,6 +144,8 @@ export const config: ApplicationConfig = {
144
144
  };
145
145
  ```
146
146
 
147
+ To have pages follow a procedure's [`redirect()` and `notFound()`](#redirects-and-not-found), add [`rpcNavigationErrors`](#navigating-on-outcomes) to `provideRouter`.
148
+
147
149
  The server config adds the generated `provideServer()`, after `provideHttpClient()`:
148
150
 
149
151
  ```ts
@@ -159,7 +161,7 @@ export const serverConfig = mergeApplicationConfig(config, {
159
161
  });
160
162
  ```
161
163
 
162
- 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)):
163
165
 
164
166
  ```ts
165
167
  // src/main.server.ts
@@ -187,8 +189,9 @@ import {
187
189
  isMainModule,
188
190
  writeResponseToNodeResponse,
189
191
  } from "@angular/ssr/node";
192
+ import { createUpgradeHandler } from "@loozo/angular-launch/node";
190
193
  import express from "express";
191
- import { createContext, handleRequest } from "../generated/server.generated";
194
+ import { createContext, handleRequest, handleUpgrade } from "../generated/server.generated";
192
195
 
193
196
  const browser = join(import.meta.dirname, "../browser");
194
197
  // An explicit list stops Angular reading NG_ALLOWED_HOSTS, so read it here.
@@ -234,44 +237,49 @@ app.use(async (request, response, next) => {
234
237
  }
235
238
  });
236
239
 
240
+ // Channels arrive as websocket upgrades, which Express never sees.
241
+ const upgrade = createUpgradeHandler((request) => handleUpgrade(request, { allowedHosts }));
242
+
237
243
  if (isMainModule(import.meta.url)) {
238
244
  const port = process.env["PORT"] || 4000;
239
-
240
- app.listen(port, (error) => {
245
+ const server = app.listen(port, (error) => {
241
246
  if (error) {
242
247
  throw error;
243
248
  }
244
249
 
245
250
  console.log(`Listening on http://localhost:${port}`);
246
251
  });
252
+
253
+ server.on("upgrade", upgrade);
247
254
  }
248
255
 
249
256
  export const reqHandler = createNodeRequestHandler(app);
250
257
  ```
251
258
 
252
- 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).
253
260
 
254
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.
255
262
 
256
263
  ## Defining RPCs
257
264
 
258
- `defineRpc(namespace, build, options?)` declares a group. `build` receives the `query` (a read) and `mutation` (a write) builders and returns the group's procedures:
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:
259
266
 
260
267
  ```ts
261
268
  defineRpc(
262
269
  "todos",
263
- ({ query, mutation }) => ({
270
+ ({ query, mutation, stream }) => ({
264
271
  list: query({ input?, use?, errors?, handler }),
265
272
  add: mutation({ input?, use?, errors?, handler }),
273
+ watch: stream({ input?, use?, errors?, handler }),
266
274
  }),
267
275
  { use? },
268
276
  );
269
277
  ```
270
278
 
271
- The handler receives `{ context, input, errors, request, signal }` and returns a value or a promise. `request` is the request the call runs in: the RPC request over HTTP, or the page request during server rendering. `signal` aborts when the caller goes away; see [Calling RPCs](#calling-rpcs).
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).
272
280
 
273
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.
274
- - **The callback** is read without running it: an arrow function that destructures `query` and/or `mutation` without renaming, returning a parenthesized object literal in which each procedure is a direct `query(...)` or `mutation(...)` call with inline options.
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.
275
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.
276
284
 
277
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.
@@ -317,7 +325,7 @@ So a caller that group middleware refuses gets `FORBIDDEN` even when its input i
317
325
  });
318
326
  ```
319
327
 
320
- - **Refusing:** `throw forbidden()` fails the call with `FORBIDDEN`; a handler can throw it too. Any other exception fails the call with `INTERNAL`. Declared errors belong to handlers.
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.
321
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:
322
330
 
323
331
  ```ts
@@ -343,6 +351,79 @@ So a caller that group middleware refuses gets `FORBIDDEN` even when its input i
343
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.
344
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.
345
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
+ }),
383
+ ```
384
+
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).
426
+
346
427
  ### JSON values
347
428
 
348
429
  Inputs and results must be strict JSON. `Date`, `undefined`, `NaN` and `Infinity`, functions, class instances, sparse arrays and cycles are rejected, so convert them explicitly (for example, a date to an ISO string). Rendering and HTTP use the same encoding, so a value that works during SSR also works in the browser. Plain and readonly interfaces work as input and result types without index signatures, and keep their declared types on the client.
@@ -373,12 +454,12 @@ Each error needs an identifier code, an integer literal `status` from 400 to 599
373
454
 
374
455
  Launch itself uses four codes, which you can't declare:
375
456
 
376
- | Code | Status | When |
377
- | --------------- | ------ | ----------------------------------------------------------------------------------------------------------------- |
378
- | `INVALID_INPUT` | 400 | The request is malformed, or its input failed schema validation |
379
- | `FORBIDDEN` | 403 | `forbidden()` was thrown, the request wasn't proven same-origin, or a mutation was called during server rendering |
380
- | `RPC_NOT_FOUND` | 404 | No such procedure |
381
- | `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 |
382
463
 
383
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.
384
465
 
@@ -396,6 +477,132 @@ try {
396
477
  }
397
478
  ```
398
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
+
399
606
  ## Calling RPCs
400
607
 
401
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:
@@ -421,7 +628,7 @@ export default class Todos {
421
628
  }
422
629
  ```
423
630
 
424
- 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:
425
632
 
426
633
  ```ts
427
634
  await rpc.todos.list();
@@ -434,7 +641,7 @@ await rpc.todos.add({ title }, { signal });
434
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. |
435
642
  | `transferCache` | Queries default to `true`. Mutations only accept `false` and never use the transfer cache. |
436
643
 
437
- `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"`.
438
645
 
439
646
  Route resolvers can call RPCs too, which is how a page gets its data during SSR:
440
647
 
@@ -454,13 +661,155 @@ export default defineRoute("todos", {
454
661
 
455
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.
456
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
+
457
806
  ### With TanStack Query
458
807
 
459
- 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.5/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.
460
809
 
461
810
  ## Server rendering and hydration
462
811
 
463
- 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.5/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.
464
813
 
465
814
  The reuse has limits, all of them Angular's transfer cache behaving as designed:
466
815
 
@@ -468,14 +817,46 @@ The reuse has limits, all of them Angular's transfer cache behaving as designed:
468
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.
469
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.
470
819
 
471
- Mutations are refused during server rendering with `FORBIDDEN`, before any middleware, validation or the handler runs. 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.
472
824
 
473
- 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.
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).
474
826
 
475
- 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).
476
828
 
477
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`.
478
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
+
479
860
  ## Deploying
480
861
 
481
862
  With `outputMode: "server"`, `ng build` writes the browser files and a bundled server:
@@ -503,7 +884,43 @@ Launch calls `/_rpc/<namespace>/<procedure>` from the root of the domain, even w
503
884
 
504
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.
505
886
 
506
- Launch has been verified on Node, and with a platform-neutral server build (below) on Deno and Cloudflare's workerd, run locally.
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.
507
924
 
508
925
  ### Hosts
509
926
 
@@ -557,6 +974,7 @@ export const reqHandler = createRequestHandler(async (request: Request) => {
557
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.
558
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`.
559
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.
560
978
 
561
979
  ### Aborted requests
562
980
 
@@ -575,7 +993,7 @@ const native = createWebRequestFromNodeRequest(request);
575
993
  const web = new Request(native, { signal: AbortSignal.any([native.signal, closed.signal]) });
576
994
  ```
577
995
 
578
- Pass `web` to both `handleRequest` and `createContext`, so page renders get the same signal. Without this wiring everything works, but handlers never see an abort over HTTP.
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.
579
997
 
580
998
  ### Other server frameworks
581
999
 
@@ -623,7 +1041,7 @@ if (isMainModule(import.meta.url)) {
623
1041
  export const reqHandler = createRequestHandler(app.fetch);
624
1042
  ```
625
1043
 
626
- Export the handler as `reqHandler`; Angular's dev server and build don't look for a default export. 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.
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.
627
1045
 
628
1046
  ## Generation
629
1047
 
@@ -638,7 +1056,7 @@ generate(workspace: string, options: GenerationOptions, stopped?: () => boolean)
638
1056
  | `tsconfig` | `string` | Your app tsconfig, relative to `workspace` |
639
1057
  | `scanDirectories` | `string[]` | Exactly one route directory, relative to the tsconfig's directory |
640
1058
  | `outDirectory` | `string` | Where the app-wide generated files go, relative to `workspace` |
641
- | `tanstackQuery` | `boolean` | Also generate `injectQueries()`; see [TanStack Query](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.5/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) |
642
1060
  | `check` | `boolean` | Verify generated files without writing them; fails if anything is out of date |
643
1061
 
644
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.
@@ -649,7 +1067,7 @@ Generation reads your source without running it. It writes the router's files pl
649
1067
  | --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
650
1068
  | `rpc.generated.ts` beside each route | `injectRpc()` with the route's own and ancestor groups, plus `injectQueries()` with `tanstackQuery`; none for redirect routes |
651
1069
  | `<outDirectory>/context.generated.d.ts` | Registers your context type |
652
- | `<outDirectory>/server.generated.ts` | `createContext`, `handleRequest`, `provideServer`, the registry |
1070
+ | `<outDirectory>/server.generated.ts` | `createContext`, `handleRequest`, `handleUpgrade`, `provideServer`, the registry |
653
1071
 
654
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.
655
1073
 
@@ -657,7 +1075,7 @@ Before writing, generation type-checks the generated files, your route and RPC d
657
1075
 
658
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`.
659
1077
 
660
- `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.
661
1079
 
662
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.
663
1081
 
@@ -713,19 +1131,22 @@ The options are fixed when the session is created. Edits inside the app, includi
713
1131
 
714
1132
  ## Limitations
715
1133
 
716
- - 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.5/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.
717
1136
  - No storage adapters; persistence is your handler's job.
718
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.
719
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.
720
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.
721
1142
  - One RPC group per route, and one context per application.
722
1143
 
723
1144
  ## Further reading
724
1145
 
725
- - [TanStack Query](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.5/packages/angular-launch/tanstack-query/README.md): the optional query and mutation integration
726
- - [`specs/angular-launch.md`](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.5/specs/angular-launch.md): design and full contract
727
- - [`examples/angular-launch`](https://github.com/theo-matzavinos/loozo/tree/angular-launch@0.0.5/examples/angular-launch): the todos app. Its cookie identity and in-memory database are test fixtures, not security or deployment guidance.
728
- - [`@loozo/angular-router`](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.5/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
729
1150
 
730
1151
  ## Developing this package
731
1152