@loozo/angular-launch 0.0.3 → 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.
package/README.md CHANGED
@@ -1,12 +1,12 @@
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/packages/angular-router/README.md). You define queries and mutations in an `rpc.ts` file next to a route, and call them from that route's pages and resolvers through a generated, fully typed client.
3
+ Typed server functions for Angular applications built with [`@loozo/angular-router`](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.4/packages/angular-router/README.md). You define queries and mutations in an `rpc.ts` file next to a route, and call them from that route's pages and resolvers through a generated, fully typed client.
4
4
 
5
5
  Calls go through Angular's `HttpClient`. In the browser they're ordinary HTTP requests. During server rendering they run in-process with the current request's context, and hydration reuses their responses through Angular's transfer cache. Errors you declare on a procedure come back typed on the client.
6
6
 
7
7
  Use it when you want typed reads and writes between an Angular SSR app and its own server, without maintaining a separate API layer.
8
8
 
9
- **Status:** experimental. MIT license. It currently covers queries, mutations, guards and declared errors. There's no builder or watch mode yet, and no subscriptions, optimistic updates, automatic invalidation or storage adapters.
9
+ **Status:** experimental. MIT license. It currently covers queries, mutations, guards and declared errors, with optional [TanStack Query](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.4/packages/angular-launch/tanstack-query/README.md) options and keys. There's no builder or watch mode yet, and no subscriptions, optimistic updates, automatic invalidation or storage adapters.
10
10
 
11
11
  ## Requirements
12
12
 
@@ -14,11 +14,12 @@ Use it when you want typed reads and writes between an Angular SSR app and its o
14
14
  - `@loozo/angular-router` at exactly the version Launch pins in its `peerDependencies`, as a dependency of your app. Launch generation writes the router's files too, through an internal router entry point, so the two must match; the exact peer dependency enforces that.
15
15
  - TypeScript 6 with strict checking. Generation rejects a tsconfig where any of `noImplicitAny`, `strictNullChecks`, `strictFunctionTypes`, `strictBindCallApply`, `strictPropertyInitialization`, `strictBuiltinIteratorReturn`, `noImplicitThis` or `useUnknownInCatchVariables` is off, or where `noCheck` is on. `"strict": true` is enough unless a flag is explicitly turned off, including in an extended config. Generation never edits your tsconfig.
16
16
  - A `package.json` with a `name` in the application directory. The name is part of the generated app identity.
17
+ - Optionally, `@tanstack/angular-query` `^5.0.0-rc.5` for the [TanStack Query integration](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.4/packages/angular-launch/tanstack-query/README.md).
17
18
 
18
19
  Install both packages:
19
20
 
20
21
  ```sh
21
- pnpm add @loozo/angular-launch @loozo/angular-router@0.0.5
22
+ pnpm add @loozo/angular-launch @loozo/angular-router@0.0.6
22
23
  ```
23
24
 
24
25
  ## How it fits together
@@ -50,7 +51,7 @@ The route tree is the router's. An `rpc.ts` belongs to the route declared in the
50
51
 
51
52
  ## Setup
52
53
 
53
- The [todos example](https://github.com/theo-matzavinos/loozo/tree/angular-launch@0.0.3/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.
54
+ The [todos example](https://github.com/theo-matzavinos/loozo/tree/angular-launch@0.0.4/examples/angular-launch) is a complete app, and the snippets below are simplified from it. `db` and `sessions` stand for your own server-only modules: the example uses a test cookie instead of sessions, and its in-memory `db.todos.listForUser` also takes a test-only delay flag.
54
55
 
55
56
  ### 1. Define the context
56
57
 
@@ -301,13 +302,27 @@ Launch itself uses four codes, which you can't declare:
301
302
 
302
303
  | Code | Status | When |
303
304
  | --------------- | ------ | ----------------------------------------------------------------------------------- |
304
- | `INVALID_INPUT` | 400 | Input failed schema validation |
305
+ | `INVALID_INPUT` | 400 | The request is malformed, or its input failed schema validation |
305
306
  | `FORBIDDEN` | 403 | A guard returned `false`, or a mutation was called during server rendering |
306
307
  | `RPC_NOT_FOUND` | 404 | No such procedure |
307
308
  | `INTERNAL` | 500 | Anything else: an unexpected exception, an invalid error payload, a non-JSON result |
308
309
 
309
310
  `INTERNAL` never exposes details to the client; they go to the server log. Your own `NOT_FOUND` is fine, but `__proto__` can't be an error code.
310
311
 
312
+ `INVALID_INPUT` has `InvalidInputData`: `{ issues }`, with one `InputIssue` of `{ path, message }` per issue the input schema found, in the schema's order. `path` holds property names and array indexes into the input, such as `["lines", 1, "amount"]`. It's `[]` for the input as a whole, and for an issue whose schema path can't be sent as JSON, such as one with a symbol key. Only messages and paths reach the client, never the received input or other details of the schema library, so write your schema messages for users. A malformed request, such as a body that isn't JSON or an envelope with extra fields, has no issues. Server rendering and HTTP send the same issues. The other three codes have `null` data.
313
+
314
+ ```ts
315
+ try {
316
+ await rpc.todos.add({ title });
317
+ } catch (error) {
318
+ if (rpc.todos.add.isError(error) && error.code === "INVALID_INPUT") {
319
+ for (const issue of error.data.issues) {
320
+ showError(issue.path, issue.message); // ["title"], "Title must contain 1–200 characters"
321
+ }
322
+ }
323
+ }
324
+ ```
325
+
311
326
  ## Calling RPCs
312
327
 
313
328
  Each route that has a page or descendants with pages gets an `rpc.generated.ts` with `injectRpc()`, even without its own group; redirect routes don't. Call it in an injection context:
@@ -359,7 +374,6 @@ import { injectRpc } from "./rpc.generated";
359
374
  export default defineRoute("todos", {
360
375
  parent,
361
376
  resolve: {
362
- todos: () => injectRpc().todos.list(),
363
377
  session: () => injectRpc().session.current(),
364
378
  },
365
379
  });
@@ -367,9 +381,13 @@ export default defineRoute("todos", {
367
381
 
368
382
  `Client<typeof group>` from `@loozo/angular-launch` gives you the client type for a group, for example to type a result: `Awaited<ReturnType<Client<typeof group>["list"]>>`. Import the group with `import type` so server code stays out of the browser bundle.
369
383
 
384
+ ### With TanStack Query
385
+
386
+ With the `tanstackQuery` generation option, each `rpc.generated.ts` also exports `injectQueries()`: typed query and mutation options and keys for the same groups, for `@tanstack/angular-query`. See the [TanStack Query guide](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.4/packages/angular-launch/tanstack-query/README.md) for setup, keys, invalidation and hydration.
387
+
370
388
  ## Server rendering and hydration
371
389
 
372
- 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 }`.
390
+ During server rendering, calls run directly on the server with the context created for that page request. Queries are stored in Angular's HTTP transfer cache, so hydration reuses the responses instead of calling the server again. After the app is stable, calls are ordinary HTTP requests, each with a fresh context. Opt a query out with `{ transferCache: false }`. Queries run through [TanStack Query](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.4/packages/angular-launch/tanstack-query/README.md) opt out and are transferred by TanStack instead.
373
391
 
374
392
  The reuse has limits, all of them Angular's transfer cache behaving as designed:
375
393
 
@@ -466,22 +484,23 @@ Export the handler as `reqHandler`; Angular's dev server and build don't look fo
466
484
  generate(workspace: string, options: GenerationOptions, stopped?: () => boolean): Promise<void>;
467
485
  ```
468
486
 
469
- | Option | Type | Description |
470
- | ----------------- | ---------- | ----------------------------------------------------------------------------- |
471
- | `tsconfig` | `string` | Your app tsconfig, relative to `workspace` |
472
- | `scanDirectories` | `string[]` | Exactly one route directory, relative to the tsconfig's directory |
473
- | `outDirectory` | `string` | Where the app-wide generated files go, relative to `workspace` |
474
- | `check` | `boolean` | Verify generated files without writing them; fails if anything is out of date |
487
+ | Option | Type | Description |
488
+ | ----------------- | ---------- | ------------------------------------------------------------------------------- |
489
+ | `tsconfig` | `string` | Your app tsconfig, relative to `workspace` |
490
+ | `scanDirectories` | `string[]` | Exactly one route directory, relative to the tsconfig's directory |
491
+ | `outDirectory` | `string` | Where the app-wide generated files go, relative to `workspace` |
492
+ | `tanstackQuery` | `boolean` | Also generate `injectQueries()`; see [TanStack Query](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.4/packages/angular-launch/tanstack-query/README.md) |
493
+ | `check` | `boolean` | Verify generated files without writing them; fails if anything is out of date |
475
494
 
476
495
  `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.
477
496
 
478
497
  Generation reads your source without running it. It writes the router's files plus:
479
498
 
480
- | File | Contents |
481
- | --------------------------------------- | -------------------------------------------------------------------------------- |
482
- | `rpc.generated.ts` beside each route | `injectRpc()` with the route's own and ancestor groups; none for redirect routes |
483
- | `<outDirectory>/context.generated.d.ts` | Registers your context type |
484
- | `<outDirectory>/server.generated.ts` | `createContext`, `handleRequest`, `provideServer`, the registry |
499
+ | File | Contents |
500
+ | --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
501
+ | `rpc.generated.ts` beside each route | `injectRpc()` with the route's own and ancestor groups, plus `injectQueries()` with `tanstackQuery`; none for redirect routes |
502
+ | `<outDirectory>/context.generated.d.ts` | Registers your context type |
503
+ | `<outDirectory>/server.generated.ts` | `createContext`, `handleRequest`, `provideServer`, the registry |
485
504
 
486
505
  Each file starts with an ownership marker comment. Generation only replaces or removes files with those exact names and markers, fails rather than overwrite an unmarked file or a symlink in their place, and removes stale ones. Unchanged files aren't rewritten. Everything is validated before anything is written, so a run that fails validation changes nothing. Files are then written one at a time, with no rollback: a write error partway through, such as an unwritable file, or an interrupted run can leave some files updated and others not. The next successful run repairs them.
487
506
 
@@ -523,7 +542,7 @@ The options are fixed when the session is created. Edits inside the app, includi
523
542
  ## Limitations
524
543
 
525
544
  - No Angular builder or watch mode for Launch yet; run generation yourself before `ng build` or `ng serve`.
526
- - No subscriptions, optimistic updates, automatic invalidation, or query cache beyond hydration.
545
+ - No subscriptions, optimistic updates or automatic invalidation. Beyond hydration, the only query cache is TanStack Query's, through the optional [integration](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.4/packages/angular-launch/tanstack-query/README.md#limitations), which has its own limitations.
527
546
  - No storage adapters; persistence is your handler's job.
528
547
  - No production authentication, CSRF, CORS or caching policy. You provide those.
529
548
  - Server work isn't cancelled when the client aborts, and nothing is rolled back.
@@ -531,9 +550,10 @@ The options are fixed when the session is created. Edits inside the app, includi
531
550
 
532
551
  ## Further reading
533
552
 
534
- - [`specs/angular-launch.md`](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.3/specs/angular-launch.md): design and full contract
535
- - [`examples/angular-launch`](https://github.com/theo-matzavinos/loozo/tree/angular-launch@0.0.3/examples/angular-launch): the todos app. Its cookie identity and in-memory database are test fixtures, not security or deployment guidance.
536
- - [`@loozo/angular-router`](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.3/packages/angular-router/README.md): routes, codecs and navigation
553
+ - [TanStack Query](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.4/packages/angular-launch/tanstack-query/README.md): the optional query and mutation integration
554
+ - [`specs/angular-launch.md`](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.4/specs/angular-launch.md): design and full contract
555
+ - [`examples/angular-launch`](https://github.com/theo-matzavinos/loozo/tree/angular-launch@0.0.4/examples/angular-launch): the todos app. Its cookie identity and in-memory database are test fixtures, not security or deployment guidance.
556
+ - [`@loozo/angular-router`](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.4/packages/angular-router/README.md): routes, codecs and navigation
537
557
 
538
558
  ## Developing this package
539
559
 
package/client.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { ErrorDefinitions, Group, OutputOf, Procedure, ProcedureKind, Schema } from "./server/definitions.js";
2
+ import { type InvalidInputData } from "./input-issues.js";
2
3
  /** Per-call options for a generated query callable. */
3
4
  export interface CallOptions {
4
5
  /**
@@ -50,13 +51,15 @@ export interface ErrorMetadata {
50
51
  * The four error codes Launch itself returns, with their HTTP status and public message.
51
52
  *
52
53
  * @remarks
53
- * - `INVALID_INPUT` (400): the request or its input failed validation.
54
+ * - `INVALID_INPUT` (400): the request or its input failed validation. Its data is
55
+ * {@link InvalidInputData}: the input schema's issues, or none for a malformed request.
54
56
  * - `FORBIDDEN` (403): a guard returned `false`, or a mutation was called during
55
57
  * server rendering.
56
58
  * - `RPC_NOT_FOUND` (404): no procedure exists at the requested path.
57
59
  * - `INTERNAL` (500): anything else. Details go to the server log, never to the client.
58
60
  *
59
- * These codes are reserved: procedures can't declare errors with them.
61
+ * The other codes have `null` data. These codes are reserved: procedures can't declare
62
+ * errors with them.
60
63
  */
61
64
  export declare const frameworkFailures: {
62
65
  readonly INVALID_INPUT: {
@@ -78,6 +81,7 @@ export declare const frameworkFailures: {
78
81
  };
79
82
  /** One of the error codes Launch itself returns: a key of {@link frameworkFailures}. */
80
83
  export type FrameworkCode = keyof typeof frameworkFailures;
84
+ type FrameworkData<Code extends FrameworkCode> = Code extends "INVALID_INPUT" ? InvalidInputData : null;
81
85
  /**
82
86
  * An error response returned by a procedure: either a Launch framework failure or one
83
87
  * of the procedure's declared errors.
@@ -90,15 +94,18 @@ export type FrameworkCode = keyof typeof frameworkFailures;
90
94
  * returned by that exact procedure, not `RpcError` instances created elsewhere.
91
95
  *
92
96
  * @typeParam Code - The error code.
93
- * @typeParam Data - The error's data: `null` for framework failures, the data schema's
94
- * output for declared errors.
97
+ * @typeParam Data - The error's data: {@link InvalidInputData} for `INVALID_INPUT`,
98
+ * `null` for the other framework failures, the data schema's output for declared errors.
95
99
  */
96
- export declare class RpcError<Code extends string = FrameworkCode, Data = null> extends Error {
100
+ export declare class RpcError<Code extends string = FrameworkCode, Data = Code extends FrameworkCode ? FrameworkData<Code> : null> extends Error {
97
101
  /** The framework or declared error code. */
98
102
  readonly code: Code;
99
103
  /** The HTTP status of the response. */
100
104
  readonly status: number;
101
- /** The error's data: `null` for framework failures, validated data for declared errors. */
105
+ /**
106
+ * The error's data: {@link InvalidInputData} for `INVALID_INPUT`, `null` for the other
107
+ * framework failures, validated data for declared errors.
108
+ */
102
109
  readonly data: Data;
103
110
  /**
104
111
  * Creates an error with the given code, status and data.
@@ -115,7 +122,10 @@ export declare class RpcError<Code extends string = FrameworkCode, Data = null>
115
122
  code: Code,
116
123
  /** The HTTP status of the response. */
117
124
  status: number,
118
- /** The error's data: `null` for framework failures, validated data for declared errors. */
125
+ /**
126
+ * The error's data: {@link InvalidInputData} for `INVALID_INPUT`, `null` for the other
127
+ * framework failures, validated data for declared errors.
128
+ */
119
129
  data?: Data, message?: string);
120
130
  }
121
131
  /**
@@ -124,14 +134,21 @@ export declare class RpcError<Code extends string = FrameworkCode, Data = null>
124
134
  * @remarks
125
135
  * Internal; not exported from a public entry point. Used by the generated client to
126
136
  * convert responses into {@link RpcError}s. The body must be strict JSON shaped
127
- * exactly as `{ error: { code, message, data: null } }`, with the framework code's own
128
- * status and message.
137
+ * exactly as `{ error: { code, message, data } }`, with the framework code's own
138
+ * status and message. `data` must be exactly {@link InvalidInputData} for
139
+ * `INVALID_INPUT` and `null` for the other codes.
129
140
  *
130
141
  * @param value - The parsed response body.
131
142
  * @param status - The response's HTTP status.
132
- * @returns The framework code, or `undefined` when the body doesn't match exactly.
143
+ * @returns The framework code and data, or `undefined` when the body doesn't match
144
+ * exactly.
133
145
  */
134
- export declare function recognizedFailure(value: unknown, status: number): FrameworkCode | undefined;
146
+ export declare function recognizedFailure(value: unknown, status: number): {
147
+ /** The framework code. */
148
+ code: FrameworkCode;
149
+ /** The failure's data. */
150
+ data: InvalidInputData | null;
151
+ } | undefined;
135
152
  /**
136
153
  * Recognizes a response body that is exactly a framework failure or one of the given
137
154
  * declared errors.
@@ -153,11 +170,11 @@ export declare function recognizedError(value: unknown, status: number, declared
153
170
  code: string;
154
171
  /** The error's message. */
155
172
  message: string;
156
- /** The declared error's data as received, or `null` for a framework failure. */
173
+ /** The error's data as received. */
157
174
  data: unknown;
158
175
  } | undefined;
159
176
  type FrameworkError = {
160
- [Code in FrameworkCode]: RpcError<Code, null>;
177
+ [Code in FrameworkCode]: RpcError<Code, FrameworkData<Code>>;
161
178
  }[FrameworkCode];
162
179
  type DeclaredError<Errors extends ErrorDefinitions> = {
163
180
  [Code in keyof Errors & string]: RpcError<Code, OutputOf<Errors[Code]["data"]>>;
@@ -166,8 +183,9 @@ type DeclaredError<Errors extends ErrorDefinitions> = {
166
183
  * The errors a generated callable for a procedure can reject with as {@link RpcError}s.
167
184
  *
168
185
  * @remarks
169
- * A union discriminated by `code`: one member per framework failure with `null` data,
170
- * and one per declared error with its data schema's output type. Import the group
186
+ * A union discriminated by `code`: one member per framework failure, with
187
+ * {@link InvalidInputData} for `INVALID_INPUT` and `null` data for the others, and one
188
+ * per declared error with its data schema's output type. Import the group
171
189
  * with `import type` so server code stays out of the browser bundle.
172
190
  *
173
191
  * @example
package/client.js CHANGED
@@ -1,15 +1,18 @@
1
1
  import { serializeJson } from "./json.js";
2
+ import { isInvalidInputData } from "./input-issues.js";
2
3
  /**
3
4
  * The four error codes Launch itself returns, with their HTTP status and public message.
4
5
  *
5
6
  * @remarks
6
- * - `INVALID_INPUT` (400): the request or its input failed validation.
7
+ * - `INVALID_INPUT` (400): the request or its input failed validation. Its data is
8
+ * {@link InvalidInputData}: the input schema's issues, or none for a malformed request.
7
9
  * - `FORBIDDEN` (403): a guard returned `false`, or a mutation was called during
8
10
  * server rendering.
9
11
  * - `RPC_NOT_FOUND` (404): no procedure exists at the requested path.
10
12
  * - `INTERNAL` (500): anything else. Details go to the server log, never to the client.
11
13
  *
12
- * These codes are reserved: procedures can't declare errors with them.
14
+ * The other codes have `null` data. These codes are reserved: procedures can't declare
15
+ * errors with them.
13
16
  */
14
17
  export const frameworkFailures = {
15
18
  INVALID_INPUT: { status: 400, message: "Invalid RPC input" },
@@ -29,8 +32,8 @@ export const frameworkFailures = {
29
32
  * returned by that exact procedure, not `RpcError` instances created elsewhere.
30
33
  *
31
34
  * @typeParam Code - The error code.
32
- * @typeParam Data - The error's data: `null` for framework failures, the data schema's
33
- * output for declared errors.
35
+ * @typeParam Data - The error's data: {@link InvalidInputData} for `INVALID_INPUT`,
36
+ * `null` for the other framework failures, the data schema's output for declared errors.
34
37
  */
35
38
  export class RpcError extends Error {
36
39
  code;
@@ -51,7 +54,10 @@ export class RpcError extends Error {
51
54
  code,
52
55
  /** The HTTP status of the response. */
53
56
  status,
54
- /** The error's data: `null` for framework failures, validated data for declared errors. */
57
+ /**
58
+ * The error's data: {@link InvalidInputData} for `INVALID_INPUT`, `null` for the other
59
+ * framework failures, validated data for declared errors.
60
+ */
55
61
  data = null, message) {
56
62
  if (message === undefined) {
57
63
  if (!Object.hasOwn(frameworkFailures, code)) {
@@ -72,12 +78,14 @@ export class RpcError extends Error {
72
78
  * @remarks
73
79
  * Internal; not exported from a public entry point. Used by the generated client to
74
80
  * convert responses into {@link RpcError}s. The body must be strict JSON shaped
75
- * exactly as `{ error: { code, message, data: null } }`, with the framework code's own
76
- * status and message.
81
+ * exactly as `{ error: { code, message, data } }`, with the framework code's own
82
+ * status and message. `data` must be exactly {@link InvalidInputData} for
83
+ * `INVALID_INPUT` and `null` for the other codes.
77
84
  *
78
85
  * @param value - The parsed response body.
79
86
  * @param status - The response's HTTP status.
80
- * @returns The framework code, or `undefined` when the body doesn't match exactly.
87
+ * @returns The framework code and data, or `undefined` when the body doesn't match
88
+ * exactly.
81
89
  */
82
90
  export function recognizedFailure(value, status) {
83
91
  try {
@@ -104,11 +112,16 @@ export function recognizedFailure(value, status) {
104
112
  }
105
113
  for (const code of Object.keys(frameworkFailures)) {
106
114
  const expected = frameworkFailures[code];
107
- if (error.code === code &&
108
- status === expected.status &&
109
- error.message === expected.message &&
110
- error.data === null) {
111
- return code;
115
+ if (error.code !== code || status !== expected.status || error.message !== expected.message) {
116
+ continue;
117
+ }
118
+ if (code === "INVALID_INPUT") {
119
+ if (isInvalidInputData(error.data)) {
120
+ return { code, data: error.data };
121
+ }
122
+ }
123
+ else if (error.data === null) {
124
+ return { code, data: null };
112
125
  }
113
126
  }
114
127
  return undefined;
@@ -132,7 +145,11 @@ export function recognizedFailure(value, status) {
132
145
  export function recognizedError(value, status, declared) {
133
146
  const framework = recognizedFailure(value, status);
134
147
  if (framework) {
135
- return { code: framework, message: frameworkFailures[framework].message, data: null };
148
+ return {
149
+ code: framework.code,
150
+ message: frameworkFailures[framework.code].message,
151
+ data: framework.data,
152
+ };
136
153
  }
137
154
  try {
138
155
  serializeJson(value);
@@ -6,6 +6,13 @@ export interface GenerationOptions {
6
6
  scanDirectories: string[];
7
7
  /** Where the application-wide generated files go, relative to the workspace. */
8
8
  outDirectory: string;
9
+ /**
10
+ * Also writes `injectQueries()` and `type Queries` into each `rpc.generated.ts`: TanStack
11
+ * Query options and keys for the same groups as `injectRpc()`. Requires
12
+ * `@tanstack/angular-query` in the application and `provideLaunchQueries()` from
13
+ * `@loozo/angular-launch/tanstack-query` in its providers. Defaults to `false`.
14
+ */
15
+ tanstackQuery?: boolean;
9
16
  /**
10
17
  * Verifies the generated files without writing them, failing when any is changed,
11
18
  * missing or stale. Defaults to `false`.
@@ -113,4 +120,4 @@ export declare function generate(workspace: string, options: GenerationOptions,
113
120
  * passed per call instead.
114
121
  * @returns The session. Dispose it when done.
115
122
  */
116
- export declare function createGenerationSession(workspace: string, { tsconfig, scanDirectories, outDirectory }: Omit<GenerationOptions, "check">): GenerationSession;
123
+ export declare function createGenerationSession(workspace: string, { tsconfig, scanDirectories, outDirectory, tanstackQuery }: Omit<GenerationOptions, "check">): GenerationSession;
@@ -155,7 +155,7 @@ async function groupsOf(sources) {
155
155
  }
156
156
  return { context, groups };
157
157
  }
158
- function emitLaunch(sources, desired, context, groups, appId) {
158
+ function emitLaunch(sources, desired, context, groups, appId, tanstackQuery) {
159
159
  const payloads = [];
160
160
  function payloadImport(from, target, local, typeOnly = false) {
161
161
  payloads.push({ from, target, local });
@@ -198,7 +198,11 @@ function emitLaunch(sources, desired, context, groups, appId) {
198
198
  `import { injectClient } from '@loozo/angular-launch/_generated';`,
199
199
  `import type { Client } from '@loozo/angular-launch';`,
200
200
  ];
201
+ if (tanstackQuery) {
202
+ lines.push(`import { createQueries } from '@loozo/angular-launch/_tanstack-query';`, `import type { RpcQueries } from '@loozo/angular-launch/tanstack-query';`);
203
+ }
201
204
  const metadata = Object.create(null);
205
+ const queriesMetadata = Object.create(null);
202
206
  for (let index = 0; index < available.length; index += 1) {
203
207
  const group = available[index];
204
208
  lines.push(payloadImport(file, group.declaration.file, `group${index}`, true));
@@ -210,8 +214,16 @@ function emitLaunch(sources, desired, context, groups, appId) {
210
214
  errors,
211
215
  })),
212
216
  };
217
+ queriesMetadata[group.namespace] = Object.create(null);
218
+ for (const { name, kind, input } of group.methods) {
219
+ queriesMetadata[group.namespace][name] = { kind, input };
220
+ }
221
+ }
222
+ lines.push(`export type Rpc = { ${available.map((group, index) => `readonly ${JSON.stringify(group.namespace)}: Client<typeof group${index}>`).join("; ")} };`, `export function injectRpc(): Rpc { return injectClient(${JSON.stringify(metadata)} as const) as Rpc; }`);
223
+ if (tanstackQuery) {
224
+ lines.push(`export type Queries = { ${available.map((group, index) => `readonly ${JSON.stringify(group.namespace)}: RpcQueries<typeof group${index}>`).join("; ")} };`, `export function injectQueries(): Queries { return createQueries(injectRpc(), ${JSON.stringify(queriesMetadata)} as const) as Queries; }`);
213
225
  }
214
- lines.push(`export type Rpc = { ${available.map((group, index) => `readonly ${JSON.stringify(group.namespace)}: Client<typeof group${index}>`).join("; ")} };`, `export function injectRpc(): Rpc { return injectClient(${JSON.stringify(metadata)} as const) as Rpc; }`, "");
226
+ lines.push("");
215
227
  add(desired, file, lines.join("\n"));
216
228
  }
217
229
  return payloads;
@@ -479,7 +491,7 @@ async function runGeneration(workspace, options, stopped, compiler) {
479
491
  .update("\0")
480
492
  .update(context.call.getSourceFile().text)
481
493
  .digest("hex");
482
- const payloads = emitLaunch(sources, desired, context, groups, appId);
494
+ const payloads = emitLaunch(sources, desired, context, groups, appId, options.tanstackQuery === true);
483
495
  await auditPath(sources.output);
484
496
  const outputInventory = await walk(sources.output);
485
497
  const globals = [
@@ -570,9 +582,9 @@ export function generate(workspace, options, stopped = () => false) {
570
582
  * passed per call instead.
571
583
  * @returns The session. Dispose it when done.
572
584
  */
573
- export function createGenerationSession(workspace, { tsconfig, scanDirectories, outDirectory }) {
585
+ export function createGenerationSession(workspace, { tsconfig, scanDirectories, outDirectory, tanstackQuery }) {
574
586
  const application = resolve(workspace);
575
- const fixed = { tsconfig, scanDirectories: [...scanDirectories], outDirectory };
587
+ const fixed = { tsconfig, scanDirectories: [...scanDirectories], outDirectory, tanstackQuery };
576
588
  const compiler = {
577
589
  discovery: new CompilerState(),
578
590
  overlay: new CompilerState(),
package/index.d.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  export { RpcError, frameworkFailures } from "./client.js";
2
2
  export type { CallOptions, MutationCallOptions, Client, ClientProcedure, ClientRpcError, FrameworkCode, } from "./client.js";
3
+ export type { InputIssue, InvalidInputData } from "./input-issues.js";
@@ -0,0 +1,56 @@
1
+ /**
2
+ * One problem an input schema found, as sent to the client in `INVALID_INPUT` data.
3
+ *
4
+ * @remarks
5
+ * Only the schema issue's message and path are sent, never vendor details, input
6
+ * values or stacks, so write schema messages for users.
7
+ */
8
+ export interface InputIssue {
9
+ /**
10
+ * Where the problem is, as property names and array indexes from the procedure's
11
+ * input. Empty for the input as a whole, or when the schema's path can't be
12
+ * represented in JSON, such as a symbol key.
13
+ */
14
+ readonly path: readonly (string | number)[];
15
+ /** The schema's description of the problem. */
16
+ readonly message: string;
17
+ }
18
+ /**
19
+ * The data of an `INVALID_INPUT` error.
20
+ *
21
+ * @remarks
22
+ * A request that isn't a valid RPC envelope, such as a body that isn't JSON, has no
23
+ * issues.
24
+ */
25
+ export interface InvalidInputData {
26
+ /** The problems the input schema found, in the schema's order. */
27
+ readonly issues: readonly InputIssue[];
28
+ }
29
+ /**
30
+ * Converts Standard Schema issues to the issues sent to the client.
31
+ *
32
+ * @remarks
33
+ * Internal; not exported from a public entry point. A path segment may be a property
34
+ * key or a `{ key }` object. An issue with a segment that isn't a string or a finite
35
+ * number gets the root path `[]`; it isn't stringified.
36
+ *
37
+ * @param issues - The issues a schema returned.
38
+ * @returns Each issue's message and normalized path, in the same order.
39
+ */
40
+ export declare function inputIssues(issues: readonly {
41
+ readonly message: string;
42
+ readonly path?: readonly (PropertyKey | {
43
+ readonly key: PropertyKey;
44
+ })[] | undefined;
45
+ }[]): InputIssue[];
46
+ /**
47
+ * Checks whether a strict JSON value is exactly {@link InvalidInputData}.
48
+ *
49
+ * @remarks
50
+ * Internal; not exported from a public entry point. Used by the client to recognize
51
+ * `INVALID_INPUT` responses. Extra properties make the value unrecognized.
52
+ *
53
+ * @param value - Received error data, already checked to be strict JSON.
54
+ * @returns `true` when `value` is `{ issues }` with only `{ path, message }` issues.
55
+ */
56
+ export declare function isInvalidInputData(value: unknown): value is InvalidInputData;
@@ -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.3",
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.5",
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