@loozo/angular-launch 0.0.1 → 0.0.3

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,140 @@
1
+ import { type FrameworkCode } from "../client.js";
2
+ import type { ContextDefinition, ContextOf, Group, ProcedureDefinition } from "./definitions.js";
3
+ /**
4
+ * The application's RPC groups, keyed by namespace.
5
+ *
6
+ * @remarks
7
+ * Internal; not exported from a public entry point. Generation writes it as
8
+ * `registry` in `server.generated.ts`.
9
+ */
10
+ export type Registry = Readonly<Record<string, Group<string, Record<string, ProcedureDefinition>>>>;
11
+ declare const scopeMarker: unique symbol;
12
+ /**
13
+ * The application identity and context definition that requests are bound to.
14
+ *
15
+ * @remarks
16
+ * Internal; not exported from a public entry point. Generation writes it as
17
+ * `appBinding` in `server.generated.ts`.
18
+ *
19
+ * @typeParam Definition - The application's context definition.
20
+ */
21
+ export interface ApplicationBinding<Definition extends ContextDefinition<unknown> = ContextDefinition<unknown>> {
22
+ /** The generated application identity. */
23
+ readonly id: string;
24
+ /** The application's context definition. */
25
+ readonly context: Definition;
26
+ }
27
+ /**
28
+ * A live server request bound to the context created for it.
29
+ *
30
+ * @remarks
31
+ * Created by the generated `createContext` in `server.generated.ts`.
32
+ * Render a page by passing `scope.request` together with `scope` as Angular's request
33
+ * context; RPC calls during that render fail with `INTERNAL` if the two don't belong
34
+ * together.
35
+ *
36
+ * @typeParam Value - The context value.
37
+ */
38
+ export interface RequestScope<Value = unknown> {
39
+ /** The identity of the application the scope was created for. */
40
+ readonly appId: string;
41
+ /** A random identifier tying `request` to this scope. */
42
+ readonly binding: string;
43
+ /** A clone of the original request that carries the scope binding. */
44
+ readonly request: Request;
45
+ /** The awaited context value created for `request`. */
46
+ readonly value: Value;
47
+ /** Internal brand of genuine request scopes; not public API. */
48
+ readonly [scopeMarker]: true;
49
+ }
50
+ /**
51
+ * Checks whether a value has the shape of a {@link RequestScope}.
52
+ *
53
+ * @remarks
54
+ * Internal; not exported from a public entry point. It doesn't check which application
55
+ * or request the scope belongs to; Launch checks that separately before dispatching.
56
+ *
57
+ * @param value - The value to check.
58
+ * @returns `true` for values carrying the request scope brand and fields.
59
+ */
60
+ export declare function isRequestScope(value: unknown): value is RequestScope;
61
+ /**
62
+ * Creates the context for a live server request and binds them into a
63
+ * {@link RequestScope}.
64
+ *
65
+ * @remarks
66
+ * Internal: exported only from `@loozo/angular-launch/_server` for the generated
67
+ * `createContext` in `server.generated.ts`; call that instead.
68
+ * The scope's `request` is a clone of `request` with an added
69
+ * `x-loozo-launch-scope` header, so the original stays usable. The context factory
70
+ * receives that clone.
71
+ *
72
+ * @typeParam Definition - The application's context definition.
73
+ * @param application - The application binding.
74
+ * @param request - The live server request.
75
+ * @returns The request scope.
76
+ * @throws Rejects with whatever the context factory throws or rejects with, or with a
77
+ * `TypeError` when `request`'s body was already read and can't be cloned.
78
+ */
79
+ export declare function createRequestScope<Definition extends ContextDefinition<unknown>>(application: ApplicationBinding<Definition>, request: Request): Promise<RequestScope<ContextOf<Definition>>>;
80
+ export declare function assertBoundScope(scope: unknown, application: ApplicationBinding, request: Request): asserts scope is RequestScope;
81
+ /** The HTTP status and JSON body {@link dispatch} produces for one call. Internal. */
82
+ export interface Reply {
83
+ /** The HTTP status: 200 for a result, otherwise the error's status. */
84
+ readonly status: number;
85
+ /** The result, or an `{ error: { code, message, data } }` frame. */
86
+ readonly body: unknown;
87
+ }
88
+ export declare function failure(code: FrameworkCode): Reply;
89
+ export declare function isJsonMediaType(contentType: string | null): boolean;
90
+ /**
91
+ * Runs one procedure call within a request scope and produces its reply.
92
+ *
93
+ * @remarks
94
+ * The shared pipeline behind {@link handleRpc} and the server-rendering backend of
95
+ * {@link provideLaunchServer}. Internal; not exported from a public entry point. It
96
+ * never rejects: every failure becomes a framework failure reply, and
97
+ * unexpected errors are logged on the server.
98
+ *
99
+ * In order: the scope must belong to `application` and `request` (`INTERNAL`); the
100
+ * path must be `/_rpc/<namespace>/<procedure>` for a registered procedure
101
+ * (`RPC_NOT_FOUND`); a mutation in `"rendering"` mode is refused (`FORBIDDEN`); the
102
+ * envelope must be strict JSON (`INTERNAL` otherwise, such as for `{ input: undefined }`,
103
+ * a cycle or an accessor); it must then be exactly `{ input }` (`INVALID_INPUT`) with
104
+ * input that passes the schema, or `null` without one (`INVALID_INPUT`); the group's
105
+ * guards and then the procedure's guards must return `true` (`FORBIDDEN`). The
106
+ * handler's strict JSON result is returned with status 200, and its declared errors
107
+ * with their status.
108
+ *
109
+ * @param registry - The application's RPC groups.
110
+ * @param path - The request path.
111
+ * @param envelope - The parsed request body.
112
+ * @param scope - The request scope whose context the call receives.
113
+ * @param application - The application binding the scope must belong to.
114
+ * @param request - The request the scope must be bound to.
115
+ * @param mode - `"http"` for browser requests (the default) or `"rendering"` for calls
116
+ * made during server rendering.
117
+ * @returns The reply to send.
118
+ */
119
+ export declare function dispatch(registry: Registry, path: string, envelope: unknown, scope: RequestScope, application: ApplicationBinding, request: Request, mode?: "http" | "rendering"): Promise<Reply>;
120
+ /**
121
+ * Answers an RPC HTTP request, or returns `null` for any other request.
122
+ *
123
+ * @remarks
124
+ * Internal: exported only from `@loozo/angular-launch/_server` for the generated
125
+ * `handleRequest` in `server.generated.ts`; call that instead.
126
+ * Any path starting with `/_rpc/` is treated as an RPC request. It must be a `POST`
127
+ * with an `application/json` content type and no query string, otherwise the reply is
128
+ * `INVALID_INPUT` and no context is created. A fresh context is then created before the
129
+ * body is parsed; if that fails the reply is `INTERNAL`, even when the body isn't JSON.
130
+ * Otherwise a body that isn't JSON gives `INVALID_INPUT`. Responses are JSON with
131
+ * `Cache-Control: private, no-store` and `Vary: Cookie`.
132
+ *
133
+ * @typeParam Definition - The application's context definition.
134
+ * @param registry - The application's RPC groups.
135
+ * @param application - The application binding.
136
+ * @param request - The incoming server request.
137
+ * @returns The RPC response, or `null` when the path doesn't start with `/_rpc/`.
138
+ */
139
+ export declare function handleRpc<Definition extends ContextDefinition<unknown>>(registry: Registry, application: ApplicationBinding<Definition>, request: Request): Promise<Response | null>;
140
+ export {};
@@ -3,6 +3,16 @@ import { serializeJson } from "../json.js";
3
3
  import { declaredFailures } from "./errors.js";
4
4
  const scopeMarker = Symbol.for("@loozo/angular-launch/private-request-scope/v1");
5
5
  const bindingHeader = "x-loozo-launch-scope";
6
+ /**
7
+ * Checks whether a value has the shape of a {@link RequestScope}.
8
+ *
9
+ * @remarks
10
+ * Internal; not exported from a public entry point. It doesn't check which application
11
+ * or request the scope belongs to; Launch checks that separately before dispatching.
12
+ *
13
+ * @param value - The value to check.
14
+ * @returns `true` for values carrying the request scope brand and fields.
15
+ */
6
16
  export function isRequestScope(value) {
7
17
  return (typeof value === "object" &&
8
18
  value !== null &&
@@ -16,6 +26,24 @@ export function isRequestScope(value) {
16
26
  typeof value.binding === "string" &&
17
27
  "value" in value);
18
28
  }
29
+ /**
30
+ * Creates the context for a live server request and binds them into a
31
+ * {@link RequestScope}.
32
+ *
33
+ * @remarks
34
+ * Internal: exported only from `@loozo/angular-launch/_server` for the generated
35
+ * `createContext` in `server.generated.ts`; call that instead.
36
+ * The scope's `request` is a clone of `request` with an added
37
+ * `x-loozo-launch-scope` header, so the original stays usable. The context factory
38
+ * receives that clone.
39
+ *
40
+ * @typeParam Definition - The application's context definition.
41
+ * @param application - The application binding.
42
+ * @param request - The live server request.
43
+ * @returns The request scope.
44
+ * @throws Rejects with whatever the context factory throws or rejects with, or with a
45
+ * `TypeError` when `request`'s body was already read and can't be cloned.
46
+ */
19
47
  export async function createRequestScope(application, request) {
20
48
  const binding = crypto.randomUUID();
21
49
  const headers = new Headers(request.headers);
@@ -47,10 +75,39 @@ export function failure(code) {
47
75
  export function isJsonMediaType(contentType) {
48
76
  return contentType?.split(";", 1)[0].trim().toLowerCase() === "application/json";
49
77
  }
78
+ /**
79
+ * Runs one procedure call within a request scope and produces its reply.
80
+ *
81
+ * @remarks
82
+ * The shared pipeline behind {@link handleRpc} and the server-rendering backend of
83
+ * {@link provideLaunchServer}. Internal; not exported from a public entry point. It
84
+ * never rejects: every failure becomes a framework failure reply, and
85
+ * unexpected errors are logged on the server.
86
+ *
87
+ * In order: the scope must belong to `application` and `request` (`INTERNAL`); the
88
+ * path must be `/_rpc/<namespace>/<procedure>` for a registered procedure
89
+ * (`RPC_NOT_FOUND`); a mutation in `"rendering"` mode is refused (`FORBIDDEN`); the
90
+ * envelope must be strict JSON (`INTERNAL` otherwise, such as for `{ input: undefined }`,
91
+ * a cycle or an accessor); it must then be exactly `{ input }` (`INVALID_INPUT`) with
92
+ * input that passes the schema, or `null` without one (`INVALID_INPUT`); the group's
93
+ * guards and then the procedure's guards must return `true` (`FORBIDDEN`). The
94
+ * handler's strict JSON result is returned with status 200, and its declared errors
95
+ * with their status.
96
+ *
97
+ * @param registry - The application's RPC groups.
98
+ * @param path - The request path.
99
+ * @param envelope - The parsed request body.
100
+ * @param scope - The request scope whose context the call receives.
101
+ * @param application - The application binding the scope must belong to.
102
+ * @param request - The request the scope must be bound to.
103
+ * @param mode - `"http"` for browser requests (the default) or `"rendering"` for calls
104
+ * made during server rendering.
105
+ * @returns The reply to send.
106
+ */
50
107
  export async function dispatch(registry, path, envelope, scope, application, request, mode = "http") {
51
108
  try {
52
109
  assertBoundScope(scope, application, request);
53
- const parts = /^\/_rpc\/([a-f0-9]{24})\/([A-Za-z_][A-Za-z0-9_]*)$/.exec(path);
110
+ const parts = /^\/_rpc\/([A-Za-z_][A-Za-z0-9_]*)\/([A-Za-z_][A-Za-z0-9_]*)$/.exec(path);
54
111
  if (!parts || !Object.hasOwn(registry, parts[1])) {
55
112
  return failure("RPC_NOT_FOUND");
56
113
  }
@@ -131,6 +188,25 @@ export async function dispatch(registry, path, envelope, scope, application, req
131
188
  return failure("INTERNAL");
132
189
  }
133
190
  }
191
+ /**
192
+ * Answers an RPC HTTP request, or returns `null` for any other request.
193
+ *
194
+ * @remarks
195
+ * Internal: exported only from `@loozo/angular-launch/_server` for the generated
196
+ * `handleRequest` in `server.generated.ts`; call that instead.
197
+ * Any path starting with `/_rpc/` is treated as an RPC request. It must be a `POST`
198
+ * with an `application/json` content type and no query string, otherwise the reply is
199
+ * `INVALID_INPUT` and no context is created. A fresh context is then created before the
200
+ * body is parsed; if that fails the reply is `INTERNAL`, even when the body isn't JSON.
201
+ * Otherwise a body that isn't JSON gives `INVALID_INPUT`. Responses are JSON with
202
+ * `Cache-Control: private, no-store` and `Vary: Cookie`.
203
+ *
204
+ * @typeParam Definition - The application's context definition.
205
+ * @param registry - The application's RPC groups.
206
+ * @param application - The application binding.
207
+ * @param request - The incoming server request.
208
+ * @returns The RPC response, or `null` when the path doesn't start with `/_rpc/`.
209
+ */
134
210
  export async function handleRpc(registry, application, request) {
135
211
  const url = new URL(request.url);
136
212
  if (!url.pathname.startsWith("/_rpc/")) {
@@ -1,8 +1,18 @@
1
1
  import type { ErrorDefinition, ErrorDefinitions, ErrorFactories } from "./definitions.js";
2
2
  export declare const declaredFailures: unique symbol;
3
+ /**
4
+ * An error a procedure's error factory created, as recorded on the procedure.
5
+ *
6
+ * @remarks
7
+ * The server looks it up when a handler throws, to send the declared error. Application
8
+ * code doesn't create or read it.
9
+ */
3
10
  export interface DeclaredFailure {
11
+ /** The declared error code. */
4
12
  readonly code: string;
13
+ /** The error's declaration. */
5
14
  readonly definition: ErrorDefinition;
15
+ /** The data passed to the factory, before validation. */
6
16
  readonly data: unknown;
7
17
  }
8
18
  export declare function createErrors<Definitions extends ErrorDefinitions>(definitions: Definitions): {
@@ -0,0 +1,2 @@
1
+ export { createRequestScope, handleRpc } from "./dispatch.js";
2
+ export { provideLaunchServer } from "./backend.js";
@@ -0,0 +1,3 @@
1
+ // Internal entry point for the generated server.generated.ts; not public API.
2
+ export { createRequestScope, handleRpc } from "./dispatch.js";
3
+ export { provideLaunchServer } from "./backend.js";
@@ -0,0 +1,6 @@
1
+ export { defineContext, defineRpc, query, mutation } from "./definitions.js";
2
+ export type { Register, Context, ContextOf, ContextDefinition, ErrorDefinition, ErrorDefinitions, ErrorFactories, ErrorStatus, Group, Guard, InputOf, OutputOf, Procedure, ProcedureDefinition, ProcedureGuard, ProcedureKind, ProcedureOptions, Schema, } from "./definitions.js";
3
+ export type { DeclaredFailure } from "./errors.js";
4
+ export type { JsonShape } from "../json.js";
5
+ export type { RequestScope } from "./dispatch.js";
6
+ export { finishLaunchRendering } from "./backend.js";
@@ -0,0 +1,2 @@
1
+ export { defineContext, defineRpc, query, mutation } from "./definitions.js";
2
+ export { finishLaunchRendering } from "./backend.js";
package/dist/client.d.ts DELETED
@@ -1,62 +0,0 @@
1
- import type { ErrorDefinitions, Group, OutputOf, Procedure, ProcedureKind, Schema } from "./server/definitions.js";
2
- export type { Json } from "./json.js";
3
- export interface CallOptions {
4
- readonly signal?: AbortSignal;
5
- readonly transferCache?: boolean;
6
- }
7
- export interface MutationCallOptions {
8
- readonly signal?: AbortSignal;
9
- readonly transferCache?: false;
10
- }
11
- export interface ErrorMetadata {
12
- readonly code: string;
13
- readonly status: number;
14
- readonly message: string;
15
- }
16
- export declare const frameworkFailures: {
17
- readonly INVALID_INPUT: {
18
- readonly status: 400;
19
- readonly message: "Invalid RPC input";
20
- };
21
- readonly FORBIDDEN: {
22
- readonly status: 403;
23
- readonly message: "RPC forbidden";
24
- };
25
- readonly RPC_NOT_FOUND: {
26
- readonly status: 404;
27
- readonly message: "RPC not found";
28
- };
29
- readonly INTERNAL: {
30
- readonly status: 500;
31
- readonly message: "Internal server error";
32
- };
33
- };
34
- export type FrameworkCode = keyof typeof frameworkFailures;
35
- export declare class RpcError<Code extends string = FrameworkCode, Data = null> extends Error {
36
- readonly code: Code;
37
- readonly status: number;
38
- readonly data: Data;
39
- constructor(code: Code, status: number, data?: Data, message?: string);
40
- }
41
- export declare function recognizedFailure(value: unknown, status: number): FrameworkCode | undefined;
42
- export declare function recognizedError(value: unknown, status: number, declared: readonly ErrorMetadata[]): {
43
- code: string;
44
- message: string;
45
- data: unknown;
46
- } | undefined;
47
- type FrameworkError = {
48
- [Code in FrameworkCode]: RpcError<Code, null>;
49
- }[FrameworkCode];
50
- type DeclaredError<Errors extends ErrorDefinitions> = {
51
- [Code in keyof Errors & string]: RpcError<Code, OutputOf<Errors[Code]["data"]>>;
52
- }[keyof Errors & string];
53
- export type ClientRpcError<Value> = Value extends Procedure<infer _Input, infer _Output, infer _Kind, infer Errors> ? FrameworkError | DeclaredError<Errors> : never;
54
- type Options<Kind extends ProcedureKind> = Kind extends "mutation" ? MutationCallOptions : CallOptions;
55
- type Callable<Input, Output, Kind extends ProcedureKind> = Input extends Schema<infer Caller, unknown> ? (input: Caller, options?: Options<Kind>) => Promise<Output> : (options?: Options<Kind>) => Promise<Output>;
56
- export type ClientProcedure<Value> = Value extends Procedure<infer Input, infer Output, infer Kind, infer Errors> ? Callable<Input, Awaited<Output>, Kind> & {
57
- readonly kind: Kind;
58
- isError(error: unknown): error is FrameworkError | DeclaredError<Errors>;
59
- } : never;
60
- export type Client<Value> = Value extends Group<string, infer Procedures> ? {
61
- readonly [Key in keyof Procedures]: ClientProcedure<Procedures[Key]>;
62
- } : never;
package/dist/client.js DELETED
@@ -1,97 +0,0 @@
1
- import { serializeJson } from "./json.js";
2
- export const frameworkFailures = {
3
- INVALID_INPUT: { status: 400, message: "Invalid RPC input" },
4
- FORBIDDEN: { status: 403, message: "RPC forbidden" },
5
- RPC_NOT_FOUND: { status: 404, message: "RPC not found" },
6
- INTERNAL: { status: 500, message: "Internal server error" },
7
- };
8
- export class RpcError extends Error {
9
- code;
10
- status;
11
- data;
12
- constructor(code, status, data = null, message) {
13
- if (message === undefined) {
14
- if (!Object.hasOwn(frameworkFailures, code)) {
15
- throw new TypeError("Declared RPC errors require their public message");
16
- }
17
- message = frameworkFailures[code].message;
18
- }
19
- super(message);
20
- this.code = code;
21
- this.status = status;
22
- this.data = data;
23
- this.name = "RpcError";
24
- }
25
- }
26
- export function recognizedFailure(value, status) {
27
- try {
28
- serializeJson(value);
29
- }
30
- catch {
31
- return undefined;
32
- }
33
- if (typeof value !== "object" ||
34
- value === null ||
35
- !("error" in value) ||
36
- Object.keys(value).length !== 1) {
37
- return undefined;
38
- }
39
- const error = value.error;
40
- if (typeof error !== "object" ||
41
- error === null ||
42
- !("code" in error) ||
43
- !("message" in error) ||
44
- !("data" in error) ||
45
- Object.keys(error).length !== 3 ||
46
- typeof error.code !== "string") {
47
- return undefined;
48
- }
49
- for (const code of Object.keys(frameworkFailures)) {
50
- const expected = frameworkFailures[code];
51
- if (error.code === code &&
52
- status === expected.status &&
53
- error.message === expected.message &&
54
- error.data === null) {
55
- return code;
56
- }
57
- }
58
- return undefined;
59
- }
60
- export function recognizedError(value, status, declared) {
61
- const framework = recognizedFailure(value, status);
62
- if (framework) {
63
- return { code: framework, message: frameworkFailures[framework].message, data: null };
64
- }
65
- try {
66
- serializeJson(value);
67
- }
68
- catch {
69
- return undefined;
70
- }
71
- if (typeof value !== "object" ||
72
- value === null ||
73
- !("error" in value) ||
74
- Object.keys(value).length !== 1) {
75
- return undefined;
76
- }
77
- const error = value.error;
78
- if (typeof error !== "object" ||
79
- error === null ||
80
- !("code" in error) ||
81
- !("message" in error) ||
82
- !("data" in error) ||
83
- Object.keys(error).length !== 3 ||
84
- typeof error.code !== "string" ||
85
- typeof error.message !== "string") {
86
- return undefined;
87
- }
88
- for (const definition of declared) {
89
- if (!Object.hasOwn(frameworkFailures, definition.code) &&
90
- definition.code === error.code &&
91
- definition.status === status &&
92
- definition.message === error.message) {
93
- return { code: error.code, message: error.message, data: error.data };
94
- }
95
- }
96
- return undefined;
97
- }
@@ -1,13 +0,0 @@
1
- export interface GenerationOptions {
2
- tsconfig: string;
3
- scanDirectories: string[];
4
- outDirectory: string;
5
- check?: boolean;
6
- }
7
- export interface GenerationSession {
8
- generate(options?: Pick<GenerationOptions, "check">, stopped?: () => boolean): Promise<void>;
9
- dispose(): Promise<void>;
10
- }
11
- export declare function generate(workspace: string, options: GenerationOptions, stopped?: () => boolean): Promise<void>;
12
- /** Owns compiler reuse for one explicitly sequenced application-generation lifetime. */
13
- export declare function createGenerationSession(workspace: string, { tsconfig, scanDirectories, outDirectory }: Omit<GenerationOptions, "check">): GenerationSession;
@@ -1,4 +0,0 @@
1
- import type { ApplicationRef, EnvironmentProviders } from "@angular/core";
2
- import { type ApplicationBinding, type Registry } from "./dispatch.js";
3
- export declare function provideLaunchServer(registry: Registry, application: ApplicationBinding): EnvironmentProviders;
4
- export declare function finishLaunchRendering(app: ApplicationRef): Promise<ApplicationRef>;
@@ -1,108 +0,0 @@
1
- import type { JsonShape } from "../json.js";
2
- import type { FrameworkCode } from "../client.js";
3
- import { declaredFailures } from "./errors.js";
4
- import type { DeclaredFailure } from "./errors.js";
5
- export interface Register {
6
- }
7
- export type Context = Register extends {
8
- context: infer Value;
9
- } ? Value : never;
10
- export interface Schema<Input = unknown, Output = Input> {
11
- readonly "~standard": {
12
- readonly version: 1;
13
- readonly vendor: string;
14
- readonly types?: {
15
- readonly input: Input;
16
- readonly output: Output;
17
- };
18
- readonly validate: (value: unknown) => {
19
- readonly value: Output;
20
- readonly issues?: undefined;
21
- } | {
22
- readonly issues: readonly {
23
- readonly message: string;
24
- }[];
25
- } | Promise<{
26
- readonly value: Output;
27
- readonly issues?: undefined;
28
- } | {
29
- readonly issues: readonly {
30
- readonly message: string;
31
- }[];
32
- }>;
33
- };
34
- }
35
- export type InputOf<S extends Schema> = NonNullable<S["~standard"]["types"]>["input"];
36
- export type OutputOf<S> = S extends Schema<unknown, infer Output> ? Output : undefined;
37
- export interface ContextDefinition<Value> {
38
- readonly create: (request: Request) => Value;
39
- }
40
- export declare function defineContext<Value>(create: (request: Request) => Value): ContextDefinition<Value>;
41
- export type ContextOf<Definition> = Definition extends ContextDefinition<infer Value> ? Awaited<Value> : never;
42
- export type Guard = (args: {
43
- readonly context: Context;
44
- readonly request: Request;
45
- }) => boolean | Promise<boolean>;
46
- export type ProcedureGuard<Input> = (args: {
47
- readonly context: Context;
48
- readonly request: Request;
49
- readonly input: OutputOf<Input>;
50
- }) => boolean | Promise<boolean>;
51
- type Digit = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
52
- type StatusNumber<Value> = Value extends `${infer Status extends number}` ? Status : never;
53
- export type ErrorStatus = StatusNumber<`${4 | 5}${Digit}${Digit}`>;
54
- export interface ErrorDefinition<Data extends Schema = Schema> {
55
- readonly status: ErrorStatus;
56
- readonly message: string;
57
- readonly data: Data;
58
- }
59
- export type ErrorDefinitions = Readonly<Record<string, ErrorDefinition>>;
60
- export type ErrorFactories<Definitions extends ErrorDefinitions> = {
61
- readonly [Code in keyof Definitions]: (data: InputOf<Definitions[Code]["data"]>) => Error;
62
- };
63
- type JsonContract<Value> = 0 extends 1 & Value ? never : [Value] extends [JsonShape<Value>] ? unknown : never;
64
- type InputContract<Input> = Input extends Schema ? JsonContract<InputOf<Input>> : unknown;
65
- type ErrorContract<Definitions extends ErrorDefinitions> = {
66
- readonly [Code in keyof Definitions]: Code extends FrameworkCode | "__proto__" ? never : Definitions[Code]["message"] extends "" ? never : Definitions[Code] & JsonContract<OutputOf<Definitions[Code]["data"]>>;
67
- };
68
- type JsonResult<Value> = Value extends Promise<infer Result> ? Promise<JsonShape<Result>> : JsonShape<Value>;
69
- export type ProcedureKind = "query" | "mutation";
70
- export interface Procedure<Input, Output, Kind extends ProcedureKind = "query", Errors extends ErrorDefinitions = {}> {
71
- readonly kind: Kind;
72
- readonly input: Input;
73
- readonly errors: Errors;
74
- readonly canActivate: readonly ProcedureGuard<Input>[];
75
- readonly handler: (args: {
76
- readonly context: Context;
77
- readonly input: OutputOf<Input>;
78
- readonly errors: ErrorFactories<Errors>;
79
- }) => Output | Promise<Output>;
80
- readonly [declaredFailures]: WeakMap<object, DeclaredFailure>;
81
- }
82
- interface ProcedureOptions<Input, Output, Errors extends ErrorDefinitions> {
83
- readonly input?: Input & InputContract<NoInfer<Input>>;
84
- readonly errors?: Errors & ErrorContract<NoInfer<Errors>>;
85
- readonly canActivate?: readonly ProcedureGuard<Input>[];
86
- readonly handler: (args: {
87
- readonly context: Context;
88
- readonly input: OutputOf<Input>;
89
- readonly errors: ErrorFactories<Errors>;
90
- }) => Output & JsonResult<NoInfer<Output>>;
91
- }
92
- 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>;
93
- 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>;
94
- export interface ProcedureDefinition {
95
- readonly kind: ProcedureKind;
96
- }
97
- export interface QueryDefinition extends ProcedureDefinition {
98
- readonly kind: "query";
99
- }
100
- export interface Group<Name extends string, Procedures extends Record<string, ProcedureDefinition>> {
101
- readonly name: Name;
102
- readonly procedures: Procedures;
103
- readonly canActivate: readonly Guard[];
104
- }
105
- export declare function defineRpc<Name extends string, Procedures extends Record<string, ProcedureDefinition>>(name: Name, procedures: Procedures, { canActivate }?: {
106
- readonly canActivate?: readonly Guard[];
107
- }): Group<Name, Procedures>;
108
- export {};
@@ -1,25 +0,0 @@
1
- import { createErrors, declaredFailures } from "./errors.js";
2
- export function defineContext(create) {
3
- return { create };
4
- }
5
- function procedure(kind, options) {
6
- const definitions = (options.errors ?? {});
7
- const { factories, failures } = createErrors(definitions);
8
- return {
9
- kind,
10
- input: options.input,
11
- errors: definitions,
12
- canActivate: options.canActivate ?? [],
13
- handler: ({ context, input }) => options.handler({ context, input, errors: factories }),
14
- [declaredFailures]: failures,
15
- };
16
- }
17
- export function query(options) {
18
- return procedure("query", options);
19
- }
20
- export function mutation(options) {
21
- return procedure("mutation", options);
22
- }
23
- export function defineRpc(name, procedures, { canActivate = [] } = {}) {
24
- return { name, procedures, canActivate };
25
- }
@@ -1,27 +0,0 @@
1
- import { type FrameworkCode } from "../client.js";
2
- import type { ContextDefinition, ContextOf, Group, ProcedureDefinition } from "./definitions.js";
3
- export type Registry = Readonly<Record<string, Group<string, Record<string, ProcedureDefinition>>>>;
4
- declare const scopeMarker: unique symbol;
5
- export interface ApplicationBinding<Definition extends ContextDefinition<unknown> = ContextDefinition<unknown>> {
6
- readonly id: string;
7
- readonly context: Definition;
8
- }
9
- export interface RequestScope<Value = unknown> {
10
- readonly appId: string;
11
- readonly binding: string;
12
- readonly request: Request;
13
- readonly value: Value;
14
- readonly [scopeMarker]: true;
15
- }
16
- export declare function isRequestScope(value: unknown): value is RequestScope;
17
- export declare function createRequestScope<Definition extends ContextDefinition<unknown>>(application: ApplicationBinding<Definition>, request: Request): Promise<RequestScope<ContextOf<Definition>>>;
18
- export declare function assertBoundScope(scope: unknown, application: ApplicationBinding, request: Request): asserts scope is RequestScope;
19
- export interface Reply {
20
- readonly status: number;
21
- readonly body: unknown;
22
- }
23
- export declare function failure(code: FrameworkCode): Reply;
24
- export declare function isJsonMediaType(contentType: string | null): boolean;
25
- export declare function dispatch(registry: Registry, path: string, envelope: unknown, scope: RequestScope, application: ApplicationBinding, request: Request, mode?: "http" | "rendering"): Promise<Reply>;
26
- export declare function handleRpc<Definition extends ContextDefinition<unknown>>(registry: Registry, application: ApplicationBinding<Definition>, request: Request): Promise<Response | null>;
27
- export {};
@@ -1,5 +0,0 @@
1
- export { defineContext, defineRpc, query, mutation } from "./definitions.js";
2
- export type { Register, Context, ContextOf, ContextDefinition, Group, Guard, Procedure, ProcedureGuard, Schema, InputOf, OutputOf, QueryDefinition, ProcedureDefinition, ProcedureKind, ErrorDefinition, ErrorDefinitions, ErrorFactories, ErrorStatus, } from "./definitions.js";
3
- export { createRequestScope, isRequestScope, dispatch, handleRpc } from "./dispatch.js";
4
- export type { ApplicationBinding, Registry, RequestScope, Reply } from "./dispatch.js";
5
- export { provideLaunchServer, finishLaunchRendering } from "./backend.js";
@@ -1,3 +0,0 @@
1
- export { defineContext, defineRpc, query, mutation } from "./definitions.js";
2
- export { createRequestScope, isRequestScope, dispatch, handleRpc } from "./dispatch.js";
3
- export { provideLaunchServer, finishLaunchRendering } from "./backend.js";
File without changes
File without changes