@temporary-name/server 1.9.3-alpha.5dc8b200530586870ac736830d4584e0333cfd05 → 1.9.3-alpha.62d88f5cf3908d4411b5278f1824b69334da8072

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 (42) hide show
  1. package/dist/adapters/aws-lambda/index.d.mts +5 -6
  2. package/dist/adapters/aws-lambda/index.d.ts +5 -6
  3. package/dist/adapters/aws-lambda/index.mjs +5 -6
  4. package/dist/adapters/fetch/index.d.mts +8 -85
  5. package/dist/adapters/fetch/index.d.ts +8 -85
  6. package/dist/adapters/fetch/index.mjs +17 -157
  7. package/dist/adapters/node/index.d.mts +9 -63
  8. package/dist/adapters/node/index.d.ts +9 -63
  9. package/dist/adapters/node/index.mjs +15 -122
  10. package/dist/{adapters/standard → handler}/index.d.mts +5 -7
  11. package/dist/{adapters/standard → handler}/index.d.ts +5 -7
  12. package/dist/handler/index.mjs +8 -0
  13. package/dist/index.d.mts +355 -208
  14. package/dist/index.d.ts +355 -208
  15. package/dist/index.mjs +421 -207
  16. package/dist/openapi/index.d.mts +18 -53
  17. package/dist/openapi/index.d.ts +18 -53
  18. package/dist/openapi/index.mjs +391 -368
  19. package/dist/shared/server.Blt424vz.mjs +523 -0
  20. package/dist/shared/server.Bmxjwleq.d.ts +39 -0
  21. package/dist/shared/server.BnAF9pfn.mjs +339 -0
  22. package/dist/shared/server.CCWAen7P.mjs +156 -0
  23. package/dist/shared/server.CjPiuQYH.d.mts +51 -0
  24. package/dist/shared/server.CjPiuQYH.d.ts +51 -0
  25. package/dist/shared/server.DLyn62VH.d.mts +39 -0
  26. package/dist/shared/server.DpIhEnBO.d.mts +515 -0
  27. package/dist/shared/server.DpIhEnBO.d.ts +515 -0
  28. package/dist/shared/server.MJ43MXYj.mjs +432 -0
  29. package/package.json +13 -19
  30. package/dist/adapters/standard/index.mjs +0 -9
  31. package/dist/plugins/index.d.mts +0 -84
  32. package/dist/plugins/index.d.ts +0 -84
  33. package/dist/plugins/index.mjs +0 -116
  34. package/dist/shared/server.B-meye9-.d.ts +0 -55
  35. package/dist/shared/server.Ba0Z2fNc.mjs +0 -254
  36. package/dist/shared/server.DkYpsO6W.d.mts +0 -251
  37. package/dist/shared/server.DkYpsO6W.d.ts +0 -251
  38. package/dist/shared/server.DwNnHUZP.d.ts +0 -23
  39. package/dist/shared/server.I-tTl_ce.d.mts +0 -23
  40. package/dist/shared/server.JtIZ8YG7.mjs +0 -237
  41. package/dist/shared/server.miXh-9wo.mjs +0 -416
  42. package/dist/shared/server.vLcMd_kA.d.mts +0 -55
@@ -1,116 +0,0 @@
1
- import { value, ORPCError } from '@temporary-name/shared';
2
- import { maybeSetHeader } from '@temporary-name/standard-server';
3
-
4
- class CORSPlugin {
5
- options;
6
- order = 9e6;
7
- constructor(options = {}) {
8
- const defaults = {
9
- origin: (origin) => origin,
10
- allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"]
11
- };
12
- this.options = {
13
- ...defaults,
14
- ...options
15
- };
16
- }
17
- init(options) {
18
- options.rootInterceptors ??= [];
19
- options.rootInterceptors.unshift(async (interceptorOptions) => {
20
- if (interceptorOptions.request.method === "OPTIONS") {
21
- const resHeaders = new Headers();
22
- if (this.options.maxAge !== void 0) {
23
- resHeaders.set("access-control-max-age", this.options.maxAge.toString());
24
- }
25
- maybeSetHeader(resHeaders, "access-control-allow-methods", this.options.allowMethods);
26
- const allowHeaders = this.options.allowHeaders ?? interceptorOptions.request.headers.get("access-control-request-headers");
27
- maybeSetHeader(resHeaders, "access-control-allow-headers", allowHeaders);
28
- return {
29
- matched: true,
30
- response: {
31
- status: 204,
32
- headers: resHeaders,
33
- body: void 0
34
- }
35
- };
36
- }
37
- return interceptorOptions.next();
38
- });
39
- options.rootInterceptors.unshift(async (interceptorOptions) => {
40
- const result = await interceptorOptions.next();
41
- if (!result.matched) {
42
- return result;
43
- }
44
- const origin = interceptorOptions.request.headers.get("origin") ?? "";
45
- const allowedOrigin = await value(this.options.origin, origin, interceptorOptions);
46
- const allowedOriginArr = Array.isArray(allowedOrigin) ? allowedOrigin : [allowedOrigin];
47
- if (allowedOriginArr.includes("*")) {
48
- result.response.headers.set("access-control-allow-origin", "*");
49
- } else {
50
- if (allowedOriginArr.includes(origin)) {
51
- result.response.headers.set("access-control-allow-origin", origin);
52
- }
53
- result.response.headers.set("vary", interceptorOptions.request.headers.get("vary") ?? "origin");
54
- }
55
- const allowedTimingOrigin = await value(this.options.timingOrigin, origin, interceptorOptions);
56
- const allowedTimingOriginArr = Array.isArray(allowedTimingOrigin) ? allowedTimingOrigin : [allowedTimingOrigin];
57
- if (allowedTimingOriginArr.includes("*")) {
58
- result.response.headers.set("timing-allow-origin", "*");
59
- } else if (allowedTimingOriginArr.includes(origin)) {
60
- result.response.headers.set("timing-allow-origin", origin);
61
- }
62
- if (this.options.credentials) {
63
- result.response.headers.set("access-control-allow-credentials", "true");
64
- }
65
- maybeSetHeader(result.response.headers, "access-control-expose-headers", this.options.exposeHeaders);
66
- return result;
67
- });
68
- }
69
- }
70
-
71
- const SIMPLE_CSRF_PROTECTION_CONTEXT_SYMBOL = Symbol("SIMPLE_CSRF_PROTECTION_CONTEXT");
72
- class SimpleCsrfProtectionHandlerPlugin {
73
- headerName;
74
- headerValue;
75
- exclude;
76
- error;
77
- constructor(options = {}) {
78
- this.headerName = options.headerName ?? "x-csrf-token";
79
- this.headerValue = options.headerValue ?? "orpc";
80
- this.exclude = options.exclude ?? false;
81
- this.error = options.error ?? new ORPCError("CSRF_TOKEN_MISMATCH", {
82
- status: 403,
83
- message: "Invalid CSRF token"
84
- });
85
- }
86
- order = 8e6;
87
- init(options) {
88
- options.rootInterceptors ??= [];
89
- options.clientInterceptors ??= [];
90
- options.rootInterceptors.unshift(async (options2) => {
91
- const headerName = await value(this.headerName, options2);
92
- const headerValue = await value(this.headerValue, options2);
93
- return options2.next({
94
- ...options2,
95
- context: {
96
- ...options2.context,
97
- [SIMPLE_CSRF_PROTECTION_CONTEXT_SYMBOL]: options2.request.headers.get(headerName) === headerValue
98
- }
99
- });
100
- });
101
- options.clientInterceptors.unshift(async (options2) => {
102
- if (typeof options2.context[SIMPLE_CSRF_PROTECTION_CONTEXT_SYMBOL] !== "boolean") {
103
- throw new TypeError(
104
- "[SimpleCsrfProtectionHandlerPlugin] CSRF protection context has been corrupted or modified by another plugin or interceptor"
105
- );
106
- }
107
- const excluded = await value(this.exclude, options2);
108
- if (!excluded && !options2.context[SIMPLE_CSRF_PROTECTION_CONTEXT_SYMBOL]) {
109
- throw this.error;
110
- }
111
- return options2.next();
112
- });
113
- }
114
- }
115
-
116
- export { CORSPlugin, SimpleCsrfProtectionHandlerPlugin };
@@ -1,55 +0,0 @@
1
- import { Meta } from '@temporary-name/contract';
2
- import { HTTPPath, StandardLazyRequest, Interceptor, StandardResponse } from '@temporary-name/shared';
3
- import { C as Context, R as Router, N as ProcedureClientInterceptorOptions } from './server.DkYpsO6W.js';
4
-
5
- interface StandardHandlerPlugin<T extends Context> {
6
- order?: number;
7
- init?(options: StandardHandlerOptions<T>, router: Router<any, T>): void;
8
- }
9
- declare class CompositeStandardHandlerPlugin<T extends Context, TPlugin extends StandardHandlerPlugin<T>> implements StandardHandlerPlugin<T> {
10
- protected readonly plugins: TPlugin[];
11
- constructor(plugins?: readonly TPlugin[]);
12
- init(options: StandardHandlerOptions<T>, router: Router<any, T>): void;
13
- }
14
-
15
- interface StandardHandleOptions<T extends Context> {
16
- prefix?: HTTPPath;
17
- context: T;
18
- }
19
- type StandardHandleResult = {
20
- matched: true;
21
- response: StandardResponse;
22
- } | {
23
- matched: false;
24
- response: undefined;
25
- };
26
- interface StandardHandlerInterceptorOptions<T extends Context> extends StandardHandleOptions<T> {
27
- request: StandardLazyRequest;
28
- }
29
- interface StandardHandlerOptions<TContext extends Context> {
30
- plugins?: StandardHandlerPlugin<TContext>[];
31
- /**
32
- * Interceptors at the request level, helpful when you want catch errors
33
- */
34
- interceptors?: Interceptor<StandardHandlerInterceptorOptions<TContext>, Promise<StandardHandleResult>>[];
35
- /**
36
- * Interceptors at the root level, helpful when you want override the request/response
37
- */
38
- rootInterceptors?: Interceptor<StandardHandlerInterceptorOptions<TContext>, Promise<StandardHandleResult>>[];
39
- /**
40
- *
41
- * Interceptors for procedure client.
42
- */
43
- clientInterceptors?: Interceptor<ProcedureClientInterceptorOptions<TContext, Record<never, never>, Meta>, Promise<unknown>>[];
44
- }
45
- declare class StandardHandler<T extends Context> {
46
- private readonly interceptors;
47
- private readonly clientInterceptors;
48
- private readonly rootInterceptors;
49
- private readonly matcher;
50
- constructor(router: Router<any, T>, options: NoInfer<StandardHandlerOptions<T>>);
51
- handle(request: StandardLazyRequest, options: StandardHandleOptions<T>): Promise<StandardHandleResult>;
52
- }
53
-
54
- export { CompositeStandardHandlerPlugin as C, StandardHandler as e };
55
- export type { StandardHandlerInterceptorOptions as S, StandardHandlerPlugin as a, StandardHandlerOptions as b, StandardHandleOptions as c, StandardHandleResult as d };
@@ -1,254 +0,0 @@
1
- import { stringifyJSON, isObject, isORPCErrorStatus, tryDecodeURIComponent, toHttpPath, toArray, intercept, runWithSpan, ORPC_NAME, isAsyncIteratorObject, asyncIteratorWithSpan, setSpanError, ORPCError, toORPCError } from '@temporary-name/shared';
2
- import { c as createProcedureClient } from './server.miXh-9wo.mjs';
3
- import { fallbackContractConfig, standardizeHTTPPath } from '@temporary-name/contract';
4
- import { d as deserialize, b as bracketNotationDeserialize, s as serialize } from './server.JtIZ8YG7.mjs';
5
- import { traverseContractProcedures, isProcedure, getLazyMeta, unlazy, getRouter, createContractedProcedure } from '@temporary-name/server';
6
- import { createRouter, addRoute, findRoute } from 'rou3';
7
-
8
- async function decode(request, pathParams) {
9
- return {
10
- path: pathParams ?? {},
11
- query: bracketNotationDeserialize(Array.from(request.url.searchParams.entries())),
12
- headers: request.headers,
13
- body: deserialize(await request.body()) ?? {}
14
- };
15
- }
16
- function encode(output, procedure) {
17
- const successStatus = fallbackContractConfig(
18
- "defaultSuccessStatus",
19
- procedure["~orpc"].route.successStatus
20
- );
21
- const outputStructure = fallbackContractConfig(
22
- "defaultOutputStructure",
23
- procedure["~orpc"].route.outputStructure
24
- );
25
- if (outputStructure === "compact") {
26
- return {
27
- status: successStatus,
28
- headers: new Headers(),
29
- body: serialize(output)
30
- };
31
- }
32
- if (!isDetailedOutput(output)) {
33
- throw new Error(`
34
- Invalid "detailed" output structure:
35
- \u2022 Expected an object with optional properties:
36
- - status (number 200-399)
37
- - headers (Record<string, string | string[]>)
38
- - body (any)
39
- \u2022 No extra keys allowed.
40
-
41
- Actual value:
42
- ${stringifyJSON(output)}
43
- `);
44
- }
45
- return {
46
- status: output.status ?? successStatus,
47
- headers: output.headers ?? new Headers(),
48
- body: serialize(output.body)
49
- };
50
- }
51
- function encodeError(error) {
52
- return {
53
- status: error.status,
54
- headers: new Headers(),
55
- body: serialize(error.toJSON(), { outputFormat: "plain" })
56
- };
57
- }
58
- function isDetailedOutput(output) {
59
- if (!isObject(output)) {
60
- return false;
61
- }
62
- if (output.headers && !isObject(output.headers)) {
63
- return false;
64
- }
65
- if (output.status !== void 0 && (typeof output.status !== "number" || !Number.isInteger(output.status) || isORPCErrorStatus(output.status))) {
66
- return false;
67
- }
68
- return true;
69
- }
70
-
71
- function resolveFriendlyStandardHandleOptions(options) {
72
- return {
73
- ...options,
74
- context: options.context ?? {}
75
- // Context only optional if all fields are optional
76
- };
77
- }
78
- function toRou3Pattern(path) {
79
- return standardizeHTTPPath(path).replace(/\/\{\+([^}]+)\}/g, "/**:$1").replace(/\/\{([^}]+)\}/g, "/:$1");
80
- }
81
- function decodeParams(params) {
82
- return Object.fromEntries(
83
- Object.entries(params).map(([key, value]) => [key, tryDecodeURIComponent(value)])
84
- );
85
- }
86
-
87
- class StandardOpenAPIMatcher {
88
- tree = createRouter();
89
- pendingRouters = [];
90
- init(router, path = []) {
91
- const laziedOptions = traverseContractProcedures({ router, path }, (traverseOptions) => {
92
- const { path: path2, contract } = traverseOptions;
93
- const method = fallbackContractConfig("defaultMethod", contract["~orpc"].route.method);
94
- const httpPath = toRou3Pattern(contract["~orpc"].route.path ?? toHttpPath(path2));
95
- if (isProcedure(contract)) {
96
- addRoute(this.tree, method, httpPath, {
97
- path: path2,
98
- contract,
99
- procedure: contract,
100
- // this mean dev not used contract-first so we can used contract as procedure directly
101
- router
102
- });
103
- } else {
104
- addRoute(this.tree, method, httpPath, {
105
- path: path2,
106
- contract,
107
- procedure: void 0,
108
- router
109
- });
110
- }
111
- });
112
- this.pendingRouters.push(
113
- ...laziedOptions.map((option) => ({
114
- ...option,
115
- httpPathPrefix: toHttpPath(option.path),
116
- laziedPrefix: getLazyMeta(option.router).prefix
117
- }))
118
- );
119
- }
120
- async match(method, pathname) {
121
- if (this.pendingRouters.length) {
122
- const newPendingRouters = [];
123
- for (const pendingRouter of this.pendingRouters) {
124
- if (!pendingRouter.laziedPrefix || pathname.startsWith(pendingRouter.laziedPrefix) || pathname.startsWith(pendingRouter.httpPathPrefix)) {
125
- const { default: router } = await unlazy(pendingRouter.router);
126
- this.init(router, pendingRouter.path);
127
- } else {
128
- newPendingRouters.push(pendingRouter);
129
- }
130
- }
131
- this.pendingRouters = newPendingRouters;
132
- }
133
- const match = findRoute(this.tree, method, pathname);
134
- if (!match) {
135
- return void 0;
136
- }
137
- if (!match.data.procedure) {
138
- const { default: maybeProcedure } = await unlazy(getRouter(match.data.router, match.data.path));
139
- if (!isProcedure(maybeProcedure)) {
140
- throw new Error(`
141
- [Contract-First] Missing or invalid implementation for procedure at path: ${toHttpPath(match.data.path)}.
142
- Ensure that the procedure is correctly defined and matches the expected contract.
143
- `);
144
- }
145
- match.data.procedure = createContractedProcedure(maybeProcedure, match.data.contract);
146
- }
147
- return {
148
- path: match.data.path,
149
- procedure: match.data.procedure,
150
- params: match.params ? decodeParams(match.params) : void 0
151
- };
152
- }
153
- }
154
-
155
- class CompositeStandardHandlerPlugin {
156
- plugins;
157
- constructor(plugins = []) {
158
- this.plugins = [...plugins].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
159
- }
160
- init(options, router) {
161
- for (const plugin of this.plugins) {
162
- plugin.init?.(options, router);
163
- }
164
- }
165
- }
166
-
167
- class StandardHandler {
168
- interceptors;
169
- clientInterceptors;
170
- rootInterceptors;
171
- matcher;
172
- constructor(router, options) {
173
- this.matcher = new StandardOpenAPIMatcher();
174
- const plugins = new CompositeStandardHandlerPlugin(options.plugins);
175
- plugins.init(options, router);
176
- this.interceptors = toArray(options.interceptors);
177
- this.clientInterceptors = toArray(options.clientInterceptors);
178
- this.rootInterceptors = toArray(options.rootInterceptors);
179
- this.matcher.init(router);
180
- }
181
- async handle(request, options) {
182
- const prefix = options.prefix?.replace(/\/$/, "") || void 0;
183
- if (prefix && !request.url.pathname.startsWith(`${prefix}/`) && request.url.pathname !== prefix) {
184
- return { matched: false, response: void 0 };
185
- }
186
- return intercept(this.rootInterceptors, { ...options, request, prefix }, async (interceptorOptions) => {
187
- return runWithSpan({ name: `${request.method} ${request.url.pathname}` }, async (span) => {
188
- let step;
189
- try {
190
- return await intercept(
191
- this.interceptors,
192
- interceptorOptions,
193
- async ({ request: request2, context, prefix: prefix2 }) => {
194
- const method = request2.method;
195
- const url = request2.url;
196
- const pathname = prefix2 ? url.pathname.replace(prefix2, "") : url.pathname;
197
- const match = await runWithSpan(
198
- { name: "find_procedure" },
199
- () => this.matcher.match(method, `/${pathname.replace(/^\/|\/$/g, "")}`)
200
- );
201
- if (!match) {
202
- return { matched: false, response: void 0 };
203
- }
204
- span?.updateName(`${ORPC_NAME}.${match.path.join("/")}`);
205
- span?.setAttribute("rpc.system", ORPC_NAME);
206
- span?.setAttribute("rpc.method", match.path.join("."));
207
- step = "decode_input";
208
- const input = await runWithSpan({ name: "decode_input" }, () => decode(request2, match.params));
209
- step = void 0;
210
- if (isAsyncIteratorObject(input.body)) {
211
- input.body = asyncIteratorWithSpan(
212
- { name: "consume_event_iterator_input", signal: request2.signal },
213
- input.body
214
- );
215
- }
216
- const client = createProcedureClient(match.procedure, {
217
- context,
218
- path: match.path,
219
- interceptors: this.clientInterceptors
220
- });
221
- step = "call_procedure";
222
- const output = await client(input, {
223
- request: request2,
224
- signal: request2.signal,
225
- lastEventId: request2.headers.get("last-event-id") ?? void 0
226
- });
227
- step = void 0;
228
- const response = encode(output, match.procedure);
229
- return {
230
- matched: true,
231
- response
232
- };
233
- }
234
- );
235
- } catch (e) {
236
- if (step !== "call_procedure") {
237
- setSpanError(span, e);
238
- }
239
- const error = step === "decode_input" && !(e instanceof ORPCError) ? new ORPCError("BAD_REQUEST", {
240
- message: `Malformed request. Ensure the request body is properly formatted and the 'Content-Type' header is set correctly.`,
241
- cause: e
242
- }) : toORPCError(e);
243
- const response = encodeError(error);
244
- return {
245
- matched: true,
246
- response
247
- };
248
- }
249
- });
250
- });
251
- }
252
- }
253
-
254
- export { CompositeStandardHandlerPlugin as C, StandardHandler as S, encodeError as a, StandardOpenAPIMatcher as b, decodeParams as c, decode as d, encode as e, resolveFriendlyStandardHandleOptions as r, toRou3Pattern as t };
@@ -1,251 +0,0 @@
1
- import { ErrorMap, ErrorMapItem, InferSchemaInput, Meta, Schemas, ContractProcedureDef, AnyContractRouter, ContractProcedure, InferProcedureClientInputs, InferSchemaOutput, EnhanceRouteOptions, MergedErrorMap, AnyContractProcedure, ContractRouter, AnySchema, ErrorFromErrorMap } from '@temporary-name/contract';
2
- import { ORPCErrorCode, MaybeOptionalOptions, ORPCErrorOptions, ORPCError, Promisable, StandardLazyRequest, HTTPPath, ClientContext, Interceptor, PromiseWithError, Value, Client } from '@temporary-name/shared';
3
-
4
- type Context = Record<PropertyKey, any>;
5
- type MergedInitialContext<TInitial extends Context, TAdditional extends Context, TCurrent extends Context> = TInitial & Omit<TAdditional, keyof TCurrent>;
6
- type MergedCurrentContext<T extends Context, U extends Context> = Omit<T, keyof U> & U;
7
- type BuildContextWithAuth<TContext extends Context, TAuthContext> = MergedCurrentContext<TContext, {
8
- auth: TAuthContext | ('auth' extends keyof TContext ? TContext['auth'] : never);
9
- }>;
10
- declare function mergeCurrentContext<T extends Context, U extends Context>(context: T, other: U): MergedCurrentContext<T, U>;
11
-
12
- type ORPCErrorConstructorMapItemOptions<TData> = Omit<ORPCErrorOptions<TData>, 'defined' | 'status'>;
13
- type ORPCErrorConstructorMapItem<TCode extends ORPCErrorCode, TInData> = (...rest: MaybeOptionalOptions<ORPCErrorConstructorMapItemOptions<TInData>>) => ORPCError<TCode, TInData>;
14
- type ORPCErrorConstructorMap<T extends ErrorMap> = {
15
- [K in keyof T]: K extends ORPCErrorCode ? T[K] extends ErrorMapItem<infer UInputSchema> ? ORPCErrorConstructorMapItem<K, InferSchemaInput<UInputSchema>> : never : never;
16
- };
17
- declare function createORPCErrorConstructorMap<T extends ErrorMap>(errors: T): ORPCErrorConstructorMap<T>;
18
-
19
- type MiddlewareResult<TOutContext extends Context, TOutput> = Promisable<{
20
- output: TOutput;
21
- context: TOutContext;
22
- }>;
23
- interface MiddlewareNextFn<TOutput> {
24
- <U extends Context = {}>(options?: {
25
- context?: U;
26
- }): MiddlewareResult<U, TOutput>;
27
- }
28
- interface MiddlewareOutputFn<TOutput> {
29
- (output: TOutput): MiddlewareResult<Record<never, never>, TOutput>;
30
- }
31
- interface MiddlewareOptions<TInContext extends Context, TOutput, TErrorConstructorMap extends ORPCErrorConstructorMap<any>, TMeta extends Meta> extends ProcedureHandlerOptions<TInContext, TErrorConstructorMap, TMeta> {
32
- next: MiddlewareNextFn<TOutput>;
33
- }
34
- /**
35
- * A function that represents a middleware.
36
- *
37
- * @see {@link https://orpc.unnoq.com/docs/middleware Middleware Docs}
38
- */
39
- interface Middleware<TInContext extends Context, TOutContext extends Context, TInput, TOutput, TErrorConstructorMap extends ORPCErrorConstructorMap<any>, TMeta extends Meta> {
40
- (options: MiddlewareOptions<TInContext, TOutput, TErrorConstructorMap, TMeta>, input: TInput, output: MiddlewareOutputFn<TOutput>): Promisable<MiddlewareResult<TOutContext, TOutput>>;
41
- }
42
- type AnyMiddleware = Middleware<any, any, any, any, any, any>;
43
- interface MapInputMiddleware<TInput, TMappedInput> {
44
- (input: TInput): TMappedInput;
45
- }
46
- declare function middlewareOutputFn<TOutput>(output: TOutput): MiddlewareResult<Record<never, never>, TOutput>;
47
-
48
- type DefaultProcedureHandlerOptions = ProcedureHandlerOptions<Context, ORPCErrorConstructorMap<ErrorMap>, Meta>;
49
- interface ProcedureHandlerOptions<TCurrentContext extends Context, TErrorConstructorMap extends ORPCErrorConstructorMap<any>, TMeta extends Meta> {
50
- context: TCurrentContext;
51
- path: readonly string[];
52
- procedure: Procedure<Context, Context, Schemas, ErrorMap, TMeta>;
53
- signal?: AbortSignal;
54
- request?: StandardLazyRequest;
55
- lastEventId: string | undefined;
56
- errors: TErrorConstructorMap;
57
- }
58
- interface ProcedureHandler<TCurrentContext extends Context, TInput extends {
59
- path: any;
60
- query: any;
61
- body: any;
62
- }, THandlerOutput, TErrorMap extends ErrorMap, TMeta extends Meta> {
63
- (input: TInput, opt: ProcedureHandlerOptions<TCurrentContext, ORPCErrorConstructorMap<TErrorMap>, TMeta>): Promisable<THandlerOutput>;
64
- }
65
- interface ProcedureDef<TInitialContext extends Context, TCurrentContext extends Context, TSchemas extends Schemas, TErrorMap extends ErrorMap, TMeta extends Meta> extends ContractProcedureDef<TSchemas, TErrorMap, TMeta> {
66
- __initialContext?: (type: TInitialContext) => unknown;
67
- middlewares: readonly AnyMiddleware[];
68
- authConfigs: TypedAuthConfig[];
69
- inputValidationIndex: number;
70
- outputValidationIndex: number;
71
- handler: ProcedureHandler<TCurrentContext, any, any, any, any>;
72
- }
73
- /**
74
- * This class represents a procedure.
75
- *
76
- * @see {@link https://orpc.unnoq.com/docs/procedure Procedure Docs}
77
- */
78
- declare class Procedure<TInitialContext extends Context, TCurrentContext extends Context, TSchemas extends Schemas, TErrorMap extends ErrorMap, TMeta extends Meta> {
79
- /**
80
- * This property holds the defined options.
81
- */
82
- '~orpc': ProcedureDef<TInitialContext, TCurrentContext, TSchemas, TErrorMap, TMeta>;
83
- constructor(def: ProcedureDef<TInitialContext, TCurrentContext, TSchemas, TErrorMap, TMeta>);
84
- }
85
- type AnyProcedure = Procedure<any, any, Schemas, any, any>;
86
- declare function isProcedure(item: unknown): item is AnyProcedure;
87
-
88
- type ValidatedAuthContext = {};
89
- interface BasicAuthConfig<TAuthContext extends ValidatedAuthContext, TCurrentContext extends Context, TMeta extends Meta> {
90
- tokenPrefix?: string;
91
- validate: (username: string, password: string, options: ProcedureHandlerOptions<TCurrentContext, ORPCErrorConstructorMap<any>, TMeta>) => Promisable<TAuthContext>;
92
- }
93
- interface TokenAuthConfig<TAuthContext extends ValidatedAuthContext, TCurrentContext extends Context, TMeta extends Meta> {
94
- tokenPrefix?: string;
95
- validate: (token: string, options: ProcedureHandlerOptions<TCurrentContext, ORPCErrorConstructorMap<any>, TMeta>) => Promisable<TAuthContext>;
96
- }
97
- interface NamedTokenAuthConfig<TAuthContext extends ValidatedAuthContext, TCurrentContext extends Context, TMeta extends Meta> extends TokenAuthConfig<TAuthContext, TCurrentContext, TMeta> {
98
- name: string;
99
- }
100
- type AuthType = 'header' | 'query' | 'cookie' | 'bearer' | 'basic' | 'none';
101
- type AuthConfig<TAuthType extends AuthType, TAuthContext extends ValidatedAuthContext = ValidatedAuthContext, TCurrentContext extends Context = Context, TMeta extends Meta = Meta> = TAuthType extends 'basic' ? BasicAuthConfig<TAuthContext, TCurrentContext, TMeta> : TAuthType extends 'bearer' ? TokenAuthConfig<TAuthContext, TCurrentContext, TMeta> : TAuthType extends 'header' ? NamedTokenAuthConfig<TAuthContext, TCurrentContext, TMeta> : TAuthType extends 'query' ? NamedTokenAuthConfig<TAuthContext, TCurrentContext, TMeta> : TAuthType extends 'cookie' ? NamedTokenAuthConfig<TAuthContext, TCurrentContext, TMeta> : TAuthType extends 'none' ? {} : never;
102
- type TypedAuthConfig<TAuthType extends AuthType = AuthType> = {
103
- type: TAuthType;
104
- } & AuthConfig<TAuthType, object>;
105
-
106
- /**
107
- * Represents a router, which defines a hierarchical structure of procedures.
108
- *
109
- * @info A procedure is a router too.
110
- * @see {@link https://orpc.unnoq.com/docs/contract-first/define-contract#contract-router Contract Router Docs}
111
- */
112
- type Router<T extends AnyContractRouter, TInitialContext extends Context> = T extends ContractProcedure<infer USchemas, infer UErrorMap, infer UMeta> ? Procedure<TInitialContext, any, USchemas, UErrorMap, UMeta> : {
113
- [K in keyof T]: T[K] extends AnyContractRouter ? Lazyable<Router<T[K], TInitialContext>> : never;
114
- };
115
- type AnyRouter = Router<any, any>;
116
- type InferRouterInitialContext<T extends AnyRouter> = T extends Router<any, infer UInitialContext> ? UInitialContext : never;
117
- /**
118
- * Infer all initial context of the router.
119
- *
120
- * @info A procedure is a router too.
121
- * @see {@link https://orpc.unnoq.com/docs/router#utilities Router Utilities Docs}
122
- */
123
- type InferRouterInitialContexts<T extends AnyRouter> = T extends Procedure<infer UInitialContext, any, any, any, any> ? UInitialContext : {
124
- [K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? InferRouterInitialContexts<U> : never;
125
- };
126
- /**
127
- * Infer all current context of the router.
128
- *
129
- * @info A procedure is a router too.
130
- * @see {@link https://orpc.unnoq.com/docs/router#utilities Router Utilities Docs}
131
- */
132
- type InferRouterCurrentContexts<T extends AnyRouter> = T extends Procedure<any, infer UCurrentContext, any, any, any> ? UCurrentContext : {
133
- [K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? InferRouterCurrentContexts<U> : never;
134
- };
135
- /**
136
- * Infer all router inputs
137
- *
138
- * @info A procedure is a router too.
139
- * @see {@link https://orpc.unnoq.com/docs/router#utilities Router Utilities Docs}
140
- */
141
- type InferRouterInputs<T extends AnyRouter> = T extends Procedure<any, any, infer USchemas, any, any> ? InferProcedureClientInputs<USchemas> : {
142
- [K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? InferRouterInputs<U> : never;
143
- };
144
- /**
145
- * Infer all router outputs
146
- *
147
- * @info A procedure is a router too.
148
- * @see {@link https://orpc.unnoq.com/docs/router#utilities Router Utilities Docs}
149
- */
150
- type InferRouterOutputs<T extends AnyRouter> = T extends Procedure<any, any, infer USchemas, any, any> ? InferSchemaOutput<USchemas['outputSchema']> : {
151
- [K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? InferRouterOutputs<U> : never;
152
- };
153
-
154
- declare function getRouter<T extends Lazyable<AnyRouter | undefined>>(router: T, path: readonly string[]): T extends Lazy<any> ? Lazy<AnyRouter | undefined> : Lazyable<AnyRouter | undefined>;
155
- type AccessibleLazyRouter<T extends Lazyable<AnyRouter | undefined>> = T extends Lazy<infer U extends AnyRouter | undefined | Lazy<AnyRouter | undefined>> ? AccessibleLazyRouter<U> : T extends AnyProcedure | undefined ? Lazy<T> : Lazy<T> & {
156
- [K in keyof T]: T[K] extends Lazyable<AnyRouter> ? AccessibleLazyRouter<T[K]> : never;
157
- };
158
- declare function createAccessibleLazyRouter<T extends Lazy<AnyRouter | undefined>>(lazied: T): AccessibleLazyRouter<T>;
159
- type EnhancedRouter<T extends Lazyable<AnyRouter>, TInitialContext extends Context, TCurrentContext extends Context, TErrorMap extends ErrorMap> = T extends Lazy<infer U extends AnyRouter> ? AccessibleLazyRouter<EnhancedRouter<U, TInitialContext, TCurrentContext, TErrorMap>> : T extends (Procedure<infer UInitialContext, infer UCurrentContext, infer USchemas, infer UErrorMap, infer UMeta>) ? Procedure<MergedInitialContext<TInitialContext, UInitialContext, TCurrentContext>, UCurrentContext, USchemas, MergedErrorMap<TErrorMap, UErrorMap>, UMeta> : {
160
- [K in keyof T]: T[K] extends Lazyable<AnyRouter> ? EnhancedRouter<T[K], TInitialContext, TCurrentContext, TErrorMap> : never;
161
- };
162
- interface EnhanceRouterOptions<TErrorMap extends ErrorMap> extends EnhanceRouteOptions {
163
- middlewares: readonly AnyMiddleware[];
164
- errorMap: TErrorMap;
165
- dedupeLeadingMiddlewares: boolean;
166
- }
167
- declare function enhanceRouter<T extends Lazyable<AnyRouter>, TInitialContext extends Context, TCurrentContext extends Context, TErrorMap extends ErrorMap>(router: T, options: EnhanceRouterOptions<TErrorMap>): EnhancedRouter<T, TInitialContext, TCurrentContext, TErrorMap>;
168
- interface TraverseContractProceduresOptions {
169
- router: AnyContractRouter | AnyRouter;
170
- path: readonly string[];
171
- }
172
- interface TraverseContractProcedureCallbackOptions {
173
- contract: AnyContractProcedure | AnyProcedure;
174
- path: readonly string[];
175
- }
176
- /**
177
- * @deprecated Use `TraverseContractProcedureCallbackOptions` instead.
178
- */
179
- type ContractProcedureCallbackOptions = TraverseContractProcedureCallbackOptions;
180
- interface LazyTraverseContractProceduresOptions {
181
- router: Lazy<AnyRouter>;
182
- path: readonly string[];
183
- }
184
- declare function traverseContractProcedures(options: TraverseContractProceduresOptions, callback: (options: TraverseContractProcedureCallbackOptions) => void, lazyOptions?: LazyTraverseContractProceduresOptions[]): LazyTraverseContractProceduresOptions[];
185
- declare function resolveContractProcedures(options: TraverseContractProceduresOptions, callback: (options: TraverseContractProcedureCallbackOptions) => void): Promise<void>;
186
- type UnlaziedRouter<T extends AnyRouter> = T extends AnyProcedure ? T : {
187
- [K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? UnlaziedRouter<U> : never;
188
- };
189
- declare function unlazyRouter<T extends AnyRouter>(router: T): Promise<UnlaziedRouter<T>>;
190
-
191
- declare const LAZY_SYMBOL: unique symbol;
192
- interface LazyMeta {
193
- prefix?: HTTPPath;
194
- }
195
- interface Lazy<T> {
196
- [LAZY_SYMBOL]: {
197
- loader: () => Promise<{
198
- default: T;
199
- }>;
200
- meta: LazyMeta;
201
- };
202
- }
203
- type Lazyable<T> = T | Lazy<T>;
204
- /**
205
- * @internal
206
- */
207
- declare function lazyInternal<T>(loader: () => Promise<{
208
- default: T;
209
- }>, meta?: LazyMeta): Lazy<T>;
210
- /**
211
- * Creates a lazy-loaded item.
212
- *
213
- * @warning The `prefix` in `meta` only holds metadata and does not apply the prefix to the lazy router, use `os.prefix(...).lazyRoute(...)` instead.
214
- */
215
- declare function lazy<T extends Router<ContractRouter<{}>, any>>(prefix: HTTPPath, loader: () => Promise<{
216
- default: T;
217
- }>): EnhancedRouter<Lazy<T>, {}, {}, {}>;
218
- declare function isLazy(item: unknown): item is Lazy<any>;
219
- declare function getLazyMeta(lazied: Lazy<any>): LazyMeta;
220
- declare function unlazy<T extends Lazyable<any>>(lazied: T): Promise<{
221
- default: T extends Lazy<infer U> ? U : T;
222
- }>;
223
-
224
- type ProcedureClient<TClientContext extends ClientContext, TSchemas extends Schemas, TErrorMap extends ErrorMap> = Client<TClientContext, InferProcedureClientInputs<TSchemas>, InferSchemaOutput<TSchemas['outputSchema']>, ErrorFromErrorMap<TErrorMap>>;
225
- interface ProcedureClientInterceptorOptions<TInitialContext extends Context, TErrorMap extends ErrorMap, TMeta extends Meta> extends ProcedureHandlerOptions<TInitialContext, ORPCErrorConstructorMap<TErrorMap>, TMeta> {
226
- input: {
227
- path: unknown;
228
- query: unknown;
229
- body: unknown;
230
- };
231
- }
232
- type CreateProcedureClientOptions<TInitialContext extends Context, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta, TClientContext extends ClientContext> = {
233
- /**
234
- * This is helpful for logging and analytics.
235
- */
236
- path?: readonly string[];
237
- interceptors?: Interceptor<ProcedureClientInterceptorOptions<TInitialContext, TErrorMap, TMeta>, PromiseWithError<InferSchemaOutput<TOutputSchema>, ErrorFromErrorMap<TErrorMap>>>[];
238
- } & (Record<never, never> extends TInitialContext ? {
239
- context?: Value<Promisable<TInitialContext>, [clientContext: TClientContext]>;
240
- } : {
241
- context: Value<Promisable<TInitialContext>, [clientContext: TClientContext]>;
242
- });
243
- /**
244
- * Create Server-side client from a procedure.
245
- *
246
- * @see {@link https://orpc.unnoq.com/docs/client/server-side Server-side Client Docs}
247
- */
248
- declare function createProcedureClient<TInitialContext extends Context, TSchemas extends Schemas, TErrorMap extends ErrorMap, TMeta extends Meta, TClientContext extends ClientContext>(lazyableProcedure: Lazyable<Procedure<TInitialContext, any, TSchemas, TErrorMap, TMeta>>, ...rest: MaybeOptionalOptions<CreateProcedureClientOptions<TInitialContext, TSchemas['outputSchema'], TErrorMap, TMeta, TClientContext>>): ProcedureClient<TClientContext, TSchemas, TErrorMap>;
249
-
250
- export { enhanceRouter as $, middlewareOutputFn as F, isProcedure as K, Procedure as P, createProcedureClient as Q, getRouter as Y, createAccessibleLazyRouter as _, traverseContractProcedures as a4, resolveContractProcedures as a5, unlazyRouter as a7, mergeCurrentContext as m, createORPCErrorConstructorMap as p, LAZY_SYMBOL as q, lazyInternal as s, lazy as t, isLazy as u, getLazyMeta as v, unlazy as w };
251
- export type { AuthType as A, BuildContextWithAuth as B, Context as C, MiddlewareOptions as D, EnhanceRouterOptions as E, DefaultProcedureHandlerOptions as G, ProcedureHandlerOptions as H, InferRouterInitialContext as I, ProcedureDef as J, Lazy as L, Middleware as M, ProcedureClientInterceptorOptions as N, ORPCErrorConstructorMap as O, Router as R, InferRouterInitialContexts as S, TypedAuthConfig as T, InferRouterCurrentContexts as U, ValidatedAuthContext as V, InferRouterInputs as W, InferRouterOutputs as X, AccessibleLazyRouter as Z, CreateProcedureClientOptions as a, TraverseContractProceduresOptions as a0, TraverseContractProcedureCallbackOptions as a1, ContractProcedureCallbackOptions as a2, LazyTraverseContractProceduresOptions as a3, UnlaziedRouter as a6, ProcedureClient as b, MergedInitialContext as c, MergedCurrentContext as d, AuthConfig as e, ProcedureHandler as f, EnhancedRouter as g, MapInputMiddleware as h, AnyMiddleware as i, AnyProcedure as j, Lazyable as k, AnyRouter as l, ORPCErrorConstructorMapItemOptions as n, ORPCErrorConstructorMapItem as o, LazyMeta as r, MiddlewareResult as x, MiddlewareNextFn as y, MiddlewareOutputFn as z };