@loozo/angular-launch 0.0.2 → 0.0.4

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.
@@ -0,0 +1,78 @@
1
+ function segment(value) {
2
+ if (typeof value === "string") {
3
+ return value;
4
+ }
5
+ if (typeof value === "number" && Number.isFinite(value)) {
6
+ return value;
7
+ }
8
+ return undefined;
9
+ }
10
+ /**
11
+ * Converts Standard Schema issues to the issues sent to the client.
12
+ *
13
+ * @remarks
14
+ * Internal; not exported from a public entry point. A path segment may be a property
15
+ * key or a `{ key }` object. An issue with a segment that isn't a string or a finite
16
+ * number gets the root path `[]`; it isn't stringified.
17
+ *
18
+ * @param issues - The issues a schema returned.
19
+ * @returns Each issue's message and normalized path, in the same order.
20
+ */
21
+ export function inputIssues(issues) {
22
+ const result = [];
23
+ for (const issue of issues) {
24
+ let path = [];
25
+ for (const raw of issue.path ?? []) {
26
+ let normalized;
27
+ if (typeof raw === "object" && raw !== null) {
28
+ normalized = segment(raw.key);
29
+ }
30
+ else {
31
+ normalized = segment(raw);
32
+ }
33
+ if (normalized === undefined) {
34
+ path = [];
35
+ break;
36
+ }
37
+ path.push(normalized);
38
+ }
39
+ result.push({ path, message: issue.message });
40
+ }
41
+ return result;
42
+ }
43
+ /**
44
+ * Checks whether a strict JSON value is exactly {@link InvalidInputData}.
45
+ *
46
+ * @remarks
47
+ * Internal; not exported from a public entry point. Used by the client to recognize
48
+ * `INVALID_INPUT` responses. Extra properties make the value unrecognized.
49
+ *
50
+ * @param value - Received error data, already checked to be strict JSON.
51
+ * @returns `true` when `value` is `{ issues }` with only `{ path, message }` issues.
52
+ */
53
+ export function isInvalidInputData(value) {
54
+ if (typeof value !== "object" ||
55
+ value === null ||
56
+ !("issues" in value) ||
57
+ Object.keys(value).length !== 1 ||
58
+ !Array.isArray(value.issues)) {
59
+ return false;
60
+ }
61
+ for (const issue of value.issues) {
62
+ if (typeof issue !== "object" ||
63
+ issue === null ||
64
+ !("path" in issue) ||
65
+ !("message" in issue) ||
66
+ Object.keys(issue).length !== 2 ||
67
+ typeof issue.message !== "string" ||
68
+ !Array.isArray(issue.path)) {
69
+ return false;
70
+ }
71
+ for (const part of issue.path) {
72
+ if (typeof part !== "string" && typeof part !== "number") {
73
+ return false;
74
+ }
75
+ }
76
+ }
77
+ return true;
78
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@loozo/angular-launch",
3
- "version": "0.0.2",
3
+ "version": "0.0.4",
4
4
  "description": "Typed queries, mutations and declared errors on Angular's native router, HTTP and SSR pipeline.",
5
5
  "bugs": "https://github.com/theo-matzavinos/loozo/issues",
6
6
  "license": "MIT",
@@ -32,6 +32,14 @@
32
32
  "types": "./generation/index.d.ts",
33
33
  "node": "./generation/index.js"
34
34
  },
35
+ "./tanstack-query": {
36
+ "types": "./tanstack-query/index.d.ts",
37
+ "default": "./tanstack-query/index.js"
38
+ },
39
+ "./_tanstack-query": {
40
+ "types": "./tanstack-query/generated.d.ts",
41
+ "default": "./tanstack-query/generated.js"
42
+ },
35
43
  "./package.json": "./package.json"
36
44
  },
37
45
  "publishConfig": {
@@ -44,7 +52,13 @@
44
52
  "peerDependencies": {
45
53
  "@angular/common": "^22.0.0",
46
54
  "@angular/core": "^22.0.0",
47
- "@loozo/angular-router": "0.0.4",
55
+ "@loozo/angular-router": "0.0.6",
56
+ "@tanstack/angular-query": "^5.0.0-rc.5",
48
57
  "rxjs": "^7.8.2"
58
+ },
59
+ "peerDependenciesMeta": {
60
+ "@tanstack/angular-query": {
61
+ "optional": true
62
+ }
49
63
  }
50
64
  }
@@ -17,9 +17,9 @@ import { type ApplicationBinding, type Registry } from "./dispatch.js";
17
17
  *
18
18
  * For intercepted calls, Angular's `REQUEST_CONTEXT` must be the {@link RequestScope}
19
19
  * created for Angular's `REQUEST`, or the calls fail with `INTERNAL`. A generated-client
20
- * call outside `/_rpc/` on the current request's origin fails with `INVALID_INPUT`, as
21
- * does any intercepted call with a query string, fragment, URL credentials, a method
22
- * other than `POST`, a non-JSON content type, its own `Authorization`,
20
+ * call outside `/_rpc/` on the current request's origin fails with `INVALID_INPUT` with no
21
+ * issues, as does any intercepted call with a query string, fragment, URL credentials, a
22
+ * method other than `POST`, a non-JSON content type, its own `Authorization`,
23
23
  * `Proxy-Authorization` or `Cookie` header, or its own credentials setting.
24
24
  *
25
25
  * Without a live request, as during prerendering, calls from generated clients and
package/server/backend.js CHANGED
@@ -2,7 +2,7 @@ import { inject, InjectionToken, REQUEST, REQUEST_CONTEXT, makeEnvironmentProvid
2
2
  import { FetchBackend, HttpBackend, HttpErrorResponse, HttpResponse } from "@angular/common/http";
3
3
  import { Observable } from "rxjs";
4
4
  import { RPC_CALL } from "../generated.js";
5
- import { dispatch, failure, isJsonMediaType, assertBoundScope, } from "./dispatch.js";
5
+ import { dispatch, failure, invalidInput, isJsonMediaType, assertBoundScope, } from "./dispatch.js";
6
6
  const renderFaults = new InjectionToken("Launch render faults");
7
7
  /**
8
8
  * Provides the server-rendering transport that runs RPC calls in-process with the
@@ -21,9 +21,9 @@ const renderFaults = new InjectionToken("Launch render faults");
21
21
  *
22
22
  * For intercepted calls, Angular's `REQUEST_CONTEXT` must be the {@link RequestScope}
23
23
  * created for Angular's `REQUEST`, or the calls fail with `INTERNAL`. A generated-client
24
- * call outside `/_rpc/` on the current request's origin fails with `INVALID_INPUT`, as
25
- * does any intercepted call with a query string, fragment, URL credentials, a method
26
- * other than `POST`, a non-JSON content type, its own `Authorization`,
24
+ * call outside `/_rpc/` on the current request's origin fails with `INVALID_INPUT` with no
25
+ * issues, as does any intercepted call with a query string, fragment, URL credentials, a
26
+ * method other than `POST`, a non-JSON content type, its own `Authorization`,
27
27
  * `Proxy-Authorization` or `Cookie` header, or its own credentials setting.
28
28
  *
29
29
  * Without a live request, as during prerendering, calls from generated clients and
@@ -105,20 +105,20 @@ export function provideLaunchServer(registry, application) {
105
105
  request.method !== "POST" ||
106
106
  !isJsonMediaType(contentType) ||
107
107
  authOverride) {
108
- deliver(failure("INVALID_INPUT"));
108
+ deliver(invalidInput());
109
109
  return;
110
110
  }
111
111
  let envelope;
112
112
  try {
113
113
  const body = request.serializeBody();
114
114
  if (typeof body !== "string") {
115
- deliver(failure("INVALID_INPUT"));
115
+ deliver(invalidInput());
116
116
  return;
117
117
  }
118
118
  envelope = JSON.parse(body);
119
119
  }
120
120
  catch {
121
- deliver(failure("INVALID_INPUT"));
121
+ deliver(invalidInput());
122
122
  return;
123
123
  }
124
124
  void dispatch(registry, target.pathname, envelope, context, application, nativeRequest, "rendering").then(deliver);
@@ -87,10 +87,18 @@ export interface Schema<Input = unknown, Output = Input> {
87
87
  /** Absent on success. */
88
88
  readonly issues?: undefined;
89
89
  } | {
90
- /** The problems found, which mark a failure. Not sent to clients. */
90
+ /**
91
+ * The problems found, which mark a failure. For a procedure input, each issue's
92
+ * message and path are sent to the client as `INVALID_INPUT` data.
93
+ */
91
94
  readonly issues: readonly {
92
95
  /** A description of the problem. */
93
96
  readonly message: string;
97
+ /** Where the problem is: property keys, or `{ key }` segments. */
98
+ readonly path?: readonly (PropertyKey | {
99
+ /** The segment's property key. */
100
+ readonly key: PropertyKey;
101
+ })[] | undefined;
94
102
  }[];
95
103
  } | Promise<{
96
104
  /** The validated, possibly transformed value. */
@@ -98,10 +106,18 @@ export interface Schema<Input = unknown, Output = Input> {
98
106
  /** Absent on success. */
99
107
  readonly issues?: undefined;
100
108
  } | {
101
- /** The problems found, which mark a failure. Not sent to clients. */
109
+ /**
110
+ * The problems found, which mark a failure. For a procedure input, each issue's
111
+ * message and path are sent to the client as `INVALID_INPUT` data.
112
+ */
102
113
  readonly issues: readonly {
103
114
  /** A description of the problem. */
104
115
  readonly message: string;
116
+ /** Where the problem is: property keys, or `{ key }` segments. */
117
+ readonly path?: readonly (PropertyKey | {
118
+ /** The segment's property key. */
119
+ readonly key: PropertyKey;
120
+ })[] | undefined;
105
121
  }[];
106
122
  }>;
107
123
  };
@@ -447,7 +463,8 @@ export interface Group<Name extends string, Procedures extends Record<string, Pr
447
463
  * identifiers other than `__proto__` for the namespace and procedure names, and
448
464
  * write the procedures, options and `canActivate` arrays inline. Each route's
449
465
  * generated `injectRpc()` exposes its own group and its ancestors' groups under their
450
- * namespaces, so a namespace can't repeat within one route's ancestry.
466
+ * namespaces. Each namespace must be unique across the app: calls go to
467
+ * `/_rpc/<namespace>/<procedure>`.
451
468
  *
452
469
  * Exposure isn't authorization: anyone who can reach the server can call any
453
470
  * procedure, so guard every group and procedure that needs it.
@@ -136,7 +136,8 @@ export function mutation(options) {
136
136
  * identifiers other than `__proto__` for the namespace and procedure names, and
137
137
  * write the procedures, options and `canActivate` arrays inline. Each route's
138
138
  * generated `injectRpc()` exposes its own group and its ancestors' groups under their
139
- * namespaces, so a namespace can't repeat within one route's ancestry.
139
+ * namespaces. Each namespace must be unique across the app: calls go to
140
+ * `/_rpc/<namespace>/<procedure>`.
140
141
  *
141
142
  * Exposure isn't authorization: anyone who can reach the server can call any
142
143
  * procedure, so guard every group and procedure that needs it.
@@ -1,7 +1,8 @@
1
1
  import { type FrameworkCode } from "../client.js";
2
+ import { type InputIssue } from "../input-issues.js";
2
3
  import type { ContextDefinition, ContextOf, Group, ProcedureDefinition } from "./definitions.js";
3
4
  /**
4
- * The application's RPC groups, keyed by generated group ID.
5
+ * The application's RPC groups, keyed by namespace.
5
6
  *
6
7
  * @remarks
7
8
  * Internal; not exported from a public entry point. Generation writes it as
@@ -85,7 +86,8 @@ export interface Reply {
85
86
  /** The result, or an `{ error: { code, message, data } }` frame. */
86
87
  readonly body: unknown;
87
88
  }
88
- export declare function failure(code: FrameworkCode): Reply;
89
+ export declare function failure(code: Exclude<FrameworkCode, "INVALID_INPUT">): Reply;
90
+ export declare function invalidInput(issues?: readonly InputIssue[]): Reply;
89
91
  export declare function isJsonMediaType(contentType: string | null): boolean;
90
92
  /**
91
93
  * Runs one procedure call within a request scope and produces its reply.
@@ -97,11 +99,12 @@ export declare function isJsonMediaType(contentType: string | null): boolean;
97
99
  * unexpected errors are logged on the server.
98
100
  *
99
101
  * In order: the scope must belong to `application` and `request` (`INTERNAL`); the
100
- * path must be `/_rpc/<group ID>/<procedure>` for a registered procedure
102
+ * path must be `/_rpc/<namespace>/<procedure>` for a registered procedure
101
103
  * (`RPC_NOT_FOUND`); a mutation in `"rendering"` mode is refused (`FORBIDDEN`); the
102
104
  * envelope must be strict JSON (`INTERNAL` otherwise, such as for `{ input: undefined }`,
103
- * a cycle or an accessor); it must then be exactly `{ input }` (`INVALID_INPUT`) with
104
- * input that passes the schema, or `null` without one (`INVALID_INPUT`); the group's
105
+ * a cycle or an accessor); it must then be exactly `{ input }` (`INVALID_INPUT` with no
106
+ * issues) with input that passes the schema (`INVALID_INPUT` with the schema's issues),
107
+ * or `null` without one (`INVALID_INPUT` with no issues); the group's
105
108
  * guards and then the procedure's guards must return `true` (`FORBIDDEN`). The
106
109
  * handler's strict JSON result is returned with status 200, and its declared errors
107
110
  * with their status.
@@ -125,10 +128,10 @@ export declare function dispatch(registry: Registry, path: string, envelope: unk
125
128
  * `handleRequest` in `server.generated.ts`; call that instead.
126
129
  * Any path starting with `/_rpc/` is treated as an RPC request. It must be a `POST`
127
130
  * with an `application/json` content type and no query string, otherwise the reply is
128
- * `INVALID_INPUT` and no context is created. A fresh context is then created before the
129
- * body is parsed; if that fails the reply is `INTERNAL`, even when the body isn't JSON.
130
- * Otherwise a body that isn't JSON gives `INVALID_INPUT`. Responses are JSON with
131
- * `Cache-Control: private, no-store` and `Vary: Cookie`.
131
+ * `INVALID_INPUT` with no issues and no context is created. A fresh context is then
132
+ * created before the body is parsed; if that fails the reply is `INTERNAL`, even when the
133
+ * body isn't JSON. Otherwise a body that isn't JSON gives `INVALID_INPUT` with no issues.
134
+ * Responses are JSON with `Cache-Control: private, no-store` and `Vary: Cookie`.
132
135
  *
133
136
  * @typeParam Definition - The application's context definition.
134
137
  * @param registry - The application's RPC groups.
@@ -1,5 +1,6 @@
1
1
  import { frameworkFailures } from "../client.js";
2
2
  import { serializeJson } from "../json.js";
3
+ import { inputIssues } from "../input-issues.js";
3
4
  import { declaredFailures } from "./errors.js";
4
5
  const scopeMarker = Symbol.for("@loozo/angular-launch/private-request-scope/v1");
5
6
  const bindingHeader = "x-loozo-launch-scope";
@@ -72,6 +73,15 @@ export function failure(code) {
72
73
  const frame = frameworkFailures[code];
73
74
  return { status: frame.status, body: { error: { code, message: frame.message, data: null } } };
74
75
  }
76
+ export function invalidInput(issues = []) {
77
+ const frame = frameworkFailures.INVALID_INPUT;
78
+ // Both transports publish the same strict JSON, as for declared error data.
79
+ const data = JSON.parse(serializeJson({ issues }));
80
+ return {
81
+ status: frame.status,
82
+ body: { error: { code: "INVALID_INPUT", message: frame.message, data } },
83
+ };
84
+ }
75
85
  export function isJsonMediaType(contentType) {
76
86
  return contentType?.split(";", 1)[0].trim().toLowerCase() === "application/json";
77
87
  }
@@ -85,11 +95,12 @@ export function isJsonMediaType(contentType) {
85
95
  * unexpected errors are logged on the server.
86
96
  *
87
97
  * In order: the scope must belong to `application` and `request` (`INTERNAL`); the
88
- * path must be `/_rpc/<group ID>/<procedure>` for a registered procedure
98
+ * path must be `/_rpc/<namespace>/<procedure>` for a registered procedure
89
99
  * (`RPC_NOT_FOUND`); a mutation in `"rendering"` mode is refused (`FORBIDDEN`); the
90
100
  * envelope must be strict JSON (`INTERNAL` otherwise, such as for `{ input: undefined }`,
91
- * a cycle or an accessor); it must then be exactly `{ input }` (`INVALID_INPUT`) with
92
- * input that passes the schema, or `null` without one (`INVALID_INPUT`); the group's
101
+ * a cycle or an accessor); it must then be exactly `{ input }` (`INVALID_INPUT` with no
102
+ * issues) with input that passes the schema (`INVALID_INPUT` with the schema's issues),
103
+ * or `null` without one (`INVALID_INPUT` with no issues); the group's
93
104
  * guards and then the procedure's guards must return `true` (`FORBIDDEN`). The
94
105
  * handler's strict JSON result is returned with status 200, and its declared errors
95
106
  * with their status.
@@ -107,7 +118,7 @@ export function isJsonMediaType(contentType) {
107
118
  export async function dispatch(registry, path, envelope, scope, application, request, mode = "http") {
108
119
  try {
109
120
  assertBoundScope(scope, application, request);
110
- const parts = /^\/_rpc\/([a-f0-9]{24})\/([A-Za-z_][A-Za-z0-9_]*)$/.exec(path);
121
+ const parts = /^\/_rpc\/([A-Za-z_][A-Za-z0-9_]*)\/([A-Za-z_][A-Za-z0-9_]*)$/.exec(path);
111
122
  if (!parts || !Object.hasOwn(registry, parts[1])) {
112
123
  return failure("RPC_NOT_FOUND");
113
124
  }
@@ -131,18 +142,18 @@ export async function dispatch(registry, path, envelope, scope, application, req
131
142
  Array.isArray(normalized) ||
132
143
  !("input" in normalized) ||
133
144
  Object.keys(normalized).length !== 1) {
134
- return failure("INVALID_INPUT");
145
+ return invalidInput();
135
146
  }
136
147
  let input;
137
148
  if (procedure.input) {
138
149
  const parsed = await procedure.input["~standard"].validate(normalized.input);
139
150
  if (parsed.issues) {
140
- return failure("INVALID_INPUT");
151
+ return invalidInput(inputIssues(parsed.issues));
141
152
  }
142
153
  input = parsed.value;
143
154
  }
144
155
  else if (normalized.input !== null) {
145
- return failure("INVALID_INPUT");
156
+ return invalidInput();
146
157
  }
147
158
  const context = scope.value;
148
159
  for (const guard of group.canActivate) {
@@ -196,10 +207,10 @@ export async function dispatch(registry, path, envelope, scope, application, req
196
207
  * `handleRequest` in `server.generated.ts`; call that instead.
197
208
  * Any path starting with `/_rpc/` is treated as an RPC request. It must be a `POST`
198
209
  * with an `application/json` content type and no query string, otherwise the reply is
199
- * `INVALID_INPUT` and no context is created. A fresh context is then created before the
200
- * body is parsed; if that fails the reply is `INTERNAL`, even when the body isn't JSON.
201
- * Otherwise a body that isn't JSON gives `INVALID_INPUT`. Responses are JSON with
202
- * `Cache-Control: private, no-store` and `Vary: Cookie`.
210
+ * `INVALID_INPUT` with no issues and no context is created. A fresh context is then
211
+ * created before the body is parsed; if that fails the reply is `INTERNAL`, even when the
212
+ * body isn't JSON. Otherwise a body that isn't JSON gives `INVALID_INPUT` with no issues.
213
+ * Responses are JSON with `Cache-Control: private, no-store` and `Vary: Cookie`.
203
214
  *
204
215
  * @typeParam Definition - The application's context definition.
205
216
  * @param registry - The application's RPC groups.
@@ -216,7 +227,7 @@ export async function handleRpc(registry, application, request) {
216
227
  if (request.method !== "POST" ||
217
228
  !isJsonMediaType(request.headers.get("content-type")) ||
218
229
  url.search !== "") {
219
- reply = failure("INVALID_INPUT");
230
+ reply = invalidInput();
220
231
  }
221
232
  else {
222
233
  try {
@@ -226,7 +237,7 @@ export async function handleRpc(registry, application, request) {
226
237
  envelope = await request.json();
227
238
  }
228
239
  catch {
229
- return response(failure("INVALID_INPUT"));
240
+ return response(invalidInput());
230
241
  }
231
242
  reply = await dispatch(registry, url.pathname, envelope, scope, application, scope.request);
232
243
  }
@@ -0,0 +1,168 @@
1
+ # TanStack Query
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 writes typed query and mutation options and keys for your groups, and server-rendered query data reaches the browser through TanStack's own hydration, with no request on load even with `staleTime: 0`.
4
+
5
+ It's optional. Without it, Launch never imports TanStack.
6
+
7
+ ## Setup
8
+
9
+ Install the adapter. Launch supports `@tanstack/angular-query` `^5.0.0-rc.5` as an optional peer dependency, and is tested with `5.0.0-rc.5`:
10
+
11
+ ```sh
12
+ pnpm add @tanstack/angular-query@5.0.0-rc.5
13
+ ```
14
+
15
+ Turn on the `tanstackQuery` generation option:
16
+
17
+ ```js
18
+ // generate.mjs
19
+ import { generate } from "@loozo/angular-launch/generation";
20
+
21
+ await generate(import.meta.dirname, {
22
+ tsconfig: "tsconfig.app.json",
23
+ scanDirectories: ["src/routes"],
24
+ outDirectory: "generated",
25
+ tanstackQuery: true,
26
+ check: process.argv.includes("--check"),
27
+ });
28
+ ```
29
+
30
+ Each `rpc.generated.ts` then also exports `injectQueries()` and its type `Queries`, for the same groups as its `injectRpc()`. With the option off, generated files are exactly as without this entry point.
31
+
32
+ Add TanStack's provider and `provideLaunchQueries()` to the application's providers, which the server config inherits:
33
+
34
+ ```ts
35
+ // src/config.ts
36
+ import { provideHttpClient } from "@angular/common/http";
37
+ import { provideClientHydration } from "@angular/platform-browser";
38
+ import { provideRouter } from "@angular/router";
39
+ import type { ApplicationConfig } from "@angular/core";
40
+ import { provideLaunchQueries } from "@loozo/angular-launch/tanstack-query";
41
+ import { provideTanStackQuery, QueryClient } from "@tanstack/angular-query";
42
+ import { routes } from "../generated/routes.generated";
43
+
44
+ export const config: ApplicationConfig = {
45
+ providers: [
46
+ provideHttpClient(),
47
+ provideClientHydration(),
48
+ provideRouter(routes),
49
+ provideTanStackQuery(() => new QueryClient()),
50
+ provideLaunchQueries(),
51
+ ],
52
+ };
53
+ ```
54
+
55
+ 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. `injectQueries()` throws without it.
56
+
57
+ ## Queries and mutations
58
+
59
+ Call `injectQueries()` in an injection context, like `injectRpc()`, and pass its options to TanStack:
60
+
61
+ ```ts
62
+ // src/routes/+authenticated/todos/page.ts
63
+ import { Component, inject } from "@angular/core";
64
+ import { injectMutation, injectQuery, QueryClient } from "@tanstack/angular-query";
65
+ import { injectQueries, injectRpc } from "./rpc.generated";
66
+
67
+ @Component({/* … */})
68
+ export default class Todos {
69
+ readonly #rpc = injectRpc();
70
+ readonly #queries = injectQueries();
71
+ readonly #client = inject(QueryClient);
72
+ readonly todos = injectQuery(() => this.#queries.todos.list.queryOptions());
73
+ readonly #complete = injectMutation(() =>
74
+ this.#queries.todos.complete.mutationOptions({
75
+ onSuccess: () => this.#client.invalidateQueries({ queryKey: this.#queries.todos.$key() }),
76
+ }),
77
+ );
78
+
79
+ async complete(id: string): Promise<void> {
80
+ try {
81
+ await this.#complete.mutateAsync({ id });
82
+ } catch (error) {
83
+ if (this.#rpc.todos.complete.isError(error) && error.code === "NOT_FOUND") {
84
+ const missingId: string = error.data.id;
85
+ }
86
+ }
87
+ }
88
+ }
89
+ ```
90
+
91
+ Each query procedure has `queryOptions` and each mutation procedure `mutationOptions`, never both:
92
+
93
+ ```ts
94
+ queries.todos.list.queryOptions(overrides?); // a query without input
95
+ queries.todos.byId.queryOptions(input, overrides?); // a query with input
96
+ queries.todos.byId.queryOptions(skipToken); // disabled until there's an input
97
+ queries.todos.add.mutationOptions(overrides?); // variables are the input
98
+ queries.todos.clear.mutationOptions(overrides?); // no input: mutate() takes none
99
+ ```
100
+
101
+ The options work anywhere TanStack takes them: `injectQuery`, `injectMutation`, `QueryClient.fetchQuery`, `ensureQueryData` and the like. `overrides` are any other TanStack options, such as `staleTime`, `select`, `enabled`, `onSuccess` or `onError`. They can't replace the key or the query or mutation function. Queries call the procedure with TanStack's `signal`, so a cancelled query aborts its HTTP request; mutations aren't cancelled.
102
+
103
+ The data is the procedure's output, or `select`'s result. Errors are typed `unknown`: narrow them with the callable's `isError`, as above. The rejection is the callable's own, so `isError` recognizes it.
104
+
105
+ ## Keys
106
+
107
+ Keys start with `"launch"` and the namespace, so a shorter key matches every longer key under it:
108
+
109
+ | Call | Key |
110
+ | ------------------------------------- | ------------------------------------------ |
111
+ | `queries.todos.$key()` | `["launch", "todos"]` |
112
+ | `queries.todos.list.key()` | `["launch", "todos", "list"]` |
113
+ | `queries.todos.byId.key()` | `["launch", "todos", "byId"]` |
114
+ | `queries.todos.byId.key({ id: "1" })` | `["launch", "todos", "byId", { id: "1" }]` |
115
+ | `queries.todos.add.key()` | `["launch", "todos", "add"]` |
116
+
117
+ `queryOptions` uses the full key: with the input as you passed it, or without one for a query without input. A query disabled with `skipToken` is keyed without input. `mutationOptions` uses the mutation's `key()` as its `mutationKey`.
118
+
119
+ Full query keys are tagged with the procedure's output type, so `client.getQueryData(queries.todos.list.key())` and `client.setQueryData(...)` are typed. `$key` can't clash with a procedure: Launch names can't contain `$`.
120
+
121
+ ## Invalidation
122
+
123
+ Nothing is invalidated for you. Invalidate in a mutation's `onSuccess`, by group, procedure or input:
124
+
125
+ ```ts
126
+ onSuccess: () => client.invalidateQueries({ queryKey: queries.todos.$key() }),
127
+ ```
128
+
129
+ Returning the promise, as here, keeps the mutation pending until the refetch finishes. A failed refetch doesn't fail the mutation, though: `invalidateQueries` resolves anyway, and the query keeps its previous data next to the error. To treat it as a failure, for example to tell the user the list may be out of date, pass `throwOnError`:
130
+
131
+ ```ts
132
+ onSuccess: () =>
133
+ client.invalidateQueries({ queryKey: queries.todos.$key() }, { throwOnError: true }),
134
+ ```
135
+
136
+ `mutateAsync` then rejects with the refetch's error, although the write itself succeeded.
137
+
138
+ ## Server rendering and hydration
139
+
140
+ During server rendering, queries run in-process with the page request's context, like direct calls, and Angular waits for them before rendering. TanStack then writes the successful queries' data into the HTML, and the browser's `QueryClient` starts with it. Generated query functions call with `transferCache: false`, so the data appears in the HTML once, as TanStack's, not again in Angular's HTTP transfer cache. Direct calls, such as from resolvers, still use the transfer cache as described in the [package README](../README.md#server-rendering-and-hydration).
141
+
142
+ In the browser, a query with data normally refetches when it mounts if it's stale, which with the default `staleTime: 0` is always. Generated query options default `refetchOnMount` to `false` while the app hydrates, from bootstrap until the app is first stable, the same window Angular's HTTP transfer cache uses. So with `staleTime: 0` the first render shows the server's data and no RPC is made on load. After that, `refetchOnMount` follows your `QueryClient` defaults (`true` unless you change them), invalidation always refetches, and a query mounted later, for example after navigating back or from a `@defer` block that hydrates on interaction, refetches if it's stale. A `refetchOnMount` override replaces the default, including during hydration.
143
+
144
+ The window opens in any browser app, also one without server rendering. Queries without data load regardless, since `refetchOnMount` only applies to data that's already there; but a query with `initialData`, or one you put in the cache before the first page mounts, doesn't refetch on mount until the app is first stable.
145
+
146
+ The limits follow from TanStack's hydration:
147
+
148
+ - 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.
149
+ - Queries are part of the HTML: only return data the user may see, and serve personalized pages with `Cache-Control: private, no-store`.
150
+ - Mutations are refused during server rendering with `FORBIDDEN`, as for direct calls.
151
+ - Prerendering a page that runs a query fails the build, as for direct calls.
152
+
153
+ ## Defaults
154
+
155
+ | Option | Default |
156
+ | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
157
+ | `retry` | No retry for an `RpcError` (a framework failure or declared error); for anything else, your `QueryClient` default for the key, or three retries |
158
+ | `refetchOnMount` | `false` while hydrating; then your `QueryClient` default for the key, or `true` |
159
+
160
+ 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 an `RpcError`, 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.
161
+
162
+ ## Limitations
163
+
164
+ - No infinite queries, optimistic-update helpers, automatic invalidation, mutation cancellation or persistence.
165
+ - Errors aren't dehydrated: a failed server query runs again in the browser.
166
+ - Only `@tanstack/angular-query`, not `@tanstack/angular-query-experimental`.
167
+ - 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.
168
+ - TanStack also exports an `injectQueries` (for running several queries); import one of the two under another name if you need both in a file.
@@ -0,0 +1,5 @@
1
+ export interface QueriesMethod {
2
+ readonly kind: "query" | "mutation";
3
+ readonly input: boolean;
4
+ }
5
+ export declare function createQueries(rpc: Readonly<Record<string, Readonly<Record<string, unknown>>>>, groups: Readonly<Record<string, Readonly<Record<string, QueriesMethod>>>>): unknown;