@loozo/angular-launch 0.0.4 → 0.0.6

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 (59) hide show
  1. package/README.md +695 -102
  2. package/builders/application.d.ts +4 -0
  3. package/builders/application.js +71 -0
  4. package/builders/options.d.ts +10 -0
  5. package/builders/options.js +64 -0
  6. package/builders/serve.d.ts +8 -0
  7. package/builders/serve.js +248 -0
  8. package/builders.json +15 -0
  9. package/channel.d.ts +53 -0
  10. package/channel.js +231 -0
  11. package/client.d.ts +59 -16
  12. package/client.js +3 -2
  13. package/connect.d.ts +201 -0
  14. package/connect.js +148 -0
  15. package/generated.d.ts +1 -1
  16. package/generated.js +86 -3
  17. package/generation/context-file.d.ts +2 -0
  18. package/generation/context-file.js +3 -0
  19. package/generation/index.js +77 -36
  20. package/index.d.ts +6 -1
  21. package/index.js +2 -0
  22. package/json.d.ts +9 -0
  23. package/json.js +24 -0
  24. package/navigation.d.ts +36 -0
  25. package/navigation.js +47 -0
  26. package/node/index.d.ts +57 -0
  27. package/node/index.js +175 -0
  28. package/outcomes.d.ts +55 -0
  29. package/outcomes.js +100 -0
  30. package/package.json +14 -4
  31. package/schemas/application.json +756 -0
  32. package/schemas/serve.json +153 -0
  33. package/server/backend.d.ts +42 -23
  34. package/server/backend.js +137 -47
  35. package/server/channel-messages.d.ts +54 -0
  36. package/server/channel-messages.js +84 -0
  37. package/server/channel-socket.d.ts +67 -0
  38. package/server/channel-socket.js +322 -0
  39. package/server/definitions.d.ts +463 -181
  40. package/server/definitions.js +90 -103
  41. package/server/dispatch.d.ts +99 -20
  42. package/server/dispatch.js +337 -89
  43. package/server/event-stream.d.ts +63 -0
  44. package/server/event-stream.js +173 -0
  45. package/server/generated.d.ts +1 -0
  46. package/server/generated.js +1 -0
  47. package/server/index.d.ts +6 -3
  48. package/server/index.js +2 -1
  49. package/server/outcomes.d.ts +75 -0
  50. package/server/outcomes.js +90 -0
  51. package/server/response-effects.d.ts +105 -0
  52. package/server/response-effects.js +78 -0
  53. package/server/upgrade.d.ts +58 -0
  54. package/server/upgrade.js +117 -0
  55. package/stream.d.ts +31 -0
  56. package/stream.js +159 -0
  57. package/tanstack-query/README.md +110 -22
  58. package/tanstack-query/generated.js +5 -2
  59. package/tanstack-query/queries.d.ts +8 -6
@@ -2,6 +2,7 @@ import type { JsonShape } from "../json.js";
2
2
  import type { FrameworkCode } from "../client.js";
3
3
  import { declaredFailures } from "./errors.js";
4
4
  import type { DeclaredFailure } from "./errors.js";
5
+ import type { ResponseControl } from "./response-effects.js";
5
6
  /**
6
7
  * Registration point for the application's context type.
7
8
  *
@@ -16,7 +17,7 @@ export interface Register {
16
17
  * The application's context type, as registered by generation.
17
18
  *
18
19
  * @remarks
19
- * Handlers and guards receive a value of this type as `context`. It's `never` until
20
+ * Middleware and handlers start from a value of this type as `context`. It's `never` until
20
21
  * generation has registered the context type, so include the generated files in your
21
22
  * tsconfig.
22
23
  */
@@ -30,8 +31,8 @@ export type Context = Register extends {
30
31
  * @remarks
31
32
  * Launch uses schemas for procedure inputs and declared error data. Validation may be
32
33
  * asynchronous and may transform the value. For a procedure input, callers pass the
33
- * input type and the procedure's guards and handler receive the output type; group
34
- * guards receive no input, and the client's success value is the handler's result,
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,
35
36
  * not a schema output. For declared error data, the client receives the output type.
36
37
  *
37
38
  * @example
@@ -136,9 +137,10 @@ export type OutputOf<S> = S extends Schema<unknown, infer Output> ? Output : und
136
137
  */
137
138
  export interface ContextDefinition<Value> {
138
139
  /**
139
- * Creates the context for one live server request.
140
+ * Creates the context for one live server request, or for one page Angular prerenders.
140
141
  *
141
- * @param request - The request bound to the new request scope.
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.
142
144
  * @returns The context value, or a promise of it.
143
145
  */
144
146
  readonly create: (request: Request) => Value;
@@ -153,8 +155,12 @@ export interface ContextDefinition<Value> {
153
155
  * from this entry point and call it without type arguments; a context assigned to a
154
156
  * variable and exported later, or `defineContext<MyContext>(...)`, fails generation.
155
157
  * The factory runs once per live server request, for page renders
156
- * and RPC requests alike, and its value is what handlers and guards receive as
157
- * `context`. Keep per-request state in the context rather than in module variables.
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.
158
164
  *
159
165
  * @example
160
166
  * ```ts
@@ -174,52 +180,6 @@ export interface ContextDefinition<Value> {
174
180
  export declare function defineContext<Value>(create: (request: Request) => Value): ContextDefinition<Value>;
175
181
  /** The awaited context type of a context created by {@link defineContext}. */
176
182
  export type ContextOf<Definition> = Definition extends ContextDefinition<infer Value> ? Awaited<Value> : never;
177
- /**
178
- * A group guard, passed to `defineRpc` in `canActivate`.
179
- *
180
- * @remarks
181
- * Group guards run after input validation and before the procedure's guards, for
182
- * every procedure in the group. Returning `false` fails the call with `FORBIDDEN`;
183
- * throwing fails it with `INTERNAL`. Guards aren't inherited through the route tree
184
- * and don't narrow types.
185
- *
186
- * @example
187
- * ```ts
188
- * import type { Guard } from "@loozo/angular-launch/server";
189
- *
190
- * export const isSignedIn: Guard = ({ context }) => context.user !== null;
191
- * ```
192
- */
193
- export type Guard = (args: {
194
- /** The context created for the request. */
195
- readonly context: Context;
196
- /**
197
- * The live request the call runs in, bound to its request scope: the scope's copy of
198
- * the RPC HTTP request, or, during server rendering, the page request given to Angular.
199
- */
200
- readonly request: Request;
201
- }) => boolean | Promise<boolean>;
202
- /**
203
- * A procedure guard, passed to `query` or `mutation` in `canActivate`.
204
- *
205
- * @remarks
206
- * Procedure guards run after the group's guards and receive the validated input as
207
- * well. Returning `false` fails the call with `FORBIDDEN`; throwing fails it with
208
- * `INTERNAL`.
209
- *
210
- * @typeParam Input - The procedure's input schema, or `undefined` without input.
211
- */
212
- export type ProcedureGuard<Input> = (args: {
213
- /** The context created for the request. */
214
- readonly context: Context;
215
- /**
216
- * The live request the call runs in, bound to its request scope: the scope's copy of
217
- * the RPC HTTP request, or, during server rendering, the page request given to Angular.
218
- */
219
- readonly request: Request;
220
- /** The validated input: the schema's output, or `undefined` without an input schema. */
221
- readonly input: OutputOf<Input>;
222
- }) => boolean | Promise<boolean>;
223
183
  type Digit = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
224
184
  type StatusNumber<Value> = Value extends `${infer Status extends number}` ? Status : never;
225
185
  /** An HTTP error status from 400 to 599, as an integer literal type. */
@@ -268,14 +228,232 @@ export type ErrorFactories<Definitions extends ErrorDefinitions> = {
268
228
  };
269
229
  type JsonContract<Value> = 0 extends 1 & Value ? never : [Value] extends [JsonShape<Value>] ? unknown : never;
270
230
  type InputContract<Input> = Input extends Schema ? JsonContract<InputOf<Input>> : unknown;
231
+ type MessageContract<Message> = Message extends Schema ? JsonContract<InputOf<Message>> : never;
271
232
  type ErrorContract<Definitions extends ErrorDefinitions> = {
272
233
  readonly [Code in keyof Definitions]: Code extends FrameworkCode | "__proto__" ? never : Definitions[Code]["message"] extends "" ? never : Definitions[Code] & JsonContract<OutputOf<Definitions[Code]["data"]>>;
273
234
  };
274
235
  type JsonResult<Value> = Value extends Promise<infer Result> ? Promise<JsonShape<Result>> : JsonShape<Value>;
275
- /** Whether a procedure reads (`"query"`) or writes (`"mutation"`). */
276
- export type ProcedureKind = "query" | "mutation";
277
236
  /**
278
- * A procedure created by {@link query} or {@link mutation}.
237
+ * Whether a procedure reads (`"query"`), writes (`"mutation"`), streams values while it
238
+ * runs (`"stream"`) or talks both ways over a websocket (`"channel"`).
239
+ */
240
+ export type ProcedureKind = "query" | "mutation" | "stream" | "channel";
241
+ type StreamResult<Value> = Value extends AsyncIterable<infer Item> ? AsyncIterable<JsonShape<Item>, void> : never;
242
+ 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
+ /**
251
+ * What a middleware's `next()` resolves to, and what the middleware must return.
252
+ *
253
+ * @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.
256
+ *
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.
261
+ *
262
+ * @typeParam Added - The values the middleware passed to `next()`.
263
+ * @typeParam Keys - The keys of `Added`. Leave it to its default.
264
+ */
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
+ };
273
+ }
274
+ /**
275
+ * What middleware and handlers receive for one call.
276
+ *
277
+ * @typeParam ContextValue - The context at this point of the call.
278
+ * @typeParam Input - The validated input, or `unknown` for group middleware.
279
+ */
280
+ export interface CallArgs<ContextValue, Input> {
281
+ /**
282
+ * The context created for the request, with what earlier middleware added to it.
283
+ *
284
+ * @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.
287
+ */
288
+ readonly context: Readonly<ContextValue>;
289
+ /**
290
+ * The validated input: the schema's output, or `undefined` without an input schema.
291
+ * Group middleware runs before validation and receives `undefined`.
292
+ */
293
+ readonly input: Input;
294
+ /**
295
+ * The live request the call runs in, bound to its request scope: the scope's copy of
296
+ * the RPC HTTP request, or, during server rendering, the page request given to Angular.
297
+ * When Angular prerenders a page, it's a cookie-less `GET` of the page's URL.
298
+ */
299
+ readonly request: Request;
300
+ /**
301
+ * Aborts when the caller goes away: over HTTP when the incoming request's signal
302
+ * aborts, and during server rendering when the page request aborts or `HttpClient`
303
+ * unsubscribes before the call settled. When Angular prerenders a page, the page
304
+ * request aborts when the render's application is destroyed. Advisory: pass it on to work that accepts one.
305
+ */
306
+ readonly signal: AbortSignal;
307
+ /**
308
+ * The call's cookies and headers. Over HTTP they go on the RPC response; during server
309
+ * rendering, cookies go on the page response and headers are dropped. A prerendered page
310
+ * has no response, so a cookie set while Angular prerenders it fails the build, unless
311
+ * it's set after the app is first stable, such as in a `BEFORE_APP_SERIALIZED` hook.
312
+ */
313
+ readonly response: ResponseControl;
314
+ }
315
+ /**
316
+ * What a middleware receives: the call's arguments and `next`.
317
+ *
318
+ * @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.
323
+ *
324
+ * @example
325
+ * ```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
+ * }
333
+ *
334
+ * return next({ todo });
335
+ * },
336
+ * );
337
+ * ```
338
+ *
339
+ * @typeParam Needs - The context the middleware needs. Defaults to {@link Context}.
340
+ * @typeParam Input - The input the middleware needs. Defaults to `unknown`.
341
+ */
342
+ export interface MiddlewareArgs<Needs = Context, Input = unknown> extends CallArgs<Needs, Input> {
343
+ /**
344
+ * Continues the call, optionally with values merged into the context.
345
+ *
346
+ * @remarks
347
+ * A function property rather than a method, so destructuring it is safe.
348
+ */
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
+ };
374
+ }
375
+ /**
376
+ * A middleware created by {@link middleware}.
377
+ *
378
+ * @typeParam Needs - The context it needs.
379
+ * @typeParam Added - The values it adds to the context.
380
+ * @typeParam Input - The input it needs.
381
+ */
382
+ export interface MiddlewareDefinition<Needs, Added, Input> {
383
+ /** Runs the middleware for one call. */
384
+ readonly run: (args: MiddlewareArgs<Needs, Input>) => Promise<MiddlewareResult<Added>>;
385
+ }
386
+ type AnyMiddleware = {
387
+ readonly run: (args: never) => Promise<{
388
+ readonly [middlewareResult]: {
389
+ readonly keys: (key: never) => PropertyKey;
390
+ readonly values: object;
391
+ };
392
+ }>;
393
+ };
394
+ /**
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.
397
+ *
398
+ * @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.
405
+ *
406
+ * `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.
416
+ *
417
+ * 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
419
+ * `INTERNAL` and is logged on the server. Declared errors belong to handlers.
420
+ *
421
+ * @example
422
+ * ```ts
423
+ * import { forbidden, middleware } from "@loozo/angular-launch/server";
424
+ *
425
+ * export const signedIn = middleware(async ({ context, next }) => {
426
+ * if (context.user === null) {
427
+ * throw forbidden();
428
+ * }
429
+ *
430
+ * return next({ user: context.user });
431
+ * });
432
+ * ```
433
+ *
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`.
439
+ * @param run - Runs the middleware for one call.
440
+ * @returns The middleware, to list in a `use` array.
441
+ */
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> ? [
450
+ [
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] : [];
455
+ /**
456
+ * A procedure created by a group's `query`, `mutation`, `stream` or `channel` builder.
279
457
  *
280
458
  * @remarks
281
459
  * Procedures are values for `defineRpc`. Their types drive the generated client;
@@ -283,158 +461,255 @@ export type ProcedureKind = "query" | "mutation";
283
461
  *
284
462
  * @typeParam Input - The input schema, or `undefined` without input.
285
463
  * @typeParam Output - The handler's return type.
286
- * @typeParam Kind - Whether the procedure is a query or a mutation.
464
+ * @typeParam Kind - Whether the procedure is a query, a mutation, a stream or a channel.
287
465
  * @typeParam Errors - The declared errors.
466
+ * @typeParam Message - A channel's message schema; `undefined` for the other kinds.
288
467
  */
289
- export interface Procedure<Input, Output, Kind extends ProcedureKind = "query", Errors extends ErrorDefinitions = {}> {
290
- /** Whether the procedure is a `"query"` or a `"mutation"`. */
468
+ export interface Procedure<Input, Output, Kind extends ProcedureKind = "query", Errors extends ErrorDefinitions = {}, Message = undefined> {
469
+ /** Whether the procedure is a `"query"`, a `"mutation"`, a `"stream"` or a `"channel"`. */
291
470
  readonly kind: Kind;
292
471
  /** The input schema, or `undefined` for a procedure without input. */
293
472
  readonly input: Input;
473
+ /**
474
+ * The schema a channel validates each message from its caller with; `undefined` for the
475
+ * other kinds.
476
+ */
477
+ readonly message: Message;
294
478
  /** The declared errors, as written in the procedure's options. */
295
479
  readonly errors: Errors;
296
- /** The procedure's guards, in the order they run. Empty when none were given. */
297
- readonly canActivate: readonly ProcedureGuard<Input>[];
480
+ /** The procedure's middleware, in the order it runs. Empty when none was given. */
481
+ readonly use: readonly AnyMiddleware[];
298
482
  /**
299
483
  * Runs the authored handler with the procedure's own error factories.
300
484
  *
301
- * @param args - The context and the validated input. Any `errors` passed here are
302
- * ignored in favor of the procedure's own factories.
485
+ * @param args - The call's arguments. Any `errors` passed here are ignored in favor of
486
+ * the procedure's own factories.
303
487
  * @returns The handler's result.
304
488
  */
305
- readonly handler: (args: {
306
- /** The context created for the request. */
307
- readonly context: Context;
308
- /** The validated input: the schema's output, or `undefined` without an input schema. */
309
- readonly input: OutputOf<Input>;
310
- /** Ignored; the authored handler receives the procedure's own factories. */
311
- readonly errors: ErrorFactories<Errors>;
312
- }) => Output | Promise<Output>;
489
+ readonly handler: (args: CallArgs<never, never>) => Output | Promise<Output>;
313
490
  /** Internal record of errors created by this procedure's factories; not public API. */
314
491
  readonly [declaredFailures]: WeakMap<object, DeclaredFailure>;
315
492
  }
316
493
  /**
317
- * The options {@link query} and {@link mutation} take.
494
+ * The options a group's `query` and `mutation` builders take.
318
495
  *
319
496
  * @remarks
320
497
  * Write them inline in the call; generation reads them statically.
321
498
  *
499
+ * @typeParam ContextValue - The context after the group's middleware.
322
500
  * @typeParam Input - The input schema, or `undefined` without input.
501
+ * @typeParam Use - The procedure's middleware.
323
502
  * @typeParam Output - The handler's return type.
324
503
  * @typeParam Errors - The declared errors.
325
504
  */
326
- export interface ProcedureOptions<Input, Output, Errors extends ErrorDefinitions> {
505
+ export interface ProcedureOptions<ContextValue, Input, Use extends readonly AnyMiddleware[], Output, Errors extends ErrorDefinitions> {
327
506
  /** The schema the server validates the input with; omit it for a procedure without input. */
328
507
  readonly input?: Input & InputContract<NoInfer<Input>>;
329
- /** The declared errors, keyed by error code. */
330
- readonly errors?: Errors & ErrorContract<NoInfer<Errors>>;
331
508
  /**
332
- * Guards run in order after the group's guards. The first to return `false` rejects the
333
- * call as `FORBIDDEN`.
509
+ * Middleware that runs in order after the group's middleware and input validation,
510
+ * with the validated input. Each entry must accept the context and input before it.
334
511
  */
335
- readonly canActivate?: readonly ProcedureGuard<Input>[];
512
+ readonly use?: Use & CheckChain<ContextValue, OutputOf<Input>, NoInfer<Use>>;
513
+ /** The declared errors, keyed by error code. */
514
+ readonly errors?: Errors & ErrorContract<NoInfer<Errors>>;
336
515
  /**
337
516
  * Runs the call and returns its strict JSON result.
338
517
  *
339
- * @param args - The request's context, the validated input and the error factories.
518
+ * @param args - The call's arguments and the error factories.
340
519
  * @returns The call's result, or a promise of it.
341
520
  */
342
- readonly handler: (args: {
343
- /** The context created for the request. */
344
- readonly context: Context;
345
- /** The validated input: the schema's output, or `undefined` without an input schema. */
346
- readonly input: OutputOf<Input>;
521
+ readonly handler: (args: CallArgs<ContextAfter<ContextValue, Use>, OutputOf<Input>> & {
347
522
  /** One factory per declared error code, creating an error to `throw`. */
348
523
  readonly errors: ErrorFactories<Errors>;
349
524
  }) => Output & JsonResult<NoInfer<Output>>;
350
525
  }
351
526
  /**
352
- * Defines a procedure that reads data.
353
- *
354
- * @remarks
355
- * The handler receives `{ context, input, errors }`: the request's {@link Context},
356
- * the validated input (`undefined` without an input schema) and the
357
- * error factories for the declared errors. A call validates the input, runs the
358
- * group's guards, then the procedure's guards, then the handler. Inputs and results
359
- * must be strict JSON; a result that isn't fails the call with `INTERNAL`. Throwing an
360
- * error created by `errors` returns that declared error; any other exception fails the
361
- * call with `INTERNAL` and is logged on the server.
362
- *
363
- * An explicit `input` schema must have a concrete type, without `undefined`, `null`,
364
- * `any` or `unknown` branches, or generation fails: `Schema<string> | undefined` is
365
- * rejected. The schema's caller input type may still be a JSON union, as in
366
- * `Schema<string | number, number>`.
367
- *
368
- * Query responses are stored in Angular's HTTP transfer cache during server rendering
369
- * by default, so hydration reuses them.
370
- *
371
- * @example
372
- * ```ts
373
- * list: query({
374
- * handler: ({ context }) => context.db.todos.listForUser(requireUser(context).id),
375
- * }),
376
- * ```
377
- *
378
- * @typeParam Input - The input schema; omit `input` for a procedure without input.
379
- * @typeParam Output - The handler's return type.
380
- * @typeParam Errors - The declared errors, written inline.
381
- * @param options - The procedure's `input` schema, `canActivate` guards, inline
382
- * `errors` declarations and `handler`.
383
- * @returns The procedure, to use as a value in `defineRpc`.
384
- * @throws TypeError when a declared error is invalid: its code isn't an identifier, is
385
- * `__proto__` or a framework code, its status isn't an integer from 400 to 599, its
386
- * message is empty, or its data isn't a Standard Schema V1.
527
+ * The options a group's `stream` builder takes: those of `query`, with a handler that
528
+ * returns an async iterable, usually an `async function*`.
529
+ */
530
+ export interface StreamOptions<ContextValue, Input, Use extends readonly AnyMiddleware[], Output, Errors extends ErrorDefinitions> extends Omit<ProcedureOptions<ContextValue, Input, Use, Output, Errors>, "handler"> {
531
+ /**
532
+ * Runs the stream: each value it yields is sent to the caller as strict JSON, until it
533
+ * returns or throws.
534
+ */
535
+ readonly handler: (args: CallArgs<ContextAfter<ContextValue, Use>, OutputOf<Input>> & {
536
+ /** One factory per declared error code, creating an error to `throw`. */
537
+ readonly errors: ErrorFactories<Errors>;
538
+ }) => Output & StreamResult<NoInfer<Output>>;
539
+ }
540
+ /**
541
+ * The options a group's `channel` builder takes: those of `stream`, with a required
542
+ * `message` schema and a handler that also receives the caller's `messages`.
387
543
  */
388
- export declare function query<Input extends Schema | undefined = undefined, Output = unknown, const Errors extends ErrorDefinitions = {}>(options: ProcedureOptions<Input, Output, Errors>): Procedure<Input, Output, "query", Errors>;
544
+ export interface ChannelOptions<ContextValue, Input, Message, Use extends readonly AnyMiddleware[], Output, Errors extends ErrorDefinitions> extends Omit<ProcedureOptions<ContextValue, Input, Use, Output, Errors>, "handler"> {
545
+ /**
546
+ * The schema the server validates each message from the caller with, when the handler
547
+ * reads it. Its caller input type is what the client's `send` takes.
548
+ */
549
+ readonly message: Message & MessageContract<NoInfer<Message>>;
550
+ /**
551
+ * Runs the channel: each value it yields is sent to the caller as strict JSON, until it
552
+ * returns or throws.
553
+ */
554
+ readonly handler: (args: CallArgs<ContextAfter<ContextValue, Use>, OutputOf<Input>> & {
555
+ /** One factory per declared error code, creating an error to `throw`. */
556
+ readonly errors: ErrorFactories<Errors>;
557
+ /**
558
+ * The caller's messages, validated with `message` as they're read, in arrival order.
559
+ *
560
+ * @remarks
561
+ * One consumer only: a second iterator throws. Iteration ends when the caller closes
562
+ * the channel. A message that fails validation ends the call with `INVALID_INPUT` and
563
+ * the schema's issues.
564
+ */
565
+ readonly messages: AsyncIterable<OutputOf<Message>>;
566
+ }) => Output & StreamResult<NoInfer<Output>>;
567
+ }
389
568
  /**
390
- * Defines a procedure that writes data.
569
+ * The `query`, `mutation`, `stream` and `channel` builders `defineRpc` passes to its callback.
391
570
  *
392
571
  * @remarks
393
- * The handler receives `{ context, input, errors }`: the request's {@link Context},
394
- * the validated input (`undefined` without an input schema) and the
395
- * error factories for the declared errors. A call validates the input, runs the
396
- * group's guards, then the procedure's guards, then the handler. Inputs and results
397
- * must be strict JSON; a result that isn't fails the call with `INTERNAL`. Throwing an
398
- * error created by `errors` returns that declared error; any other exception fails the
399
- * call with `INTERNAL` and is logged on the server.
400
- *
401
- * An explicit `input` schema must have a concrete type, without `undefined`, `null`,
402
- * `any` or `unknown` branches, or generation fails: `Schema<string> | undefined` is
403
- * rejected. The schema's caller input type may still be a JSON union, as in
404
- * `Schema<string | number, number>`.
405
- *
406
- * Mutations never use the HTTP transfer cache. During server rendering they fail with
407
- * `FORBIDDEN` before validation, guards or the handler run.
408
- *
409
- * @example
410
- * ```ts
411
- * add: mutation({
412
- * input: titleSchema,
413
- * handler: ({ input, context }) =>
414
- * context.db.todos.addForUser(requireUser(context).id, input.title),
415
- * }),
416
- * ```
572
+ * Function properties rather than methods, so destructuring them is safe.
417
573
  *
418
- * @typeParam Input - The input schema; omit `input` for a procedure without input.
419
- * @typeParam Output - The handler's return type.
420
- * @typeParam Errors - The declared errors, written inline.
421
- * @param options - The procedure's `input` schema, `canActivate` guards, inline
422
- * `errors` declarations and `handler`.
423
- * @returns The procedure, to use as a value in `defineRpc`.
424
- * @throws TypeError when a declared error is invalid: its code isn't an identifier, is
425
- * `__proto__` or a framework code, its status isn't an integer from 400 to 599, its
426
- * message is empty, or its data isn't a Standard Schema V1.
574
+ * @typeParam ContextValue - The context after the group's middleware.
427
575
  */
428
- export declare function mutation<Input extends Schema | undefined = undefined, Output = unknown, const Errors extends ErrorDefinitions = {}>(options: ProcedureOptions<Input, Output, Errors>): Procedure<Input, Output, "mutation", Errors>;
576
+ export interface ProcedureBuilder<ContextValue> {
577
+ /**
578
+ * Defines a procedure that reads data.
579
+ *
580
+ * @remarks
581
+ * The handler receives `{ context, input, errors, request, signal, response }`: the
582
+ * context after the group's and the procedure's middleware, the validated input
583
+ * (`undefined` without an input schema), the error factories for the declared errors,
584
+ * the request the call runs in, its abort signal and its response cookies and headers. Inputs and results must be strict JSON; a
585
+ * result that isn't fails the call with `INTERNAL`. Throwing an error created by
586
+ * `errors` returns that declared error, throwing `forbidden()` fails the call with
587
+ * `FORBIDDEN`, and throwing `notFound()` or `redirect(to)` answers it with that outcome;
588
+ * any other exception fails the call with `INTERNAL` and is logged on the server.
589
+ *
590
+ * An explicit `input` schema must have a concrete type, without `undefined`, `null`,
591
+ * `any` or `unknown` branches, or generation fails: `Schema<string> | undefined` is
592
+ * rejected. The schema's caller input type may still be a JSON union, as in
593
+ * `Schema<string | number, number>`.
594
+ *
595
+ * Query responses are stored in Angular's HTTP transfer cache during server rendering
596
+ * by default, so hydration reuses them.
597
+ *
598
+ * @example
599
+ * ```ts
600
+ * list: query({
601
+ * handler: ({ context, signal }) => context.db.todos.listForUser(context.user.id, { signal }),
602
+ * }),
603
+ * ```
604
+ *
605
+ * @typeParam Input - The input schema; omit `input` for a procedure without input.
606
+ * @typeParam Use - The procedure's middleware, written inline.
607
+ * @typeParam Output - The handler's return type.
608
+ * @typeParam Errors - The declared errors, written inline.
609
+ * @param options - The procedure's `input` schema, `use` middleware, inline `errors`
610
+ * declarations and `handler`.
611
+ * @returns The procedure, to use as a value in the callback's result.
612
+ * @throws TypeError when a declared error is invalid: its code isn't an identifier, is
613
+ * `__proto__` or a framework code, its status isn't an integer from 400 to 599, its
614
+ * message is empty, or its data isn't a Standard Schema V1.
615
+ */
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>;
617
+ /**
618
+ * Defines a procedure that writes data.
619
+ *
620
+ * @remarks
621
+ * Takes the same options as `query`, and its handler receives the same arguments.
622
+ *
623
+ * Mutations never use the HTTP transfer cache. During server rendering they fail with
624
+ * `FORBIDDEN` before any middleware, validation or the handler runs.
625
+ *
626
+ * @example
627
+ * ```ts
628
+ * add: mutation({
629
+ * input: titleSchema,
630
+ * handler: ({ input, context }) => context.db.todos.addForUser(context.user.id, input.title),
631
+ * }),
632
+ * ```
633
+ *
634
+ * @typeParam Input - The input schema; omit `input` for a procedure without input.
635
+ * @typeParam Use - The procedure's middleware, written inline.
636
+ * @typeParam Output - The handler's return type.
637
+ * @typeParam Errors - The declared errors, written inline.
638
+ * @param options - The procedure's `input` schema, `use` middleware, inline `errors`
639
+ * declarations and `handler`.
640
+ * @returns The procedure, to use as a value in the callback's result.
641
+ * @throws TypeError when a declared error is invalid, as for `query`.
642
+ */
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>;
644
+ /**
645
+ * Defines a procedure that sends values while it runs: a stream.
646
+ *
647
+ * @remarks
648
+ * Takes the same options as `query`, except that the handler returns an async iterable,
649
+ * usually written as `handler: async function* ({ context, input, signal }) { … }`. Each
650
+ * value it yields reaches the caller as soon as it's yielded.
651
+ *
652
+ * 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.
655
+ *
656
+ * @example
657
+ * ```ts
658
+ * watch: stream({
659
+ * input: idSchema,
660
+ * handler: async function* ({ context, input, signal }) {
661
+ * for await (const chat of context.chats.changes(input.id, { signal })) {
662
+ * yield chat;
663
+ * }
664
+ * },
665
+ * }),
666
+ * ```
667
+ */
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>;
669
+ /**
670
+ * Defines a procedure that talks both ways over a websocket: a channel.
671
+ *
672
+ * @remarks
673
+ * Takes a stream's options plus a required `message` schema. The handler is a stream
674
+ * handler that also receives `messages`, the caller's messages validated with `message` as
675
+ * it reads them, written as `handler: async function* ({ context, input, messages }) { … }`.
676
+ * Each value it yields reaches the caller as soon as the caller has room for it; a slow
677
+ * reader pauses the handler at its `yield`, and a handler that stops reading `messages`
678
+ * makes the caller's `send` wait.
679
+ *
680
+ * 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.
686
+ *
687
+ * @example
688
+ * ```ts
689
+ * talk: channel({
690
+ * input: chatSchema,
691
+ * message: textSchema,
692
+ * handler: async function* ({ context, input, messages, signal }) {
693
+ * yield { kind: "history", messages: await context.chats.history(input.chatId) };
694
+ *
695
+ * for await (const message of messages) {
696
+ * yield { kind: "answer", text: await context.chats.answer(input.chatId, message.text, signal) };
697
+ * }
698
+ * },
699
+ * }),
700
+ * ```
701
+ */
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>;
703
+ }
429
704
  /**
430
705
  * The minimal shape `defineRpc` accepts for each procedure.
431
706
  *
432
707
  * @remarks
433
- * Create procedures with {@link query} or {@link mutation}; generation rejects any
434
- * other value.
708
+ * Create procedures with the `query` and `mutation` builders `defineRpc` passes to its
709
+ * callback; generation rejects any other value.
435
710
  */
436
711
  export interface ProcedureDefinition {
437
- /** Whether the procedure is a `"query"` or a `"mutation"`. */
712
+ /** Whether the procedure is a `"query"`, a `"mutation"`, a `"stream"` or a `"channel"`. */
438
713
  readonly kind: ProcedureKind;
439
714
  }
440
715
  /**
@@ -448,8 +723,8 @@ export interface Group<Name extends string, Procedures extends Record<string, Pr
448
723
  readonly name: Name;
449
724
  /** The group's procedures, keyed by procedure name. */
450
725
  readonly procedures: Procedures;
451
- /** The group's guards, in the order they run. Empty when none were given. */
452
- readonly canActivate: readonly Guard[];
726
+ /** The group's middleware, in the order it runs. Empty when none was given. */
727
+ readonly use: readonly AnyMiddleware[];
453
728
  }
454
729
  /**
455
730
  * Defines the RPC group for the route declared in the same directory.
@@ -458,46 +733,53 @@ export interface Group<Name extends string, Procedures extends Record<string, Pr
458
733
  * Default-export the result from a file next to the route's `route.ts`; one group per
459
734
  * route. That route must be one that gets generated files: not a redirect, and with a
460
735
  * page or descendants with pages that aren't all redirects. Generation reads the call
461
- * statically without running it: import `defineRpc`, `query` and `mutation` by name
462
- * from this entry point, call them directly without type arguments, use literal
463
- * identifiers other than `__proto__` for the namespace and procedure names, and
464
- * write the procedures, options and `canActivate` arrays inline. Each route's
465
- * generated `injectRpc()` exposes its own group and its ancestors' groups under their
466
- * namespaces. Each namespace must be unique across the app: calls go to
467
- * `/_rpc/<namespace>/<procedure>`.
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.
468
748
  *
469
749
  * Exposure isn't authorization: anyone who can reach the server can call any
470
- * procedure, so guard every group and procedure that needs it.
750
+ * procedure, so protect every group and procedure that needs it.
471
751
  *
472
752
  * @example
473
753
  * ```ts
474
- * import { defineRpc, query } from "@loozo/angular-launch/server";
475
- * import { isSignedIn, requireUser } from "../../auth.server";
754
+ * import { defineRpc } from "@loozo/angular-launch/server";
755
+ * import { signedIn } from "../../auth.server";
476
756
  *
477
757
  * export default defineRpc(
478
758
  * "todos",
479
- * {
759
+ * ({ query }) => ({
480
760
  * list: query({
481
- * handler: ({ context }) => context.db.todos.listForUser(requireUser(context).id),
761
+ * handler: ({ context }) => context.db.todos.listForUser(context.user.id),
482
762
  * }),
483
- * },
484
- * { canActivate: [isSignedIn] },
763
+ * }),
764
+ * { use: [signedIn] },
485
765
  * );
486
766
  * ```
487
767
  *
488
768
  * @typeParam Name - The namespace literal.
769
+ * @typeParam Use - The group's middleware, written inline.
489
770
  * @typeParam Procedures - The procedures, keyed by name.
490
771
  * @param name - The namespace the generated client exposes the group under.
491
- * @param procedures - The procedures, keyed by name.
492
- * @param options - `canActivate`: group guards that run for every procedure in the
493
- * group.
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.
494
775
  * @returns The group, to default-export.
495
776
  */
496
- export declare function defineRpc<Name extends string, Procedures extends Record<string, ProcedureDefinition>>(name: Name, procedures: Procedures, { canActivate, }?: {
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, }?: {
497
778
  /**
498
- * Guards run in order for every call to any procedure in the group, before the
499
- * procedure's own guards. The first to return `false` rejects the call as `FORBIDDEN`.
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.
500
782
  */
501
- readonly canActivate?: readonly Guard[];
783
+ readonly use?: Use & CheckChain<Context, unknown, NoInfer<Use>>;
502
784
  }): Group<Name, Procedures>;
503
785
  export {};