@loozo/angular-launch 0.0.5 → 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 +1068 -187
- 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 +55 -0
- package/channel.js +232 -0
- package/client.d.ts +63 -33
- package/connect.d.ts +201 -0
- package/connect.js +148 -0
- package/generation/index.d.ts +2 -123
- package/generation/index.js +3 -669
- 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 +8 -1
- package/index.js +3 -0
- package/json.d.ts +9 -0
- package/json.js +24 -0
- package/launch-queries.d.ts +16 -0
- package/launch-queries.js +3 -0
- package/navigation.d.ts +36 -0
- package/navigation.js +47 -0
- package/node/index.d.ts +60 -0
- package/node/index.js +178 -0
- package/node/upgrade-listener-slot.d.ts +1 -0
- package/node/upgrade-listener-slot.js +4 -0
- package/outcomes.d.ts +71 -0
- package/outcomes.js +146 -0
- package/package.json +21 -11
- package/redirect-translation.d.ts +53 -0
- package/redirect-translation.js +141 -0
- package/{generated.d.ts → remote-client.d.ts} +1 -1
- package/remote-client.js +179 -0
- 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 +62 -31
- package/server/backend.js +149 -55
- package/server/channel-messages.d.ts +54 -0
- package/server/channel-messages.js +84 -0
- package/server/channel-socket.d.ts +67 -0
- package/server/channel-socket.js +322 -0
- package/server/definitions.d.ts +270 -294
- package/server/definitions.js +35 -115
- package/server/dispatch.d.ts +121 -66
- package/server/dispatch.js +267 -87
- package/server/event-stream.d.ts +63 -0
- package/server/event-stream.js +173 -0
- package/server/generated.d.ts +3 -1
- package/server/generated.js +3 -1
- package/server/index.d.ts +6 -3
- package/server/index.js +3 -2
- package/server/outcomes.d.ts +64 -2
- package/server/outcomes.js +85 -4
- package/server/read-cookies.d.ts +19 -0
- package/server/read-cookies.js +39 -0
- package/server/response-effects.d.ts +105 -0
- package/server/response-effects.js +78 -0
- package/server/stages.d.ts +62 -0
- package/server/stages.js +51 -0
- package/server/upgrade.d.ts +57 -0
- package/server/upgrade.js +116 -0
- package/source-text.d.ts +1 -0
- package/source-text.js +56 -0
- package/stream.d.ts +34 -0
- package/stream.js +161 -0
- package/tanstack-query/README.md +113 -21
- package/tanstack-query/create-queries.d.ts +2 -0
- package/tanstack-query/{generated.js → create-queries.js} +13 -11
- 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 +50 -33
- 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/generated.js +0 -90
- package/generation/context-file.d.ts +0 -2
- package/generation/context-file.js +0 -3
- package/tanstack-query/generated.d.ts +0 -5
package/tanstack-query/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# TanStack Query
|
|
2
2
|
|
|
3
|
-
`@loozo/angular-launch/tanstack-query` connects Launch procedures to [TanStack Query for Angular](https://tanstack.com/query/latest/docs/framework/angular/overview) (`@tanstack/angular-query`). Generation
|
|
3
|
+
`@loozo/angular-launch/tanstack-query` connects Launch procedures to [TanStack Query for Angular](https://tanstack.com/query/latest/docs/framework/angular/overview) (`@tanstack/angular-query`). Generation adds typed query and mutation options and keys to your routes' handles, and server-rendered query data reaches the browser through TanStack's own hydration, with no request on load even with `staleTime: 0`.
|
|
4
4
|
|
|
5
5
|
It's optional. Without it, Launch never imports TanStack.
|
|
6
6
|
|
|
@@ -23,7 +23,7 @@ Turn on the `tanstackQuery` generation option in your `@loozo/angular-launch:app
|
|
|
23
23
|
}
|
|
24
24
|
```
|
|
25
25
|
|
|
26
|
-
Each
|
|
26
|
+
Each route's handle then also has `queries`, and its `route.generated.ts` exports its type `Queries`, for the same namespaces as `remote`. With the option off, route copies have neither and don't import this entry point.
|
|
27
27
|
|
|
28
28
|
Add TanStack's provider and `provideLaunchQueries()` to the application's providers, which the server config inherits:
|
|
29
29
|
|
|
@@ -48,27 +48,27 @@ export const config: ApplicationConfig = {
|
|
|
48
48
|
};
|
|
49
49
|
```
|
|
50
50
|
|
|
51
|
-
Pass `provideTanStackQuery` a factory, as above, not a shared client: the factory runs once per application, so every server render gets its own cache and one user's data never reaches another's page. `provideLaunchQueries()` belongs in the application's providers, not a route's or component's. `
|
|
51
|
+
Pass `provideTanStackQuery` a factory, as above, not a shared client: the factory runs once per application, so every server render gets its own cache and one user's data never reaches another's page. `provideLaunchQueries()` belongs in the application's providers, not a route's or component's. Reading `route.queries` throws without it; `route.remote` doesn't need it.
|
|
52
52
|
|
|
53
53
|
## Queries and mutations
|
|
54
54
|
|
|
55
|
-
|
|
55
|
+
Read `queries` from the route's handle and pass its options to TanStack. Like `remote`, it's built on first read with the handle's injector, so reading it later, outside an injection context, is fine:
|
|
56
56
|
|
|
57
57
|
```ts
|
|
58
58
|
// src/routes/+authenticated/todos/page.ts
|
|
59
59
|
import { Component, inject } from "@angular/core";
|
|
60
60
|
import { injectMutation, injectQuery, QueryClient } from "@tanstack/angular-query";
|
|
61
|
-
import {
|
|
61
|
+
import { injectRoute } from "./route.generated";
|
|
62
62
|
|
|
63
63
|
@Component({/* … */})
|
|
64
64
|
export default class Todos {
|
|
65
|
-
readonly #
|
|
66
|
-
readonly #queries = injectQueries();
|
|
65
|
+
readonly #route = injectRoute();
|
|
67
66
|
readonly #client = inject(QueryClient);
|
|
68
|
-
readonly todos = injectQuery(() => this.#queries.todos.list.queryOptions());
|
|
67
|
+
readonly todos = injectQuery(() => this.#route.queries.todos.list.queryOptions());
|
|
69
68
|
readonly #complete = injectMutation(() =>
|
|
70
|
-
this.#queries.todos.complete.mutationOptions({
|
|
71
|
-
onSuccess: () =>
|
|
69
|
+
this.#route.queries.todos.complete.mutationOptions({
|
|
70
|
+
onSuccess: () =>
|
|
71
|
+
this.#client.invalidateQueries({ queryKey: this.#route.queries.todos.$key() }),
|
|
72
72
|
}),
|
|
73
73
|
);
|
|
74
74
|
|
|
@@ -76,7 +76,7 @@ export default class Todos {
|
|
|
76
76
|
try {
|
|
77
77
|
await this.#complete.mutateAsync({ id });
|
|
78
78
|
} catch (error) {
|
|
79
|
-
if (this.#
|
|
79
|
+
if (this.#route.remote.todos.complete.isError(error) && error.code === "NOT_FOUND") {
|
|
80
80
|
const missingId: string = error.data.id;
|
|
81
81
|
}
|
|
82
82
|
}
|
|
@@ -116,7 +116,7 @@ Full query keys are tagged with the procedure's output type, so `client.getQuery
|
|
|
116
116
|
|
|
117
117
|
## Invalidation
|
|
118
118
|
|
|
119
|
-
|
|
119
|
+
Launch invalidates nothing itself; TanStack does, with the keys above. Invalidate in a mutation's `onSuccess`, by namespace, procedure or input:
|
|
120
120
|
|
|
121
121
|
```ts
|
|
122
122
|
onSuccess: () => client.invalidateQueries({ queryKey: queries.todos.$key() }),
|
|
@@ -129,7 +129,96 @@ onSuccess: () =>
|
|
|
129
129
|
client.invalidateQueries({ queryKey: queries.todos.$key() }, { throwOnError: true }),
|
|
130
130
|
```
|
|
131
131
|
|
|
132
|
-
`mutateAsync` then rejects with the refetch's error, although the write itself succeeded.
|
|
132
|
+
`mutateAsync` then rejects with the refetch's error, although the write itself succeeded, and TanStack runs the mutation's `onError` for it. Don't combine this with an [optimistic update](#optimistic-updates): its rollback would undo a write that succeeded.
|
|
133
|
+
|
|
134
|
+
### After every write
|
|
135
|
+
|
|
136
|
+
To read every Launch query on screen again after any write, give the `QueryClient` a `MutationCache`, as the example does:
|
|
137
|
+
|
|
138
|
+
```ts
|
|
139
|
+
provideTanStackQuery(() => {
|
|
140
|
+
// Writes whose onSettled has run: their server call is done.
|
|
141
|
+
const settled = new WeakSet<object>();
|
|
142
|
+
|
|
143
|
+
return new QueryClient({
|
|
144
|
+
mutationCache: new MutationCache({
|
|
145
|
+
onSettled: (_data, _error, _input, _result, mutation, { client }) => {
|
|
146
|
+
settled.add(mutation);
|
|
147
|
+
|
|
148
|
+
const unsettled = client.getMutationCache().findAll({
|
|
149
|
+
mutationKey: ["launch"],
|
|
150
|
+
status: "pending",
|
|
151
|
+
predicate: (other) => !settled.has(other),
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
// A write still on its way reads for this one when it settles.
|
|
155
|
+
if (unsettled.length > 0) {
|
|
156
|
+
return undefined;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
return client.invalidateQueries({ queryKey: ["launch"] });
|
|
160
|
+
},
|
|
161
|
+
}),
|
|
162
|
+
});
|
|
163
|
+
}),
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
- Every Launch key starts with `"launch"`, so this matches every Launch query and mutation, of every namespace, and nothing else in the cache. Only active queries, ones a component observes, refetch; the others are marked stale and refetch when they next mount.
|
|
167
|
+
- `onSettled` also runs after a failed write, which can still mean the data changed: a declared `NOT_FOUND` for a todo deleted elsewhere does.
|
|
168
|
+
- TanStack awaits the cache's callbacks, before the mutation's own, so the mutation stays pending until the read finishes.
|
|
169
|
+
- Skipping while another write is still on its way keeps an earlier write's read from replacing a later write's optimistic data, and the last write reads once for all. Count only writes that haven't reached `onSettled`: a mutation stays pending until its callbacks finish, so with `isMutating() > 1` two writes that settle together, in different scopes, each see the other and both skip the read.
|
|
170
|
+
- Don't pass `throwOnError` here, for the reason above. To tell the user the read failed, show the query's own error next to its data: `todos.isError()` while `todos.data()` is still there.
|
|
171
|
+
|
|
172
|
+
## Optimistic updates
|
|
173
|
+
|
|
174
|
+
Launch adds nothing here either: TanStack's `onMutate` and `onError` work on the generated options, typed by the procedure. The [todos example](https://github.com/theo-matzavinos/loozo/blob/main/examples/angular-launch/src/routes/+authenticated/todos/page.ts) completes and deletes todos this way:
|
|
175
|
+
|
|
176
|
+
```ts
|
|
177
|
+
const key = queries.todos.list.key();
|
|
178
|
+
|
|
179
|
+
injectMutation(() =>
|
|
180
|
+
queries.todos.complete.mutationOptions({
|
|
181
|
+
scope: { id: "todos" },
|
|
182
|
+
onMutate: async ({ id }, { client }) => {
|
|
183
|
+
// A read in flight would replace the optimistic data when it lands.
|
|
184
|
+
await client.cancelQueries({ queryKey: key });
|
|
185
|
+
|
|
186
|
+
const before = client.getQueryData(key)?.todos.find((todo) => todo.id === id);
|
|
187
|
+
|
|
188
|
+
client.setQueryData(key, (list) => markCompleted(list, id));
|
|
189
|
+
|
|
190
|
+
return { before };
|
|
191
|
+
},
|
|
192
|
+
onError: (error, { id }, result, { client }) => {
|
|
193
|
+
// The server says it's gone: show that instead of the todo as it was.
|
|
194
|
+
if (rpc.todos.complete.isError(error) && error.code === "NOT_FOUND") {
|
|
195
|
+
client.setQueryData(key, (list) => withoutTodo(list, id));
|
|
196
|
+
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const before = result?.before;
|
|
201
|
+
|
|
202
|
+
if (before !== undefined) {
|
|
203
|
+
client.setQueryData(key, (list) => withTodo(list, before));
|
|
204
|
+
}
|
|
205
|
+
},
|
|
206
|
+
}),
|
|
207
|
+
);
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
`markCompleted`, `withoutTodo` and `withTodo` stand for updates of your procedure's output; the example's are on its page. The list is read again by the [`MutationCache` above](#after-every-write), or by your own `onSettled`.
|
|
211
|
+
|
|
212
|
+
- The key is tagged with the procedure's output, so `getQueryData` and `setQueryData` are typed, and `onMutate`'s result reaches `onError` typed, without annotations. `context.client` is the `QueryClient`.
|
|
213
|
+
- `cancelQueries` aborts the query's HTTP request, since generated queries pass TanStack's `signal`, so the handler sees its `signal` abort.
|
|
214
|
+
- The declared errors decide the rollback. The rejection is the callable's own, so `isError` recognizes the write's declared errors and framework codes, and nothing else: not a failed read of the list. Anything it doesn't recognize, such as a network failure, leaves the write's outcome unknown; restore the row and let the read tell.
|
|
215
|
+
- Undo the row you changed, not a snapshot of the whole list: with two writes pending, restoring the first's snapshot would also undo the second's change.
|
|
216
|
+
- Mutations with the same `scope` id reach the server one at a time, in order. TanStack still runs each `onMutate` at once, so the page shows every pending write.
|
|
217
|
+
- Don't let two pending writes change the same row: the second's `onMutate` saves the first's optimistic row, and if both fail, its rollback restores that. The example disables a row's controls while a write to it is pending.
|
|
218
|
+
- A read that starts while a write is pending replaces its optimistic data with the server's older state. The example disables Refresh while any write is pending. A refetch on window focus can do the same; the read after the last write corrects it.
|
|
219
|
+
- During server rendering, mutations are refused with `FORBIDDEN`, so none of this runs. A click made before the app hydrates is replayed by Angular's event replay, which `provideClientHydration()` turns on with incremental hydration, and the write then runs as above. Until then there's no feedback.
|
|
220
|
+
|
|
221
|
+
For an add, which needs the id the server gives it, TanStack's other approach fits better: render the pending mutation's `variables()` instead of writing to the cache.
|
|
133
222
|
|
|
134
223
|
## Server rendering and hydration
|
|
135
224
|
|
|
@@ -144,21 +233,24 @@ The limits follow from TanStack's hydration:
|
|
|
144
233
|
- Only successful queries reach the browser. A query that fails during server rendering, with a declared error or a framework code, runs again over HTTP in the browser, with a fresh context. The handler runs twice, and the page shows whatever the second call returns.
|
|
145
234
|
- Queries are part of the HTML: only return data the user may see, and serve personalized pages with `Cache-Control: private, no-store`.
|
|
146
235
|
- Mutations are refused during server rendering with `FORBIDDEN`, as for direct calls.
|
|
147
|
-
-
|
|
236
|
+
- A query that rejects with `RpcRedirect` or `RpcNotFound` doesn't navigate: only guards and resolvers do, through [`rpcNavigationErrors`](../README.md#navigating-on-outcomes). Read the error and act on it in the page.
|
|
237
|
+
- A prerendered page dehydrates its queries like a server-rendered one, from an anonymous context; a query that fails while prerendering fails the build, as for direct calls. See [Prerendering](../README.md#prerendering).
|
|
148
238
|
|
|
149
239
|
## Defaults
|
|
150
240
|
|
|
151
|
-
| Option | Default
|
|
152
|
-
| ---------------- |
|
|
153
|
-
| `retry` | No retry for an `RpcError` (a framework failure or declared error)
|
|
154
|
-
| `refetchOnMount` | `false` while hydrating; then your `QueryClient` default for the key, or `true`
|
|
241
|
+
| Option | Default |
|
|
242
|
+
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
243
|
+
| `retry` | No retry for an `RpcError` (a framework failure or declared error), an `RpcRedirect` or an `RpcNotFound`; for anything else, your `QueryClient` default for the key, or three retries |
|
|
244
|
+
| `refetchOnMount` | `false` while hydrating; then your `QueryClient` default for the key, or `true` |
|
|
155
245
|
|
|
156
|
-
Everything else is TanStack's or your `QueryClient`'s. Overrides replace either default per call. Your `QueryClient` defaults still apply through them: a default `retry` decides retries for errors other than
|
|
246
|
+
Everything else is TanStack's or your `QueryClient`'s. Overrides replace either default per call. Your `QueryClient` defaults still apply through them: a default `retry` decides retries for errors other than those three, and a default `refetchOnMount` applies after hydration. On the server, TanStack's adapter defaults `retry` to `false`, so a failed query doesn't retry during server rendering.
|
|
157
247
|
|
|
158
248
|
## Limitations
|
|
159
249
|
|
|
160
|
-
- No infinite queries,
|
|
250
|
+
- No infinite queries, mutation cancellation or persistence. Optimistic updates and invalidation are TanStack's, as [above](#invalidation): Launch adds no helpers for them.
|
|
251
|
+
- No options for [streams](../README.md#calling-streams): `route.queries` leaves them out. TanStack's `streamedQuery` keeps a query fetching until its stream ends, and the Angular adapter keeps the app from becoming stable while a query is fetching, which would hold hydration open as long as the stream runs. It's also still `experimental_streamedQuery` in query-core 5.104. Follow the stream with [`connect()`](../README.md#following-streams-and-channels-with-connect) instead.
|
|
252
|
+
- No options for [channels](../README.md#calling-channels) either, for the same reasons; use `connect()`.
|
|
253
|
+
- A narrowed active-route handle's `queries` uses the `QueryClient` of the `injectActiveRoute()` caller, not one a route provides: a route-level `QueryClient` reaches only that route's own `injectRoute()`.
|
|
161
254
|
- Errors aren't dehydrated: a failed server query runs again in the browser.
|
|
162
255
|
- Only `@tanstack/angular-query`, not `@tanstack/angular-query-experimental`.
|
|
163
256
|
- No special handling for `@defer`: queries in a deferred block follow the same window, so ones that mount after the app is stable refetch when stale.
|
|
164
|
-
- TanStack also exports an `injectQueries` (for running several queries); import one of the two under another name if you need both in a file.
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { inject } from "@angular/core";
|
|
2
2
|
import { QueryClient, skipToken } from "@tanstack/angular-query";
|
|
3
3
|
import { RpcError } from "../client.js";
|
|
4
|
-
import {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
4
|
+
import { RpcNotFound, RpcRedirect } from "../outcomes.js";
|
|
5
|
+
import { hydrationWindow } from "./hydration-window.js";
|
|
6
|
+
// Builds a route's `queries` over its `remote` client. `route.queries` calls it in the
|
|
7
|
+
// handle creator's injection context, once it checked that `provideLaunchQueries()`, which
|
|
8
|
+
// provides both tokens, is there.
|
|
9
|
+
export const createQueries = (rpc, namespaces) => {
|
|
10
|
+
const hydration = inject(hydrationWindow);
|
|
11
11
|
const client = inject(QueryClient);
|
|
12
12
|
// An arrow function keeps the null check's narrowing; a function declaration is hoisted.
|
|
13
13
|
const refetchOnMount = (query) => {
|
|
@@ -28,10 +28,12 @@ export function createQueries(rpc, groups) {
|
|
|
28
28
|
return fallback;
|
|
29
29
|
};
|
|
30
30
|
// Resolved per call, in query-core's merge order, so the client's default (the adapter's
|
|
31
|
-
// `false` on the server) applies to everything but
|
|
31
|
+
// `false` on the server) applies to everything but the server's answers.
|
|
32
32
|
function retryFor(queryKey) {
|
|
33
33
|
return (failures, error) => {
|
|
34
|
-
if (error instanceof RpcError
|
|
34
|
+
if (error instanceof RpcError ||
|
|
35
|
+
error instanceof RpcRedirect ||
|
|
36
|
+
error instanceof RpcNotFound) {
|
|
35
37
|
return false;
|
|
36
38
|
}
|
|
37
39
|
const defaults = {
|
|
@@ -52,7 +54,7 @@ export function createQueries(rpc, groups) {
|
|
|
52
54
|
};
|
|
53
55
|
}
|
|
54
56
|
const result = Object.create(null);
|
|
55
|
-
for (const [namespace, methods] of Object.entries(
|
|
57
|
+
for (const [namespace, methods] of Object.entries(namespaces)) {
|
|
56
58
|
const group = Object.create(null);
|
|
57
59
|
group["$key"] = () => ["launch", namespace];
|
|
58
60
|
for (const [name, method] of Object.entries(methods)) {
|
|
@@ -124,4 +126,4 @@ export function createQueries(rpc, groups) {
|
|
|
124
126
|
result[namespace] = group;
|
|
125
127
|
}
|
|
126
128
|
return result;
|
|
127
|
-
}
|
|
129
|
+
};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { InjectionToken } from "@angular/core";
|
|
2
|
+
/**
|
|
3
|
+
* Whether the app is still hydrating: open in the browser from bootstrap until the app is
|
|
4
|
+
* first stable, never open on the server.
|
|
5
|
+
*
|
|
6
|
+
* @remarks
|
|
7
|
+
* Internal; provided by `provideLaunchQueries()` and read by route query options.
|
|
8
|
+
*/
|
|
9
|
+
export declare const hydrationWindow: InjectionToken<{
|
|
10
|
+
open: boolean;
|
|
11
|
+
}>;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { InjectionToken } from "@angular/core";
|
|
2
|
+
/**
|
|
3
|
+
* Whether the app is still hydrating: open in the browser from bootstrap until the app is
|
|
4
|
+
* first stable, never open on the server.
|
|
5
|
+
*
|
|
6
|
+
* @remarks
|
|
7
|
+
* Internal; provided by `provideLaunchQueries()` and read by route query options.
|
|
8
|
+
*/
|
|
9
|
+
export const hydrationWindow = new InjectionToken("Launch hydration window");
|
|
@@ -1,23 +1,13 @@
|
|
|
1
|
-
import { InjectionToken } from "@angular/core";
|
|
2
1
|
import type { EnvironmentProviders } from "@angular/core";
|
|
3
2
|
/**
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* @remarks
|
|
8
|
-
* Internal; provided by {@link provideLaunchQueries} and read by generated query options.
|
|
9
|
-
*/
|
|
10
|
-
export declare const hydrationWindow: InjectionToken<{
|
|
11
|
-
open: boolean;
|
|
12
|
-
}>;
|
|
13
|
-
/**
|
|
14
|
-
* Provides what generated `injectQueries()` functions need: the app's hydration window.
|
|
3
|
+
* Provides what route handles' `queries` need: the TanStack factories and the app's
|
|
4
|
+
* hydration window.
|
|
15
5
|
*
|
|
16
6
|
* @remarks
|
|
17
7
|
* Add it to the application's providers next to TanStack's `provideTanStackQuery(...)`,
|
|
18
|
-
* not to a route or component. `
|
|
8
|
+
* not to a route or component. Reading `route.queries` throws without it.
|
|
19
9
|
*
|
|
20
|
-
* In the browser,
|
|
10
|
+
* In the browser, query options don't refetch on mount while the app hydrates,
|
|
21
11
|
* from bootstrap until the app is first stable, so data dehydrated during server rendering
|
|
22
12
|
* is used as is even with `staleTime: 0`. After that, `refetchOnMount` follows your
|
|
23
13
|
* `QueryClient` defaults. This is the same window Angular's HTTP transfer cache uses.
|
|
@@ -1,21 +1,17 @@
|
|
|
1
1
|
import { isPlatformBrowser } from "@angular/common";
|
|
2
|
-
import { APP_BOOTSTRAP_LISTENER, ApplicationRef, inject,
|
|
2
|
+
import { APP_BOOTSTRAP_LISTENER, ApplicationRef, inject, makeEnvironmentProviders, PLATFORM_ID, } from "@angular/core";
|
|
3
|
+
import { launchQueries } from "../launch-queries.js";
|
|
4
|
+
import { createQueries } from "./create-queries.js";
|
|
5
|
+
import { hydrationWindow } from "./hydration-window.js";
|
|
3
6
|
/**
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* @remarks
|
|
8
|
-
* Internal; provided by {@link provideLaunchQueries} and read by generated query options.
|
|
9
|
-
*/
|
|
10
|
-
export const hydrationWindow = new InjectionToken("Launch hydration window");
|
|
11
|
-
/**
|
|
12
|
-
* Provides what generated `injectQueries()` functions need: the app's hydration window.
|
|
7
|
+
* Provides what route handles' `queries` need: the TanStack factories and the app's
|
|
8
|
+
* hydration window.
|
|
13
9
|
*
|
|
14
10
|
* @remarks
|
|
15
11
|
* Add it to the application's providers next to TanStack's `provideTanStackQuery(...)`,
|
|
16
|
-
* not to a route or component. `
|
|
12
|
+
* not to a route or component. Reading `route.queries` throws without it.
|
|
17
13
|
*
|
|
18
|
-
* In the browser,
|
|
14
|
+
* In the browser, query options don't refetch on mount while the app hydrates,
|
|
19
15
|
* from bootstrap until the app is first stable, so data dehydrated during server rendering
|
|
20
16
|
* is used as is even with `staleTime: 0`. After that, `refetchOnMount` follows your
|
|
21
17
|
* `QueryClient` defaults. This is the same window Angular's HTTP transfer cache uses.
|
|
@@ -43,6 +39,7 @@ export const hydrationWindow = new InjectionToken("Launch hydration window");
|
|
|
43
39
|
*/
|
|
44
40
|
export function provideLaunchQueries() {
|
|
45
41
|
return makeEnvironmentProviders([
|
|
42
|
+
{ provide: launchQueries, useValue: createQueries },
|
|
46
43
|
{
|
|
47
44
|
provide: hydrationWindow,
|
|
48
45
|
useFactory: () => ({ open: isPlatformBrowser(inject(PLATFORM_ID)) }),
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export { provideLaunchQueries } from "./hydration.js";
|
|
2
|
-
export type {
|
|
2
|
+
export type { NamespaceQueries, QueriesOf } from "./queries.js";
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import type { CreateMutationOptions, DataTag, QueryKeyWithDataTag, SkipToken, UndefinedInitialDataOptions } from "@tanstack/angular-query";
|
|
2
|
-
import type {
|
|
3
|
-
type
|
|
2
|
+
import type { ContributionOf } from "@loozo/angular-router/_core";
|
|
3
|
+
import type { ChainNamespaces } from "../route-types.js";
|
|
4
|
+
import type { Procedure, Schema } from "../server/definitions.js";
|
|
5
|
+
type NamespaceKey<Namespace> = readonly ["launch", Namespace];
|
|
4
6
|
type ProcedureKey<Namespace, Name> = readonly ["launch", Namespace, Name];
|
|
5
7
|
type InputKey<Namespace, Name, Input> = readonly ["launch", Namespace, Name, Input];
|
|
6
8
|
type QueryOverrides<Output, Data, Key extends readonly unknown[]> = Omit<UndefinedInitialDataOptions<Output, unknown, Data, Key>, "queryKey" | "queryFn">;
|
|
@@ -79,46 +81,61 @@ type MutationProcedure<Namespace, Name, Input, Output> = {
|
|
|
79
81
|
key(): ProcedureKey<Namespace, Name>;
|
|
80
82
|
};
|
|
81
83
|
type Variables<Input> = Input extends Schema<infer Caller, unknown> ? Caller : void;
|
|
82
|
-
type ProcedureQueries<Namespace, Name, Value> = Value extends Procedure<infer Input, infer Output, infer Kind, infer _Errors> ? Kind extends "query" ? QueryProcedure<Namespace, Name, Input, Awaited<Output>> : MutationProcedure<Namespace, Name, Input, Awaited<Output>> : never;
|
|
84
|
+
type ProcedureQueries<Namespace, Name, Value> = Value extends Procedure<infer Input, infer Output, infer Kind, infer _Errors, infer _Message> ? Kind extends "query" ? QueryProcedure<Namespace, Name, Input, Awaited<Output>> : MutationProcedure<Namespace, Name, Input, Awaited<Output>> : never;
|
|
83
85
|
/**
|
|
84
|
-
* The TanStack Query factories for
|
|
85
|
-
* procedure, plus the
|
|
86
|
+
* The TanStack Query factories for one `.remote()` namespace: query or mutation options and
|
|
87
|
+
* keys per procedure, plus the namespace's key.
|
|
86
88
|
*
|
|
87
89
|
* @remarks
|
|
88
|
-
*
|
|
89
|
-
*
|
|
90
|
-
*
|
|
91
|
-
*
|
|
92
|
-
*
|
|
93
|
-
*
|
|
94
|
-
* typed `unknown`: narrow them with the callable's `isError`.
|
|
90
|
+
* Keys are `["launch", namespace]` for the namespace, `["launch", namespace, procedure]`
|
|
91
|
+
* for a procedure and `["launch", namespace, procedure, input]` for one input, so
|
|
92
|
+
* invalidating a shorter key also invalidates the longer ones under it. Queries call the
|
|
93
|
+
* procedure with the query's `signal` and `transferCache: false`, since TanStack transfers
|
|
94
|
+
* the data itself. Errors are typed `unknown`: narrow them with the callable's `isError`.
|
|
95
|
+
* Streams and channels have no factories.
|
|
95
96
|
*
|
|
96
|
-
* Query options default `retry` to never for an `RpcError
|
|
97
|
-
* default, or three retries, for anything else,
|
|
98
|
-
* app hydrates and to your `QueryClient`
|
|
99
|
-
* either default.
|
|
97
|
+
* Query options default `retry` to never for an `RpcError`, `RpcRedirect` or
|
|
98
|
+
* `RpcNotFound` and to your `QueryClient` default, or three retries, for anything else,
|
|
99
|
+
* and `refetchOnMount` to `false` while the app hydrates and to your `QueryClient`
|
|
100
|
+
* default, or `true`, after. Overrides replace either default.
|
|
100
101
|
*
|
|
101
|
-
* @
|
|
102
|
-
*
|
|
103
|
-
* import { injectQueries } from "./rpc.generated";
|
|
104
|
-
*
|
|
105
|
-
* const queries = injectQueries();
|
|
106
|
-
*
|
|
107
|
-
* injectQuery(() => queries.todos.list.queryOptions());
|
|
108
|
-
* injectMutation(() => queries.todos.add.mutationOptions());
|
|
109
|
-
* client.invalidateQueries({ queryKey: queries.todos.$key() });
|
|
110
|
-
* ```
|
|
111
|
-
*
|
|
112
|
-
* @typeParam Value - A group created by `defineRpc`.
|
|
102
|
+
* @typeParam Namespace - The namespace's name.
|
|
103
|
+
* @typeParam Procedures - Its procedures, keyed by name, as `.remote()` returns them.
|
|
113
104
|
*/
|
|
114
|
-
export type
|
|
105
|
+
export type NamespaceQueries<Namespace, Procedures> = {
|
|
115
106
|
/**
|
|
116
|
-
* The key of every query and mutation of the
|
|
107
|
+
* The key of every query and mutation of the namespace.
|
|
117
108
|
*
|
|
118
109
|
* @returns `["launch", namespace]`.
|
|
119
110
|
*/
|
|
120
|
-
$key():
|
|
111
|
+
$key(): NamespaceKey<Namespace>;
|
|
121
112
|
} & {
|
|
122
|
-
readonly [Name in keyof Procedures
|
|
123
|
-
|
|
113
|
+
readonly [Name in keyof Procedures as Procedures[Name] extends {
|
|
114
|
+
readonly kind: "stream" | "channel";
|
|
115
|
+
} ? never : Name]: ProcedureQueries<Namespace, Name, Procedures[Name]>;
|
|
116
|
+
};
|
|
117
|
+
/**
|
|
118
|
+
* A route's TanStack Query factories: one {@link NamespaceQueries} per namespace the route
|
|
119
|
+
* can see, its own and its ancestors'.
|
|
120
|
+
*
|
|
121
|
+
* @remarks
|
|
122
|
+
* The type of `route.queries` and of the `Queries` a route copy exports, which generation
|
|
123
|
+
* writes when its `tanstackQuery` option is on.
|
|
124
|
+
*
|
|
125
|
+
* @example
|
|
126
|
+
* ```ts
|
|
127
|
+
* readonly route = injectRoute();
|
|
128
|
+
* readonly todos = injectQuery(() => this.route.queries.todos.list.queryOptions());
|
|
129
|
+
* readonly add = injectMutation(() => this.route.queries.todos.add.mutationOptions());
|
|
130
|
+
*
|
|
131
|
+
* refresh() {
|
|
132
|
+
* return this.client.invalidateQueries({ queryKey: this.route.queries.todos.$key() });
|
|
133
|
+
* }
|
|
134
|
+
* ```
|
|
135
|
+
*
|
|
136
|
+
* @typeParam Route - A route made by Launch's `defineRoute`, or its copy.
|
|
137
|
+
*/
|
|
138
|
+
export type QueriesOf<Route> = {
|
|
139
|
+
readonly [Namespace in keyof ChainNamespaces<ContributionOf<Route>>]: NamespaceQueries<Namespace, ChainNamespaces<ContributionOf<Route>>[Namespace]>;
|
|
140
|
+
};
|
|
124
141
|
export {};
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import type { AnyRoute, ContributionOf } from "@loozo/angular-router/_core";
|
|
2
|
+
import type { InvalidInputData } from "../input-issues.js";
|
|
3
|
+
import type { ChainContext } from "../route-types.js";
|
|
4
|
+
import type { ErrorDefinitions, OutputOf, Procedure, Schema } from "../server/definitions.js";
|
|
5
|
+
type OwnNamespaces<Route> = ContributionOf<Route> extends readonly [...unknown[], infer Own] ? Own extends {
|
|
6
|
+
readonly remote: (...args: never[]) => infer Namespaces;
|
|
7
|
+
} ? Namespaces : {} : {};
|
|
8
|
+
type CallableName<Procedures> = {
|
|
9
|
+
[Name in keyof Procedures & string]: Procedures[Name] extends {
|
|
10
|
+
readonly kind: "query" | "mutation";
|
|
11
|
+
} ? Name : never;
|
|
12
|
+
}[keyof Procedures & string];
|
|
13
|
+
type ProcedureAt<Route, Namespace, Name> = Namespace extends keyof OwnNamespaces<Route> ? Name extends keyof OwnNamespaces<Route>[Namespace] ? OwnNamespaces<Route>[Namespace][Name] : never : never;
|
|
14
|
+
type RootContext<Route> = ContributionOf<Route> extends readonly [infer Root, ...unknown[]] ? ChainContext<readonly [Root]> : never;
|
|
15
|
+
type InputOption<Value> = Value extends Procedure<infer Input, infer _Output, infer _Kind, infer _Errors, infer _Message> ? Input extends Schema<infer Caller, unknown> ? {
|
|
16
|
+
/** The input as a caller sends it: the input schema's input type. */
|
|
17
|
+
readonly input: Caller;
|
|
18
|
+
} : {
|
|
19
|
+
/** A procedure without an input schema takes no input. */
|
|
20
|
+
readonly input?: undefined;
|
|
21
|
+
} : never;
|
|
22
|
+
/**
|
|
23
|
+
* The options {@link callProcedure} takes.
|
|
24
|
+
*
|
|
25
|
+
* @typeParam Route - The route that declares the procedure's namespace.
|
|
26
|
+
* @typeParam Value - The procedure, as the route's `.remote()` declares it.
|
|
27
|
+
*/
|
|
28
|
+
export type CallProcedureOptions<Route, Value> = {
|
|
29
|
+
/**
|
|
30
|
+
* The context the root route's `.context()` stage would return, which the stages below it
|
|
31
|
+
* receive; `{}` when the root route has no stage. The root stage itself doesn't run, so
|
|
32
|
+
* what it would provide, such as the user or a database client, can be a fake.
|
|
33
|
+
*/
|
|
34
|
+
readonly context: RootContext<Route>;
|
|
35
|
+
/**
|
|
36
|
+
* The request stages, middleware and the handler receive as `request`, and whose signal
|
|
37
|
+
* they receive as `signal`. Defaults to a `POST` to
|
|
38
|
+
* `http://localhost/_rpc/<namespace>/<procedure>`.
|
|
39
|
+
*/
|
|
40
|
+
readonly request?: Request;
|
|
41
|
+
} & InputOption<Value>;
|
|
42
|
+
type FrameworkError = {
|
|
43
|
+
/** The input failed the input schema, or was sent to a procedure without one. */
|
|
44
|
+
readonly code: "INVALID_INPUT";
|
|
45
|
+
/** Launch's message for the code. */
|
|
46
|
+
readonly message: string;
|
|
47
|
+
/** The input schema's issues; none for input sent to a procedure without one. */
|
|
48
|
+
readonly data: InvalidInputData;
|
|
49
|
+
} | {
|
|
50
|
+
/** A stage, middleware or the handler threw `forbidden()`, or the call failed. */
|
|
51
|
+
readonly code: "FORBIDDEN" | "INTERNAL";
|
|
52
|
+
/** Launch's message for the code. */
|
|
53
|
+
readonly message: string;
|
|
54
|
+
/** Always `null`. */
|
|
55
|
+
readonly data: null;
|
|
56
|
+
};
|
|
57
|
+
type DeclaredError<Errors extends ErrorDefinitions> = {
|
|
58
|
+
[Code in keyof Errors & string]: {
|
|
59
|
+
/** The declared error's code. */
|
|
60
|
+
readonly code: Code;
|
|
61
|
+
/** The declared message. */
|
|
62
|
+
readonly message: string;
|
|
63
|
+
/** The error's data, as its data schema produced it. */
|
|
64
|
+
readonly data: OutputOf<Errors[Code]["data"]>;
|
|
65
|
+
};
|
|
66
|
+
}[keyof Errors & string];
|
|
67
|
+
/**
|
|
68
|
+
* How a {@link callProcedure} call settled, as the browser would receive it, with the
|
|
69
|
+
* cookies and headers it set.
|
|
70
|
+
*
|
|
71
|
+
* @remarks
|
|
72
|
+
* Narrow with `"result" in call`, `"error" in call`, `"redirect" in call` or
|
|
73
|
+
* `"notFound" in call`, then an error by its `code`. Results and error data are what the
|
|
74
|
+
* wire carries: strict JSON, parsed back.
|
|
75
|
+
*
|
|
76
|
+
* @typeParam Value - The procedure, as the route's `.remote()` declares it.
|
|
77
|
+
*/
|
|
78
|
+
export type ProcedureCall<Value> = Value extends Procedure<infer _Input, infer Output, infer _Kind, infer Errors, infer _Message> ? ({
|
|
79
|
+
/** Always 200: the handler returned. */
|
|
80
|
+
readonly status: 200;
|
|
81
|
+
/** The handler's result. */
|
|
82
|
+
readonly result: Awaited<Output>;
|
|
83
|
+
} | {
|
|
84
|
+
/** The error's status: the declared one, or Launch's for its own codes. */
|
|
85
|
+
readonly status: number;
|
|
86
|
+
/** A framework failure or one of the procedure's declared errors. */
|
|
87
|
+
readonly error: FrameworkError | DeclaredError<Errors>;
|
|
88
|
+
} | {
|
|
89
|
+
/** Always 303. */
|
|
90
|
+
readonly status: 303;
|
|
91
|
+
/**
|
|
92
|
+
* A stage, middleware or the handler threw `redirect()`. Never with `words`: the
|
|
93
|
+
* test's binding isn't translated.
|
|
94
|
+
*/
|
|
95
|
+
readonly redirect: {
|
|
96
|
+
/** The root-relative URL `createUrl` built for the destination. */
|
|
97
|
+
readonly to: `/${string}`;
|
|
98
|
+
};
|
|
99
|
+
} | {
|
|
100
|
+
/** Always 404. */
|
|
101
|
+
readonly status: 404;
|
|
102
|
+
/** A stage, middleware or the handler threw `notFound()`. Always `null`. */
|
|
103
|
+
readonly notFound: null;
|
|
104
|
+
}) & {
|
|
105
|
+
/** The `Set-Cookie` values the call set, in order. */
|
|
106
|
+
readonly cookies: readonly string[];
|
|
107
|
+
/** The headers the call set, without Launch's own response headers. */
|
|
108
|
+
readonly headers: Headers;
|
|
109
|
+
} : never;
|
|
110
|
+
/**
|
|
111
|
+
* Calls a query or mutation of a route's own namespace in a test, from the context its root
|
|
112
|
+
* route's stage would return.
|
|
113
|
+
*
|
|
114
|
+
* @remarks
|
|
115
|
+
* The call runs as an RPC over HTTP from that point: the `.context()` stages below the root
|
|
116
|
+
* route, in a fresh request scope; the declaring route's `.use()` middleware; input
|
|
117
|
+
* validation; the procedure's middleware; then the handler. The root route's own stage
|
|
118
|
+
* never runs: `options.context` stands in for what it returns, so a test can pass fakes for
|
|
119
|
+
* what that stage provides. The root route is the first route of the chain that uses a
|
|
120
|
+
* Launch step.
|
|
121
|
+
*
|
|
122
|
+
* The call isn't an HTTP request: there's no host, origin, method or content-type check,
|
|
123
|
+
* no `createRequestScope` and no server rendering. Test those through the generated
|
|
124
|
+
* `handleRequest`.
|
|
125
|
+
*
|
|
126
|
+
* Every outcome settles to a value: a result, an error, a redirect or a not-found. An
|
|
127
|
+
* unexpected failure settles to `INTERNAL`, logged with `console.error` as the server logs
|
|
128
|
+
* it. Streams and channels can't be called.
|
|
129
|
+
*
|
|
130
|
+
* @example
|
|
131
|
+
* ```ts
|
|
132
|
+
* import { callProcedure } from "@loozo/angular-launch/testing";
|
|
133
|
+
* import todos from "./route";
|
|
134
|
+
*
|
|
135
|
+
* const call = await callProcedure(todos, "todos", "complete", {
|
|
136
|
+
* context: { todos: fakeTodos, user: { id: "alice" } },
|
|
137
|
+
* input: { id: "2" },
|
|
138
|
+
* });
|
|
139
|
+
*
|
|
140
|
+
* expect(call).toMatchObject({ status: 404, error: { code: "NOT_FOUND" } });
|
|
141
|
+
* ```
|
|
142
|
+
*
|
|
143
|
+
* @param route - The authored route (its `route.ts` default export) whose own `.remote()`
|
|
144
|
+
* declares `namespace`. Call an ancestor's namespace through the ancestor's route.
|
|
145
|
+
* @param namespace - One of the route's own namespaces.
|
|
146
|
+
* @param procedure - A query or mutation of the namespace.
|
|
147
|
+
* @param options - The root context, the input and the request.
|
|
148
|
+
* @returns How the call settled, with the cookies and headers it set.
|
|
149
|
+
* @throws TypeError for a route Launch's `defineRoute` didn't make, a namespace the route
|
|
150
|
+
* doesn't declare, an unknown procedure, a stream or a channel. Rejects when
|
|
151
|
+
* `options.request`'s body was already read.
|
|
152
|
+
*/
|
|
153
|
+
export declare function callProcedure<Route extends AnyRoute, Namespace extends keyof OwnNamespaces<Route> & string, Name extends CallableName<OwnNamespaces<Route>[Namespace]>>(route: Route, namespace: Namespace, procedure: Name, options: CallProcedureOptions<Route, ProcedureAt<Route, Namespace, Name>>): Promise<ProcedureCall<ProcedureAt<Route, Namespace, Name>>>;
|
|
154
|
+
export {};
|