@loozo/angular-launch 0.0.6 → 0.1.0
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 +715 -255
- package/builders/application.js +32 -3
- package/builders/channel-forwarding.d.ts +15 -0
- package/builders/channel-forwarding.js +61 -0
- package/builders/options.d.ts +6 -2
- package/builders/options.js +16 -5
- package/builders/serve.js +198 -140
- package/channel.d.ts +3 -1
- package/channel.js +3 -2
- package/client.d.ts +14 -24
- package/generation/index.d.ts +2 -123
- package/generation/index.js +3 -685
- package/generation/redirects.d.ts +14 -0
- package/generation/redirects.js +43 -0
- package/generation/run.d.ts +168 -0
- package/generation/run.js +659 -0
- package/index.d.ts +2 -0
- package/index.js +1 -0
- package/launch-queries.d.ts +16 -0
- package/launch-queries.js +3 -0
- package/navigation.d.ts +3 -3
- package/navigation.js +1 -1
- package/node/index.d.ts +3 -0
- package/node/index.js +6 -3
- package/node/upgrade-listener-slot.d.ts +1 -0
- package/node/upgrade-listener-slot.js +4 -0
- package/outcomes.d.ts +23 -7
- package/outcomes.js +58 -12
- package/package.json +15 -11
- package/redirect-translation.d.ts +53 -0
- package/redirect-translation.js +141 -0
- package/{generated.js → remote-client.js} +27 -21
- package/route-types.d.ts +130 -0
- package/route-types.js +1 -0
- package/route.d.ts +45 -0
- package/route.js +113 -0
- package/schemas/application.json +19 -3
- package/schemas/serve.json +3 -3
- package/server/application.d.ts +107 -0
- package/server/application.js +108 -0
- package/server/backend.d.ts +25 -13
- package/server/backend.js +39 -24
- package/server/channel-messages.d.ts +1 -1
- package/server/channel-messages.js +1 -1
- package/server/channel-socket.d.ts +1 -1
- package/server/definitions.d.ts +146 -298
- package/server/definitions.js +29 -117
- package/server/dispatch.d.ts +67 -63
- package/server/dispatch.js +121 -61
- package/server/event-stream.d.ts +2 -2
- package/server/event-stream.js +1 -1
- package/server/generated.d.ts +2 -1
- package/server/generated.js +2 -1
- package/server/index.d.ts +3 -2
- package/server/index.js +2 -1
- package/server/outcomes.d.ts +26 -13
- package/server/outcomes.js +43 -16
- package/server/read-cookies.d.ts +19 -0
- package/server/read-cookies.js +39 -0
- package/server/response-effects.d.ts +2 -2
- package/server/stages.d.ts +62 -0
- package/server/stages.js +51 -0
- package/server/upgrade.d.ts +11 -12
- package/server/upgrade.js +13 -14
- package/source-text.d.ts +1 -0
- package/source-text.js +56 -0
- package/stream.d.ts +6 -3
- package/stream.js +8 -6
- package/tanstack-query/README.md +15 -15
- package/tanstack-query/create-queries.d.ts +2 -0
- package/tanstack-query/{generated.js → create-queries.js} +8 -9
- package/tanstack-query/hydration-window.d.ts +11 -0
- package/tanstack-query/hydration-window.js +9 -0
- package/tanstack-query/hydration.d.ts +4 -14
- package/tanstack-query/hydration.js +9 -12
- package/tanstack-query/index.d.ts +1 -1
- package/tanstack-query/queries.d.ts +42 -27
- package/testing/call-procedure.d.ts +154 -0
- package/testing/call-procedure.js +97 -0
- package/testing/index.d.ts +2 -0
- package/testing/index.js +1 -0
- package/generation/context-file.d.ts +0 -2
- package/generation/context-file.js +0 -3
- package/tanstack-query/generated.d.ts +0 -5
- /package/{generated.d.ts → remote-client.d.ts} +0 -0
package/README.md
CHANGED
|
@@ -1,102 +1,116 @@
|
|
|
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
|
|
3
|
+
Typed server functions for Angular applications built with [`@loozo/angular-router`](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-router/README.md). A route declares its server behavior on its own `route.ts`: a context stage, middleware and queries, mutations, streams and channels. The route's pages and resolvers call them through a fully typed client on the route's handle.
|
|
4
4
|
|
|
5
|
-
Calls go through Angular's `HttpClient`. In the browser they're ordinary HTTP requests. During server rendering they run in-process
|
|
5
|
+
Calls go through Angular's `HttpClient`. In the browser they're ordinary HTTP requests. During server rendering they run in-process in the current request's scope, 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, streams (over server-sent events), channels (over websockets, on
|
|
9
|
+
**Status:** experimental. MIT license. It currently covers queries, mutations, streams (over server-sent events), channels (over websockets, on Node), middleware, declared errors and redirect and not-found outcomes, with optional [TanStack Query](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/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`, `@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.
|
|
14
|
-
- `@angular/build` `~22.
|
|
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.3.0.
|
|
14
|
+
- `@angular/build` `~22.3.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.1.0/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
|
|
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.1.0/packages/angular-launch/tanstack-query/README.md), and `@angular/localize` for [translated URLs](#translated-urls).
|
|
19
19
|
|
|
20
20
|
Install both packages:
|
|
21
21
|
|
|
22
22
|
```sh
|
|
23
|
-
pnpm add @loozo/angular-launch @loozo/angular-router@0.0
|
|
23
|
+
pnpm add @loozo/angular-launch @loozo/angular-router@0.1.0
|
|
24
24
|
```
|
|
25
25
|
|
|
26
26
|
## How it fits together
|
|
27
27
|
|
|
28
28
|
```text
|
|
29
29
|
src/
|
|
30
|
-
├── context.ts defineContext: per-request server context
|
|
31
30
|
└── routes/
|
|
32
|
-
├── route.ts defineRoute("")
|
|
31
|
+
├── route.ts defineRoute("").context(…): the per-request context
|
|
33
32
|
└── +authenticated/
|
|
34
|
-
├── route.ts pathless route
|
|
35
|
-
├── rpc.ts defineRpc("session", …)
|
|
33
|
+
├── route.ts a pathless route: .context(signedIn).remote(… session …)
|
|
36
34
|
└── todos/
|
|
37
|
-
├── route.ts defineRoute("todos")
|
|
38
|
-
├──
|
|
39
|
-
├──
|
|
40
|
-
|
|
41
|
-
└── rpc.generated.ts generated: injectRpc() with session and todos
|
|
35
|
+
├── route.ts defineRoute("todos").remote(… todos …).resolve(…)
|
|
36
|
+
├── page.ts injectRoute().remote.todos.list()
|
|
37
|
+
├── destination.generated.ts generated by the router: URL facts for links and createUrl
|
|
38
|
+
└── route.generated.ts generated: the browser copy, Remote and Context, injectRoute()
|
|
42
39
|
generated/
|
|
43
|
-
├── routes.generated.ts router: routes for provideRouter
|
|
44
|
-
|
|
45
|
-
├── context.generated.d.ts registers your context type
|
|
46
|
-
└── server.generated.ts createContext, handleRequest, handleUpgrade, provideServer
|
|
40
|
+
├── routes.generated.ts router: routes for provideRouter, injectActiveRoute()
|
|
41
|
+
└── server.generated.ts createRequestScope, handleRequest, handleUpgrade, provideServer
|
|
47
42
|
```
|
|
48
43
|
|
|
49
|
-
|
|
44
|
+
Import `defineRoute` from `@loozo/angular-launch` instead of the router in every `route.ts`. It's the router's `defineRoute` with three more steps offered first, `.context()`, `.use()` and `.remote()`, each at most once and in that order, before the router's own steps. All three run only on the server: the router writes each route's browser copy, `route.generated.ts`, without them, and Launch adds the route's procedure metadata, its `Remote` and `Context` types and `remote` on its `injectRoute()` handle. `server.generated.ts` imports the routes themselves, so the server runs the steps.
|
|
50
45
|
|
|
51
|
-
|
|
46
|
+
A route sees its own namespaces and its ancestors'. App code, server code included, imports a route's `destination` or its `route.generated.ts`, never its `route.ts`.
|
|
52
47
|
|
|
53
48
|
## Setup
|
|
54
49
|
|
|
55
|
-
The [todos example](https://github.com/theo-matzavinos/loozo/tree/angular-launch@0.0
|
|
50
|
+
The [todos example](https://github.com/theo-matzavinos/loozo/tree/angular-launch@0.1.0/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
51
|
|
|
57
|
-
### 1.
|
|
52
|
+
### 1. Declare the context on the root route
|
|
58
53
|
|
|
59
|
-
|
|
54
|
+
The root route's `.context()` stage builds the context every procedure below it starts from:
|
|
60
55
|
|
|
61
56
|
```ts
|
|
62
|
-
// src/
|
|
63
|
-
import {
|
|
64
|
-
import { db } from "
|
|
65
|
-
import { sessions } from "
|
|
57
|
+
// src/routes/route.ts
|
|
58
|
+
import { defineRoute } from "@loozo/angular-launch";
|
|
59
|
+
import { db } from "../database.server";
|
|
60
|
+
import { sessions } from "../sessions.server";
|
|
66
61
|
|
|
67
|
-
export default
|
|
68
|
-
request,
|
|
62
|
+
export default defineRoute("", {}).context(async ({ request }) => ({
|
|
69
63
|
db,
|
|
70
64
|
user: await sessions.authenticate(request),
|
|
71
65
|
}));
|
|
72
66
|
```
|
|
73
67
|
|
|
74
|
-
|
|
68
|
+
A stage runs at most once per request scope, and only when a call needs it: a page render that makes no RPC runs none. Keep per-request state in the context rather than in module-level variables.
|
|
75
69
|
|
|
76
|
-
### 2.
|
|
70
|
+
### 2. Declare procedures on a route
|
|
77
71
|
|
|
78
72
|
```ts
|
|
79
|
-
// src/routes/+authenticated/
|
|
80
|
-
import {
|
|
81
|
-
import {
|
|
73
|
+
// src/routes/+authenticated/route.ts
|
|
74
|
+
import { defineRoute } from "@loozo/angular-launch";
|
|
75
|
+
import { redirect } from "@loozo/angular-launch/server";
|
|
76
|
+
import { destination as signIn } from "../sign-in/destination.generated";
|
|
77
|
+
import parent from "../route";
|
|
78
|
+
|
|
79
|
+
export default defineRoute("", { parent })
|
|
80
|
+
.context(({ context }) => {
|
|
81
|
+
if (context.user === null) {
|
|
82
|
+
throw redirect(signIn, {});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
return { ...context, user: context.user }; // `User | null` above, `User` below
|
|
86
|
+
})
|
|
87
|
+
.remote(({ query }) => ({
|
|
88
|
+
session: { current: query({ handler: ({ context }) => ({ user: context.user.id }) }) },
|
|
89
|
+
}));
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
// src/routes/+authenticated/todos/route.ts
|
|
94
|
+
import { defineRoute } from "@loozo/angular-launch";
|
|
82
95
|
import { idSchema, titleSchema } from "../../../todo-input.server";
|
|
96
|
+
import parent from "../route";
|
|
83
97
|
|
|
84
|
-
export default
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
);
|
|
98
|
+
export default defineRoute("todos", { parent })
|
|
99
|
+
.remote(({ query, mutation }) => ({
|
|
100
|
+
todos: {
|
|
101
|
+
list: query({
|
|
102
|
+
handler: ({ context }) => context.db.todos.listForUser(context.user.id),
|
|
103
|
+
}),
|
|
104
|
+
add: mutation({
|
|
105
|
+
input: titleSchema,
|
|
106
|
+
handler: ({ input, context }) => context.db.todos.addForUser(context.user.id, input.title),
|
|
107
|
+
}),
|
|
108
|
+
},
|
|
109
|
+
}))
|
|
110
|
+
.resolve({ todos: ({ remote }) => remote.todos.list() });
|
|
97
111
|
```
|
|
98
112
|
|
|
99
|
-
`
|
|
113
|
+
The `+authenticated` stage narrows `context.user` for every procedure at or below it, and its redirect refuses them for a signed-out caller. The `todos` route's resolver calls its own procedure through `remote`; see [Calling RPCs](#calling-rpcs).
|
|
100
114
|
|
|
101
115
|
### 3. Generate
|
|
102
116
|
|
|
@@ -125,7 +139,7 @@ Generation runs inside two Angular builders that replace your project's `build`
|
|
|
125
139
|
|
|
126
140
|
`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
141
|
|
|
128
|
-
Include the generated files
|
|
142
|
+
Include the generated files in your app tsconfig: `"include": ["src/**/*.ts", "generated/**/*.ts"]`. See [Builders](#builders) for the builder options and [Generation](#generation) for what gets written.
|
|
129
143
|
|
|
130
144
|
### 4. Wire the browser and server apps
|
|
131
145
|
|
|
@@ -144,7 +158,7 @@ export const config: ApplicationConfig = {
|
|
|
144
158
|
};
|
|
145
159
|
```
|
|
146
160
|
|
|
147
|
-
To have pages follow a procedure's [`redirect()` and `notFound()`](#redirects-and-not-found), add [`rpcNavigationErrors`](#navigating-on-outcomes) to `provideRouter`.
|
|
161
|
+
To have pages follow a procedure's [`redirect()` and `notFound()`](#redirects-and-not-found), add [`rpcNavigationErrors`](#navigating-on-outcomes) to `provideRouter`. With [translated URLs](#translated-urls), add `provideRedirectTranslation()` here too.
|
|
148
162
|
|
|
149
163
|
The server config adds the generated `provideServer()`, after `provideHttpClient()`:
|
|
150
164
|
|
|
@@ -177,7 +191,7 @@ export default async function bootstrap(context: BootstrapContext) {
|
|
|
177
191
|
}
|
|
178
192
|
```
|
|
179
193
|
|
|
180
|
-
In the server entry, let `handleRequest` answer RPC requests (it returns `null` for anything else), and render pages with a request scope from `
|
|
194
|
+
In the server entry, let `handleRequest` answer RPC requests (it returns `null` for anything else), and render pages with a request scope from `createRequestScope`. 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:
|
|
181
195
|
|
|
182
196
|
```ts
|
|
183
197
|
// src/server.ts
|
|
@@ -191,7 +205,7 @@ import {
|
|
|
191
205
|
} from "@angular/ssr/node";
|
|
192
206
|
import { createUpgradeHandler } from "@loozo/angular-launch/node";
|
|
193
207
|
import express from "express";
|
|
194
|
-
import {
|
|
208
|
+
import { createRequestScope, handleRequest, handleUpgrade } from "../generated/server.generated";
|
|
195
209
|
|
|
196
210
|
const browser = join(import.meta.dirname, "../browser");
|
|
197
211
|
// An explicit list stops Angular reading NG_ALLOWED_HOSTS, so read it here.
|
|
@@ -208,7 +222,8 @@ app.use(async (request, response, next) => {
|
|
|
208
222
|
|
|
209
223
|
response.once("close", () => {
|
|
210
224
|
if (!response.writableFinished) {
|
|
211
|
-
|
|
225
|
+
// Once Angular's helper has cancelled a body it was writing.
|
|
226
|
+
queueMicrotask(() => closed.abort());
|
|
212
227
|
}
|
|
213
228
|
});
|
|
214
229
|
|
|
@@ -222,7 +237,7 @@ app.use(async (request, response, next) => {
|
|
|
222
237
|
return;
|
|
223
238
|
}
|
|
224
239
|
|
|
225
|
-
const scope =
|
|
240
|
+
const scope = createRequestScope(web); // runs nothing until an RPC needs a stage
|
|
226
241
|
const page = await angular.handle(scope.request, scope);
|
|
227
242
|
|
|
228
243
|
if (!page) {
|
|
@@ -233,6 +248,11 @@ app.use(async (request, response, next) => {
|
|
|
233
248
|
|
|
234
249
|
await writeResponseToNodeResponse(page, response);
|
|
235
250
|
} catch (error) {
|
|
251
|
+
// Angular rejects a render whose client left; there's no one to answer.
|
|
252
|
+
if (response.destroyed && error instanceof DOMException && error.name === "AbortError") {
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
|
|
236
256
|
next(error);
|
|
237
257
|
}
|
|
238
258
|
});
|
|
@@ -256,104 +276,139 @@ if (isMainModule(import.meta.url)) {
|
|
|
256
276
|
export const reqHandler = createNodeRequestHandler(app);
|
|
257
277
|
```
|
|
258
278
|
|
|
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);
|
|
279
|
+
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); `ng serve` uses it too. See [Channels on Node](#channels-on-node).
|
|
260
280
|
|
|
261
|
-
|
|
281
|
+
Import `server.generated` before any module that reaches a route, as above: with [translated URLs](#translated-urls) that order is required.
|
|
262
282
|
|
|
263
|
-
|
|
283
|
+
Always pass `scope.request` together with `scope`, not your original request. The scope ties the render's stages 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.
|
|
264
284
|
|
|
265
|
-
|
|
285
|
+
## Declaring server behavior on routes
|
|
286
|
+
|
|
287
|
+
A route's server steps come before its router steps, each at most once, in this order:
|
|
266
288
|
|
|
267
289
|
```ts
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
(
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
290
|
+
defineRoute("todos", { parent })
|
|
291
|
+
.context(stage) // derive this route's context from its ancestors'
|
|
292
|
+
.use(...middleware) // wrap this route's own procedures
|
|
293
|
+
.remote(({ query, mutation, stream, channel }) => ({
|
|
294
|
+
todos: {
|
|
295
|
+
list: query({ input?, use?, errors?, handler }),
|
|
296
|
+
add: mutation({ input?, use?, errors?, handler }),
|
|
297
|
+
watch: stream({ input?, use?, errors?, handler }),
|
|
298
|
+
},
|
|
299
|
+
}))
|
|
300
|
+
.resolve({ … }); // router steps follow, typed with `remote`
|
|
277
301
|
```
|
|
278
302
|
|
|
279
|
-
|
|
303
|
+
### Context stages
|
|
304
|
+
|
|
305
|
+
`.context(stage)` derives a route's context. The stage receives `{ context, request, response, signal }`: the context of the stages above it (`{}` at the first), the request scope's request and signal, and the [cookies and headers](#cookies-and-headers) of the call that first needs it. It returns the route's whole context, an object or a promise of one, which the stages and procedures below receive as it is, type included. To add to the context above, spread it: `({ context }) => ({ ...context, user })`.
|
|
306
|
+
|
|
307
|
+
- **When it runs:** at most once per request scope, and only for an RPC call whose namespace sits at or below it. A call runs the stages from the root down to the route that declared its namespace; a page render that makes no RPC runs none. Its result, failures included, is reused by every later call in the scope, such as every call in one server render.
|
|
308
|
+
- **Refusing:** a stage can `throw forbidden()`, `notFound()` or `redirect(destination, values)`, which answers every call that needs it with that [outcome](#redirects-and-not-found): a signed-out stage on a pathless route refuses its whole subtree. Any other exception fails those calls with `INTERNAL`, logged with the route whose stage threw.
|
|
309
|
+
- **Its value** can be any object type: a union, an object with optional keys or a class instance, which keeps its methods. A key above that the stage doesn't return is gone below it, and so is its type.
|
|
310
|
+
- **Standalone stages** type their argument with `StageArgs` from `@loozo/angular-launch/server` and the context they receive, such as the parent route's `Context` from its `route.generated.ts`:
|
|
311
|
+
|
|
312
|
+
```ts
|
|
313
|
+
// src/auth.server.ts
|
|
314
|
+
import { redirect, type StageArgs } from "@loozo/angular-launch/server";
|
|
315
|
+
import type { Context } from "./routes/route.generated";
|
|
316
|
+
import { destination as signIn } from "./routes/sign-in/destination.generated";
|
|
317
|
+
|
|
318
|
+
export function signedIn({ context }: StageArgs<Context>) {
|
|
319
|
+
if (context.user === null) {
|
|
320
|
+
throw redirect(signIn, {});
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
return { ...context, user: context.user };
|
|
324
|
+
}
|
|
325
|
+
```
|
|
326
|
+
|
|
327
|
+
A stage function shared by two routes still runs once per route.
|
|
328
|
+
|
|
329
|
+
### Procedures
|
|
330
|
+
|
|
331
|
+
`.remote(build)` declares the route's procedures in namespaces. `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. The route and its descendants call them as `route.remote.<namespace>.<procedure>`.
|
|
332
|
+
|
|
333
|
+
The handler receives `{ context, input, errors, request, signal, response }` and returns a value or a promise; a [stream's](#streams) returns an async iterable. `context` is what the stages from the root to this route built. 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).
|
|
280
334
|
|
|
281
|
-
- **Namespaces and procedure names** are literal ASCII identifiers. `__proto__` is not allowed; `constructor` and `toString` are fine.
|
|
282
|
-
- **The callback** is read without running it: an arrow function that destructures any of `query`, `mutation` and `
|
|
335
|
+
- **Namespaces and procedure names** are literal ASCII identifiers. `__proto__` is not allowed; `constructor` and `toString` are fine. A route may declare several namespaces, and each is unique across the app because it names the procedures' URLs.
|
|
336
|
+
- **The callback** is read without running it: an arrow function that destructures any of `query`, `mutation`, `stream` and `channel` without renaming, returning a parenthesized object literal of namespaces, each an object literal in which each procedure is a direct builder call with inline options.
|
|
283
337
|
- **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.
|
|
338
|
+
- **A namespace belongs to the route that declares it.** A call runs that route's stages and `.use()` middleware, whichever page called it: the session namespace above runs the root and `+authenticated` stages even when `todos` calls it.
|
|
284
339
|
|
|
285
|
-
Availability isn't authorization: anyone who can reach your server can call any procedure, so protect every
|
|
340
|
+
Availability isn't authorization: anyone who can reach your server can call any procedure, so protect every route and procedure that needs it with a stage or middleware. Route params aren't passed to procedures automatically; pass what you need as input and validate it.
|
|
286
341
|
|
|
287
342
|
### Middleware
|
|
288
343
|
|
|
289
|
-
Middleware runs around a call to refuse it
|
|
344
|
+
Middleware runs around a call to refuse it or wrap the rest of it:
|
|
290
345
|
|
|
291
346
|
```ts
|
|
292
|
-
// src/
|
|
293
|
-
import {
|
|
347
|
+
// src/timing.server.ts
|
|
348
|
+
import { middleware } from "@loozo/angular-launch/server";
|
|
294
349
|
|
|
295
|
-
export const
|
|
296
|
-
|
|
297
|
-
|
|
350
|
+
export const timing = middleware(async ({ next, response }) => {
|
|
351
|
+
const start = performance.now();
|
|
352
|
+
|
|
353
|
+
try {
|
|
354
|
+
return await next();
|
|
355
|
+
} finally {
|
|
356
|
+
response.headers.append("server-timing", `rpc;dur=${(performance.now() - start).toFixed(1)}`);
|
|
298
357
|
}
|
|
358
|
+
});
|
|
359
|
+
```
|
|
299
360
|
|
|
300
|
-
|
|
361
|
+
List middleware in a route's `.use()` to run it for that route's own procedures, or in a procedure's `use` to run it for that procedure. Middleware used in one place can be a bare async function written in the list, which receives the route's context, and on a procedure the validated input, already typed:
|
|
362
|
+
|
|
363
|
+
```ts
|
|
364
|
+
defineRoute("todos", { parent }).use(async ({ context, next }) => {
|
|
365
|
+
log(context.user.id); // the stages' User
|
|
366
|
+
|
|
367
|
+
return next();
|
|
301
368
|
});
|
|
302
369
|
```
|
|
303
370
|
|
|
304
|
-
|
|
371
|
+
A call runs, in order:
|
|
305
372
|
|
|
306
|
-
1. the
|
|
307
|
-
2. input
|
|
308
|
-
3.
|
|
309
|
-
4. the
|
|
373
|
+
1. the stages from the root to the route that declared the namespace;
|
|
374
|
+
2. that route's `.use()` middleware, with no input;
|
|
375
|
+
3. input validation;
|
|
376
|
+
4. the procedure's middleware, with the validated input;
|
|
377
|
+
5. the handler.
|
|
310
378
|
|
|
311
|
-
So a caller that
|
|
379
|
+
So a caller that a stage or the route's middleware refuses gets that answer even when its input is invalid, and can't probe your schemas.
|
|
312
380
|
|
|
313
|
-
- **`next()`** continues the call
|
|
314
|
-
- **Wrapping:** `next()` rejects when anything after it throws, declared errors included, so a middleware can time, log or run the rest of the call in a transaction that rolls back
|
|
381
|
+
- **`next()`** continues the call and resolves to the result the middleware must return. Middleware doesn't change the context: derive values in a [stage](#context-stages). A middleware must call `next` exactly once and return its result; calling it twice or returning anything else fails the call with `INTERNAL`.
|
|
382
|
+
- **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.
|
|
383
|
+
- **Refusing:** `throw forbidden()` fails the call with `FORBIDDEN`, and `throw notFound()` or `throw redirect(destination, values)` 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.
|
|
384
|
+
- **Needs:** a `middleware()` needs nothing unless you say so, so it fits anywhere. Pass the context it reads as a type argument, or annotate its argument with `MiddlewareArgs<Needs, Input>` to require an input shape too. Written inline, `middleware(…)` doesn't pick up the route's context type either, so write inline middleware as a bare function and keep `middleware()` for middleware you share.
|
|
315
385
|
|
|
316
386
|
```ts
|
|
317
|
-
export const
|
|
318
|
-
|
|
387
|
+
export const audit = middleware<{ user: User }>(async ({ context, next }) => {
|
|
388
|
+
log(context.user.id);
|
|
319
389
|
|
|
320
|
-
|
|
321
|
-
return await next();
|
|
322
|
-
} finally {
|
|
323
|
-
console.log(`RPC took ${(performance.now() - start).toFixed(1)} ms`);
|
|
324
|
-
}
|
|
390
|
+
return next();
|
|
325
391
|
});
|
|
326
|
-
```
|
|
327
|
-
|
|
328
|
-
- **Refusing:** `throw forbidden()` fails the call with `FORBIDDEN`, and `throw notFound()` or `throw redirect(to)` answer it with that [outcome](#redirects-and-not-found); a handler can throw them too. Any other exception fails the call with `INTERNAL`. Declared errors belong to handlers.
|
|
329
|
-
- **Needs:** a middleware without an annotation needs your `Context` and accepts any input, so it fits anywhere. Annotate its argument with `MiddlewareArgs<Needs, Input>` to require values that earlier middleware adds, or an input shape:
|
|
330
392
|
|
|
331
|
-
```ts
|
|
332
393
|
export const ownTodo = middleware(
|
|
333
394
|
async ({ context, input, next }: MiddlewareArgs<{ user: User; db: Db }, { id: string }>) => {
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
if (todo === null) {
|
|
395
|
+
if ((await context.db.todos.findForUser(context.user.id, input.id)) === null) {
|
|
337
396
|
throw forbidden();
|
|
338
397
|
}
|
|
339
398
|
|
|
340
|
-
return next(
|
|
399
|
+
return next();
|
|
341
400
|
},
|
|
342
401
|
);
|
|
343
402
|
```
|
|
344
403
|
|
|
345
|
-
Each
|
|
404
|
+
Each entry must accept the route's context, its own stage included, and the input; the error lands on the entry that doesn't, including a bare function whose annotated argument asks for more. A route's `.use()` gets no input, so a middleware that needs input only fits on a procedure.
|
|
346
405
|
|
|
347
|
-
- **Server rendering:** middleware
|
|
348
|
-
- There's no dedupe: middleware listed in both
|
|
349
|
-
- **Known limits:**
|
|
350
|
-
- Casting an addition to `object` or `{}`, or deliberately widening a middleware's result type, hides the keys it adds, so the context type no longer matches what runs.
|
|
351
|
-
- Only the top level of the context is read-only. Writing to a nested object, such as `context.session.user = null`, can still invalidate a narrowing nested inside it.
|
|
352
|
-
- Separate `next({ user: null })` and `next({ user: context.user })` calls don't infer `User | null` when `context.user` is a `User`; write the single-call form above.
|
|
406
|
+
- **Server rendering:** stages and middleware run 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.
|
|
407
|
+
- `.use()` isn't inherited through the route tree: a child route's procedures don't run it. There's no dedupe: middleware listed in both `.use()` and a procedure runs twice.
|
|
353
408
|
|
|
354
409
|
### Cookies and headers
|
|
355
410
|
|
|
356
|
-
|
|
411
|
+
Stages, middleware and handlers set cookies and headers through `response`:
|
|
357
412
|
|
|
358
413
|
```ts
|
|
359
414
|
login: mutation({
|
|
@@ -386,43 +441,47 @@ logout: mutation({
|
|
|
386
441
|
- **`response.deleteCookie(name, options?)`** expires a cookie. Pass the `path`, `domain` and security options it was set with, or the browser keeps it.
|
|
387
442
|
- **`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
443
|
- **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
|
|
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
|
|
444
|
+
- **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 shares the render's request scope, whose stages read the page request's cookies, so a cookie one call sets isn't visible to later calls. 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.
|
|
445
|
+
- **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 such as `timing` above can add a header after `await next()` for queries and mutations, and it's ignored for streams.
|
|
446
|
+
- **A stage's cookies** go to the call that ran it, once per scope: the first call that needs the stage carries them, and later calls reuse the stage's result without setting them again.
|
|
391
447
|
|
|
392
|
-
|
|
393
|
-
export const timing = middleware(async ({ next, response }) => {
|
|
394
|
-
const start = performance.now();
|
|
448
|
+
A stage can refresh a session cookie. It runs once per request scope, so the refresh runs once per page render or RPC request, however many calls need it:
|
|
395
449
|
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
}
|
|
401
|
-
});
|
|
402
|
-
```
|
|
450
|
+
```ts
|
|
451
|
+
// src/session.server.ts
|
|
452
|
+
import type { StageArgs } from "@loozo/angular-launch/server";
|
|
453
|
+
import type { Context } from "./routes/route.generated"; // the root's sessions and token
|
|
403
454
|
|
|
404
|
-
|
|
455
|
+
export function session({ context, response }: StageArgs<Context>) {
|
|
456
|
+
const current = context.sessions.read(context.token);
|
|
405
457
|
|
|
406
|
-
|
|
407
|
-
|
|
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
|
-
});
|
|
458
|
+
if (current !== null && current.expiresSoon) {
|
|
459
|
+
response.setCookie("session", context.sessions.extend(current), { maxAge: 60 * 60 * 24 * 30 });
|
|
417
460
|
}
|
|
418
461
|
|
|
419
|
-
return
|
|
420
|
-
}
|
|
462
|
+
return { ...context, user: current?.user ?? null };
|
|
463
|
+
}
|
|
421
464
|
```
|
|
422
465
|
|
|
423
|
-
Concurrent RPC requests from the browser each have their own
|
|
466
|
+
Concurrent RPC requests from the browser each have their own scope, 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
467
|
|
|
425
|
-
|
|
468
|
+
`readCookies(request)` from `@loozo/angular-launch/server` reads a request's cookies, such as the root's `token` the stage above reads:
|
|
469
|
+
|
|
470
|
+
```ts
|
|
471
|
+
// src/routes/route.ts
|
|
472
|
+
import { defineRoute } from "@loozo/angular-launch";
|
|
473
|
+
import { readCookies } from "@loozo/angular-launch/server";
|
|
474
|
+
import { sessions } from "../sessions.server";
|
|
475
|
+
|
|
476
|
+
export default defineRoute("", {}).context(({ request }) => ({
|
|
477
|
+
sessions,
|
|
478
|
+
token: readCookies(request).get("session") ?? null,
|
|
479
|
+
}));
|
|
480
|
+
```
|
|
481
|
+
|
|
482
|
+
- **It returns** a read-only `Map` of cookie values by name: `get` returns `undefined` for a cookie the request doesn't carry, and `Object.fromEntries(cookies)` gives a plain object, such as for a log. Values come as the browser sent them, without decoding, as `setCookie` doesn't encode them.
|
|
483
|
+
- **A repeated name** reads as its first occurrence in the header. Browsers usually send the cookie with the longer path first, such as one set for `/todos` before one set for `/`, but the header doesn't say which path or domain each came from, so don't rely on which one wins: give cookies that mustn't collide distinct names. Pairs without a name are skipped.
|
|
484
|
+
- **It reads the request you pass**, so during server rendering every call sees the page request's cookies, not the ones calls set earlier in the render, and a prerendered page reads none.
|
|
426
485
|
|
|
427
486
|
### JSON values
|
|
428
487
|
|
|
@@ -467,9 +526,9 @@ Launch itself uses four codes, which you can't declare:
|
|
|
467
526
|
|
|
468
527
|
```ts
|
|
469
528
|
try {
|
|
470
|
-
await
|
|
529
|
+
await remote.todos.add({ title });
|
|
471
530
|
} catch (error) {
|
|
472
|
-
if (
|
|
531
|
+
if (remote.todos.add.isError(error) && error.code === "INVALID_INPUT") {
|
|
473
532
|
for (const issue of error.data.issues) {
|
|
474
533
|
showError(issue.path, issue.message); // ["title"], "Title must contain 1–200 characters"
|
|
475
534
|
}
|
|
@@ -479,21 +538,22 @@ try {
|
|
|
479
538
|
|
|
480
539
|
### Redirects and not found
|
|
481
540
|
|
|
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.
|
|
541
|
+
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. Stages, middleware and handlers throw them:
|
|
483
542
|
|
|
484
543
|
```ts
|
|
485
|
-
// src/
|
|
486
|
-
import {
|
|
487
|
-
import {
|
|
488
|
-
import signIn from "
|
|
544
|
+
// src/routes/+authenticated/route.ts
|
|
545
|
+
import { defineRoute } from "@loozo/angular-launch";
|
|
546
|
+
import { redirect } from "@loozo/angular-launch/server";
|
|
547
|
+
import { destination as signIn } from "../sign-in/destination.generated";
|
|
548
|
+
import parent from "../route";
|
|
489
549
|
|
|
490
|
-
//
|
|
491
|
-
export
|
|
550
|
+
// Every procedure at or below this route answers a signed-out caller with the redirect.
|
|
551
|
+
export default defineRoute("", { parent }).context(({ context }) => {
|
|
492
552
|
if (context.user === null) {
|
|
493
|
-
throw redirect(
|
|
553
|
+
throw redirect(signIn, {});
|
|
494
554
|
}
|
|
495
555
|
|
|
496
|
-
return
|
|
556
|
+
return { ...context, user: context.user };
|
|
497
557
|
});
|
|
498
558
|
```
|
|
499
559
|
|
|
@@ -515,8 +575,8 @@ get: query({
|
|
|
515
575
|
}),
|
|
516
576
|
```
|
|
517
577
|
|
|
518
|
-
- **`redirect(
|
|
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.
|
|
578
|
+
- **`redirect(destination, values)`** goes to `createUrl(destination, values)`, and takes the same arguments: a `destination` from a `destination.generated.ts`, and its params, search and fragment, `{}` for none. Wrong values fail to type-check, and a URL string is a type error, so only declared pages are targets: to send the visitor on afterwards, declare a search key such as `next` on the sign-in route and pass `redirect(signIn, { search: { next: createUrl(todos, {}) } })`. An external redirect, such as to an OAuth provider, is data your page acts on.
|
|
579
|
+
- **On the wire** a redirect is a 303 with `{ "redirect": { "to": "/sign-in" } }` and no `Location` header (with [translated URLs](#translated-urls), also its `words`), 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
580
|
- **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
581
|
- **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
582
|
|
|
@@ -525,27 +585,25 @@ get: query({
|
|
|
525
585
|
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
586
|
|
|
527
587
|
```ts
|
|
528
|
-
export default
|
|
529
|
-
|
|
530
|
-
({ stream }) => ({
|
|
588
|
+
export default defineRoute("live", { parent }).remote(({ stream }) => ({
|
|
589
|
+
live: {
|
|
531
590
|
watch: stream({
|
|
532
591
|
handler: async function* ({ context, signal }) {
|
|
533
592
|
yield* context.db.todos.watchForUser(context.user.id, signal);
|
|
534
593
|
},
|
|
535
594
|
}),
|
|
536
|
-
}
|
|
537
|
-
|
|
538
|
-
);
|
|
595
|
+
},
|
|
596
|
+
}));
|
|
539
597
|
```
|
|
540
598
|
|
|
541
599
|
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
600
|
|
|
543
601
|
- **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
602
|
- **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
|
-
- **
|
|
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
|
|
603
|
+
- **Stages and middleware** run 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.
|
|
604
|
+
- **Cookies and headers** are sent with the stream's response, which starts once the handler returned its iterable. Set them in a stage, 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).
|
|
605
|
+
- **Failures** before the handler returns its iterable, such as a refusing stage or 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}`.
|
|
606
|
+
- **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 stages 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
607
|
|
|
550
608
|
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
609
|
|
|
@@ -562,9 +620,8 @@ data: {"status":404,"error":{"code":"NOT_FOUND","message":"Todo does not exist",
|
|
|
562
620
|
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
621
|
|
|
564
622
|
```ts
|
|
565
|
-
export default
|
|
566
|
-
|
|
567
|
-
({ channel }) => ({
|
|
623
|
+
export default defineRoute("live", { parent }).remote(({ channel }) => ({
|
|
624
|
+
live: {
|
|
568
625
|
// The user's todos now, then again after each title the caller sends is added.
|
|
569
626
|
add: channel({
|
|
570
627
|
message: titleSchema,
|
|
@@ -577,16 +634,15 @@ export default defineRpc(
|
|
|
577
634
|
}
|
|
578
635
|
},
|
|
579
636
|
}),
|
|
580
|
-
}
|
|
581
|
-
|
|
582
|
-
);
|
|
637
|
+
},
|
|
638
|
+
}));
|
|
583
639
|
```
|
|
584
640
|
|
|
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
|
|
641
|
+
Everything in [Streams](#streams) applies: values are strict JSON, the handler is written `handler: async function* (…)`, yields the current state first and returns nothing, stages and middleware run once and `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 stage or middleware.
|
|
586
642
|
|
|
587
643
|
- **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
644
|
- **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
|
|
645
|
+
- **Failures** before the handler returns its iterable, such as a refusing stage or 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 any stage runs, 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
646
|
- **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
647
|
- **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
648
|
|
|
@@ -605,22 +661,24 @@ A binary or malformed frame, a message beyond the caller's credit, or a grant fo
|
|
|
605
661
|
|
|
606
662
|
## Calling RPCs
|
|
607
663
|
|
|
608
|
-
|
|
664
|
+
A route's handle carries its client: `injectRoute().remote` from the route's `route.generated.ts` has the route's own namespaces and its ancestors'. Call `injectRoute()` in an injection context, such as a field initializer; reading `remote` and calling it later, from an event or after an `await`, is fine:
|
|
609
665
|
|
|
610
666
|
```ts
|
|
611
667
|
import { Component } from "@angular/core";
|
|
612
|
-
import {
|
|
668
|
+
import { injectRoute } from "./route.generated";
|
|
613
669
|
|
|
614
670
|
@Component({/* … */})
|
|
615
671
|
export default class Todos {
|
|
616
|
-
readonly
|
|
672
|
+
readonly route = injectRoute();
|
|
617
673
|
|
|
618
674
|
async complete(id: string): Promise<void> {
|
|
675
|
+
const { todos } = this.route.remote;
|
|
676
|
+
|
|
619
677
|
try {
|
|
620
|
-
await
|
|
621
|
-
await
|
|
678
|
+
await todos.complete({ id });
|
|
679
|
+
await todos.list(); // read again explicitly; nothing is invalidated for you
|
|
622
680
|
} catch (error) {
|
|
623
|
-
if (
|
|
681
|
+
if (todos.complete.isError(error) && error.code === "NOT_FOUND") {
|
|
624
682
|
const missingId: string = error.data.id;
|
|
625
683
|
}
|
|
626
684
|
}
|
|
@@ -631,35 +689,30 @@ export default class Todos {
|
|
|
631
689
|
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:
|
|
632
690
|
|
|
633
691
|
```ts
|
|
634
|
-
await
|
|
635
|
-
await
|
|
636
|
-
await
|
|
692
|
+
await remote.todos.list();
|
|
693
|
+
await remote.todos.list({ signal, transferCache: false });
|
|
694
|
+
await remote.todos.add({ title }, { signal });
|
|
637
695
|
```
|
|
638
696
|
|
|
639
|
-
| Option | Effect
|
|
640
|
-
| --------------- |
|
|
641
|
-
| `signal` | Abort the HTTP request; the call rejects with an `AbortError`. The server's middleware and handler see their `signal` abort, but aborting is advisory: work that ignores it finishes, and a write may already have committed. |
|
|
642
|
-
| `transferCache` | Queries default to `true`. Mutations only accept `false` and never use the transfer cache.
|
|
697
|
+
| Option | Effect |
|
|
698
|
+
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
699
|
+
| `signal` | Abort the HTTP request; the call rejects with an `AbortError`. The server's stages, middleware and handler see their `signal` abort, but aborting is advisory: work that ignores it finishes, and a write may already have committed. |
|
|
700
|
+
| `transferCache` | Queries default to `true`. Mutations only accept `false` and never use the transfer cache. |
|
|
643
701
|
|
|
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.
|
|
702
|
+
`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. Each callable also has a literal `kind` of `"query"`, `"mutation"`, `"stream"` or `"channel"`.
|
|
645
703
|
|
|
646
|
-
Route resolvers
|
|
704
|
+
Route resolvers, guards and titles kept on a route get the same client as `remote`, which is how a page gets its data during SSR:
|
|
647
705
|
|
|
648
706
|
```ts
|
|
649
707
|
// src/routes/+authenticated/todos/route.ts
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
export default defineRoute("todos", {
|
|
655
|
-
parent,
|
|
656
|
-
resolve: {
|
|
657
|
-
session: () => injectRpc().session.current(),
|
|
658
|
-
},
|
|
659
|
-
});
|
|
708
|
+
export default defineRoute("todos", { parent })
|
|
709
|
+
.remote(/* … */)
|
|
710
|
+
.resolve({ session: ({ remote }) => remote.session.current() });
|
|
660
711
|
```
|
|
661
712
|
|
|
662
|
-
|
|
713
|
+
A route copy exports its client's type as `Remote`, for example to type a result: `Awaited<ReturnType<Remote["todos"]["list"]>>` with `import type { Remote } from "./route.generated"`. It names the server's types through the route's declaration, erased, so no server code reaches the browser bundle.
|
|
714
|
+
|
|
715
|
+
A narrowed [active route](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-router/README.md) handle carries the same `remote`, so a shell can call the active page's procedures. Its client is built with the injector of the `injectActiveRoute()` caller, not the route's: providers a route adds, such as an `HttpClient` interceptor, reach only that route's own `injectRoute()`.
|
|
663
716
|
|
|
664
717
|
### Navigating on outcomes
|
|
665
718
|
|
|
@@ -670,7 +723,7 @@ export default defineRoute("todos", {
|
|
|
670
723
|
import { provideRouter, withNavigationErrorHandler } from "@angular/router";
|
|
671
724
|
import { rpcNavigationErrors } from "@loozo/angular-launch";
|
|
672
725
|
import { createUrl } from "@loozo/angular-router";
|
|
673
|
-
import notFound from "./routes/not-found/
|
|
726
|
+
import { destination as notFound } from "./routes/not-found/destination.generated";
|
|
674
727
|
|
|
675
728
|
provideRouter(
|
|
676
729
|
routes,
|
|
@@ -681,6 +734,7 @@ provideRouter(
|
|
|
681
734
|
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
735
|
|
|
683
736
|
- Only navigation acts on outcomes. A call from a component, a click handler or a TanStack query just rejects.
|
|
737
|
+
- With Angular's `withErrorBoundaries`, an outcome thrown while a page renders, such as from a resource its template reads, reaches the boundary's error component as its `error` input. `rpcNavigationErrors` never sees it, so it neither redirects nor answers 404.
|
|
684
738
|
- 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
739
|
- The 404 needs the route's `RenderMode.Server`. While Angular prerenders a page, an outcome fails the build instead; see [Prerendering](#prerendering).
|
|
686
740
|
|
|
@@ -689,7 +743,7 @@ When a guard or resolver's call rejects with `RpcRedirect`, the navigation goes
|
|
|
689
743
|
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
744
|
|
|
691
745
|
```ts
|
|
692
|
-
for await (const todos of
|
|
746
|
+
for await (const todos of remote.live.watch({ signal })) {
|
|
693
747
|
this.todos.set(todos);
|
|
694
748
|
}
|
|
695
749
|
```
|
|
@@ -701,20 +755,20 @@ Each iteration sends a new request; leaving the loop early or aborting `signal`
|
|
|
701
755
|
- throws an `AbortError` when `signal` aborts;
|
|
702
756
|
- throws a `TypeError` when the connection fails or closes before the stream ended.
|
|
703
757
|
|
|
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
|
|
758
|
+
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 in a fresh request scope, and the stream starts over from the handler's first value.
|
|
705
759
|
|
|
706
760
|
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
761
|
|
|
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.
|
|
762
|
+
Streams don't run during server rendering: there, iterating one fails at once with `FORBIDDEN`, before any stage or 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
763
|
|
|
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
|
|
764
|
+
TanStack Query options aren't generated for streams; see the [TanStack Query guide](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-launch/tanstack-query/README.md#limitations).
|
|
711
765
|
|
|
712
766
|
### Calling channels
|
|
713
767
|
|
|
714
768
|
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
769
|
|
|
716
770
|
```ts
|
|
717
|
-
const adding =
|
|
771
|
+
const adding = remote.live.add({ signal });
|
|
718
772
|
|
|
719
773
|
const sending = (async () => {
|
|
720
774
|
for (const title of titles) {
|
|
@@ -730,7 +784,7 @@ for await (const todos of adding) {
|
|
|
730
784
|
- **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
785
|
- **`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
786
|
- **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
|
|
787
|
+
- **Nothing reconnects for you,** and each call is new: a new request scope, the handler's first value again.
|
|
734
788
|
|
|
735
789
|
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
790
|
|
|
@@ -756,13 +810,12 @@ A stream's or channel's callable also has `connect()`, which follows it as signa
|
|
|
756
810
|
`,
|
|
757
811
|
})
|
|
758
812
|
export default class Live {
|
|
759
|
-
readonly #rpc = injectRpc();
|
|
760
813
|
readonly #route = injectRoute();
|
|
761
814
|
// The server renders the resolver's list; after hydration the stream follows it.
|
|
762
|
-
protected readonly todos = this.#
|
|
815
|
+
protected readonly todos = this.#route.remote.live.watch.connect({
|
|
763
816
|
initial: () => this.#route.data().todos,
|
|
764
817
|
});
|
|
765
|
-
protected readonly adding = this.#
|
|
818
|
+
protected readonly adding = this.#route.remote.live.add.connect({ initial: () => null });
|
|
766
819
|
|
|
767
820
|
protected async add(event: SubmitEvent, input: HTMLInputElement): Promise<void> {
|
|
768
821
|
event.preventDefault();
|
|
@@ -805,11 +858,11 @@ On the server it never connects: `status` is `"idle"` and `value` is `initial()`
|
|
|
805
858
|
|
|
806
859
|
### With TanStack Query
|
|
807
860
|
|
|
808
|
-
With the `tanstackQuery` generation option, each
|
|
861
|
+
With the `tanstackQuery` generation option, each route's handle also has `queries`, and its copy exports `Queries`: typed query and mutation options and keys for the same namespaces as `remote`, for `@tanstack/angular-query`. See the [TanStack Query guide](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-launch/tanstack-query/README.md) for setup, keys, invalidation, optimistic updates and hydration.
|
|
809
862
|
|
|
810
863
|
## Server rendering and hydration
|
|
811
864
|
|
|
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
|
|
865
|
+
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.1.0/packages/angular-launch/tanstack-query/README.md) opt out and are transferred by TanStack instead.
|
|
813
866
|
|
|
814
867
|
The reuse has limits, all of them Angular's transfer cache behaving as designed:
|
|
815
868
|
|
|
@@ -822,9 +875,9 @@ Outcomes in a guard or resolver become a 302 or a 404 page with [`rpcNavigationE
|
|
|
822
875
|
- 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
876
|
- Any other failure of a guard or resolver during server rendering, such as `FORBIDDEN`, `INTERNAL`, a declared error, or an outcome without `rpcNavigationErrors`, fails the initial navigation. Angular then renders no page and `angular.handle` returns `null`, so your server's fallback answers, such as the example's plain 404, without the cookies calls set during the render. Handle such errors in the route if the page should show something, or throw an outcome instead.
|
|
824
877
|
|
|
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).
|
|
878
|
+
Mutations are refused during server rendering with `FORBIDDEN`, before any stage, 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).
|
|
826
879
|
|
|
827
|
-
|
|
880
|
+
Stages, middleware and handlers run during server rendering too, with the page request as `request`. A render's calls share one request scope, so each stage runs at most once per render. They run in the server entry's copy of your server code, the one that answers RPCs: Angular bundles the server entry apart from the server application that renders, so a module both import, such as your database client, is loaded once in each, and Launch runs a render's calls in the copy that created its request scope. A page and an RPC therefore see the same module state, such as an in-memory store or a connection pool. The other copy still evaluates the module, so whatever it starts at import time, such as a pool's connections or a timer, starts twice: create those on first use instead. While Angular [prerenders](#prerendering) a page, its calls run in the server application's copy. 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).
|
|
828
881
|
|
|
829
882
|
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`.
|
|
830
883
|
|
|
@@ -840,22 +893,413 @@ export const rendering: ServerRoute[] = [
|
|
|
840
893
|
];
|
|
841
894
|
```
|
|
842
895
|
|
|
843
|
-
Angular prerenders without a request, so Launch creates the page's
|
|
896
|
+
Angular prerenders without a request, so Launch creates the page's request scope 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: a stage or middleware that needs a signed-in user refuses, and that fails the build.
|
|
844
897
|
|
|
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
|
|
898
|
+
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 a stage or 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 a context stage throws: the error names the stage's route and has the stage's error as its `cause`. Without it, Angular can write the page with the failure rendered into it, or skip the page and still report success.
|
|
846
899
|
|
|
847
900
|
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
901
|
|
|
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
|
|
902
|
+
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 request scope. So:
|
|
850
903
|
|
|
851
904
|
- 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
905
|
- Everything a prerendered call returns is in a file served to every visitor.
|
|
853
906
|
- 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
|
-
-
|
|
855
|
-
- `ng serve` renders prerendered routes on every request the same way,
|
|
907
|
+
- Context stages run at build time, at most once per prerendered page, in Angular's prerender workers, so whatever they use, 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.
|
|
908
|
+
- `ng serve` renders prerendered routes on every request the same way, anonymously whatever cookies the browser sends.
|
|
909
|
+
- With [translated URLs](#translated-urls), prerendered calls run in that locale's server app, so `createUrl` in a procedure returns the locale's words there, unlike on a live server.
|
|
856
910
|
- 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
911
|
|
|
858
|
-
Blocking initial navigation (`withEnabledBlockingInitialNavigation`)
|
|
912
|
+
Blocking initial navigation (`withEnabledBlockingInitialNavigation`) works with `finishLaunchRendering`. With it, Angular also runs the initial navigation to `/` while it discovers your routes at build time, so resolvers on the routes that match `/`, such as the root route's, make their calls then, once, with the anonymous context. A call refused there, such as one that needs a signed-in user, doesn't fail the build: Angular logs the error and still finds every route. Pages you prerender still fail the build for it, as above, and server-rendered pages make the call again with each visitor's context. Angular documents blocking initial navigation for server rendering without hydration, and Launch apps hydrate: hydration is what enables the HTTP transfer cache.
|
|
913
|
+
|
|
914
|
+
## Translated URLs
|
|
915
|
+
|
|
916
|
+
The router can [translate static URL segments](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-router/README.md#translated-urls) per Angular localize build, so the German build serves `/de/anmelden` where the source build serves `/en/sign-in`. A Launch app turns it on in its application builder, and Launch then also puts every RPC redirect in the page's language: a German visitor sent to sign in lands on `/de/anmelden`, whether the redirect reaches them through a call in the browser or as the 302 that answers a server-rendered page.
|
|
917
|
+
|
|
918
|
+
Set it up in this order:
|
|
919
|
+
|
|
920
|
+
1. Turn on `translateSegments` with Angular's `i18n`, `localize` and the `@angular/localize/init` polyfill, as the router's guide describes, and add `"types": ["@angular/localize"]` to the app tsconfig. With several locales, serve one at a time from a development configuration such as `"localize": ["de"]`: Angular's dev server doesn't localize a multi-locale `localize: true` build.
|
|
921
|
+
|
|
922
|
+
```jsonc
|
|
923
|
+
// angular.json (excerpt)
|
|
924
|
+
"i18n": { "sourceLocale": "en", "locales": { "de": "src/locale/messages.de.xlf" } },
|
|
925
|
+
"build": {
|
|
926
|
+
"builder": "@loozo/angular-launch:application",
|
|
927
|
+
"options": {
|
|
928
|
+
"translateSegments": true,
|
|
929
|
+
"localize": true,
|
|
930
|
+
"i18nMissingTranslation": "error",
|
|
931
|
+
"polyfills": ["@angular/localize/init"]
|
|
932
|
+
// …the rest as in Setup
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
```
|
|
936
|
+
|
|
937
|
+
2. Import `server.generated` in `server.ts` before any import that reaches a route: an authored module that imports a `destination.generated.ts` or `route.generated.ts`, directly or through other modules. The setup above already does. Angular runs no polyfills in the server entry, so `server.generated.ts` first installs a `$localize` that returns each message's source text, and any destination copy evaluated before it fails the build, or the server's start, with `ReferenceError: $localize is not defined`.
|
|
938
|
+
|
|
939
|
+
The server entry must stay in the source language: if something else installs a `$localize` there first that translates, such as `loadTranslations` or a catalog loaded at runtime, Launch keeps it, and redirects are then built from translated words. That isn't supported. A word the page's build doesn't know stays as it is, so the German page can't match the URL; and a translated word that happens to be another route's canonical word is translated again, which reaches the wrong page: with `sign-in` → `anmelden` and a route whose canonical word is `anmelden`, a German visitor sent to sign in lands on that route's German path instead.
|
|
940
|
+
|
|
941
|
+
3. Add `provideRedirectTranslation()` from the generated `redirects.generated.ts` to the config both apps share. Generation fails until some application file imports it; it can't check that both the browser and the server app install it, so put it in `config.ts`, which `config.server.ts` merges:
|
|
942
|
+
|
|
943
|
+
```ts
|
|
944
|
+
// src/config.ts
|
|
945
|
+
import { provideRedirectTranslation } from "../generated/redirects.generated";
|
|
946
|
+
|
|
947
|
+
export const config: ApplicationConfig = {
|
|
948
|
+
providers: [
|
|
949
|
+
provideHttpClient(),
|
|
950
|
+
provideClientHydration(),
|
|
951
|
+
provideRouter(
|
|
952
|
+
routes,
|
|
953
|
+
withNavigationErrorHandler(rpcNavigationErrors({ notFound: createUrl(notFound, {}) })),
|
|
954
|
+
),
|
|
955
|
+
provideRedirectTranslation(),
|
|
956
|
+
],
|
|
957
|
+
};
|
|
958
|
+
```
|
|
959
|
+
|
|
960
|
+
An app that leaves it out redirects German visitors to the source-language path, which the German build can't match: navigation stays where it was, and the server answers a guarded German page as if it had no page.
|
|
961
|
+
|
|
962
|
+
Procedures don't change. `redirect(signIn, {})` builds the source-language URL on the server, whose code Angular never localizes, and the redirect frame also lists which of its path segments, counted from 0, are static words: `{ "redirect": { "to": "/sign-in", "words": [0] } }`. The page's own build, in the browser or rendering a live request, swaps those segments for its words when its generated client recognizes the frame, so `RpcRedirect.to` is `/anmelden` in the German build: exactly what `createUrl(signIn, {})` returns there. Parameter and catchall values, the search and the fragment stay as they are, as they do in that build's `createUrl`.
|
|
963
|
+
|
|
964
|
+
A destination in a [named outlet](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-router/README.md#named-outlets) counts its anchor's segments first, then its group's, and its outlet name is never a word, even when it's spelled like one. `redirect(item, { params: { team: "products", id: "3" } })` for `item/$id` in the `detail` outlet below `teams/$team` is `{ "to": "/teams/products/(detail:item/3)", "words": [0, 2] }`; the German build makes it `/mannschaften/products/(detail:artikel/3)`, and `/(chat:chat/7)` at the root becomes `/(chat:plaudern/7)`.
|
|
965
|
+
|
|
966
|
+
Which page a translated URL reaches is the router's: Launch's redirect equals the German link byte for byte, and generation rejects a catalog that puts one route's translated path under a catchall Angular tries first, where the source words don't ([Translated URLs](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-router/README.md#translated-urls)).
|
|
967
|
+
|
|
968
|
+
What stays in the source language:
|
|
969
|
+
|
|
970
|
+
- The wire frame, and what every `HttpInterceptor` sees of it, in the browser and during server rendering. With the option on, an interceptor or a test that compares redirect bodies exactly sees `words` too.
|
|
971
|
+
- URLs inside search values: `redirect(signIn, { search: { next: createUrl(todos, {}) } })` sends the visitor on to the source-language `next` after signing in, which the German build can't match. Pass an id instead and build the URL in the page.
|
|
972
|
+
- URLs a procedure returns as data, sets in a `Location` header through `response`, logs, or sends by email or webhook, and redirects your `server.ts` issues itself. While prerendering, procedures run in the localized server app, so `createUrl` there returns that locale's words: return ids and build URLs in the page.
|
|
973
|
+
- [`callProcedure`](#testing-handlers-stages-and-middleware) results, which never carry `words`.
|
|
974
|
+
|
|
975
|
+
A browser still running the client of a build from before the option was turned on doesn't recognize a frame with `words` and rejects with Angular's `HttpErrorResponse` until it reloads.
|
|
976
|
+
|
|
977
|
+
**Language switcher and hreflang.** The router's `localeUrls(destination, values)` and the active route's `localeUrls` signal work in a Launch app as they do with the router's own builders: Launch's application and serve builders hand the router every configured locale's base href and words, from the catalogs generation just checked, so the German sign-in page `/de/anmelden` links to `/en/sign-in`. Use the router's [switcher and hreflang snippets](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-router/README.md#translated-urls) as they are; its rules for which locales are listed, what's carried and when the list is empty apply unchanged. Live server rendering, prerendering and the browser all see the same list. A localized build gets it without `translateSegments` too, with your source words under each locale's base. The builders pass it as Angular's `define.loozoRouterLocales`, so that key is reserved in your own `define`, in the build and the serve options.
|
|
978
|
+
|
|
979
|
+
`ng serve` also watches the catalogs: an edit runs the router's per-locale checks again and logs a `Locale de: …` error without stopping the server. Angular's dev server applies a catalog at its next rebuild, not at the edit. A single-locale `ng serve` (`"localize": ["de"]`) gets the switcher's list with its own locale at the dev server's unprefixed base, `/anmelden`, and the list keeps the words `ng serve` started with: after an edit that changes them, it logs `Locale words changed (route.segment.guarded in de). Links from localeUrls keep the words ng serve started with until you restart it.` Restart it to refresh the list. The other locales' links point at builds this dev server doesn't serve, so check them in a production build.
|
|
980
|
+
|
|
981
|
+
## Testing
|
|
982
|
+
|
|
983
|
+
Point Angular's unit-test builder at the Launch application target, the same way `ng new` points it at the official one:
|
|
984
|
+
|
|
985
|
+
```json
|
|
986
|
+
"test": {
|
|
987
|
+
"builder": "@angular/build:unit-test",
|
|
988
|
+
"options": { "buildTarget": "app:build", "tsConfig": "tsconfig.spec.json" }
|
|
989
|
+
}
|
|
990
|
+
```
|
|
991
|
+
|
|
992
|
+
`ng test` doesn't run generation; it uses the generated files already on disk. After you add, move or remove routes or procedures, run `ng build` first, or keep `ng serve` running. `ng test` warns that the `buildTarget` uses `@loozo/angular-launch:application`, "which is not supported". The warning is expected: the unit-test builder reads the target's options, and Angular ignores Launch's own ones.
|
|
993
|
+
|
|
994
|
+
Give specs their own `tsconfig.spec.json` with `"types": ["vitest/globals"]`, and exclude `src/**/*.spec.ts` from the application tsconfig, which also keeps them out of generation's type check. With `vitest/globals`, the imports from `vitest` below are optional.
|
|
995
|
+
|
|
996
|
+
The specs below run in this package's CI against the [snippets app](https://github.com/theo-matzavinos/loozo/tree/angular-launch@0.1.0/packages/angular-launch/snippets), whose `todos` route has a `list` query and a `complete` mutation with a declared `NOT_FOUND`, behind a `signedIn` stage.
|
|
997
|
+
|
|
998
|
+
### Testing components and resolvers
|
|
999
|
+
|
|
1000
|
+
A route's client needs only `HttpClient`: a query or mutation is a `POST /_rpc/<namespace>/<procedure>` with the body `{ "input": … }`, `null` for a procedure without input. So Angular's HTTP testing providers work, and `HttpTestingController` answers the calls. `injectRoute()` needs its route's activated record, so test a page, or a component inside one, through the router: navigate with `RouterTestingHarness` over the generated routes, answer the resolver's calls, then use the page's `route.remote` or the component it rendered:
|
|
1001
|
+
|
|
1002
|
+
`snippets/src/routes/todos/todo-item.spec.ts`
|
|
1003
|
+
|
|
1004
|
+
```ts
|
|
1005
|
+
import { provideHttpClient } from "@angular/common/http";
|
|
1006
|
+
import { HttpTestingController, provideHttpClientTesting } from "@angular/common/http/testing";
|
|
1007
|
+
import { TestBed } from "@angular/core/testing";
|
|
1008
|
+
import { By } from "@angular/platform-browser";
|
|
1009
|
+
import { provideRouter } from "@angular/router";
|
|
1010
|
+
import { RouterTestingHarness } from "@angular/router/testing";
|
|
1011
|
+
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
1012
|
+
import { routes } from "../../../generated/routes.generated.js";
|
|
1013
|
+
import TodosPage from "./page.js";
|
|
1014
|
+
import { TodoItem } from "./todo-item.js";
|
|
1015
|
+
|
|
1016
|
+
// TodoItem reads the todos route's handle, so it renders inside the page the router shows.
|
|
1017
|
+
async function renderedItem() {
|
|
1018
|
+
const http = TestBed.inject(HttpTestingController);
|
|
1019
|
+
const harness = await RouterTestingHarness.create();
|
|
1020
|
+
const navigation = harness.navigateByUrl("/todos", TodosPage);
|
|
1021
|
+
|
|
1022
|
+
await vi.waitFor(() =>
|
|
1023
|
+
http.expectOne("/_rpc/todos/list").flush([{ id: "1", title: "Buy milk", completed: false }]),
|
|
1024
|
+
);
|
|
1025
|
+
await navigation;
|
|
1026
|
+
harness.detectChanges();
|
|
1027
|
+
|
|
1028
|
+
return harness.fixture.debugElement.query(By.directive(TodoItem)).componentInstance as TodoItem;
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
describe("TodoItem", () => {
|
|
1032
|
+
beforeEach(() => {
|
|
1033
|
+
TestBed.configureTestingModule({
|
|
1034
|
+
providers: [provideHttpClient(), provideHttpClientTesting(), provideRouter(routes)],
|
|
1035
|
+
});
|
|
1036
|
+
});
|
|
1037
|
+
|
|
1038
|
+
it("completes the todo", async () => {
|
|
1039
|
+
const item = await renderedItem();
|
|
1040
|
+
const http = TestBed.inject(HttpTestingController);
|
|
1041
|
+
const completing = item.complete();
|
|
1042
|
+
const call = http.expectOne({ method: "POST", url: "/_rpc/todos/complete" });
|
|
1043
|
+
|
|
1044
|
+
expect(call.request.body).toEqual({ input: { id: "1" } });
|
|
1045
|
+
call.flush({ id: "1", title: "Buy milk", completed: true });
|
|
1046
|
+
await completing;
|
|
1047
|
+
|
|
1048
|
+
expect(item.status()).toBe("Completed");
|
|
1049
|
+
http.verify();
|
|
1050
|
+
});
|
|
1051
|
+
|
|
1052
|
+
it("handles the procedure's declared NOT_FOUND error", async () => {
|
|
1053
|
+
const item = await renderedItem();
|
|
1054
|
+
const http = TestBed.inject(HttpTestingController);
|
|
1055
|
+
const completing = item.complete();
|
|
1056
|
+
|
|
1057
|
+
// Status and message must match the declaration, or the client doesn't recognize the error.
|
|
1058
|
+
http
|
|
1059
|
+
.expectOne("/_rpc/todos/complete")
|
|
1060
|
+
.flush(
|
|
1061
|
+
{ error: { code: "NOT_FOUND", message: "Todo does not exist", data: { id: "1" } } },
|
|
1062
|
+
{ status: 404, statusText: "Not Found" },
|
|
1063
|
+
);
|
|
1064
|
+
await completing;
|
|
1065
|
+
|
|
1066
|
+
expect(item.status()).toBe("This todo no longer exists.");
|
|
1067
|
+
});
|
|
1068
|
+
});
|
|
1069
|
+
```
|
|
1070
|
+
|
|
1071
|
+
Answer a call with what the server would send:
|
|
1072
|
+
|
|
1073
|
+
| Outcome | Body | Status |
|
|
1074
|
+
| --------------- | -------------------------------------------------------------------------------------- | ---------------- |
|
|
1075
|
+
| Result | the result | 200, the default |
|
|
1076
|
+
| Declared error | `{ error: { code, message, data } }`, with the declared `message` | the declared one |
|
|
1077
|
+
| `INVALID_INPUT` | `{ error: { code: "INVALID_INPUT", message: "Invalid RPC input", data: { issues } } }` | 400 |
|
|
1078
|
+
| `FORBIDDEN` | `{ error: { code: "FORBIDDEN", message: "RPC forbidden", data: null } }` | 403 |
|
|
1079
|
+
| `RPC_NOT_FOUND` | `{ error: { code: "RPC_NOT_FOUND", message: "RPC not found", data: null } }` | 404 |
|
|
1080
|
+
| `INTERNAL` | `{ error: { code: "INTERNAL", message: "Internal server error", data: null } }` | 500 |
|
|
1081
|
+
| `redirect()` | `{ redirect: { to } }`, plus `words` with [translated URLs](#translated-urls) | 303 |
|
|
1082
|
+
| `notFound()` | `{ notFound: null }` | 404 |
|
|
1083
|
+
|
|
1084
|
+
Pass the status as `flush(body, { status, statusText })`. The client recognizes an error only when its code, status and message all match, the procedure's declaration for a declared error and the table for Launch's own codes, and its data has the shape shown. A failing status whose body is neither a recognized error nor an outcome rejects with Angular's `HttpErrorResponse`, so a mistyped message makes `isError` false without any other sign. A body flushed with a success status is a result, whatever it contains.
|
|
1085
|
+
|
|
1086
|
+
A resolver calls its procedure while Angular navigates. Navigate through the generated routes with `RouterTestingHarness`, as the [router's guide](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-router/README.md#testing-pages) shows, and answer the call while the navigation waits for it:
|
|
1087
|
+
|
|
1088
|
+
`snippets/src/routes/todos/route.spec.ts`
|
|
1089
|
+
|
|
1090
|
+
```ts
|
|
1091
|
+
import { provideHttpClient } from "@angular/common/http";
|
|
1092
|
+
import { HttpTestingController, provideHttpClientTesting } from "@angular/common/http/testing";
|
|
1093
|
+
import { TestBed } from "@angular/core/testing";
|
|
1094
|
+
import { provideRouter } from "@angular/router";
|
|
1095
|
+
import { RouterTestingHarness } from "@angular/router/testing";
|
|
1096
|
+
import { describe, expect, it, vi } from "vitest";
|
|
1097
|
+
import { routes } from "../../../generated/routes.generated.js";
|
|
1098
|
+
import TodosPage from "./page.js";
|
|
1099
|
+
|
|
1100
|
+
describe("todos route", () => {
|
|
1101
|
+
it("resolves the list before showing the page", async () => {
|
|
1102
|
+
TestBed.configureTestingModule({
|
|
1103
|
+
providers: [provideHttpClient(), provideHttpClientTesting(), provideRouter(routes)],
|
|
1104
|
+
});
|
|
1105
|
+
|
|
1106
|
+
const http = TestBed.inject(HttpTestingController);
|
|
1107
|
+
const harness = await RouterTestingHarness.create();
|
|
1108
|
+
const navigation = harness.navigateByUrl("/todos", TodosPage);
|
|
1109
|
+
|
|
1110
|
+
// The resolver calls the procedure once the navigation reaches it.
|
|
1111
|
+
await vi.waitFor(() => {
|
|
1112
|
+
const call = http.expectOne({ method: "POST", url: "/_rpc/todos/list" });
|
|
1113
|
+
|
|
1114
|
+
expect(call.request.body).toEqual({ input: null });
|
|
1115
|
+
call.flush([{ id: "1", title: "Buy milk", completed: false }]);
|
|
1116
|
+
});
|
|
1117
|
+
|
|
1118
|
+
const page = await navigation;
|
|
1119
|
+
|
|
1120
|
+
expect(page.route.data().todos).toEqual([{ id: "1", title: "Buy milk", completed: false }]);
|
|
1121
|
+
expect(harness.routeNativeElement?.querySelector("li")?.textContent).toContain("Buy milk");
|
|
1122
|
+
});
|
|
1123
|
+
});
|
|
1124
|
+
```
|
|
1125
|
+
|
|
1126
|
+
[Streams](#calling-streams) and [channels](#calling-channels) use the browser's `fetch` and `WebSocket`, not `HttpClient`, so `HttpTestingController` doesn't see them. A component that uses `route.queries` also needs the TanStack providers; see the [TanStack Query guide](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-launch/tanstack-query/README.md#setup).
|
|
1127
|
+
|
|
1128
|
+
### Testing handlers, stages and middleware
|
|
1129
|
+
|
|
1130
|
+
To test a procedure, call it with `callProcedure` from `@loozo/angular-launch/testing`. Pass the authored route, the default export of its `route.ts`, one of the route's own namespaces, the procedure's name and the context your root route's stage returns. The root stage doesn't run, so what it provides, such as the user or a database client, can be a fake. The rest of the [call order](#middleware) runs as on the server: the stages below the root, the route's middleware, input validation, the procedure's middleware and the handler.
|
|
1131
|
+
|
|
1132
|
+
`snippets/src/routes/todos/procedures.spec.ts`
|
|
1133
|
+
|
|
1134
|
+
```ts
|
|
1135
|
+
import { callProcedure } from "@loozo/angular-launch/testing";
|
|
1136
|
+
import { describe, expect, it } from "vitest";
|
|
1137
|
+
import type { Todo } from "../../todos.server.js";
|
|
1138
|
+
import todos from "./route.js";
|
|
1139
|
+
|
|
1140
|
+
// What the root route's stage returns, with a store holding one todo in place of the real one.
|
|
1141
|
+
function rootContext(user: { id: string } | null) {
|
|
1142
|
+
const milk: Todo = { id: "1", title: "Buy milk", completed: false };
|
|
1143
|
+
|
|
1144
|
+
return {
|
|
1145
|
+
user,
|
|
1146
|
+
todos: {
|
|
1147
|
+
async listForUser() {
|
|
1148
|
+
return [milk];
|
|
1149
|
+
},
|
|
1150
|
+
async completeForUser(_user: string, id: string) {
|
|
1151
|
+
if (id !== milk.id) {
|
|
1152
|
+
return null;
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
return { ...milk, completed: true };
|
|
1156
|
+
},
|
|
1157
|
+
},
|
|
1158
|
+
};
|
|
1159
|
+
}
|
|
1160
|
+
|
|
1161
|
+
describe("todos.complete", () => {
|
|
1162
|
+
it("completes the user's todo", async () => {
|
|
1163
|
+
const call = await callProcedure(todos, "todos", "complete", {
|
|
1164
|
+
context: rootContext({ id: "alice" }),
|
|
1165
|
+
input: { id: "1" },
|
|
1166
|
+
});
|
|
1167
|
+
|
|
1168
|
+
expect(call).toMatchObject({
|
|
1169
|
+
status: 200,
|
|
1170
|
+
result: { id: "1", title: "Buy milk", completed: true },
|
|
1171
|
+
});
|
|
1172
|
+
});
|
|
1173
|
+
|
|
1174
|
+
it("answers NOT_FOUND for a todo the user doesn't have", async () => {
|
|
1175
|
+
const call = await callProcedure(todos, "todos", "complete", {
|
|
1176
|
+
context: rootContext({ id: "alice" }),
|
|
1177
|
+
input: { id: "2" },
|
|
1178
|
+
});
|
|
1179
|
+
|
|
1180
|
+
expect(call).toMatchObject({
|
|
1181
|
+
status: 404,
|
|
1182
|
+
error: { code: "NOT_FOUND", message: "Todo does not exist", data: { id: "2" } },
|
|
1183
|
+
});
|
|
1184
|
+
|
|
1185
|
+
// The declared error's data is typed once its code narrows it.
|
|
1186
|
+
if ("error" in call && call.error.code === "NOT_FOUND") {
|
|
1187
|
+
const id: string = call.error.data.id;
|
|
1188
|
+
|
|
1189
|
+
expect(id).toBe("2");
|
|
1190
|
+
}
|
|
1191
|
+
});
|
|
1192
|
+
|
|
1193
|
+
it("refuses callers without a session through the signedIn stage", async () => {
|
|
1194
|
+
const call = await callProcedure(todos, "todos", "complete", {
|
|
1195
|
+
context: rootContext(null),
|
|
1196
|
+
input: { id: "1" },
|
|
1197
|
+
});
|
|
1198
|
+
|
|
1199
|
+
expect(call).toMatchObject({ status: 403, error: { code: "FORBIDDEN" } });
|
|
1200
|
+
});
|
|
1201
|
+
|
|
1202
|
+
it("rejects input the schema refuses", async () => {
|
|
1203
|
+
const call = await callProcedure(todos, "todos", "complete", {
|
|
1204
|
+
context: rootContext({ id: "alice" }),
|
|
1205
|
+
// The input is typed, so input the schema refuses needs a cast.
|
|
1206
|
+
input: { id: 1 } as never,
|
|
1207
|
+
});
|
|
1208
|
+
|
|
1209
|
+
expect(call).toMatchObject({
|
|
1210
|
+
status: 400,
|
|
1211
|
+
error: {
|
|
1212
|
+
code: "INVALID_INPUT",
|
|
1213
|
+
data: { issues: [{ path: ["id"], message: "Expected a todo id" }] },
|
|
1214
|
+
},
|
|
1215
|
+
});
|
|
1216
|
+
});
|
|
1217
|
+
});
|
|
1218
|
+
|
|
1219
|
+
describe("todos.list", () => {
|
|
1220
|
+
it("lists the user's todos", async () => {
|
|
1221
|
+
const call = await callProcedure(todos, "todos", "list", {
|
|
1222
|
+
context: rootContext({ id: "alice" }),
|
|
1223
|
+
});
|
|
1224
|
+
|
|
1225
|
+
expect(call).toMatchObject({ status: 200, result: [{ id: "1" }], cookies: [] });
|
|
1226
|
+
});
|
|
1227
|
+
});
|
|
1228
|
+
```
|
|
1229
|
+
|
|
1230
|
+
- The call settles to what the browser would get, the bodies in the table above with their status: `{ status: 200, result }`, `{ status, error: { code, message, data } }`, `{ status: 303, redirect: { to } }` (never with `words`, even in a [translated](#translated-urls) app: `to` is whatever `createUrl` gives in the graph the test imports) or `{ status: 404, notFound: null }`. It also has `cookies`, the `Set-Cookie` values the call set, and `headers`, the headers it set. Narrow with `"error" in call`, then by `call.error.code`, to reach a declared error's typed data. An unexpected failure is `INTERNAL`, and Launch logs it with `console.error` as the server does.
|
|
1231
|
+
- `context`, `input` and the result are typed from the route: `context` as the root route's stage returns it (`{}` without one), so input the schema refuses needs a cast.
|
|
1232
|
+
- Stages, middleware and the handler receive a `POST` to `http://localhost/_rpc/<namespace>/<procedure>` as their `request`. Pass `request` to give them your own, with headers or an abort signal.
|
|
1233
|
+
- A namespace belongs to the route whose `.remote()` declares it: call an ancestor's namespace through the ancestor's route. Streams and channels can't be called this way.
|
|
1234
|
+
- The root route is the topmost route that uses `.context()`, `.use()` or `.remote()`, normally `src/routes/route.ts`.
|
|
1235
|
+
- Specs import `route.ts`, which application code mustn't. That's fine because the application tsconfig excludes them, as above.
|
|
1236
|
+
|
|
1237
|
+
`callProcedure` skips what only an HTTP request goes through: the host, origin and method checks, and the root stage. To test those too, call the generated `handleRequest` with a web `Request`, as your server does, and assert on the status and body the browser would get:
|
|
1238
|
+
|
|
1239
|
+
`snippets/src/routes/todos/http.spec.ts`
|
|
1240
|
+
|
|
1241
|
+
```ts
|
|
1242
|
+
// @vitest-environment node
|
|
1243
|
+
// Server code: Node's Request keeps the Origin header, which happy-dom's Request drops.
|
|
1244
|
+
import { describe, expect, it } from "vitest";
|
|
1245
|
+
import { handleRequest } from "../../../generated/server.generated.js";
|
|
1246
|
+
|
|
1247
|
+
describe("POST /_rpc/todos/complete", () => {
|
|
1248
|
+
it("completes the todo of the user the session cookie names", async () => {
|
|
1249
|
+
const request = new Request("http://localhost/_rpc/todos/complete", {
|
|
1250
|
+
method: "POST",
|
|
1251
|
+
headers: {
|
|
1252
|
+
"content-type": "application/json",
|
|
1253
|
+
origin: "http://localhost",
|
|
1254
|
+
cookie: "session=alice-session",
|
|
1255
|
+
},
|
|
1256
|
+
body: JSON.stringify({ input: { id: "1" } }),
|
|
1257
|
+
});
|
|
1258
|
+
|
|
1259
|
+
const response = await handleRequest(request, { allowedHosts: ["localhost"] });
|
|
1260
|
+
|
|
1261
|
+
expect(response?.status).toBe(200);
|
|
1262
|
+
expect(await response?.json()).toEqual({ id: "1", title: "Buy milk", completed: true });
|
|
1263
|
+
});
|
|
1264
|
+
});
|
|
1265
|
+
```
|
|
1266
|
+
|
|
1267
|
+
- Run the file in Node with `// @vitest-environment node`: it's server code. Angular's unit-test builder otherwise runs specs in a DOM emulation, happy-dom when it's installed and jsdom if not. happy-dom's `Request` drops the `Origin` header, so Launch's [cross-origin check](#cross-origin-requests) would refuse every call with `FORBIDDEN`.
|
|
1268
|
+
- Send `Origin` with the request URL's origin, and pass a matching `allowedHosts`.
|
|
1269
|
+
- The call uses your real stages and what they import. Angular's unit-test builder rejects `vi.mock()` for relative imports, so you can't replace a module a stage imports, such as your database client.
|
|
1270
|
+
|
|
1271
|
+
A standalone stage is a function of `StageArgs`, so you can test it on its own with a context you build; a middleware's `run` likewise takes the call's arguments and a `next` you watch:
|
|
1272
|
+
|
|
1273
|
+
`snippets/src/auth.server.spec.ts`
|
|
1274
|
+
|
|
1275
|
+
```ts
|
|
1276
|
+
import { describe, expect, it, vi } from "vitest";
|
|
1277
|
+
import { signedIn } from "./auth.server.js";
|
|
1278
|
+
import { todos } from "./todos.server.js";
|
|
1279
|
+
|
|
1280
|
+
function args(user: { id: string } | null) {
|
|
1281
|
+
const request = new Request("http://localhost/_rpc/todos/list", { method: "POST" });
|
|
1282
|
+
|
|
1283
|
+
return {
|
|
1284
|
+
context: { todos, user },
|
|
1285
|
+
request,
|
|
1286
|
+
signal: request.signal,
|
|
1287
|
+
response: { headers: new Headers(), setCookie: vi.fn(), deleteCookie: vi.fn() },
|
|
1288
|
+
};
|
|
1289
|
+
}
|
|
1290
|
+
|
|
1291
|
+
describe("signedIn", () => {
|
|
1292
|
+
it("narrows the context to the signed-in user", () => {
|
|
1293
|
+
expect(signedIn(args({ id: "alice" }))).toEqual({ todos, user: { id: "alice" } });
|
|
1294
|
+
});
|
|
1295
|
+
|
|
1296
|
+
it("refuses a caller without a user", () => {
|
|
1297
|
+
expect(() => signedIn(args(null))).toThrow();
|
|
1298
|
+
});
|
|
1299
|
+
});
|
|
1300
|
+
```
|
|
1301
|
+
|
|
1302
|
+
`forbidden()`, `notFound()` and `redirect()` throw plain `Error`s, not types a test can check, so a test that calls a stage directly checks that it threw. To check which outcome it answered with, call a procedure behind it with `callProcedure`, as `procedures.spec.ts` above does for `FORBIDDEN`.
|
|
859
1303
|
|
|
860
1304
|
## Deploying
|
|
861
1305
|
|
|
@@ -884,7 +1328,7 @@ Launch calls `/_rpc/<namespace>/<procedure>` from the root of the domain, even w
|
|
|
884
1328
|
|
|
885
1329
|
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.
|
|
886
1330
|
|
|
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
|
|
1331
|
+
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 and under `ng serve` in Chromium, Firefox and WebKit.
|
|
888
1332
|
|
|
889
1333
|
### Streams behind proxies
|
|
890
1334
|
|
|
@@ -917,6 +1361,8 @@ createUpgradeHandler((request) => handleUpgrade(request, { allowedHosts }), {
|
|
|
917
1361
|
});
|
|
918
1362
|
```
|
|
919
1363
|
|
|
1364
|
+
Under `ng serve`, `listen` doesn't run, so your code never attaches the listener. Launch's serve builder forwards channel upgrades to it instead: on the dev server's first request it adds one `upgrade` listener to the dev server, which passes `/_rpc/` upgrades to the latest listener `createUpgradeHandler` created and leaves every other upgrade, such as Vite's live-reload socket, to the dev server. The dev server loads your server module with the first request that reaches your server, such as a page, and again with the first such request after you edit server code; each load creates a new listener, which takes over. Rebuilding alone doesn't load it. With live reload, the default, the reload that follows a server edit is that request, so the reloaded page's channels reach the new code. With `--live-reload=false`, or for an upgrade sent before any page request since the rebuild, the previously loaded module keeps answering until a page request loads the new one. Channels already open stay on the code they started with. A channel upgrade that arrives while no listener exists, because the module hasn't loaded yet or creates none, is answered with a plain-text 503, and the dev server logs one warning naming `createUpgradeHandler`; the client sees a `TypeError`. An upgrade that arrives before the dev server has answered any request isn't forwarded, which doesn't happen in a browser, since the page loads first.
|
|
1365
|
+
|
|
920
1366
|
- **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
1367
|
- **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
1368
|
- **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.
|
|
@@ -952,7 +1398,7 @@ List a sibling site's origin the same way to let it call. Only HTTP requests are
|
|
|
952
1398
|
```ts
|
|
953
1399
|
// src/server.ts
|
|
954
1400
|
import { AngularAppEngine, createRequestHandler } from "@angular/ssr";
|
|
955
|
-
import {
|
|
1401
|
+
import { createRequestScope, handleRequest } from "../generated/server.generated";
|
|
956
1402
|
|
|
957
1403
|
const allowedHosts = ["app.example.com"];
|
|
958
1404
|
const angular = new AngularAppEngine({ allowedHosts });
|
|
@@ -964,7 +1410,7 @@ export const reqHandler = createRequestHandler(async (request: Request) => {
|
|
|
964
1410
|
return rpc;
|
|
965
1411
|
}
|
|
966
1412
|
|
|
967
|
-
const scope =
|
|
1413
|
+
const scope = createRequestScope(request);
|
|
968
1414
|
const page = await angular.handle(scope.request, scope);
|
|
969
1415
|
|
|
970
1416
|
return page ?? new Response("Not found", { status: 404 });
|
|
@@ -973,7 +1419,7 @@ export const reqHandler = createRequestHandler(async (request: Request) => {
|
|
|
973
1419
|
|
|
974
1420
|
- Import from `@angular/ssr`, not `@angular/ssr/node`. `AngularAppEngine` doesn't read `NG_ALLOWED_HOSTS` or `NG_TRUST_PROXY_HEADERS`: pass `allowedHosts`, and `trustProxyHeaders` if you're behind a proxy (it's off by default), to its constructor, and the same hosts to `handleRequest`. List them in the entry as above, or read them from your platform's configuration.
|
|
975
1421
|
- The bundle neither serves the `browser` files nor starts a server. Point your platform's static hosting at `dist/<app>/browser` and its request handler at the exported `reqHandler`.
|
|
976
|
-
- Nothing polyfills Node modules for you, so your
|
|
1422
|
+
- Nothing polyfills Node modules for you, so your stages, handlers and their dependencies must run on the platform. In-memory state lasts only as long as the platform keeps an instance alive.
|
|
977
1423
|
- `handleUpgrade` takes a web `Request` and runs a channel on any standard `WebSocket` the platform accepts, sending `headers` on its `101` response, but it hasn't been verified on Deno or workerd, and neither has workerd's `bufferedAmount`, which the server's flow control reads.
|
|
978
1424
|
|
|
979
1425
|
### Aborted requests
|
|
@@ -985,7 +1431,7 @@ const closed = new AbortController();
|
|
|
985
1431
|
|
|
986
1432
|
response.once("close", () => {
|
|
987
1433
|
if (!response.writableFinished) {
|
|
988
|
-
closed.abort();
|
|
1434
|
+
queueMicrotask(() => closed.abort());
|
|
989
1435
|
}
|
|
990
1436
|
});
|
|
991
1437
|
|
|
@@ -993,11 +1439,21 @@ const native = createWebRequestFromNodeRequest(request);
|
|
|
993
1439
|
const web = new Request(native, { signal: AbortSignal.any([native.signal, closed.signal]) });
|
|
994
1440
|
```
|
|
995
1441
|
|
|
996
|
-
Pass `web` to both `handleRequest` and `
|
|
1442
|
+
Pass `web` to both `handleRequest` and `createRequestScope`, 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.
|
|
1443
|
+
|
|
1444
|
+
The abort waits a microtask because this listener runs before the one Angular's `writeResponseToNodeResponse` adds for the same `close` event later. Aborting right away fails a stream's body before Angular's helper cancels it, and the helper then logs that failure as `DOMException [AbortError]` whenever a client leaves a stream.
|
|
1445
|
+
|
|
1446
|
+
Angular rejects a page render whose request aborted with an `AbortError`. When the response is gone by then, nobody is left to answer, so the server entry returns instead of passing the error to `next`, which would log it. Every other error still reaches `next`:
|
|
1447
|
+
|
|
1448
|
+
```ts
|
|
1449
|
+
if (response.destroyed && error instanceof DOMException && error.name === "AbortError") {
|
|
1450
|
+
return;
|
|
1451
|
+
}
|
|
1452
|
+
```
|
|
997
1453
|
|
|
998
1454
|
### Other server frameworks
|
|
999
1455
|
|
|
1000
|
-
`handleRequest` and `
|
|
1456
|
+
`handleRequest` and `createRequestScope` 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:
|
|
1001
1457
|
|
|
1002
1458
|
```ts
|
|
1003
1459
|
// src/server.ts
|
|
@@ -1007,7 +1463,7 @@ import { AngularNodeAppEngine, isMainModule } from "@angular/ssr/node";
|
|
|
1007
1463
|
import { serve } from "@hono/node-server";
|
|
1008
1464
|
import { serveStatic } from "@hono/node-server/serve-static";
|
|
1009
1465
|
import { Hono } from "hono";
|
|
1010
|
-
import {
|
|
1466
|
+
import { createRequestScope, handleRequest } from "../generated/server.generated";
|
|
1011
1467
|
|
|
1012
1468
|
const browser = fileURLToPath(new URL("../browser", import.meta.url));
|
|
1013
1469
|
// An explicit list stops Angular reading NG_ALLOWED_HOSTS, so read it here.
|
|
@@ -1024,7 +1480,7 @@ app.all("*", async (c) => {
|
|
|
1024
1480
|
return rpc;
|
|
1025
1481
|
}
|
|
1026
1482
|
|
|
1027
|
-
const scope =
|
|
1483
|
+
const scope = createRequestScope(c.req.raw);
|
|
1028
1484
|
const page = await angular.handle(scope.request, scope);
|
|
1029
1485
|
|
|
1030
1486
|
return page ?? c.notFound();
|
|
@@ -1051,33 +1507,35 @@ The [builders](#builders) run generation for you. Underneath, it's a Node functi
|
|
|
1051
1507
|
generate(workspace: string, options: GenerationOptions, stopped?: () => boolean): Promise<void>;
|
|
1052
1508
|
```
|
|
1053
1509
|
|
|
1054
|
-
| Option
|
|
1055
|
-
|
|
|
1056
|
-
| `tsconfig`
|
|
1057
|
-
| `scanDirectories`
|
|
1058
|
-
| `outDirectory`
|
|
1059
|
-
| `tanstackQuery`
|
|
1060
|
-
| `
|
|
1510
|
+
| Option | Type | Description |
|
|
1511
|
+
| ------------------- | -------------- | ---------------------------------------------------------------------------------------------------------- |
|
|
1512
|
+
| `tsconfig` | `string` | Your app tsconfig, relative to `workspace` |
|
|
1513
|
+
| `scanDirectories` | `string[]` | Exactly one route directory, relative to the tsconfig's directory |
|
|
1514
|
+
| `outDirectory` | `string` | Where the app-wide generated files go, relative to `workspace` |
|
|
1515
|
+
| `tanstackQuery` | `boolean` | Also add `route.queries`; see [TanStack Query](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-launch/tanstack-query/README.md) |
|
|
1516
|
+
| `translateSegments` | `boolean` | Translate static segments per Angular localize build; see [Translated URLs](#translated-urls) |
|
|
1517
|
+
| `localization` | `Localization` | The build's `i18n` and polyfills, required with `translateSegments`; the builders read it from the project |
|
|
1518
|
+
| `check` | `boolean` | Verify generated files without writing them; fails if anything is out of date |
|
|
1061
1519
|
|
|
1062
1520
|
`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.
|
|
1063
1521
|
|
|
1064
|
-
Generation reads your source without running it. It writes the router's files plus:
|
|
1522
|
+
Generation reads your source without running it. It writes the router's files, with Launch's additions, plus its own:
|
|
1065
1523
|
|
|
1066
|
-
| File | Contents
|
|
1067
|
-
| --------------------------------------- |
|
|
1068
|
-
| `
|
|
1069
|
-
| `<outDirectory>/
|
|
1070
|
-
| `<outDirectory>/
|
|
1524
|
+
| File | Contents |
|
|
1525
|
+
| --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1526
|
+
| `route.generated.ts` beside each route | The router's browser copy without the server steps, carrying the route's procedure metadata, `Remote`, `Context` and `remote` on `injectRoute()`; `Queries` and `queries` with `tanstackQuery` |
|
|
1527
|
+
| `<outDirectory>/server.generated.ts` | `createRequestScope`, `handleRequest`, `handleUpgrade` and `provideServer`, bound to every route with a server step |
|
|
1528
|
+
| `<outDirectory>/redirects.generated.ts` | With `translateSegments` only: `provideRedirectTranslation`, every static route word with the router's message for it |
|
|
1071
1529
|
|
|
1072
|
-
Each file
|
|
1530
|
+
Each file carries 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, including the `rpc.generated.ts` and `context.generated.d.ts` files an earlier Launch version wrote. 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.
|
|
1073
1531
|
|
|
1074
|
-
Before writing, generation type-checks the generated files, your route
|
|
1532
|
+
Before writing, generation type-checks the generated files, your route declarations, and any file that directly imports a generated file, using `skipLibCheck: false`. Other files are left to your Angular build.
|
|
1075
1533
|
|
|
1076
|
-
Generated browser code contains only names, kinds and error metadata, never your schemas,
|
|
1534
|
+
Generated browser code contains only names, kinds and error metadata, never your schemas, stages, middleware or handlers: a route copy drops the server steps and the imports only they used, and names their types through an erased `import type` of its own `route.ts`. Keep server-only modules out of anything a page imports at runtime; the example names them `*.server.ts`. Each route copy loads with the record that reads it: a top-level route's with `routes.generated.ts`, in the startup bundle, and a nested route's with its parent's lazily loaded children, as the router's [lazy route children](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-router/README.md#lazy-route-children) describes.
|
|
1077
1535
|
|
|
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
|
|
1536
|
+
`server.generated.ts` binds Launch's internal `bindApplication`, `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 and the generation tsconfig's and output directory's paths within the app, so neither route edits nor moving the whole app directory change it.
|
|
1079
1537
|
|
|
1080
|
-
RPC URLs are `/_rpc/<namespace>/<procedure>`, so they change only when you rename a namespace or procedure. Moving
|
|
1538
|
+
RPC URLs are `/_rpc/<namespace>/<procedure>`, so they change only when you rename a namespace or procedure. Moving a route 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.
|
|
1081
1539
|
|
|
1082
1540
|
`@loozo/angular-launch/generation` is Node-only.
|
|
1083
1541
|
|
|
@@ -1085,7 +1543,7 @@ RPC URLs are `/_rpc/<namespace>/<procedure>`, so they change only when you renam
|
|
|
1085
1543
|
|
|
1086
1544
|
#### `@loozo/angular-launch:application`
|
|
1087
1545
|
|
|
1088
|
-
All `@angular/build:application` options, plus the generation options above (`tsconfig`, `scanDirectories`, `outDirectory`, `tanstackQuery` and `check`, which default to `false`). It takes those out and passes every other option through unchanged.
|
|
1546
|
+
All `@angular/build:application` options, plus the generation options above (`tsconfig`, `scanDirectories`, `outDirectory`, and `tanstackQuery`, `translateSegments` and `check`, which default to `false`). It takes those out and passes every other option through unchanged. With `translateSegments`, it reads `localization` from the project's `i18n` and the build's `polyfills`, so it must run as a project target.
|
|
1089
1547
|
|
|
1090
1548
|
The builder runs generation once, then the official application build. Invalid options stop the build before generation starts. Generation errors, including drift with `check: true`, are logged and fail the build before the Angular build runs. `watch: true` is rejected; use the serve builder for watching.
|
|
1091
1549
|
|
|
@@ -1100,7 +1558,7 @@ All `@angular/build:dev-server` options, set in `angular.json` or on the command
|
|
|
1100
1558
|
|
|
1101
1559
|
Invalid options stop the serve builder before it generates anything, and so does an invalid build target. The build target must not resolve `check: true`, because serving always writes generated files. The initial generation must succeed before the dev server starts; if it fails, the error is logged and the builder reports a failed build.
|
|
1102
1560
|
|
|
1103
|
-
The builder then watches the scan directory and
|
|
1561
|
+
The builder then watches the scan directory, and with `translateSegments` the catalogs too, 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. Other files, such as a server module a stage imports, don't trigger generation: route copies name their types through their route's declaration, not as text, so there's nothing to regenerate, and Angular's build still checks them. A route edit rebuilds twice, once for the edit and once for its regenerated copy, so the first reload can briefly pair new server code with the old copy.
|
|
1104
1562
|
|
|
1105
1563
|
Polling is on by default because Angular 22.2.2's native file watcher misses edits to files inside a renamed directory, which leaves the dev server serving stale output. It costs some idle CPU. Set `"poll": false` in the serve target to go back to native file events; Angular's own configuration then applies, including a `poll` on the build target. A positive number overrides the build target's `poll`; `0` is rejected. On the command line, `--poll` accepts milliseconds only. `poll` configures Angular's dev-server watcher; Launch's own watcher uses native file events.
|
|
1106
1564
|
|
|
@@ -1131,22 +1589,24 @@ The options are fixed when the session is created. Edits inside the app, includi
|
|
|
1131
1589
|
|
|
1132
1590
|
## Limitations
|
|
1133
1591
|
|
|
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
|
|
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
|
|
1592
|
+
- 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.
|
|
1593
|
+
- Beyond hydration, the only query cache is TanStack Query's, through the optional [integration](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/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.1.0/packages/angular-launch/tanstack-query/README.md#optimistic-updates); Launch adds no helpers for them. Without it, nothing is invalidated for you.
|
|
1136
1594
|
- No storage adapters; persistence is your handler's job.
|
|
1137
1595
|
- 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
|
|
1596
|
+
- No success status other than 200: a result is always 200, and other statuses come from failures and outcomes. During server rendering, a cookie set by one call isn't visible to later calls in the same render, a failed initial navigation loses the render's cookies, and headers are dropped.
|
|
1139
1597
|
- Aborting is advisory: handlers get a `signal`, but work that ignores it finishes, a write may already have committed, and nothing is rolled back.
|
|
1140
1598
|
- Middleware is server-side only: there's no client middleware (use an Angular HTTP interceptor), and no dedupe of middleware listed twice.
|
|
1141
|
-
- Redirects
|
|
1142
|
-
-
|
|
1599
|
+
- Redirects go to declared destinations only: an external destination, such as an OAuth provider, is data your page acts on, and a redirect target's search keys must be declared on its route. Outcomes act only in navigation, through `rpcNavigationErrors`, and nothing maps `FORBIDDEN` to a page: a stage that guards a page's reads throws `redirect()` or `notFound()` instead.
|
|
1600
|
+
- A route can't opt out of its ancestors' stages, and a stage's failure fails every later call in the same request scope, such as the rest of a server render.
|
|
1601
|
+
- An active-route handle's `remote` and `queries` use the `injectActiveRoute()` caller's injector, so providers a route adds reach only its own `injectRoute()`.
|
|
1602
|
+
- Middleware written inline in `.use()` doesn't infer the route's context type; give it the keys it reads.
|
|
1143
1603
|
|
|
1144
1604
|
## Further reading
|
|
1145
1605
|
|
|
1146
|
-
- [TanStack Query](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0
|
|
1147
|
-
- [`
|
|
1148
|
-
- [`examples/angular-launch`](https://github.com/theo-matzavinos/loozo/tree/angular-launch@0.0
|
|
1149
|
-
- [`@loozo/angular-router`](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0
|
|
1606
|
+
- [TanStack Query](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-launch/tanstack-query/README.md): the optional query and mutation integration
|
|
1607
|
+
- [`SPEC.md`](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-launch/SPEC.md): the full contract, including every edge case
|
|
1608
|
+
- [`examples/angular-launch`](https://github.com/theo-matzavinos/loozo/tree/angular-launch@0.1.0/examples/angular-launch): the todos app. Its cookie identity and in-memory database are test fixtures, not security or deployment guidance.
|
|
1609
|
+
- [`@loozo/angular-router`](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-router/README.md): routes, codecs and navigation
|
|
1150
1610
|
|
|
1151
1611
|
## Developing this package
|
|
1152
1612
|
|