@loozo/angular-launch 0.0.6 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +715 -255
  2. package/builders/application.js +32 -3
  3. package/builders/channel-forwarding.d.ts +15 -0
  4. package/builders/channel-forwarding.js +61 -0
  5. package/builders/options.d.ts +6 -2
  6. package/builders/options.js +16 -5
  7. package/builders/serve.js +198 -140
  8. package/channel.d.ts +3 -1
  9. package/channel.js +3 -2
  10. package/client.d.ts +14 -24
  11. package/generation/index.d.ts +2 -123
  12. package/generation/index.js +3 -685
  13. package/generation/redirects.d.ts +14 -0
  14. package/generation/redirects.js +43 -0
  15. package/generation/run.d.ts +168 -0
  16. package/generation/run.js +659 -0
  17. package/index.d.ts +2 -0
  18. package/index.js +1 -0
  19. package/launch-queries.d.ts +16 -0
  20. package/launch-queries.js +3 -0
  21. package/navigation.d.ts +3 -3
  22. package/navigation.js +1 -1
  23. package/node/index.d.ts +3 -0
  24. package/node/index.js +6 -3
  25. package/node/upgrade-listener-slot.d.ts +1 -0
  26. package/node/upgrade-listener-slot.js +4 -0
  27. package/outcomes.d.ts +23 -7
  28. package/outcomes.js +58 -12
  29. package/package.json +15 -11
  30. package/redirect-translation.d.ts +53 -0
  31. package/redirect-translation.js +141 -0
  32. package/{generated.js → remote-client.js} +27 -21
  33. package/route-types.d.ts +130 -0
  34. package/route-types.js +1 -0
  35. package/route.d.ts +45 -0
  36. package/route.js +113 -0
  37. package/schemas/application.json +19 -3
  38. package/schemas/serve.json +3 -3
  39. package/server/application.d.ts +107 -0
  40. package/server/application.js +108 -0
  41. package/server/backend.d.ts +25 -13
  42. package/server/backend.js +39 -24
  43. package/server/channel-messages.d.ts +1 -1
  44. package/server/channel-messages.js +1 -1
  45. package/server/channel-socket.d.ts +1 -1
  46. package/server/definitions.d.ts +146 -298
  47. package/server/definitions.js +29 -117
  48. package/server/dispatch.d.ts +67 -63
  49. package/server/dispatch.js +121 -61
  50. package/server/event-stream.d.ts +2 -2
  51. package/server/event-stream.js +1 -1
  52. package/server/generated.d.ts +2 -1
  53. package/server/generated.js +2 -1
  54. package/server/index.d.ts +3 -2
  55. package/server/index.js +2 -1
  56. package/server/outcomes.d.ts +26 -13
  57. package/server/outcomes.js +43 -16
  58. package/server/read-cookies.d.ts +19 -0
  59. package/server/read-cookies.js +39 -0
  60. package/server/response-effects.d.ts +2 -2
  61. package/server/stages.d.ts +62 -0
  62. package/server/stages.js +51 -0
  63. package/server/upgrade.d.ts +11 -12
  64. package/server/upgrade.js +13 -14
  65. package/source-text.d.ts +1 -0
  66. package/source-text.js +56 -0
  67. package/stream.d.ts +6 -3
  68. package/stream.js +8 -6
  69. package/tanstack-query/README.md +15 -15
  70. package/tanstack-query/create-queries.d.ts +2 -0
  71. package/tanstack-query/{generated.js → create-queries.js} +8 -9
  72. package/tanstack-query/hydration-window.d.ts +11 -0
  73. package/tanstack-query/hydration-window.js +9 -0
  74. package/tanstack-query/hydration.d.ts +4 -14
  75. package/tanstack-query/hydration.js +9 -12
  76. package/tanstack-query/index.d.ts +1 -1
  77. package/tanstack-query/queries.d.ts +42 -27
  78. package/testing/call-procedure.d.ts +154 -0
  79. package/testing/call-procedure.js +97 -0
  80. package/testing/index.d.ts +2 -0
  81. package/testing/index.js +1 -0
  82. package/generation/context-file.d.ts +0 -2
  83. package/generation/context-file.js +0 -3
  84. package/tanstack-query/generated.d.ts +0 -5
  85. /package/{generated.d.ts → remote-client.d.ts} +0 -0
@@ -3,27 +3,6 @@ import type { FrameworkCode } from "../client.js";
3
3
  import { declaredFailures } from "./errors.js";
4
4
  import type { DeclaredFailure } from "./errors.js";
5
5
  import type { ResponseControl } from "./response-effects.js";
6
- /**
7
- * Registration point for the application's context type.
8
- *
9
- * @remarks
10
- * Generation writes `context.generated.d.ts`, which augments this interface with a
11
- * `context` property typed as the awaited return value of your `defineContext`
12
- * factory. Don't augment it yourself.
13
- */
14
- export interface Register {
15
- }
16
- /**
17
- * The application's context type, as registered by generation.
18
- *
19
- * @remarks
20
- * Middleware and handlers start from a value of this type as `context`. It's `never` until
21
- * generation has registered the context type, so include the generated files in your
22
- * tsconfig.
23
- */
24
- export type Context = Register extends {
25
- context: infer Value;
26
- } ? Value : never;
27
6
  /**
28
7
  * A {@link https://standardschema.dev | Standard Schema} V1 validator, from any library
29
8
  * or written by hand.
@@ -31,8 +10,8 @@ export type Context = Register extends {
31
10
  * @remarks
32
11
  * Launch uses schemas for procedure inputs and declared error data. Validation may be
33
12
  * asynchronous and may transform the value. For a procedure input, callers pass the
34
- * input type and the procedure's middleware and handler receive the output type; group
35
- * middleware receives no input, and the client's success value is the handler's result,
13
+ * input type and the procedure's middleware and handler receive the output type; a
14
+ * route's `.use()` middleware receives no input, and the client's success value is the handler's result,
36
15
  * not a schema output. For declared error data, the client receives the output type.
37
16
  *
38
17
  * @example
@@ -130,56 +109,6 @@ export type InputOf<S extends Schema> = NonNullable<S["~standard"]["types"]>["in
130
109
  * as for a procedure without input.
131
110
  */
132
111
  export type OutputOf<S> = S extends Schema<unknown, infer Output> ? Output : undefined;
133
- /**
134
- * The application's context factory, created by {@link defineContext}.
135
- *
136
- * @typeParam Value - The factory's return type, possibly a promise.
137
- */
138
- export interface ContextDefinition<Value> {
139
- /**
140
- * Creates the context for one live server request, or for one page Angular prerenders.
141
- *
142
- * @param request - The request bound to the new request scope: a cookie-less `GET` of
143
- * the page's URL when Angular prerenders it.
144
- * @returns The context value, or a promise of it.
145
- */
146
- readonly create: (request: Request) => Value;
147
- }
148
- /**
149
- * Defines the application's per-request server context.
150
- *
151
- * @remarks
152
- * Default-export the call itself from exactly one file in your application's sources,
153
- * as `export default defineContext(...)`: generation finds it by that default export and
154
- * registers its awaited return type as {@link Context}. Import `defineContext` by name
155
- * from this entry point and call it without type arguments; a context assigned to a
156
- * variable and exported later, or `defineContext<MyContext>(...)`, fails generation.
157
- * The factory runs once per live server request, for page renders
158
- * and RPC requests alike, and its value is the `context` middleware and handlers start
159
- * from. Keep per-request state in the context rather than in module variables.
160
- *
161
- * When Angular prerenders a page that calls an RPC, the factory runs at build time with a
162
- * cookie-less `GET` of the page's URL on a local origin Angular picks, so a prerendered
163
- * page shows what an anonymous visitor would see.
164
- *
165
- * @example
166
- * ```ts
167
- * import { defineContext } from "@loozo/angular-launch/server";
168
- * import { sessions } from "./sessions.server";
169
- *
170
- * export default defineContext(async (request: Request) => ({
171
- * user: await sessions.authenticate(request),
172
- * }));
173
- * ```
174
- *
175
- * @typeParam Value - The factory's return type, possibly a promise.
176
- * @param create - Creates the context for one request. A rejection or throw fails that
177
- * request: an RPC request returns `INTERNAL`.
178
- * @returns The context definition to default-export.
179
- */
180
- export declare function defineContext<Value>(create: (request: Request) => Value): ContextDefinition<Value>;
181
- /** The awaited context type of a context created by {@link defineContext}. */
182
- export type ContextOf<Definition> = Definition extends ContextDefinition<infer Value> ? Awaited<Value> : never;
183
112
  type Digit = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
184
113
  type StatusNumber<Value> = Value extends `${infer Status extends number}` ? Status : never;
185
114
  /** An HTTP error status from 400 to 599, as an integer literal type. */
@@ -240,55 +169,75 @@ type JsonResult<Value> = Value extends Promise<infer Result> ? Promise<JsonShape
240
169
  export type ProcedureKind = "query" | "mutation" | "stream" | "channel";
241
170
  type StreamResult<Value> = Value extends AsyncIterable<infer Item> ? AsyncIterable<JsonShape<Item>, void> : never;
242
171
  declare const middlewareResult: unique symbol;
243
- type OptionalKeys<Value> = {
244
- [Key in keyof Value]-?: {} extends Pick<Value, Key> ? Key : never;
245
- }[keyof Value];
246
- type IsUnion<Value, Whole = Value> = Value extends unknown ? [Whole] extends [Value] ? false : true : never;
247
- type AdditionRule<Value> = true extends IsUnion<Value> ? never : {
248
- readonly [Key in OptionalKeys<Value>]-?: never;
249
- };
250
172
  /**
251
173
  * What a middleware's `next()` resolves to, and what the middleware must return.
252
174
  *
253
175
  * @remarks
254
- * Opaque: it proves the rest of the call ran, and its type carries what the middleware
255
- * added to the context. There's no other way to create one.
176
+ * Opaque: it proves the rest of the call ran. There's no other way to create one.
177
+ */
178
+ export interface MiddlewareResult {
179
+ /** Type-only brand; absent at runtime. */
180
+ readonly [middlewareResult]: true;
181
+ }
182
+ /**
183
+ * What a route's `.context()` stage receives.
256
184
  *
257
- * Results that add different keys don't combine, so a middleware whose `next(...)` calls
258
- * add different keys is a type error rather than a result that hides some of them.
259
- * Results with the same keys combine only when one's values already include the
260
- * other's, so a value that differs per branch belongs in one `next()` call.
185
+ * @remarks
186
+ * A stage runs at most once per request scope, the first time a call needs it, and returns
187
+ * the whole context the stages, middleware and handlers below it receive: spread `context`
188
+ * to keep its keys. Annotate a standalone stage's argument with this type and the context
189
+ * it receives.
261
190
  *
262
- * @typeParam Added - The values the middleware passed to `next()`.
263
- * @typeParam Keys - The keys of `Added`. Leave it to its default.
191
+ * @example
192
+ * ```ts
193
+ * import { redirect, type StageArgs } from "@loozo/angular-launch/server";
194
+ * import type { Context } from "./routes/route.generated";
195
+ * import { destination as signIn } from "./routes/sign-in/destination.generated";
196
+ *
197
+ * export function signedIn({ context }: StageArgs<Context>) {
198
+ * if (context.user === null) {
199
+ * throw redirect(signIn, {});
200
+ * }
201
+ *
202
+ * return { ...context, user: context.user };
203
+ * }
204
+ * ```
205
+ *
206
+ * @typeParam ContextValue - The context of the stages above this one; `{}` for the first.
264
207
  */
265
- export interface MiddlewareResult<Added, Keys = keyof Added> {
266
- /** Type-only brand; absent at runtime. */
267
- readonly [middlewareResult]: {
268
- /** The added keys, in both directions so that results only combine with the same keys. */
269
- readonly keys: (key: Keys) => Keys;
270
- /** The added values. */
271
- readonly values: Added;
272
- };
208
+ export interface StageArgs<ContextValue> {
209
+ /** The context of the stages above this one, read-only at the top level. */
210
+ readonly context: Readonly<ContextValue>;
211
+ /**
212
+ * The request scope's request: the scope's copy of the RPC HTTP request or of the page
213
+ * request, or, when Angular prerenders a page, a cookie-less `GET` of its URL.
214
+ */
215
+ readonly request: Request;
216
+ /**
217
+ * The cookies and headers of the call that first needed this stage. A stage runs once
218
+ * per scope, so its cookies go out once, with that call's response.
219
+ */
220
+ readonly response: ResponseControl;
221
+ /** The request scope's signal: it aborts when the request does. */
222
+ readonly signal: AbortSignal;
273
223
  }
274
224
  /**
275
225
  * What middleware and handlers receive for one call.
276
226
  *
277
- * @typeParam ContextValue - The context at this point of the call.
278
- * @typeParam Input - The validated input, or `unknown` for group middleware.
227
+ * @typeParam ContextValue - The context of the call: what the route's stages returned.
228
+ * @typeParam Input - The validated input, or `unknown` for a route's `.use()` middleware.
279
229
  */
280
230
  export interface CallArgs<ContextValue, Input> {
281
231
  /**
282
- * The context created for the request, with what earlier middleware added to it.
232
+ * The context the owning route's stages built for the request scope, root first.
283
233
  *
284
234
  * @remarks
285
- * Read-only at the top level: a middleware adds or replaces values through `next()`,
286
- * so later middleware and the handler see their types. Nested objects stay writable.
235
+ * Read-only at the top level. Nested objects stay writable.
287
236
  */
288
237
  readonly context: Readonly<ContextValue>;
289
238
  /**
290
239
  * The validated input: the schema's output, or `undefined` without an input schema.
291
- * Group middleware runs before validation and receives `undefined`.
240
+ * A route's `.use()` middleware runs before validation and receives `undefined`.
292
241
  */
293
242
  readonly input: Input;
294
243
  /**
@@ -316,148 +265,112 @@ export interface CallArgs<ContextValue, Input> {
316
265
  * What a middleware receives: the call's arguments and `next`.
317
266
  *
318
267
  * @remarks
319
- * Annotate a middleware's argument with this type to declare what it needs: the context
320
- * values earlier middleware must have added, and the input the procedure's schema must
321
- * produce. Without an annotation a middleware needs the registered {@link Context} and
322
- * `unknown` input, so it fits anywhere.
268
+ * Annotate a standalone middleware's argument with this type, or pass `middleware` its
269
+ * type arguments, to declare what it needs: the context the route's stages must have
270
+ * built, and the input the procedure's schema must produce. Without them a middleware
271
+ * needs nothing, so it fits anywhere.
323
272
  *
324
273
  * @example
325
274
  * ```ts
326
- * export const ownTodo = middleware(
327
- * async ({ context, input, next }: MiddlewareArgs<{ user: User; db: Db }, { id: string }>) => {
328
- * const todo = await context.db.todos.findForUser(context.user.id, input.id);
329
- *
330
- * if (todo === null) {
331
- * throw forbidden();
332
- * }
275
+ * export const audit = middleware<{ user: User }>(async ({ context, next }) => {
276
+ * log(context.user.id);
333
277
  *
334
- * return next({ todo });
335
- * },
336
- * );
278
+ * return next();
279
+ * });
337
280
  * ```
338
281
  *
339
- * @typeParam Needs - The context the middleware needs. Defaults to {@link Context}.
282
+ * @typeParam Needs - The context the middleware needs. Defaults to `{}`.
340
283
  * @typeParam Input - The input the middleware needs. Defaults to `unknown`.
341
284
  */
342
- export interface MiddlewareArgs<Needs = Context, Input = unknown> extends CallArgs<Needs, Input> {
285
+ export interface MiddlewareArgs<Needs = {}, Input = unknown> extends CallArgs<Needs, Input> {
343
286
  /**
344
- * Continues the call, optionally with values merged into the context.
287
+ * Continues the call.
345
288
  *
346
289
  * @remarks
347
- * A function property rather than a method, so destructuring it is safe.
290
+ * A function property rather than a method, so destructuring it is safe. Middleware
291
+ * doesn't change the context; a route's `.context()` stage does.
292
+ *
293
+ * @returns The result to return from the middleware. It rejects with whatever the rest
294
+ * of the call threw, including declared errors and outcomes such as `forbidden()`.
348
295
  */
349
- readonly next: {
350
- /**
351
- * Continues the call with the context unchanged.
352
- *
353
- * @returns The result to return from the middleware. It rejects with whatever the
354
- * rest of the call threw, including declared errors and outcomes such as `forbidden()`.
355
- */
356
- (): Promise<MiddlewareResult<{}>>;
357
- /**
358
- * Continues the call with `added` merged into the context by spread, so later
359
- * middleware and the handler see its values and types.
360
- *
361
- * @remarks
362
- * `added` must be a single object type whose properties are all required: a missing
363
- * optional value would leave the earlier one in place, which the context's type can't
364
- * follow, and a union could hide such a key in one of its members. Write a value that
365
- * may be missing as `next({ user: maybeUser })` with a type such as `User | null`, and
366
- * alternatives as a union value: `next({ session: a | b })`.
367
- *
368
- * @param added - The values to add or replace.
369
- * @returns The result to return from the middleware. It rejects with whatever the
370
- * rest of the call threw, including declared errors and outcomes such as `forbidden()`.
371
- */
372
- <Added extends object>(added: Added & AdditionRule<Added>): Promise<MiddlewareResult<Added>>;
373
- };
296
+ readonly next: () => Promise<MiddlewareResult>;
374
297
  }
375
298
  /**
376
299
  * A middleware created by {@link middleware}.
377
300
  *
378
301
  * @typeParam Needs - The context it needs.
379
- * @typeParam Added - The values it adds to the context.
380
302
  * @typeParam Input - The input it needs.
381
303
  */
382
- export interface MiddlewareDefinition<Needs, Added, Input> {
304
+ export interface MiddlewareDefinition<Needs = {}, Input = unknown> {
383
305
  /** Runs the middleware for one call. */
384
- readonly run: (args: MiddlewareArgs<Needs, Input>) => Promise<MiddlewareResult<Added>>;
306
+ readonly run: (args: MiddlewareArgs<Needs, Input>) => Promise<MiddlewareResult>;
385
307
  }
386
308
  type AnyMiddleware = {
387
- readonly run: (args: never) => Promise<{
388
- readonly [middlewareResult]: {
389
- readonly keys: (key: never) => PropertyKey;
390
- readonly values: object;
391
- };
392
- }>;
393
- };
309
+ readonly run: (args: never) => Promise<MiddlewareResult>;
310
+ } | ((args: never) => Promise<MiddlewareResult>);
311
+ type ProcedureMiddleware<ContextValue, Input> = {
312
+ readonly run: (args: never) => Promise<MiddlewareResult>;
313
+ } | MiddlewareDefinition<ContextValue, Input>["run"];
394
314
  /**
395
- * Creates a middleware: code that runs around a procedure call, to refuse it, add typed
396
- * values to its context, or wrap the rest of it.
315
+ * Creates a middleware: code that runs around a procedure call, to refuse it or wrap the
316
+ * rest of it.
397
317
  *
398
318
  * @remarks
399
- * List middleware in `defineRpc`'s `use` to run it for every procedure in the group, or
400
- * in a procedure's `use` to run it for that procedure. A call runs the group's
401
- * middleware with no input, then validates the input, then runs the procedure's
402
- * middleware with the validated input, then the handler. Middleware runs for every
403
- * call, also during server rendering, where `request` is the page request, and when
404
- * Angular prerenders a page, where it's a cookie-less `GET` of the page's URL.
319
+ * List middleware in a route's `.use()` to run it for that route's own procedures, or in
320
+ * a procedure's `use` to run it for that procedure. Those lists also take a bare `run`
321
+ * function, typed with the route's context and, on a procedure, the validated input, so use
322
+ * `middleware` for middleware you share. A call runs the owning route's stages,
323
+ * then its `.use()` middleware with no input, then validates the input, then runs the
324
+ * procedure's middleware with the validated input, then the handler. Middleware runs for
325
+ * every call, also during server rendering, where `request` is the page request, and when
326
+ * Angular prerenders a page, where it's a cookie-less `GET` of the page's URL. A route's
327
+ * `.use()` isn't inherited: a child route's procedures don't run it.
405
328
  *
406
329
  * `run` must call `next()` exactly once and return its result: calling it twice or
407
- * returning anything else fails the call with `INTERNAL`. `next(added)` merges `added`
408
- * into the context by spread, so the context must be a plain object. The context is
409
- * read-only at the top level: change it through `next()`. Every `next(...)` in a
410
- * middleware adds the same keys, and a value that differs per branch goes in one
411
- * `next()` call with a union-typed value, such as
412
- * `next({ user: preview ? null : context.user })`: separate `next({ user: null })` and
413
- * `next({ user: context.user })` calls don't infer `User | null` when `context.user` is
414
- * a `User`. `next()` rejects when anything after it throws, so `await next()` in a `try`
415
- * wraps the rest of the call.
330
+ * returning anything else fails the call with `INTERNAL`. `next()` rejects when anything
331
+ * after it throws, so `await next()` in a `try` wraps the rest of the call. Middleware
332
+ * can't add to the context: derive values in a `.context()` stage instead.
416
333
  *
417
334
  * Refuse a call with `throw forbidden()`, which fails it with `FORBIDDEN`, or answer it
418
- * with `throw notFound()` or `throw redirect(to)`. Any other exception fails it with
335
+ * with `throw notFound()` or `throw redirect(destination, values)`. Any other exception fails it with
419
336
  * `INTERNAL` and is logged on the server. Declared errors belong to handlers.
420
337
  *
421
338
  * @example
422
339
  * ```ts
423
- * import { forbidden, middleware } from "@loozo/angular-launch/server";
340
+ * import { middleware } from "@loozo/angular-launch/server";
424
341
  *
425
- * export const signedIn = middleware(async ({ context, next }) => {
426
- * if (context.user === null) {
427
- * throw forbidden();
428
- * }
342
+ * export const timing = middleware(async ({ next, response }) => {
343
+ * const start = performance.now();
429
344
  *
430
- * return next({ user: context.user });
345
+ * try {
346
+ * return await next();
347
+ * } finally {
348
+ * response.headers.append("server-timing", `rpc;dur=${performance.now() - start}`);
349
+ * }
431
350
  * });
432
351
  * ```
433
352
  *
434
- * @typeParam Needs - The context it needs, from an annotated argument. Defaults to
435
- * {@link Context}.
436
- * @typeParam Added - The values it adds, inferred from what it passes to `next()`.
437
- * @typeParam Input - The input it needs, from an annotated argument. Defaults to
438
- * `unknown`.
353
+ * @typeParam Needs - The context it needs. Defaults to `{}`, also when the call is written
354
+ * inline in `.use()`: pass the keys it reads, as in `middleware<{ user: User }>(…)`, or
355
+ * write a bare function there instead.
356
+ * @typeParam Input - The input it needs. Defaults to `unknown`.
439
357
  * @param run - Runs the middleware for one call.
440
- * @returns The middleware, to list in a `use` array.
358
+ * @returns The middleware, to list in `.use()` or a procedure's `use`.
441
359
  */
442
- export declare function middleware<Needs = Context, Added extends object = {}, Input = unknown>(run: (args: MiddlewareArgs<Needs, Input>) => Promise<MiddlewareResult<Added>>): MiddlewareDefinition<Needs, Added, Input>;
443
- type KeySpellings<Key> = Key extends number ? Key | `${Key}` : Key extends `${infer Numeric extends number}` ? number extends Numeric ? Key : `${Numeric}` extends Key ? Key | Numeric : Key : Key;
444
- type Merge<Base, Added> = [keyof Added] extends [never] ? Base : Base extends unknown ? Omit<Base, KeySpellings<keyof Added>> & Added : never;
445
- type Flat<Value> = {
446
- [Key in keyof Value]: Value[Key];
447
- } & {};
448
- type ContextAfter<Base, Use> = Use extends readonly [infer First, ...infer Rest] ? First extends MiddlewareDefinition<infer _Needs, infer Added, infer _Input> ? ContextAfter<Flat<Merge<Base, Added>>, Rest> : Base : Base;
449
- type CheckChain<Base, Input, Use> = Use extends readonly [infer First, ...infer Rest] ? First extends MiddlewareDefinition<infer Needs, infer Added, infer NeedsInput> ? [
360
+ export declare function middleware<Needs = {}, Input = unknown>(run: (args: MiddlewareArgs<Needs, Input>) => Promise<MiddlewareResult>): MiddlewareDefinition<Needs, Input>;
361
+ type CheckChain<ContextValue, Input, Use> = Use extends readonly [] ? [] : Use extends readonly [infer First, ...infer Rest] ? First extends MiddlewareDefinition<infer Needs, infer NeedsInput> ? [
450
362
  [
451
- Base
452
- ] extends [Needs] ? [Input] extends [NeedsInput] ? true extends IsUnion<Added> ? never : [OptionalKeys<Added>] extends [never] ? First : never : never : never,
453
- ...CheckChain<Flat<Merge<Base, Added>>, Input, Rest>
454
- ] : [never] : [];
363
+ ContextValue
364
+ ] extends [Needs] ? ([Input] extends [NeedsInput] ? First : never) : never,
365
+ ...CheckChain<ContextValue, Input, Rest>
366
+ ] : First extends (args: never) => Promise<MiddlewareResult> ? [First, ...CheckChain<ContextValue, Input, Rest>] : [never] : readonly (MiddlewareDefinition<ContextValue, Input> | MiddlewareDefinition<ContextValue, Input>["run"])[];
455
367
  /**
456
- * A procedure created by a group's `query`, `mutation`, `stream` or `channel` builder.
368
+ * A procedure created by a `.remote()` builder's `query`, `mutation`, `stream` or
369
+ * `channel`.
457
370
  *
458
371
  * @remarks
459
- * Procedures are values for `defineRpc`. Their types drive the generated client;
460
- * the server dispatches calls to them. Don't build one by hand.
372
+ * Procedures are values in a route's `.remote()` namespaces. Their types drive the
373
+ * route's client; the server dispatches calls to them. Don't build one by hand.
461
374
  *
462
375
  * @typeParam Input - The input schema, or `undefined` without input.
463
376
  * @typeParam Output - The handler's return type.
@@ -477,7 +390,10 @@ export interface Procedure<Input, Output, Kind extends ProcedureKind = "query",
477
390
  readonly message: Message;
478
391
  /** The declared errors, as written in the procedure's options. */
479
392
  readonly errors: Errors;
480
- /** The procedure's middleware, in the order it runs. Empty when none was given. */
393
+ /**
394
+ * The procedure's middleware, `middleware()` definitions and bare functions, in the order
395
+ * it runs. Empty when none was given.
396
+ */
481
397
  readonly use: readonly AnyMiddleware[];
482
398
  /**
483
399
  * Runs the authored handler with the procedure's own error factories.
@@ -491,12 +407,12 @@ export interface Procedure<Input, Output, Kind extends ProcedureKind = "query",
491
407
  readonly [declaredFailures]: WeakMap<object, DeclaredFailure>;
492
408
  }
493
409
  /**
494
- * The options a group's `query` and `mutation` builders take.
410
+ * The options the `query` and `mutation` builders take.
495
411
  *
496
412
  * @remarks
497
413
  * Write them inline in the call; generation reads them statically.
498
414
  *
499
- * @typeParam ContextValue - The context after the group's middleware.
415
+ * @typeParam ContextValue - The context the declaring route's stages build.
500
416
  * @typeParam Input - The input schema, or `undefined` without input.
501
417
  * @typeParam Use - The procedure's middleware.
502
418
  * @typeParam Output - The handler's return type.
@@ -506,7 +422,7 @@ export interface ProcedureOptions<ContextValue, Input, Use extends readonly AnyM
506
422
  /** The schema the server validates the input with; omit it for a procedure without input. */
507
423
  readonly input?: Input & InputContract<NoInfer<Input>>;
508
424
  /**
509
- * Middleware that runs in order after the group's middleware and input validation,
425
+ * Middleware that runs in order after the route's `.use()` middleware and input validation,
510
426
  * with the validated input. Each entry must accept the context and input before it.
511
427
  */
512
428
  readonly use?: Use & CheckChain<ContextValue, OutputOf<Input>, NoInfer<Use>>;
@@ -518,13 +434,13 @@ export interface ProcedureOptions<ContextValue, Input, Use extends readonly AnyM
518
434
  * @param args - The call's arguments and the error factories.
519
435
  * @returns The call's result, or a promise of it.
520
436
  */
521
- readonly handler: (args: CallArgs<ContextAfter<ContextValue, Use>, OutputOf<Input>> & {
437
+ readonly handler: (args: CallArgs<ContextValue, OutputOf<Input>> & {
522
438
  /** One factory per declared error code, creating an error to `throw`. */
523
439
  readonly errors: ErrorFactories<Errors>;
524
440
  }) => Output & JsonResult<NoInfer<Output>>;
525
441
  }
526
442
  /**
527
- * The options a group's `stream` builder takes: those of `query`, with a handler that
443
+ * The options the `stream` builder takes: those of `query`, with a handler that
528
444
  * returns an async iterable, usually an `async function*`.
529
445
  */
530
446
  export interface StreamOptions<ContextValue, Input, Use extends readonly AnyMiddleware[], Output, Errors extends ErrorDefinitions> extends Omit<ProcedureOptions<ContextValue, Input, Use, Output, Errors>, "handler"> {
@@ -532,13 +448,13 @@ export interface StreamOptions<ContextValue, Input, Use extends readonly AnyMidd
532
448
  * Runs the stream: each value it yields is sent to the caller as strict JSON, until it
533
449
  * returns or throws.
534
450
  */
535
- readonly handler: (args: CallArgs<ContextAfter<ContextValue, Use>, OutputOf<Input>> & {
451
+ readonly handler: (args: CallArgs<ContextValue, OutputOf<Input>> & {
536
452
  /** One factory per declared error code, creating an error to `throw`. */
537
453
  readonly errors: ErrorFactories<Errors>;
538
454
  }) => Output & StreamResult<NoInfer<Output>>;
539
455
  }
540
456
  /**
541
- * The options a group's `channel` builder takes: those of `stream`, with a required
457
+ * The options the `channel` builder takes: those of `stream`, with a required
542
458
  * `message` schema and a handler that also receives the caller's `messages`.
543
459
  */
544
460
  export interface ChannelOptions<ContextValue, Input, Message, Use extends readonly AnyMiddleware[], Output, Errors extends ErrorDefinitions> extends Omit<ProcedureOptions<ContextValue, Input, Use, Output, Errors>, "handler"> {
@@ -551,7 +467,7 @@ export interface ChannelOptions<ContextValue, Input, Message, Use extends readon
551
467
  * Runs the channel: each value it yields is sent to the caller as strict JSON, until it
552
468
  * returns or throws.
553
469
  */
554
- readonly handler: (args: CallArgs<ContextAfter<ContextValue, Use>, OutputOf<Input>> & {
470
+ readonly handler: (args: CallArgs<ContextValue, OutputOf<Input>> & {
555
471
  /** One factory per declared error code, creating an error to `throw`. */
556
472
  readonly errors: ErrorFactories<Errors>;
557
473
  /**
@@ -566,12 +482,13 @@ export interface ChannelOptions<ContextValue, Input, Message, Use extends readon
566
482
  }) => Output & StreamResult<NoInfer<Output>>;
567
483
  }
568
484
  /**
569
- * The `query`, `mutation`, `stream` and `channel` builders `defineRpc` passes to its callback.
485
+ * The `query`, `mutation`, `stream` and `channel` builders a route's `.remote()` passes to
486
+ * its callback.
570
487
  *
571
488
  * @remarks
572
489
  * Function properties rather than methods, so destructuring them is safe.
573
490
  *
574
- * @typeParam ContextValue - The context after the group's middleware.
491
+ * @typeParam ContextValue - The context the declaring route's stages build.
575
492
  */
576
493
  export interface ProcedureBuilder<ContextValue> {
577
494
  /**
@@ -579,12 +496,12 @@ export interface ProcedureBuilder<ContextValue> {
579
496
  *
580
497
  * @remarks
581
498
  * The handler receives `{ context, input, errors, request, signal, response }`: the
582
- * context after the group's and the procedure's middleware, the validated input
499
+ * context the declaring route's stages built, the validated input
583
500
  * (`undefined` without an input schema), the error factories for the declared errors,
584
501
  * the request the call runs in, its abort signal and its response cookies and headers. Inputs and results must be strict JSON; a
585
502
  * result that isn't fails the call with `INTERNAL`. Throwing an error created by
586
503
  * `errors` returns that declared error, throwing `forbidden()` fails the call with
587
- * `FORBIDDEN`, and throwing `notFound()` or `redirect(to)` answers it with that outcome;
504
+ * `FORBIDDEN`, and throwing `notFound()` or `redirect()` answers it with that outcome;
588
505
  * any other exception fails the call with `INTERNAL` and is logged on the server.
589
506
  *
590
507
  * An explicit `input` schema must have a concrete type, without `undefined`, `null`,
@@ -613,7 +530,7 @@ export interface ProcedureBuilder<ContextValue> {
613
530
  * `__proto__` or a framework code, its status isn't an integer from 400 to 599, its
614
531
  * message is empty, or its data isn't a Standard Schema V1.
615
532
  */
616
- readonly query: <Input extends Schema | undefined = undefined, const Use extends readonly AnyMiddleware[] = [], Output = unknown, const Errors extends ErrorDefinitions = {}>(options: ProcedureOptions<ContextValue, Input, Use, Output, Errors>) => Procedure<Input, Output, "query", Errors>;
533
+ readonly query: <Input extends Schema | undefined = undefined, const Use extends readonly ProcedureMiddleware<ContextValue, OutputOf<Input>>[] = readonly ProcedureMiddleware<ContextValue, OutputOf<Input>>[], Output = unknown, const Errors extends ErrorDefinitions = {}>(options: ProcedureOptions<ContextValue, Input, Use, Output, Errors>) => Procedure<Input, Output, "query", Errors>;
617
534
  /**
618
535
  * Defines a procedure that writes data.
619
536
  *
@@ -621,7 +538,7 @@ export interface ProcedureBuilder<ContextValue> {
621
538
  * Takes the same options as `query`, and its handler receives the same arguments.
622
539
  *
623
540
  * Mutations never use the HTTP transfer cache. During server rendering they fail with
624
- * `FORBIDDEN` before any middleware, validation or the handler runs.
541
+ * `FORBIDDEN` before any stage, middleware, validation or the handler runs.
625
542
  *
626
543
  * @example
627
544
  * ```ts
@@ -640,7 +557,7 @@ export interface ProcedureBuilder<ContextValue> {
640
557
  * @returns The procedure, to use as a value in the callback's result.
641
558
  * @throws TypeError when a declared error is invalid, as for `query`.
642
559
  */
643
- readonly mutation: <Input extends Schema | undefined = undefined, const Use extends readonly AnyMiddleware[] = [], Output = unknown, const Errors extends ErrorDefinitions = {}>(options: ProcedureOptions<ContextValue, Input, Use, Output, Errors>) => Procedure<Input, Output, "mutation", Errors>;
560
+ readonly mutation: <Input extends Schema | undefined = undefined, const Use extends readonly ProcedureMiddleware<ContextValue, OutputOf<Input>>[] = readonly ProcedureMiddleware<ContextValue, OutputOf<Input>>[], Output = unknown, const Errors extends ErrorDefinitions = {}>(options: ProcedureOptions<ContextValue, Input, Use, Output, Errors>) => Procedure<Input, Output, "mutation", Errors>;
644
561
  /**
645
562
  * Defines a procedure that sends values while it runs: a stream.
646
563
  *
@@ -650,8 +567,8 @@ export interface ProcedureBuilder<ContextValue> {
650
567
  * value it yields reaches the caller as soon as it's yielded.
651
568
  *
652
569
  * The stream's response starts once the handler returned its iterable, so cookies must
653
- * be set before that: in middleware before `next()`, or in a handler that isn't a
654
- * generator. Setting one later throws, and later header changes are ignored.
570
+ * be set before that: in a stage, in middleware before `next()`, or in a handler that
571
+ * isn't a generator. A stage's cookies are set before the iterable starts. Setting one later throws, and later header changes are ignored.
655
572
  *
656
573
  * @example
657
574
  * ```ts
@@ -665,7 +582,7 @@ export interface ProcedureBuilder<ContextValue> {
665
582
  * }),
666
583
  * ```
667
584
  */
668
- readonly stream: <Input extends Schema | undefined = undefined, const Use extends readonly AnyMiddleware[] = [], Output extends AsyncIterable<unknown> = AsyncIterable<unknown>, const Errors extends ErrorDefinitions = {}>(options: StreamOptions<ContextValue, Input, Use, Output, Errors>) => Procedure<Input, Output, "stream", Errors>;
585
+ readonly stream: <Input extends Schema | undefined = undefined, const Use extends readonly ProcedureMiddleware<ContextValue, OutputOf<Input>>[] = readonly ProcedureMiddleware<ContextValue, OutputOf<Input>>[], Output extends AsyncIterable<unknown> = AsyncIterable<unknown>, const Errors extends ErrorDefinitions = {}>(options: StreamOptions<ContextValue, Input, Use, Output, Errors>) => Procedure<Input, Output, "stream", Errors>;
669
586
  /**
670
587
  * Defines a procedure that talks both ways over a websocket: a channel.
671
588
  *
@@ -678,11 +595,11 @@ export interface ProcedureBuilder<ContextValue> {
678
595
  * makes the caller's `send` wait.
679
596
  *
680
597
  * The call runs over `GET /_rpc/<namespace>/<procedure>?input=…` upgraded to a websocket by
681
- * the generated `handleUpgrade`, not `handleRequest`. Middleware, input validation and the
682
- * handler run before the upgrade's `101` response, which carries the call's cookies and
683
- * headers, so cookies follow a stream's rules: set them in middleware before `next()` or in
684
- * a handler that isn't a generator. During server rendering a channel fails with
685
- * `FORBIDDEN` before any middleware runs.
598
+ * the generated `handleUpgrade`, not `handleRequest`. The route's stages, middleware, input
599
+ * validation and the handler run before the upgrade's `101` response, which carries the
600
+ * call's cookies and headers, so cookies follow a stream's rules: set them in a stage, in
601
+ * middleware before `next()` or in a handler that isn't a generator. During server
602
+ * rendering a channel fails with `FORBIDDEN` before any stage or middleware runs.
686
603
  *
687
604
  * @example
688
605
  * ```ts
@@ -699,87 +616,18 @@ export interface ProcedureBuilder<ContextValue> {
699
616
  * }),
700
617
  * ```
701
618
  */
702
- readonly channel: <Input extends Schema | undefined = undefined, Message extends Schema = Schema, const Use extends readonly AnyMiddleware[] = [], Output extends AsyncIterable<unknown> = AsyncIterable<unknown>, const Errors extends ErrorDefinitions = {}>(options: ChannelOptions<ContextValue, Input, Message, Use, Output, Errors>) => Procedure<Input, Output, "channel", Errors, Message>;
619
+ readonly channel: <Input extends Schema | undefined = undefined, Message extends Schema = Schema, const Use extends readonly ProcedureMiddleware<ContextValue, OutputOf<Input>>[] = readonly ProcedureMiddleware<ContextValue, OutputOf<Input>>[], Output extends AsyncIterable<unknown> = AsyncIterable<unknown>, const Errors extends ErrorDefinitions = {}>(options: ChannelOptions<ContextValue, Input, Message, Use, Output, Errors>) => Procedure<Input, Output, "channel", Errors, Message>;
703
620
  }
621
+ export declare const builder: ProcedureBuilder<never>;
704
622
  /**
705
- * The minimal shape `defineRpc` accepts for each procedure.
623
+ * The minimal shape `.remote()` accepts for each procedure.
706
624
  *
707
625
  * @remarks
708
- * Create procedures with the `query` and `mutation` builders `defineRpc` passes to its
709
- * callback; generation rejects any other value.
626
+ * Create procedures with the builders `.remote()` passes to its callback; generation
627
+ * rejects any other value.
710
628
  */
711
629
  export interface ProcedureDefinition {
712
630
  /** Whether the procedure is a `"query"`, a `"mutation"`, a `"stream"` or a `"channel"`. */
713
631
  readonly kind: ProcedureKind;
714
632
  }
715
- /**
716
- * An RPC group created by {@link defineRpc}.
717
- *
718
- * @typeParam Name - The group's namespace.
719
- * @typeParam Procedures - The group's procedures, keyed by name.
720
- */
721
- export interface Group<Name extends string, Procedures extends Record<string, ProcedureDefinition>> {
722
- /** The namespace the generated client exposes the group under. */
723
- readonly name: Name;
724
- /** The group's procedures, keyed by procedure name. */
725
- readonly procedures: Procedures;
726
- /** The group's middleware, in the order it runs. Empty when none was given. */
727
- readonly use: readonly AnyMiddleware[];
728
- }
729
- /**
730
- * Defines the RPC group for the route declared in the same directory.
731
- *
732
- * @remarks
733
- * Default-export the result from a file next to the route's `route.ts`; one group per
734
- * route. That route must be one that gets generated files: not a redirect, and with a
735
- * page or descendants with pages that aren't all redirects. Generation reads the call
736
- * statically without running it: import `defineRpc` by name from this entry point and
737
- * call it directly without type arguments, with a literal identifier other than
738
- * `__proto__` for the namespace; pass an arrow function whose parameter destructures
739
- * `query` and/or `mutation` without renaming and whose body is a parenthesized object
740
- * literal of procedures, each a direct `query(...)` or `mutation(...)` call with inline
741
- * options; and write the group options inline. Each route's generated `injectRpc()`
742
- * exposes its own group and its ancestors' groups under their namespaces. Each namespace
743
- * must be unique across the app: calls go to `/_rpc/<namespace>/<procedure>`.
744
- *
745
- * The group's `use` middleware runs for every procedure in the group, before input
746
- * validation, and the procedures' handlers and middleware see what it adds to the
747
- * context. It isn't inherited through the route tree.
748
- *
749
- * Exposure isn't authorization: anyone who can reach the server can call any
750
- * procedure, so protect every group and procedure that needs it.
751
- *
752
- * @example
753
- * ```ts
754
- * import { defineRpc } from "@loozo/angular-launch/server";
755
- * import { signedIn } from "../../auth.server";
756
- *
757
- * export default defineRpc(
758
- * "todos",
759
- * ({ query }) => ({
760
- * list: query({
761
- * handler: ({ context }) => context.db.todos.listForUser(context.user.id),
762
- * }),
763
- * }),
764
- * { use: [signedIn] },
765
- * );
766
- * ```
767
- *
768
- * @typeParam Name - The namespace literal.
769
- * @typeParam Use - The group's middleware, written inline.
770
- * @typeParam Procedures - The procedures, keyed by name.
771
- * @param name - The namespace the generated client exposes the group under.
772
- * @param build - Returns the procedures, keyed by name, built with the `query` and
773
- * `mutation` builders it receives.
774
- * @param options - `use`: middleware that runs for every procedure in the group.
775
- * @returns The group, to default-export.
776
- */
777
- export declare function defineRpc<Name extends string, const Use extends readonly AnyMiddleware[] = [], Procedures extends Record<string, ProcedureDefinition> = {}>(name: Name, build: (builder: ProcedureBuilder<ContextAfter<Context, Use>>) => Procedures, { use, }?: {
778
- /**
779
- * Middleware that runs in order for every call to any procedure in the group, before
780
- * input validation and the procedure's own middleware. It receives no input. Each
781
- * entry must accept the context before it.
782
- */
783
- readonly use?: Use & CheckChain<Context, unknown, NoInfer<Use>>;
784
- }): Group<Name, Procedures>;
785
633
  export {};