@loozo/angular-launch 0.0.4 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,20 +1,21 @@
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.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.
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, 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.
10
10
 
11
11
  ## Requirements
12
12
 
13
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.
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.5/packages/angular-launch/tanstack-query/README.md).
18
19
 
19
20
  Install both packages:
20
21
 
@@ -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.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
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:
99
+ `signedIn` is a [middleware](#middleware) that refuses calls without a user and narrows `context.user` for the handlers.
102
100
 
103
- ```js
104
- // generate.mjs
105
- import { generate } from "@loozo/angular-launch/generation";
106
-
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
 
@@ -171,7 +175,7 @@ export default async function bootstrap(context: BootstrapContext) {
171
175
  }
172
176
  ```
173
177
 
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:
178
+ 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
179
 
176
180
  ```ts
177
181
  // src/server.ts
@@ -187,15 +191,27 @@ import express from "express";
187
191
  import { createContext, handleRequest } from "../generated/server.generated";
188
192
 
189
193
  const browser = join(import.meta.dirname, "../browser");
190
- const angular = new AngularNodeAppEngine();
194
+ // An explicit list stops Angular reading NG_ALLOWED_HOSTS, so read it here.
195
+ const allowedHosts = (process.env["NG_ALLOWED_HOSTS"] ?? "localhost").split(",");
196
+ const angular = new AngularNodeAppEngine({ allowedHosts });
191
197
  const app = express();
192
198
 
193
199
  app.use(express.static(browser, { maxAge: "1y", index: false, redirect: false }));
194
200
 
195
201
  app.use(async (request, response, next) => {
196
202
  try {
197
- const web = createWebRequestFromNodeRequest(request);
198
- const rpc = await handleRequest(web);
203
+ // Angular's helper only aborts while the body is still arriving; abort on a closed response.
204
+ const closed = new AbortController();
205
+
206
+ response.once("close", () => {
207
+ if (!response.writableFinished) {
208
+ closed.abort();
209
+ }
210
+ });
211
+
212
+ const native = createWebRequestFromNodeRequest(request);
213
+ const web = new Request(native, { signal: AbortSignal.any([native.signal, closed.signal]) });
214
+ const rpc = await handleRequest(web, { allowedHosts });
199
215
 
200
216
  if (rpc) {
201
217
  await writeResponseToNodeResponse(rpc, response);
@@ -239,36 +255,93 @@ Always pass `scope.request` together with `scope`, not your original request. Th
239
255
 
240
256
  ## Defining RPCs
241
257
 
242
- `defineRpc(namespace, procedures, options?)` declares a group. Each procedure is a `query` (a read) or a `mutation` (a write):
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:
243
259
 
244
260
  ```ts
245
- query({ input?, canActivate?, errors?, handler });
246
- mutation({ input?, canActivate?, errors?, handler });
261
+ defineRpc(
262
+ "todos",
263
+ ({ query, mutation }) => ({
264
+ list: query({ input?, use?, errors?, handler }),
265
+ add: mutation({ input?, use?, errors?, handler }),
266
+ }),
267
+ { use? },
268
+ );
247
269
  ```
248
270
 
249
- The handler receives `{ context, input, errors }` and returns a value or a promise.
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).
250
272
 
251
273
  - **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`:
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.
275
+ - **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
+
277
+ 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.
278
+
279
+ ### Middleware
280
+
281
+ Middleware runs around a call to refuse it, add typed values to its context, or wrap the rest of it:
255
282
 
256
283
  ```ts
257
284
  // src/auth.server.ts
258
- import type { Context, Guard } from "@loozo/angular-launch/server";
285
+ import { forbidden, middleware } from "@loozo/angular-launch/server";
259
286
 
260
- export const isSignedIn: Guard = ({ context }) => context.user !== null;
261
-
262
- export function requireUser(context: Context): { id: string } {
287
+ export const signedIn = middleware(async ({ context, next }) => {
263
288
  if (context.user === null) {
264
- throw new Error("User required");
289
+ throw forbidden();
265
290
  }
266
291
 
267
- return context.user;
268
- }
292
+ return next({ user: context.user }); // later middleware and handlers see a non-null user
293
+ });
269
294
  ```
270
295
 
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.
296
+ 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:
297
+
298
+ 1. the group's middleware, with no input;
299
+ 2. input validation;
300
+ 3. the procedure's middleware, with the validated input;
301
+ 4. the handler.
302
+
303
+ So a caller that group middleware refuses gets `FORBIDDEN` even when its input is invalid, and can't probe your schemas.
304
+
305
+ - **`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`.
306
+ - **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:
307
+
308
+ ```ts
309
+ export const timing = middleware(async ({ next }) => {
310
+ const start = performance.now();
311
+
312
+ try {
313
+ return await next();
314
+ } finally {
315
+ console.log(`RPC took ${(performance.now() - start).toFixed(1)} ms`);
316
+ }
317
+ });
318
+ ```
319
+
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.
321
+ - **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
+
323
+ ```ts
324
+ export const ownTodo = middleware(
325
+ async ({ context, input, next }: MiddlewareArgs<{ user: User; db: Db }, { id: string }>) => {
326
+ const todo = await context.db.todos.findForUser(context.user.id, input.id);
327
+
328
+ if (todo === null) {
329
+ throw forbidden();
330
+ }
331
+
332
+ return next({ todo });
333
+ },
334
+ );
335
+ ```
336
+
337
+ 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.
338
+
339
+ - **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.
340
+ - There's no dedupe: middleware listed in both the group and a procedure runs twice. Middleware isn't inherited through the route tree.
341
+ - **Known limits:**
342
+ - 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.
343
+ - 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
+ - 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.
272
345
 
273
346
  ### JSON values
274
347
 
@@ -285,7 +358,7 @@ complete: mutation({
285
358
  NOT_FOUND: { status: 404, message: "Todo does not exist", data: idSchema },
286
359
  },
287
360
  handler: async ({ input, context, errors }) => {
288
- const todo = await context.db.todos.completeForUser(requireUser(context).id, input.id);
361
+ const todo = await context.db.todos.completeForUser(context.user.id, input.id);
289
362
 
290
363
  if (todo === null) {
291
364
  throw errors.NOT_FOUND({ id: input.id });
@@ -300,12 +373,12 @@ Each error needs an identifier code, an integer literal `status` from 400 to 599
300
373
 
301
374
  Launch itself uses four codes, which you can't declare:
302
375
 
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 |
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 |
309
382
 
310
383
  `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
384
 
@@ -356,10 +429,10 @@ await rpc.todos.list({ signal, transferCache: false });
356
429
  await rpc.todos.add({ title }, { signal });
357
430
  ```
358
431
 
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. |
432
+ | Option | Effect |
433
+ | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
434
+ | `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
+ | `transferCache` | Queries default to `true`. Mutations only accept `false` and never use the transfer cache. |
363
436
 
364
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"`.
365
438
 
@@ -383,11 +456,11 @@ export default defineRoute("todos", {
383
456
 
384
457
  ### With TanStack Query
385
458
 
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.
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.
387
460
 
388
461
  ## Server rendering and hydration
389
462
 
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.
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.
391
464
 
392
465
  The reuse has limits, all of them Angular's transfer cache behaving as designed:
393
466
 
@@ -395,7 +468,9 @@ The reuse has limits, all of them Angular's transfer cache behaving as designed:
395
468
  - 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
469
  - 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
470
 
398
- Mutations are refused during server rendering with `FORBIDDEN`, before validation, guards or the handler run. Rendering should only read.
471
+ Mutations are refused during server rendering with `FORBIDDEN`, before any middleware, validation or the handler runs. Rendering should only read.
472
+
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.
399
474
 
400
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.
401
476
 
@@ -417,24 +492,94 @@ Copy `dist/<app>` to the host and start the server with Node:
417
492
  PORT=8080 NG_ALLOWED_HOSTS=example.com node dist/<app>/server/server.mjs
418
493
  ```
419
494
 
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. |
495
+ The server bundle includes your dependencies by default, so the host doesn't need `node_modules`. The server reads two environment variables:
426
496
 
427
- The host check covers page rendering only. `handleRequest` runs before Angular and answers RPC requests for any host.
497
+ | Variable | Effect |
498
+ | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
499
+ | `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. |
500
+ | `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
501
 
429
502
  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
503
 
431
504
  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
505
 
433
- Launch has been verified on Node only.
506
+ Launch has been verified on Node, and with a platform-neutral server build (below) on Deno and Cloudflare's workerd, run locally.
507
+
508
+ ### Hosts
509
+
510
+ `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.
511
+
512
+ 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.
513
+
514
+ ### Cross-origin requests
515
+
516
+ `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:
517
+
518
+ 1. An `Origin` listed in `origins` passes.
519
+ 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.
520
+ 3. Otherwise, if it has `Origin`, that must equal the request URL's origin.
521
+ 4. A request with neither header is refused. There's no `Referer` fallback and no opt-out.
522
+
523
+ 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:
524
+
525
+ ```ts
526
+ const rpc = await handleRequest(web, { allowedHosts, origins: ["https://app.example.com"] });
527
+ ```
528
+
529
+ 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.
530
+
531
+ ### Other runtimes
532
+
533
+ `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:
534
+
535
+ ```ts
536
+ // src/server.ts
537
+ import { AngularAppEngine, createRequestHandler } from "@angular/ssr";
538
+ import { createContext, handleRequest } from "../generated/server.generated";
539
+
540
+ const allowedHosts = ["app.example.com"];
541
+ const angular = new AngularAppEngine({ allowedHosts });
542
+
543
+ export const reqHandler = createRequestHandler(async (request: Request) => {
544
+ const rpc = await handleRequest(request, { allowedHosts });
545
+
546
+ if (rpc) {
547
+ return rpc;
548
+ }
549
+
550
+ const scope = await createContext(request);
551
+ const page = await angular.handle(scope.request, scope);
552
+
553
+ return page ?? new Response("Not found", { status: 404 });
554
+ });
555
+ ```
556
+
557
+ - 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
+ - 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
+ - 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.
560
+
561
+ ### Aborted requests
562
+
563
+ 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:
564
+
565
+ ```ts
566
+ const closed = new AbortController();
567
+
568
+ response.once("close", () => {
569
+ if (!response.writableFinished) {
570
+ closed.abort();
571
+ }
572
+ });
573
+
574
+ const native = createWebRequestFromNodeRequest(request);
575
+ const web = new Request(native, { signal: AbortSignal.any([native.signal, closed.signal]) });
576
+ ```
577
+
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.
434
579
 
435
580
  ### Other server frameworks
436
581
 
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:
582
+ `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
583
 
439
584
  ```ts
440
585
  // src/server.ts
@@ -447,13 +592,15 @@ import { Hono } from "hono";
447
592
  import { createContext, handleRequest } from "../generated/server.generated";
448
593
 
449
594
  const browser = fileURLToPath(new URL("../browser", import.meta.url));
450
- const angular = new AngularNodeAppEngine();
595
+ // An explicit list stops Angular reading NG_ALLOWED_HOSTS, so read it here.
596
+ const allowedHosts = (process.env["NG_ALLOWED_HOSTS"] ?? "localhost").split(",");
597
+ const angular = new AngularNodeAppEngine({ allowedHosts });
451
598
  const app = new Hono();
452
599
 
453
600
  app.use("*", serveStatic({ root: browser }));
454
601
 
455
602
  app.all("*", async (c) => {
456
- const rpc = await handleRequest(c.req.raw);
603
+ const rpc = await handleRequest(c.req.raw, { allowedHosts });
457
604
 
458
605
  if (rpc) {
459
606
  return rpc;
@@ -476,10 +623,12 @@ if (isMainModule(import.meta.url)) {
476
623
  export const reqHandler = createRequestHandler(app.fetch);
477
624
  ```
478
625
 
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.
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.
480
627
 
481
628
  ## Generation
482
629
 
630
+ The [builders](#builders) run generation for you. Underneath, it's a Node function you can also call from your own tools:
631
+
483
632
  ```ts
484
633
  generate(workspace: string, options: GenerationOptions, stopped?: () => boolean): Promise<void>;
485
634
  ```
@@ -489,7 +638,7 @@ generate(workspace: string, options: GenerationOptions, stopped?: () => boolean)
489
638
  | `tsconfig` | `string` | Your app tsconfig, relative to `workspace` |
490
639
  | `scanDirectories` | `string[]` | Exactly one route directory, relative to the tsconfig's directory |
491
640
  | `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) |
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) |
493
642
  | `check` | `boolean` | Verify generated files without writing them; fails if anything is out of date |
494
643
 
495
644
  `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.
@@ -510,10 +659,33 @@ Generated browser code contains only names, kinds and error metadata, never your
510
659
 
511
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.
512
661
 
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.
662
+ 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
663
 
515
664
  `@loozo/angular-launch/generation` is Node-only.
516
665
 
666
+ ### Builders
667
+
668
+ #### `@loozo/angular-launch:application`
669
+
670
+ 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.
671
+
672
+ 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.
673
+
674
+ #### `@loozo/angular-launch:serve`
675
+
676
+ All `@angular/build:dev-server` options, set in `angular.json` or on the command line (`ng serve --port 4300`), plus:
677
+
678
+ | Option | Type | Default | Description |
679
+ | ------------- | ----------------- | -------- | ---------------------------------------------------------------------------------------- |
680
+ | `buildTarget` | `string` | required | A target that uses `@loozo/angular-launch:application`. Generation options come from it. |
681
+ | `poll` | `number \| false` | `1000` | The dev server's file-watch polling interval in milliseconds, or `false` for no default. |
682
+
683
+ 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.
684
+
685
+ 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.
686
+
687
+ 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.
688
+
517
689
  ### Generation sessions
518
690
 
519
691
  `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 +713,27 @@ The options are fixed when the session is created. Edits inside the app, includi
541
713
 
542
714
  ## Limitations
543
715
 
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.
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.
546
717
  - 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.
718
+ - 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.
719
+ - 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
+ - Middleware is server-side only: there's no client middleware (use an Angular HTTP interceptor), and no dedupe of middleware listed twice.
549
721
  - One RPC group per route, and one context per application.
550
722
 
551
723
  ## Further reading
552
724
 
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
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
557
729
 
558
730
  ## Developing this package
559
731
 
560
732
  ```sh
561
- pnpm run build # tsc
733
+ pnpm run build # builder schemas, then tsc
562
734
  pnpm run typecheck
563
735
  pnpm run test # node --test
564
736
  node tests/packed.mjs /absolute/new-directory # packed consumer check; directory must not exist
565
737
  ```
566
738
 
567
- The packed check keeps its consumer, pnpm store and temporary files inside the directory you pass.
739
+ 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.
@@ -0,0 +1,4 @@
1
+ import { type Builder } from "@angular-devkit/architect";
2
+ import { type JsonObject } from "./options.js";
3
+ declare const builder: Builder<JsonObject>;
4
+ export default builder;