@orpc/server 0.0.0-next.0787cc6 → 0.0.0-next.0c0619f

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 (47) hide show
  1. package/README.md +118 -0
  2. package/dist/chunk-7A2ZRAPK.js +182 -0
  3. package/dist/chunk-MEBJNUSY.js +32 -0
  4. package/dist/{chunk-EDQKEHUX.js → chunk-MHVECKBC.js} +51 -7
  5. package/dist/{chunk-XFBAK67J.js → chunk-WQNNSBXW.js} +7 -15
  6. package/dist/fetch.js +6 -12
  7. package/dist/hono.js +6 -12
  8. package/dist/index.js +16 -7
  9. package/dist/next.js +6 -12
  10. package/dist/node.js +7 -146
  11. package/dist/plugins.js +1 -1
  12. package/dist/src/adapters/fetch/index.d.ts +0 -1
  13. package/dist/src/adapters/fetch/rpc-handler.d.ts +3 -2
  14. package/dist/src/adapters/fetch/types.d.ts +3 -2
  15. package/dist/src/adapters/hono/middleware.d.ts +2 -3
  16. package/dist/src/adapters/next/serve.d.ts +2 -3
  17. package/dist/src/adapters/node/index.d.ts +0 -1
  18. package/dist/src/adapters/node/rpc-handler.d.ts +3 -2
  19. package/dist/src/adapters/node/types.d.ts +3 -2
  20. package/dist/src/adapters/standard/handler.d.ts +15 -13
  21. package/dist/src/adapters/standard/index.d.ts +0 -1
  22. package/dist/src/adapters/standard/rpc-codec.d.ts +4 -3
  23. package/dist/src/adapters/standard/types.d.ts +3 -26
  24. package/dist/src/builder-variants.d.ts +2 -1
  25. package/dist/src/builder.d.ts +2 -1
  26. package/dist/src/context.d.ts +0 -1
  27. package/dist/src/error.d.ts +12 -0
  28. package/dist/src/implementer-procedure.d.ts +7 -4
  29. package/dist/src/implementer-variants.d.ts +2 -1
  30. package/dist/src/implementer.d.ts +2 -1
  31. package/dist/src/index.d.ts +3 -1
  32. package/dist/src/middleware-decorated.d.ts +2 -1
  33. package/dist/src/middleware.d.ts +5 -4
  34. package/dist/src/plugins/base.d.ts +1 -3
  35. package/dist/src/procedure-client.d.ts +8 -6
  36. package/dist/src/procedure-decorated.d.ts +7 -4
  37. package/dist/src/procedure-utils.d.ts +5 -3
  38. package/dist/src/procedure.d.ts +5 -3
  39. package/dist/src/router-client.d.ts +6 -5
  40. package/dist/src/router.d.ts +1 -0
  41. package/dist/standard.js +5 -9
  42. package/package.json +7 -4
  43. package/dist/chunk-2OH4QMZ4.js +0 -145
  44. package/dist/chunk-BFGSRNYZ.js +0 -319
  45. package/dist/src/adapters/fetch/utils.d.ts +0 -5
  46. package/dist/src/adapters/node/utils.d.ts +0 -5
  47. package/dist/src/adapters/standard/rpc-serializer.d.ts +0 -16
@@ -1,7 +1,10 @@
1
- import type { ClientRest, ErrorMap, MergedErrorMap, Meta, ORPCErrorConstructorMap, Route, Schema, SchemaInput, SchemaOutput } from '@orpc/contract';
1
+ import type { ClientContext, ClientRest } from '@orpc/client';
2
+ import type { ErrorMap, MergedErrorMap, Meta, Route, Schema, SchemaInput, SchemaOutput } from '@orpc/contract';
3
+ import type { MaybeOptionalOptions } from '@orpc/shared';
2
4
  import type { ConflictContextGuard, Context, MergedContext } from './context';
5
+ import type { ORPCErrorConstructorMap } from './error';
3
6
  import type { MapInputMiddleware, Middleware } from './middleware';
4
- import type { CreateProcedureClientRest, ProcedureClient } from './procedure-client';
7
+ import type { CreateProcedureClientOptions, ProcedureClient } from './procedure-client';
5
8
  import { Procedure } from './procedure';
6
9
  export declare class DecoratedProcedure<TInitialContext extends Context, TCurrentContext extends Context, TInputSchema extends Schema, TOutputSchema extends Schema, THandlerOutput extends SchemaInput<TOutputSchema>, TErrorMap extends ErrorMap, TMeta extends Meta> extends Procedure<TInitialContext, TCurrentContext, TInputSchema, TOutputSchema, THandlerOutput, TErrorMap, TMeta> {
7
10
  errors<U extends ErrorMap>(errors: U): DecoratedProcedure<TInitialContext, TCurrentContext, TInputSchema, TOutputSchema, THandlerOutput, MergedErrorMap<TErrorMap, U>, TMeta>;
@@ -12,10 +15,10 @@ export declare class DecoratedProcedure<TInitialContext extends Context, TCurren
12
15
  /**
13
16
  * Make this procedure callable (works like a function while still being a procedure).
14
17
  */
15
- callable<TClientContext>(...rest: CreateProcedureClientRest<TInitialContext, TInputSchema, TOutputSchema, THandlerOutput, TErrorMap, TMeta, TClientContext>): Procedure<TInitialContext, TCurrentContext, TInputSchema, TOutputSchema, THandlerOutput, TErrorMap, TMeta> & ProcedureClient<TClientContext, TInputSchema, TOutputSchema, THandlerOutput, TErrorMap>;
18
+ callable<TClientContext extends ClientContext>(...rest: MaybeOptionalOptions<CreateProcedureClientOptions<TInitialContext, TInputSchema, TOutputSchema, THandlerOutput, TErrorMap, TMeta, TClientContext>>): Procedure<TInitialContext, TCurrentContext, TInputSchema, TOutputSchema, THandlerOutput, TErrorMap, TMeta> & ProcedureClient<TClientContext, TInputSchema, TOutputSchema, THandlerOutput, TErrorMap>;
16
19
  /**
17
20
  * Make this procedure compatible with server action (the same as .callable, but the type is compatible with server action).
18
21
  */
19
- actionable<TClientContext>(...rest: CreateProcedureClientRest<TInitialContext, TInputSchema, TOutputSchema, THandlerOutput, TErrorMap, TMeta, TClientContext>): Procedure<TInitialContext, TCurrentContext, TInputSchema, TOutputSchema, THandlerOutput, TErrorMap, TMeta> & ((...rest: ClientRest<TClientContext, SchemaInput<TInputSchema>>) => Promise<SchemaOutput<TOutputSchema, THandlerOutput>>);
22
+ actionable<TClientContext extends ClientContext>(...rest: MaybeOptionalOptions<CreateProcedureClientOptions<TInitialContext, TInputSchema, TOutputSchema, THandlerOutput, TErrorMap, TMeta, TClientContext>>): Procedure<TInitialContext, TCurrentContext, TInputSchema, TOutputSchema, THandlerOutput, TErrorMap, TMeta> & ((...rest: ClientRest<TClientContext, SchemaInput<TInputSchema>>) => Promise<SchemaOutput<TOutputSchema, THandlerOutput>>);
20
23
  }
21
24
  //# sourceMappingURL=procedure-decorated.d.ts.map
@@ -1,8 +1,10 @@
1
- import type { ClientPromiseResult, ErrorFromErrorMap, ErrorMap, Meta, Schema, SchemaInput, SchemaOutput } from '@orpc/contract';
1
+ import type { ClientPromiseResult } from '@orpc/client';
2
+ import type { ErrorFromErrorMap, ErrorMap, Meta, Schema, SchemaInput, SchemaOutput } from '@orpc/contract';
3
+ import type { MaybeOptionalOptions } from '@orpc/shared';
2
4
  import type { Context } from './context';
3
5
  import type { Lazyable } from './lazy';
4
6
  import type { Procedure } from './procedure';
5
- import { type CreateProcedureClientRest } from './procedure-client';
7
+ import type { CreateProcedureClientOptions } from './procedure-client';
6
8
  /**
7
9
  * Directly call a procedure without creating a client.
8
10
  *
@@ -13,5 +15,5 @@ import { type CreateProcedureClientRest } from './procedure-client';
13
15
  * ```
14
16
  *
15
17
  */
16
- export declare function call<TInitialContext extends Context, TInputSchema extends Schema, TOutputSchema extends Schema, THandlerOutput extends SchemaInput<TOutputSchema>, TErrorMap extends ErrorMap, TMeta extends Meta>(procedure: Lazyable<Procedure<TInitialContext, any, TInputSchema, TOutputSchema, THandlerOutput, TErrorMap, TMeta>>, input: SchemaInput<TInputSchema>, ...rest: CreateProcedureClientRest<TInitialContext, TInputSchema, TOutputSchema, THandlerOutput, TErrorMap, TMeta, unknown>): ClientPromiseResult<SchemaOutput<TOutputSchema, THandlerOutput>, ErrorFromErrorMap<TErrorMap>>;
18
+ export declare function call<TInitialContext extends Context, TInputSchema extends Schema, TOutputSchema extends Schema, THandlerOutput extends SchemaInput<TOutputSchema>, TErrorMap extends ErrorMap, TMeta extends Meta>(procedure: Lazyable<Procedure<TInitialContext, any, TInputSchema, TOutputSchema, THandlerOutput, TErrorMap, TMeta>>, input: SchemaInput<TInputSchema>, ...rest: MaybeOptionalOptions<CreateProcedureClientOptions<TInitialContext, TInputSchema, TOutputSchema, THandlerOutput, TErrorMap, TMeta, Record<never, never>>>): ClientPromiseResult<SchemaOutput<TOutputSchema, THandlerOutput>, ErrorFromErrorMap<TErrorMap>>;
17
19
  //# sourceMappingURL=procedure-utils.d.ts.map
@@ -1,6 +1,7 @@
1
- import type { ContractProcedureDef, ErrorMap, Meta, ORPCErrorConstructorMap, Schema, SchemaInput, SchemaOutput } from '@orpc/contract';
1
+ import type { ContractProcedureDef, ErrorMap, Meta, Schema, SchemaInput, SchemaOutput } from '@orpc/contract';
2
2
  import type { Promisable } from '@orpc/shared';
3
- import type { Context, TypeInitialContext } from './context';
3
+ import type { Context } from './context';
4
+ import type { ORPCErrorConstructorMap } from './error';
4
5
  import type { AnyMiddleware } from './middleware';
5
6
  export interface ProcedureHandlerOptions<TCurrentContext extends Context, TInput, TErrorConstructorMap extends ORPCErrorConstructorMap<any>, TMeta extends Meta> {
6
7
  context: TCurrentContext;
@@ -8,13 +9,14 @@ export interface ProcedureHandlerOptions<TCurrentContext extends Context, TInput
8
9
  path: string[];
9
10
  procedure: Procedure<Context, Context, Schema, Schema, unknown, ErrorMap, TMeta>;
10
11
  signal?: AbortSignal;
12
+ lastEventId: string | undefined;
11
13
  errors: TErrorConstructorMap;
12
14
  }
13
15
  export interface ProcedureHandler<TCurrentContext extends Context, TInputSchema extends Schema, TOutputSchema extends Schema, THandlerOutput extends SchemaInput<TOutputSchema>, TErrorMap extends ErrorMap, TMeta extends Meta> {
14
16
  (opt: ProcedureHandlerOptions<TCurrentContext, SchemaOutput<TInputSchema>, ORPCErrorConstructorMap<TErrorMap>, TMeta>): Promisable<SchemaInput<TOutputSchema, THandlerOutput>>;
15
17
  }
16
18
  export interface ProcedureDef<TInitialContext extends Context, TCurrentContext extends Context, TInputSchema extends Schema, TOutputSchema extends Schema, THandlerOutput extends SchemaInput<TOutputSchema>, TErrorMap extends ErrorMap, TMeta extends Meta> extends ContractProcedureDef<TInputSchema, TOutputSchema, TErrorMap, TMeta> {
17
- __initialContext?: TypeInitialContext<TInitialContext>;
19
+ __initialContext?: (type: TInitialContext) => unknown;
18
20
  middlewares: AnyMiddleware[];
19
21
  inputValidationIndex: number;
20
22
  outputValidationIndex: number;
@@ -1,11 +1,12 @@
1
+ import type { ClientContext } from '@orpc/client';
1
2
  import type { ErrorMap, Meta } from '@orpc/contract';
3
+ import type { MaybeOptionalOptions } from '@orpc/shared';
2
4
  import type { Lazy } from './lazy';
3
5
  import type { Procedure } from './procedure';
4
- import type { CreateProcedureClientRest, ProcedureClient } from './procedure-client';
5
- import type { AnyRouter, Router } from './router';
6
- export type RouterClient<TRouter extends AnyRouter, TClientContext> = TRouter extends Lazy<infer U extends AnyRouter> ? RouterClient<U, TClientContext> : TRouter extends Procedure<any, any, infer UInputSchema, infer UOutputSchema, infer UFuncOutput, infer UErrorMap, any> ? ProcedureClient<TClientContext, UInputSchema, UOutputSchema, UFuncOutput, UErrorMap> : {
6
+ import type { CreateProcedureClientOptions, ProcedureClient } from './procedure-client';
7
+ import type { AnyRouter, InferRouterInitialContext } from './router';
8
+ export type RouterClient<TRouter extends AnyRouter, TClientContext extends ClientContext = Record<never, never>> = TRouter extends Lazy<infer U extends AnyRouter> ? RouterClient<U, TClientContext> : TRouter extends Procedure<any, any, infer UInputSchema, infer UOutputSchema, infer UFuncOutput, infer UErrorMap, any> ? ProcedureClient<TClientContext, UInputSchema, UOutputSchema, UFuncOutput, UErrorMap> : {
7
9
  [K in keyof TRouter]: TRouter[K] extends AnyRouter ? RouterClient<TRouter[K], TClientContext> : never;
8
10
  };
9
- export type CreateRouterClientRest<TRouter extends AnyRouter, TClientContext> = CreateProcedureClientRest<TRouter extends Router<infer UContext, any> ? UContext : never, undefined, undefined, unknown, ErrorMap, Meta, TClientContext>;
10
- export declare function createRouterClient<TRouter extends AnyRouter, TClientContext>(router: TRouter | Lazy<undefined>, ...rest: CreateRouterClientRest<TRouter, TClientContext>): RouterClient<TRouter, TClientContext>;
11
+ export declare function createRouterClient<TRouter extends AnyRouter, TClientContext extends ClientContext>(router: TRouter | Lazy<undefined>, ...rest: MaybeOptionalOptions<CreateProcedureClientOptions<InferRouterInitialContext<TRouter>, undefined, undefined, unknown, ErrorMap, Meta, TClientContext>>): RouterClient<TRouter, TClientContext>;
11
12
  //# sourceMappingURL=router-client.d.ts.map
@@ -9,6 +9,7 @@ export type Router<TInitialContext extends Context, TContract extends AnyContrac
9
9
  [K in keyof TContract]: TContract[K] extends AnyContractRouter ? Router<TInitialContext, TContract[K]> : never;
10
10
  }>;
11
11
  export type AnyRouter = Router<any, any>;
12
+ export type InferRouterInitialContext<T extends AnyRouter> = T extends Router<infer UInitialContext, any> ? UInitialContext : never;
12
13
  export type InferRouterInputs<T extends AnyRouter> = T extends Lazy<infer U extends AnyRouter> ? InferRouterInputs<U> : T extends Procedure<any, any, infer UInputSchema, any, any, any, any> ? SchemaInput<UInputSchema> : {
13
14
  [K in keyof T]: T[K] extends AnyRouter ? InferRouterInputs<T[K]> : never;
14
15
  };
package/dist/standard.js CHANGED
@@ -1,17 +1,13 @@
1
1
  import {
2
2
  RPCCodec,
3
3
  RPCMatcher,
4
- RPCSerializer,
5
- StandardHandler,
6
- serializeRPCJson
7
- } from "./chunk-BFGSRNYZ.js";
8
- import "./chunk-EDQKEHUX.js";
9
- import "./chunk-XFBAK67J.js";
4
+ StandardHandler
5
+ } from "./chunk-7A2ZRAPK.js";
6
+ import "./chunk-MHVECKBC.js";
7
+ import "./chunk-WQNNSBXW.js";
10
8
  export {
11
9
  RPCCodec,
12
10
  RPCMatcher,
13
- RPCSerializer,
14
- StandardHandler,
15
- serializeRPCJson
11
+ StandardHandler
16
12
  };
17
13
  //# sourceMappingURL=standard.js.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@orpc/server",
3
3
  "type": "module",
4
- "version": "0.0.0-next.0787cc6",
4
+ "version": "0.0.0-next.0c0619f",
5
5
  "license": "MIT",
6
6
  "homepage": "https://orpc.unnoq.com",
7
7
  "repository": {
@@ -63,9 +63,12 @@
63
63
  "next": ">=14.0.0"
64
64
  },
65
65
  "dependencies": {
66
- "@tinyhttp/content-disposition": "^2.2.2",
67
- "@orpc/contract": "0.0.0-next.0787cc6",
68
- "@orpc/shared": "0.0.0-next.0787cc6"
66
+ "@orpc/server-standard": "^0.4.0",
67
+ "@orpc/server-standard-fetch": "^0.4.0",
68
+ "@orpc/server-standard-node": "^0.4.0",
69
+ "@orpc/client": "0.0.0-next.0c0619f",
70
+ "@orpc/contract": "0.0.0-next.0c0619f",
71
+ "@orpc/shared": "0.0.0-next.0c0619f"
69
72
  },
70
73
  "devDependencies": {
71
74
  "light-my-request": "^6.5.1"
@@ -1,145 +0,0 @@
1
- import {
2
- RPCCodec,
3
- RPCMatcher,
4
- StandardHandler
5
- } from "./chunk-BFGSRNYZ.js";
6
-
7
- // src/adapters/fetch/utils.ts
8
- import { once } from "@orpc/shared";
9
- import { contentDisposition, parse as parseContentDisposition } from "@tinyhttp/content-disposition";
10
- function fetchHeadersToStandardHeaders(headers) {
11
- const standardHeaders = {};
12
- for (const [key, value] of headers) {
13
- if (Array.isArray(standardHeaders[key])) {
14
- standardHeaders[key].push(value);
15
- } else if (standardHeaders[key] !== void 0) {
16
- standardHeaders[key] = [standardHeaders[key], value];
17
- } else {
18
- standardHeaders[key] = value;
19
- }
20
- }
21
- return standardHeaders;
22
- }
23
- async function fetchReToStandardBody(re) {
24
- if (!re.body) {
25
- return void 0;
26
- }
27
- const contentDisposition2 = re.headers.get("content-disposition");
28
- if (contentDisposition2) {
29
- const fileName = parseContentDisposition(contentDisposition2).parameters.filename;
30
- if (typeof fileName === "string") {
31
- const blob2 = await re.blob();
32
- return new File([blob2], fileName, {
33
- type: blob2.type
34
- });
35
- }
36
- }
37
- const contentType = re.headers.get("content-type");
38
- if (!contentType || contentType.startsWith("application/json")) {
39
- const text = await re.text();
40
- if (!text) {
41
- return void 0;
42
- }
43
- return JSON.parse(text);
44
- }
45
- if (contentType.startsWith("multipart/form-data")) {
46
- return await re.formData();
47
- }
48
- if (contentType.startsWith("application/x-www-form-urlencoded")) {
49
- return new URLSearchParams(await re.text());
50
- }
51
- if (contentType.startsWith("text/")) {
52
- return await re.text();
53
- }
54
- const blob = await re.blob();
55
- return new File([blob], "blob", {
56
- type: blob.type
57
- });
58
- }
59
- function fetchRequestToStandardRequest(request) {
60
- const url = new URL(request.url);
61
- return {
62
- raw: { request },
63
- url,
64
- signal: request.signal,
65
- method: request.method,
66
- body: once(() => {
67
- return fetchReToStandardBody(request);
68
- }),
69
- get headers() {
70
- const headers = fetchHeadersToStandardHeaders(request.headers);
71
- Object.defineProperty(this, "headers", { value: headers, writable: true });
72
- return headers;
73
- },
74
- set headers(value) {
75
- Object.defineProperty(this, "headers", { value, writable: true });
76
- }
77
- };
78
- }
79
- function standardResponseToFetchHeaders(response) {
80
- const fetchHeaders = new Headers();
81
- for (const [key, value] of Object.entries(response.headers)) {
82
- if (Array.isArray(value)) {
83
- for (const v of value) {
84
- fetchHeaders.append(key, v);
85
- }
86
- } else if (value !== void 0) {
87
- fetchHeaders.append(key, value);
88
- }
89
- }
90
- return fetchHeaders;
91
- }
92
- function standardResponseToFetchResponse(response) {
93
- const resHeaders = standardResponseToFetchHeaders(response);
94
- resHeaders.delete("content-type");
95
- resHeaders.delete("content-disposition");
96
- if (response.body === void 0) {
97
- return new Response(void 0, { headers: resHeaders, status: response.status });
98
- }
99
- if (response.body instanceof Blob) {
100
- resHeaders.set("content-type", response.body.type);
101
- resHeaders.set("content-length", response.body.size.toString());
102
- resHeaders.set(
103
- "content-disposition",
104
- contentDisposition(response.body instanceof File ? response.body.name : "blob", { type: "inline" })
105
- );
106
- return new Response(response.body, { headers: resHeaders, status: response.status });
107
- }
108
- if (response.body instanceof FormData) {
109
- return new Response(response.body, { headers: resHeaders, status: response.status });
110
- }
111
- if (response.body instanceof URLSearchParams) {
112
- return new Response(response.body, { headers: resHeaders, status: response.status });
113
- }
114
- resHeaders.set("content-type", "application/json");
115
- return new Response(JSON.stringify(response.body), { headers: resHeaders, status: response.status });
116
- }
117
-
118
- // src/adapters/fetch/rpc-handler.ts
119
- var RPCHandler = class {
120
- standardHandler;
121
- constructor(router, options) {
122
- const matcher = options?.matcher ?? new RPCMatcher();
123
- const codec = options?.codec ?? new RPCCodec();
124
- this.standardHandler = new StandardHandler(router, matcher, codec, options);
125
- }
126
- async handle(request, ...rest) {
127
- const standardRequest = fetchRequestToStandardRequest(request);
128
- const result = await this.standardHandler.handle(standardRequest, ...rest);
129
- if (!result.matched) {
130
- return result;
131
- }
132
- return {
133
- matched: true,
134
- response: standardResponseToFetchResponse(result.response)
135
- };
136
- }
137
- };
138
-
139
- export {
140
- fetchReToStandardBody,
141
- fetchRequestToStandardRequest,
142
- standardResponseToFetchResponse,
143
- RPCHandler
144
- };
145
- //# sourceMappingURL=chunk-2OH4QMZ4.js.map
@@ -1,319 +0,0 @@
1
- import {
2
- convertPathToHttpPath,
3
- createContractedProcedure,
4
- createProcedureClient,
5
- eachContractProcedure,
6
- getRouterChild,
7
- isProcedure,
8
- unlazy
9
- } from "./chunk-EDQKEHUX.js";
10
- import {
11
- CompositePlugin
12
- } from "./chunk-XFBAK67J.js";
13
-
14
- // src/adapters/standard/handler.ts
15
- import { toORPCError } from "@orpc/contract";
16
- import { intercept, trim } from "@orpc/shared";
17
- var StandardHandler = class {
18
- constructor(router, matcher, codec, options = {}) {
19
- this.matcher = matcher;
20
- this.codec = codec;
21
- this.options = options;
22
- this.plugin = new CompositePlugin(options?.plugins);
23
- this.plugin.init(this.options);
24
- this.matcher.init(router);
25
- }
26
- plugin;
27
- handle(request, ...[options]) {
28
- return intercept(
29
- this.options.interceptorsRoot ?? [],
30
- {
31
- request,
32
- ...options,
33
- context: options?.context ?? {}
34
- // context is optional only when all fields are optional so we can safely force it to have a context
35
- },
36
- async (interceptorOptions) => {
37
- try {
38
- return await intercept(
39
- this.options.interceptors ?? [],
40
- interceptorOptions,
41
- async (interceptorOptions2) => {
42
- const method = interceptorOptions2.request.method;
43
- const url = interceptorOptions2.request.url;
44
- const pathname = `/${trim(url.pathname.replace(interceptorOptions2.prefix ?? "", ""), "/")}`;
45
- const match = await this.matcher.match(method, pathname);
46
- if (!match) {
47
- return { matched: false, response: void 0 };
48
- }
49
- const clientOptions = {
50
- context: interceptorOptions2.context,
51
- path: match.path
52
- };
53
- this.plugin.beforeCreateProcedureClient(clientOptions, interceptorOptions2);
54
- const client = createProcedureClient(match.procedure, clientOptions);
55
- const input = await this.codec.decode(request, match.params, match.procedure);
56
- const output = await client(input, { signal: request.signal });
57
- const response = this.codec.encode(output, match.procedure);
58
- return {
59
- matched: true,
60
- response
61
- };
62
- }
63
- );
64
- } catch (e) {
65
- const error = toORPCError(e);
66
- const response = this.codec.encodeError(error);
67
- return {
68
- matched: true,
69
- response
70
- };
71
- }
72
- }
73
- );
74
- }
75
- };
76
-
77
- // src/adapters/standard/rpc-serializer.ts
78
- import { findDeepMatches, isObject, set } from "@orpc/shared";
79
- var RPCSerializer = class {
80
- serialize(data) {
81
- if (data === void 0) {
82
- return void 0;
83
- }
84
- if (data instanceof Blob) {
85
- return data;
86
- }
87
- const serializedJSON = serializeRPCJson(data);
88
- const { maps, values: blobs } = findDeepMatches((v) => v instanceof Blob, serializedJSON.json);
89
- if (blobs.length === 0) {
90
- return serializedJSON;
91
- }
92
- const form = new FormData();
93
- form.set("data", JSON.stringify(serializedJSON));
94
- form.set("maps", JSON.stringify(maps));
95
- for (const i in blobs) {
96
- form.set(i, blobs[i]);
97
- }
98
- return form;
99
- }
100
- deserialize(serialized) {
101
- if (serialized === void 0) {
102
- return void 0;
103
- }
104
- if (serialized instanceof Blob) {
105
- return serialized;
106
- }
107
- if (!(serialized instanceof FormData)) {
108
- return deserializeRPCJson(serialized);
109
- }
110
- const data = JSON.parse(serialized.get("data"));
111
- const maps = JSON.parse(serialized.get("maps"));
112
- for (const i in maps) {
113
- data.json = set(data.json, maps[i], serialized.get(i));
114
- }
115
- return deserializeRPCJson(data);
116
- }
117
- };
118
- function serializeRPCJson(value, segments = [], meta = []) {
119
- if (typeof value === "bigint") {
120
- meta.push(["bigint", segments]);
121
- return { json: value.toString(), meta };
122
- }
123
- if (value instanceof Date) {
124
- meta.push(["date", segments]);
125
- const data = Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString();
126
- return { json: data, meta };
127
- }
128
- if (Number.isNaN(value)) {
129
- meta.push(["nan", segments]);
130
- return { json: "NaN", meta };
131
- }
132
- if (value instanceof RegExp) {
133
- meta.push(["regexp", segments]);
134
- return { json: value.toString(), meta };
135
- }
136
- if (value instanceof URL) {
137
- meta.push(["url", segments]);
138
- return { json: value.toString(), meta };
139
- }
140
- if (isObject(value)) {
141
- const json = {};
142
- for (const k in value) {
143
- json[k] = serializeRPCJson(value[k], [...segments, k], meta).json;
144
- }
145
- return { json, meta };
146
- }
147
- if (Array.isArray(value)) {
148
- const json = value.map((v, i) => {
149
- if (v === void 0) {
150
- meta.push(["undefined", [...segments, i]]);
151
- return null;
152
- }
153
- return serializeRPCJson(v, [...segments, i], meta).json;
154
- });
155
- return { json, meta };
156
- }
157
- if (value instanceof Set) {
158
- const result = serializeRPCJson(Array.from(value), segments, meta);
159
- meta.push(["set", segments]);
160
- return result;
161
- }
162
- if (value instanceof Map) {
163
- const result = serializeRPCJson(Array.from(value.entries()), segments, meta);
164
- meta.push(["map", segments]);
165
- return result;
166
- }
167
- return { json: value, meta };
168
- }
169
- function deserializeRPCJson({
170
- json,
171
- meta
172
- }) {
173
- if (meta.length === 0) {
174
- return json;
175
- }
176
- const ref = { data: json };
177
- for (const [type, segments] of meta) {
178
- let currentRef = ref;
179
- let preSegment = "data";
180
- for (let i = 0; i < segments.length; i++) {
181
- currentRef = currentRef[preSegment];
182
- preSegment = segments[i];
183
- }
184
- switch (type) {
185
- case "nan":
186
- currentRef[preSegment] = Number.NaN;
187
- break;
188
- case "bigint":
189
- currentRef[preSegment] = BigInt(currentRef[preSegment]);
190
- break;
191
- case "date":
192
- currentRef[preSegment] = new Date(currentRef[preSegment]);
193
- break;
194
- case "regexp": {
195
- const [, pattern, flags] = currentRef[preSegment].match(/^\/(.*)\/([a-z]*)$/);
196
- currentRef[preSegment] = new RegExp(pattern, flags);
197
- break;
198
- }
199
- case "url":
200
- currentRef[preSegment] = new URL(currentRef[preSegment]);
201
- break;
202
- case "undefined":
203
- currentRef[preSegment] = void 0;
204
- break;
205
- case "map":
206
- currentRef[preSegment] = new Map(currentRef[preSegment]);
207
- break;
208
- case "set":
209
- currentRef[preSegment] = new Set(currentRef[preSegment]);
210
- break;
211
- /* v8 ignore next 3 */
212
- default: {
213
- const _expected = type;
214
- }
215
- }
216
- }
217
- return ref.data;
218
- }
219
-
220
- // src/adapters/standard/rpc-codec.ts
221
- var RPCCodec = class {
222
- serializer;
223
- constructor(options = {}) {
224
- this.serializer = options.serializer ?? new RPCSerializer();
225
- }
226
- async decode(request, _params, _procedure) {
227
- const serialized = request.method === "GET" ? JSON.parse(request.url.searchParams.getAll("data").at(-1)) : await request.body();
228
- return this.serializer.deserialize(serialized);
229
- }
230
- encode(output, _procedure) {
231
- return {
232
- status: 200,
233
- headers: {},
234
- body: this.serializer.serialize(output)
235
- };
236
- }
237
- encodeError(error) {
238
- return {
239
- status: error.status,
240
- headers: {},
241
- body: this.serializer.serialize(error.toJSON())
242
- };
243
- }
244
- };
245
-
246
- // src/adapters/standard/rpc-matcher.ts
247
- var RPCMatcher = class {
248
- tree = {};
249
- pendingRouters = [];
250
- init(router, path = []) {
251
- const laziedOptions = eachContractProcedure({
252
- router,
253
- path
254
- }, ({ path: path2, contract }) => {
255
- const httpPath = convertPathToHttpPath(path2);
256
- if (isProcedure(contract)) {
257
- this.tree[httpPath] = {
258
- path: path2,
259
- contract,
260
- procedure: contract,
261
- // this mean dev not used contract-first so we can used contract as procedure directly
262
- router
263
- };
264
- } else {
265
- this.tree[httpPath] = {
266
- path: path2,
267
- contract,
268
- procedure: void 0,
269
- router
270
- };
271
- }
272
- });
273
- this.pendingRouters.push(...laziedOptions.map((option) => ({
274
- ...option,
275
- httpPathPrefix: convertPathToHttpPath(option.path)
276
- })));
277
- }
278
- async match(_method, pathname) {
279
- if (this.pendingRouters.length) {
280
- const newPendingRouters = [];
281
- for (const pendingRouter of this.pendingRouters) {
282
- if (pathname.startsWith(pendingRouter.httpPathPrefix)) {
283
- const { default: router } = await unlazy(pendingRouter.lazied);
284
- this.init(router, pendingRouter.path);
285
- } else {
286
- newPendingRouters.push(pendingRouter);
287
- }
288
- }
289
- this.pendingRouters = newPendingRouters;
290
- }
291
- const match = this.tree[pathname];
292
- if (!match) {
293
- return void 0;
294
- }
295
- if (!match.procedure) {
296
- const { default: maybeProcedure } = await unlazy(getRouterChild(match.router, ...match.path));
297
- if (!isProcedure(maybeProcedure)) {
298
- throw new Error(`
299
- [Contract-First] Missing or invalid implementation for procedure at path: ${convertPathToHttpPath(match.path)}.
300
- Ensure that the procedure is correctly defined and matches the expected contract.
301
- `);
302
- }
303
- match.procedure = createContractedProcedure(match.contract, maybeProcedure);
304
- }
305
- return {
306
- path: match.path,
307
- procedure: match.procedure
308
- };
309
- }
310
- };
311
-
312
- export {
313
- StandardHandler,
314
- RPCSerializer,
315
- serializeRPCJson,
316
- RPCCodec,
317
- RPCMatcher
318
- };
319
- //# sourceMappingURL=chunk-BFGSRNYZ.js.map
@@ -1,5 +0,0 @@
1
- import type { StandardBody, StandardRequest, StandardResponse } from '../standard';
2
- export declare function fetchReToStandardBody(re: Request | Response): Promise<StandardBody>;
3
- export declare function fetchRequestToStandardRequest(request: Request): StandardRequest;
4
- export declare function standardResponseToFetchResponse(response: StandardResponse): Response;
5
- //# sourceMappingURL=utils.d.ts.map
@@ -1,5 +0,0 @@
1
- import type { StandardRequest, StandardResponse } from '../standard';
2
- import type { NodeHttpRequest, NodeHttpResponse } from './types';
3
- export declare function nodeHttpToStandardRequest(req: NodeHttpRequest, res: NodeHttpResponse): StandardRequest;
4
- export declare function nodeHttpResponseSendStandardResponse(res: NodeHttpResponse, standardResponse: StandardResponse): Promise<void>;
5
- //# sourceMappingURL=utils.d.ts.map
@@ -1,16 +0,0 @@
1
- import type { Segment } from '@orpc/shared';
2
- export type RPCSerializedJsonMeta = ['bigint' | 'date' | 'nan' | 'undefined' | 'set' | 'map' | 'regexp' | 'url', Segment[]][];
3
- export type RPCSerialized = {
4
- json: unknown;
5
- meta: RPCSerializedJsonMeta;
6
- } | FormData | Blob | undefined;
7
- export type RPCSerializedFormDataMaps = Segment[][];
8
- export declare class RPCSerializer {
9
- serialize(data: unknown): RPCSerialized;
10
- deserialize(serialized: RPCSerialized): unknown;
11
- }
12
- export declare function serializeRPCJson(value: unknown, segments?: Segment[], meta?: RPCSerializedJsonMeta): {
13
- json: unknown;
14
- meta: RPCSerializedJsonMeta;
15
- };
16
- //# sourceMappingURL=rpc-serializer.d.ts.map