@loozo/angular-launch 0.0.3 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4 @@
1
+ import { type Builder } from "@angular-devkit/architect";
2
+ import { type JsonObject } from "./options.js";
3
+ declare const builder: Builder<JsonObject>;
4
+ export default builder;
@@ -0,0 +1,71 @@
1
+ import { createBuilder, } from "@angular-devkit/architect";
2
+ import { generate } from "../generation/index.js";
3
+ import { message, split } from "./options.js";
4
+ const officialApplicationBuilder = "@angular/build:application";
5
+ // The conditions @angular/build 22.2's bundler uses when none are configured, chosen from the
6
+ // normalized optimization as it chooses them.
7
+ function defaultConditions(optimization = true) {
8
+ let scripts = optimization;
9
+ if (typeof optimization === "object" && optimization !== null && !Array.isArray(optimization)) {
10
+ scripts = optimization.scripts;
11
+ }
12
+ if (scripts) {
13
+ return ["module", "production"];
14
+ }
15
+ return ["module", "development"];
16
+ }
17
+ // Annotated so the emitted declaration doesn't reach into @angular-devkit/core.
18
+ const builder = createBuilder(async (options, context) => {
19
+ let stopped = false;
20
+ let acquisition;
21
+ let generation;
22
+ let cleanup;
23
+ function stop() {
24
+ stopped = true;
25
+ if (!cleanup) {
26
+ const delegateStop = acquisition?.then((run) => run.stop());
27
+ // The builder reports a failed generation itself; stopping only waits for it to settle.
28
+ const drain = generation?.catch(() => undefined);
29
+ cleanup = Promise.all([delegateStop, drain]).then(() => undefined);
30
+ }
31
+ return cleanup;
32
+ }
33
+ context.addTeardown(stop);
34
+ try {
35
+ const { launch, official } = split(options);
36
+ if (official.watch === true) {
37
+ throw new Error("The application builder runs once; it does not support watch: true");
38
+ }
39
+ // The schema's false marks an omitted conditions (scripts/builder-schemas.mjs). Omitting it
40
+ // here would reach Angular as an explicit [] again, so Angular's default list goes instead.
41
+ if (official.conditions === false) {
42
+ official.conditions = defaultConditions(official.optimization);
43
+ }
44
+ generation = generate(context.workspaceRoot, launch, () => stopped);
45
+ try {
46
+ await generation;
47
+ }
48
+ catch (error) {
49
+ // Diagnostics, ownership conflicts and check-mode drift are build failures, not crashes.
50
+ context.logger.error(message(error));
51
+ return { success: false };
52
+ }
53
+ if (stopped) {
54
+ return { success: false };
55
+ }
56
+ acquisition = context.scheduleBuilder(officialApplicationBuilder, official, {
57
+ target: context.target,
58
+ });
59
+ const run = await acquisition;
60
+ if (stopped) {
61
+ await run.stop();
62
+ return { success: false };
63
+ }
64
+ const output = await run.result;
65
+ return output;
66
+ }
67
+ finally {
68
+ await stop();
69
+ }
70
+ });
71
+ export default builder;
@@ -0,0 +1,10 @@
1
+ import { type BuilderContext } from "@angular-devkit/architect";
2
+ import type { GenerationOptions } from "../generation/index.js";
3
+ export type JsonObject = NonNullable<Parameters<BuilderContext["scheduleBuilder"]>[1]>;
4
+ export declare const applicationBuilder = "@loozo/angular-launch:application";
5
+ export declare function message(error: unknown): string;
6
+ export declare function split(options: JsonObject): {
7
+ launch: GenerationOptions;
8
+ official: JsonObject;
9
+ };
10
+ export declare function buildTargetOptions(context: BuilderContext, buildTarget: string): Promise<GenerationOptions>;
@@ -0,0 +1,64 @@
1
+ import { targetFromTargetString } from "@angular-devkit/architect";
2
+ export const applicationBuilder = "@loozo/angular-launch:application";
3
+ function validateLaunchOptions(value) {
4
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
5
+ throw new Error("Launch options must be an object");
6
+ }
7
+ for (const key of ["tsconfig", "outDirectory"]) {
8
+ const option = value[key];
9
+ if (typeof option !== "string" || option.trim() === "") {
10
+ throw new Error(`Launch option ${key} must be a nonempty string`);
11
+ }
12
+ }
13
+ const scanDirectories = value.scanDirectories;
14
+ if (!Array.isArray(scanDirectories) ||
15
+ scanDirectories.length !== 1 ||
16
+ scanDirectories.some((scan) => typeof scan !== "string" || scan.trim() === "")) {
17
+ throw new Error("scanDirectories must contain exactly one nonempty string");
18
+ }
19
+ for (const key of ["tanstackQuery", "check"]) {
20
+ if (Object.hasOwn(value, key) && typeof value[key] !== "boolean") {
21
+ throw new Error(`${key} must be a boolean`);
22
+ }
23
+ }
24
+ }
25
+ export function message(error) {
26
+ if (error instanceof Error) {
27
+ return error.message;
28
+ }
29
+ return String(error);
30
+ }
31
+ // Launch options drive generation; everything else belongs to Angular's application builder.
32
+ export function split(options) {
33
+ validateLaunchOptions(options);
34
+ const { tsconfig, scanDirectories, outDirectory, tanstackQuery, check, ...official } = options;
35
+ const launch = { tsconfig, scanDirectories, outDirectory };
36
+ if (tanstackQuery !== undefined) {
37
+ launch.tanstackQuery = tanstackQuery;
38
+ }
39
+ if (check !== undefined) {
40
+ launch.check = check;
41
+ }
42
+ return { launch, official };
43
+ }
44
+ // Launch options for serve come from its build target, resolved as Angular's dev server resolves it.
45
+ export async function buildTargetOptions(context, buildTarget) {
46
+ const project = context.target?.project;
47
+ if (!project) {
48
+ throw new Error("The serve builder must run as a project target");
49
+ }
50
+ const target = targetFromTargetString(buildTarget, project, "build");
51
+ const [builder, raw] = await Promise.all([
52
+ context.getBuilderNameForTarget(target),
53
+ context.getTargetOptions(target),
54
+ ]);
55
+ if (builder !== applicationBuilder) {
56
+ throw new Error(`buildTarget ${target.project}:${target.target} must use ${applicationBuilder}, not ${builder}`);
57
+ }
58
+ const options = await context.validateOptions(raw, builder);
59
+ const { launch } = split(options);
60
+ if (launch.check === true) {
61
+ throw new Error("Serve writes generated files; its buildTarget must not resolve check: true");
62
+ }
63
+ return launch;
64
+ }
@@ -0,0 +1,8 @@
1
+ import { type Builder } from "@angular-devkit/architect";
2
+ import { type JsonObject } from "./options.js";
3
+ type ServeOptions = JsonObject & {
4
+ buildTarget: string;
5
+ poll?: number | false;
6
+ };
7
+ declare const builder: Builder<ServeOptions>;
8
+ export default builder;
@@ -0,0 +1,248 @@
1
+ import { createBuilder, } from "@angular-devkit/architect";
2
+ import chokidar from "chokidar";
3
+ import { Observable } from "rxjs";
4
+ import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path";
5
+ import { readFile, realpath } from "node:fs/promises";
6
+ import { launchMarkers } from "@loozo/angular-router/_generation";
7
+ import { createGenerationSession } from "../generation/index.js";
8
+ import { contextFiles } from "../generation/context-file.js";
9
+ import { buildTargetOptions, message } from "./options.js";
10
+ // Polling catches what Angular 22.2's native watcher (@parcel/watcher) misses: edits to files
11
+ // inside a renamed directory, which otherwise leave the dev server serving stale output.
12
+ const defaultPoll = 1000;
13
+ const devServerBuilder = "@angular/build:dev-server";
14
+ // One change can reach the watcher as a burst of events: a save of several files, or a directory
15
+ // rename, whose unlinks chokidar holds back 100 ms to pair them with re-adds. A pass waits for the
16
+ // burst to go quiet, so it runs once and reads the finished change.
17
+ const settleDelay = 150;
18
+ // Generation's own marked outputs in the scan directory; their events need no further pass. The
19
+ // output directory can't overlap the scan directory, so its files never reach the watcher. The
20
+ // router's marker isn't part of its generation seam; if this copy drifts, a write only causes one
21
+ // redundant pass, which writes nothing.
22
+ const generatedMarkers = {
23
+ "route.generated.ts": "// @loozo/angular-router routegen: owned route.generated.ts",
24
+ "rpc.generated.ts": launchMarkers["rpc.generated.ts"],
25
+ };
26
+ function contains(directory, file) {
27
+ const suffix = relative(directory, file);
28
+ return (suffix === "" || (!isAbsolute(suffix) && suffix !== ".." && !suffix.startsWith(`..${sep}`)));
29
+ }
30
+ // Annotated so the emitted declaration doesn't reach into @angular-devkit/core.
31
+ const builder = createBuilder((options, context) => new Observable((subscriber) => {
32
+ let stopped = false;
33
+ let initial = true;
34
+ let dirty = false;
35
+ let watcher;
36
+ let contextWatcher;
37
+ let session;
38
+ let acquisition;
39
+ let forwarding;
40
+ let active;
41
+ let cleanup;
42
+ let cancelReady;
43
+ let settling;
44
+ // Resolved before the watcher starts.
45
+ let scanRoot;
46
+ let watchedContext;
47
+ // The context file can live anywhere in the app's sources, and its path and contents are part
48
+ // of the generated app identity, so a watcher of its own follows wherever the last pass found
49
+ // it. A file inside the scan directory is already watched.
50
+ function followContext() {
51
+ const contextFile = contextFiles.get(session);
52
+ if (stopped || contextFile === undefined || contextFile === watchedContext) {
53
+ return;
54
+ }
55
+ const previous = contextWatcher;
56
+ contextWatcher = undefined;
57
+ watchedContext = contextFile;
58
+ void previous?.close().catch((error) => context.logger.error(String(error)));
59
+ if (contains(scanRoot, contextFile)) {
60
+ return;
61
+ }
62
+ const followed = chokidar.watch(contextFile, {
63
+ ignoreInitial: true,
64
+ followSymlinks: false,
65
+ });
66
+ contextWatcher = followed;
67
+ followed.on("error", (error) => context.logger.error(String(error)));
68
+ followed.on("all", (_event, path) => {
69
+ void changed(path).catch((error) => context.logger.error(String(error)));
70
+ });
71
+ // The pass that found this path read the context before its watch existed, so an edit since
72
+ // went unseen. Once the watch is live, one more pass reads the current text; the watch
73
+ // covers the rest.
74
+ followed.once("ready", () => {
75
+ if (stopped || contextWatcher !== followed) {
76
+ return;
77
+ }
78
+ dirty = true;
79
+ pump();
80
+ });
81
+ }
82
+ async function changed(path) {
83
+ if (stopped) {
84
+ return;
85
+ }
86
+ const marker = generatedMarkers[basename(path)];
87
+ if (marker !== undefined) {
88
+ try {
89
+ const bytes = await readFile(path, "utf8");
90
+ if (bytes.split("\n", 1)[0] === marker) {
91
+ return;
92
+ }
93
+ }
94
+ catch (error) {
95
+ if (error.code !== "ENOENT") {
96
+ throw error;
97
+ }
98
+ }
99
+ }
100
+ if (stopped) {
101
+ return;
102
+ }
103
+ clearTimeout(settling);
104
+ settling = setTimeout(() => {
105
+ settling = undefined;
106
+ dirty = true;
107
+ pump();
108
+ }, settleDelay);
109
+ }
110
+ // A failed or stopped pass leaves the session clean; the next pass starts fresh.
111
+ async function regenerate() {
112
+ try {
113
+ await session.generate(undefined, () => stopped);
114
+ }
115
+ finally {
116
+ followContext();
117
+ }
118
+ }
119
+ function stop() {
120
+ stopped = true;
121
+ dirty = false;
122
+ clearTimeout(settling);
123
+ cancelReady?.();
124
+ forwarding?.unsubscribe();
125
+ if (!cleanup) {
126
+ const close = Promise.all([watcher?.close(), contextWatcher?.close()]);
127
+ const delegateStop = acquisition?.then((run) => run.stop(), () => undefined);
128
+ const drain = active?.catch(() => undefined);
129
+ cleanup = Promise.all([close, delegateStop, drain, session?.dispose()]).then(() => undefined);
130
+ }
131
+ return cleanup;
132
+ }
133
+ context.addTeardown(stop);
134
+ function pump() {
135
+ if (stopped || initial || active || !dirty) {
136
+ return;
137
+ }
138
+ const work = (async () => {
139
+ while (dirty && !stopped) {
140
+ dirty = false;
141
+ try {
142
+ await regenerate();
143
+ }
144
+ catch (error) {
145
+ context.logger.error(message(error));
146
+ }
147
+ }
148
+ })();
149
+ active = work;
150
+ void work.finally(() => {
151
+ if (active === work) {
152
+ active = undefined;
153
+ }
154
+ // An edit between the loop's last check and finalization must not be lost.
155
+ pump();
156
+ });
157
+ }
158
+ async function start() {
159
+ const { poll = defaultPoll, ...devServer } = options;
160
+ if (poll !== false) {
161
+ devServer.poll = poll;
162
+ }
163
+ // Architect already validated the dev-server options against schemas/serve.json, Angular's
164
+ // dev-server schema with this poll. The build target is validated before the watcher and
165
+ // generation too, so invalid options never write.
166
+ const launch = await buildTargetOptions(context, options.buildTarget);
167
+ if (stopped) {
168
+ return;
169
+ }
170
+ const application = await realpath(context.workspaceRoot);
171
+ if (stopped) {
172
+ return;
173
+ }
174
+ scanRoot = resolve(dirname(resolve(application, launch.tsconfig)), launch.scanDirectories[0]);
175
+ session = createGenerationSession(context.workspaceRoot, launch);
176
+ watcher = chokidar.watch([scanRoot], { ignoreInitial: true, followSymlinks: false });
177
+ const ready = new Promise((resolveReady, rejectReady) => {
178
+ cancelReady = () => resolveReady(false);
179
+ watcher.once("ready", () => resolveReady(true));
180
+ watcher.on("error", (error) => {
181
+ if (initial) {
182
+ rejectReady(error);
183
+ }
184
+ else {
185
+ context.logger.error(String(error));
186
+ }
187
+ });
188
+ watcher.on("all", (_event, path) => {
189
+ void changed(path).catch((error) => context.logger.error(String(error)));
190
+ });
191
+ });
192
+ const readyForGeneration = await ready;
193
+ if (stopped || !readyForGeneration) {
194
+ return;
195
+ }
196
+ dirty = false;
197
+ const generation = regenerate();
198
+ active = generation;
199
+ try {
200
+ await generation;
201
+ }
202
+ catch (error) {
203
+ // The dev server never starts on a failed initial generation; report it as a build failure.
204
+ context.logger.error(message(error));
205
+ await stop();
206
+ subscriber.next({ success: false });
207
+ subscriber.complete();
208
+ return;
209
+ }
210
+ finally {
211
+ if (active === generation) {
212
+ active = undefined;
213
+ }
214
+ }
215
+ if (stopped) {
216
+ return;
217
+ }
218
+ initial = false;
219
+ pump();
220
+ if (stopped) {
221
+ return;
222
+ }
223
+ acquisition = context.scheduleBuilder(devServerBuilder, devServer, {
224
+ target: context.target,
225
+ });
226
+ const run = await acquisition;
227
+ if (stopped) {
228
+ await run.stop();
229
+ return;
230
+ }
231
+ forwarding = run.output.subscribe({
232
+ next: (output) => subscriber.next(output),
233
+ error: (error) => {
234
+ void stop().then(() => subscriber.error(error), () => subscriber.error(error));
235
+ },
236
+ complete: () => {
237
+ void stop().then(() => subscriber.complete(), (error) => subscriber.error(error));
238
+ },
239
+ });
240
+ }
241
+ void start().catch((error) => {
242
+ void stop().then(() => subscriber.error(error), () => subscriber.error(error));
243
+ });
244
+ return () => {
245
+ void stop().catch((error) => context.logger.error(String(error)));
246
+ };
247
+ }));
248
+ export default builder;
package/builders.json ADDED
@@ -0,0 +1,15 @@
1
+ {
2
+ "$schema": "./node_modules/@angular-devkit/architect/src/builders-schema.json",
3
+ "builders": {
4
+ "application": {
5
+ "implementation": "./builders/application.js",
6
+ "schema": "./schemas/application.json",
7
+ "description": "Generate/check Launch and router files, then run @angular/build:application with the remaining options."
8
+ },
9
+ "serve": {
10
+ "implementation": "./builders/serve.js",
11
+ "schema": "./schemas/serve.json",
12
+ "description": "Watch Launch sources, then run @angular/build:dev-server with the remaining options."
13
+ }
14
+ }
15
+ }
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
  /**
@@ -6,8 +7,9 @@ export interface CallOptions {
6
7
  * `DOMException` named `AbortError`.
7
8
  *
8
9
  * @remarks
9
- * An already aborted signal rejects without sending a request. Aborting doesn't
10
- * cancel server work that has already started.
10
+ * An already aborted signal rejects without sending a request. On the server, the
11
+ * call's middleware and handler see their `signal` abort. That's advisory: work that
12
+ * doesn't pass the signal on still finishes.
11
13
  */
12
14
  readonly signal?: AbortSignal;
13
15
  /**
@@ -23,8 +25,9 @@ export interface MutationCallOptions {
23
25
  * `DOMException` named `AbortError`.
24
26
  *
25
27
  * @remarks
26
- * Aborting doesn't cancel server work that has already started, so the write may
27
- * still complete.
28
+ * On the server, the call's middleware and handler see their `signal` abort. That's
29
+ * advisory: work that doesn't pass the signal on still finishes, and the write may
30
+ * already have committed.
28
31
  */
29
32
  readonly signal?: AbortSignal;
30
33
  /** Only `false` is accepted: mutations never use the HTTP transfer cache. */
@@ -50,13 +53,16 @@ export interface ErrorMetadata {
50
53
  * The four error codes Launch itself returns, with their HTTP status and public message.
51
54
  *
52
55
  * @remarks
53
- * - `INVALID_INPUT` (400): the request or its input failed validation.
54
- * - `FORBIDDEN` (403): a guard returned `false`, or a mutation was called during
55
- * server rendering.
56
+ * - `INVALID_INPUT` (400): the request or its input failed validation. Its data is
57
+ * {@link InvalidInputData}: the input schema's issues, or none for a malformed request.
58
+ * - `FORBIDDEN` (403): middleware or a handler threw `forbidden()`, the request wasn't
59
+ * proven to come from the app's own origin, or a mutation was called during server
60
+ * rendering.
56
61
  * - `RPC_NOT_FOUND` (404): no procedure exists at the requested path.
57
62
  * - `INTERNAL` (500): anything else. Details go to the server log, never to the client.
58
63
  *
59
- * These codes are reserved: procedures can't declare errors with them.
64
+ * The other codes have `null` data. These codes are reserved: procedures can't declare
65
+ * errors with them.
60
66
  */
61
67
  export declare const frameworkFailures: {
62
68
  readonly INVALID_INPUT: {
@@ -78,6 +84,7 @@ export declare const frameworkFailures: {
78
84
  };
79
85
  /** One of the error codes Launch itself returns: a key of {@link frameworkFailures}. */
80
86
  export type FrameworkCode = keyof typeof frameworkFailures;
87
+ type FrameworkData<Code extends FrameworkCode> = Code extends "INVALID_INPUT" ? InvalidInputData : null;
81
88
  /**
82
89
  * An error response returned by a procedure: either a Launch framework failure or one
83
90
  * of the procedure's declared errors.
@@ -90,15 +97,18 @@ export type FrameworkCode = keyof typeof frameworkFailures;
90
97
  * returned by that exact procedure, not `RpcError` instances created elsewhere.
91
98
  *
92
99
  * @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.
100
+ * @typeParam Data - The error's data: {@link InvalidInputData} for `INVALID_INPUT`,
101
+ * `null` for the other framework failures, the data schema's output for declared errors.
95
102
  */
96
- export declare class RpcError<Code extends string = FrameworkCode, Data = null> extends Error {
103
+ export declare class RpcError<Code extends string = FrameworkCode, Data = Code extends FrameworkCode ? FrameworkData<Code> : null> extends Error {
97
104
  /** The framework or declared error code. */
98
105
  readonly code: Code;
99
106
  /** The HTTP status of the response. */
100
107
  readonly status: number;
101
- /** The error's data: `null` for framework failures, validated data for declared errors. */
108
+ /**
109
+ * The error's data: {@link InvalidInputData} for `INVALID_INPUT`, `null` for the other
110
+ * framework failures, validated data for declared errors.
111
+ */
102
112
  readonly data: Data;
103
113
  /**
104
114
  * Creates an error with the given code, status and data.
@@ -115,7 +125,10 @@ export declare class RpcError<Code extends string = FrameworkCode, Data = null>
115
125
  code: Code,
116
126
  /** The HTTP status of the response. */
117
127
  status: number,
118
- /** The error's data: `null` for framework failures, validated data for declared errors. */
128
+ /**
129
+ * The error's data: {@link InvalidInputData} for `INVALID_INPUT`, `null` for the other
130
+ * framework failures, validated data for declared errors.
131
+ */
119
132
  data?: Data, message?: string);
120
133
  }
121
134
  /**
@@ -124,14 +137,21 @@ export declare class RpcError<Code extends string = FrameworkCode, Data = null>
124
137
  * @remarks
125
138
  * Internal; not exported from a public entry point. Used by the generated client to
126
139
  * 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.
140
+ * exactly as `{ error: { code, message, data } }`, with the framework code's own
141
+ * status and message. `data` must be exactly {@link InvalidInputData} for
142
+ * `INVALID_INPUT` and `null` for the other codes.
129
143
  *
130
144
  * @param value - The parsed response body.
131
145
  * @param status - The response's HTTP status.
132
- * @returns The framework code, or `undefined` when the body doesn't match exactly.
146
+ * @returns The framework code and data, or `undefined` when the body doesn't match
147
+ * exactly.
133
148
  */
134
- export declare function recognizedFailure(value: unknown, status: number): FrameworkCode | undefined;
149
+ export declare function recognizedFailure(value: unknown, status: number): {
150
+ /** The framework code. */
151
+ code: FrameworkCode;
152
+ /** The failure's data. */
153
+ data: InvalidInputData | null;
154
+ } | undefined;
135
155
  /**
136
156
  * Recognizes a response body that is exactly a framework failure or one of the given
137
157
  * declared errors.
@@ -153,11 +173,11 @@ export declare function recognizedError(value: unknown, status: number, declared
153
173
  code: string;
154
174
  /** The error's message. */
155
175
  message: string;
156
- /** The declared error's data as received, or `null` for a framework failure. */
176
+ /** The error's data as received. */
157
177
  data: unknown;
158
178
  } | undefined;
159
179
  type FrameworkError = {
160
- [Code in FrameworkCode]: RpcError<Code, null>;
180
+ [Code in FrameworkCode]: RpcError<Code, FrameworkData<Code>>;
161
181
  }[FrameworkCode];
162
182
  type DeclaredError<Errors extends ErrorDefinitions> = {
163
183
  [Code in keyof Errors & string]: RpcError<Code, OutputOf<Errors[Code]["data"]>>;
@@ -166,8 +186,9 @@ type DeclaredError<Errors extends ErrorDefinitions> = {
166
186
  * The errors a generated callable for a procedure can reject with as {@link RpcError}s.
167
187
  *
168
188
  * @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
189
+ * A union discriminated by `code`: one member per framework failure, with
190
+ * {@link InvalidInputData} for `INVALID_INPUT` and `null` data for the others, and one
191
+ * per declared error with its data schema's output type. Import the group
171
192
  * with `import type` so server code stays out of the browser bundle.
172
193
  *
173
194
  * @example
package/client.js CHANGED
@@ -1,15 +1,19 @@
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
- * - `FORBIDDEN` (403): a guard returned `false`, or a mutation was called during
8
- * server rendering.
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.
9
+ * - `FORBIDDEN` (403): middleware or a handler threw `forbidden()`, the request wasn't
10
+ * proven to come from the app's own origin, or a mutation was called during server
11
+ * rendering.
9
12
  * - `RPC_NOT_FOUND` (404): no procedure exists at the requested path.
10
13
  * - `INTERNAL` (500): anything else. Details go to the server log, never to the client.
11
14
  *
12
- * These codes are reserved: procedures can't declare errors with them.
15
+ * The other codes have `null` data. These codes are reserved: procedures can't declare
16
+ * errors with them.
13
17
  */
14
18
  export const frameworkFailures = {
15
19
  INVALID_INPUT: { status: 400, message: "Invalid RPC input" },
@@ -29,8 +33,8 @@ export const frameworkFailures = {
29
33
  * returned by that exact procedure, not `RpcError` instances created elsewhere.
30
34
  *
31
35
  * @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.
36
+ * @typeParam Data - The error's data: {@link InvalidInputData} for `INVALID_INPUT`,
37
+ * `null` for the other framework failures, the data schema's output for declared errors.
34
38
  */
35
39
  export class RpcError extends Error {
36
40
  code;
@@ -51,7 +55,10 @@ export class RpcError extends Error {
51
55
  code,
52
56
  /** The HTTP status of the response. */
53
57
  status,
54
- /** The error's data: `null` for framework failures, validated data for declared errors. */
58
+ /**
59
+ * The error's data: {@link InvalidInputData} for `INVALID_INPUT`, `null` for the other
60
+ * framework failures, validated data for declared errors.
61
+ */
55
62
  data = null, message) {
56
63
  if (message === undefined) {
57
64
  if (!Object.hasOwn(frameworkFailures, code)) {
@@ -72,12 +79,14 @@ export class RpcError extends Error {
72
79
  * @remarks
73
80
  * Internal; not exported from a public entry point. Used by the generated client to
74
81
  * 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.
82
+ * exactly as `{ error: { code, message, data } }`, with the framework code's own
83
+ * status and message. `data` must be exactly {@link InvalidInputData} for
84
+ * `INVALID_INPUT` and `null` for the other codes.
77
85
  *
78
86
  * @param value - The parsed response body.
79
87
  * @param status - The response's HTTP status.
80
- * @returns The framework code, or `undefined` when the body doesn't match exactly.
88
+ * @returns The framework code and data, or `undefined` when the body doesn't match
89
+ * exactly.
81
90
  */
82
91
  export function recognizedFailure(value, status) {
83
92
  try {
@@ -104,11 +113,16 @@ export function recognizedFailure(value, status) {
104
113
  }
105
114
  for (const code of Object.keys(frameworkFailures)) {
106
115
  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;
116
+ if (error.code !== code || status !== expected.status || error.message !== expected.message) {
117
+ continue;
118
+ }
119
+ if (code === "INVALID_INPUT") {
120
+ if (isInvalidInputData(error.data)) {
121
+ return { code, data: error.data };
122
+ }
123
+ }
124
+ else if (error.data === null) {
125
+ return { code, data: null };
112
126
  }
113
127
  }
114
128
  return undefined;
@@ -132,7 +146,11 @@ export function recognizedFailure(value, status) {
132
146
  export function recognizedError(value, status, declared) {
133
147
  const framework = recognizedFailure(value, status);
134
148
  if (framework) {
135
- return { code: framework, message: frameworkFailures[framework].message, data: null };
149
+ return {
150
+ code: framework.code,
151
+ message: frameworkFailures[framework.code].message,
152
+ data: framework.data,
153
+ };
136
154
  }
137
155
  try {
138
156
  serializeJson(value);
@@ -0,0 +1,2 @@
1
+ import type { GenerationSession } from "./index.js";
2
+ export declare const contextFiles: WeakMap<GenerationSession, string>;