@orpc/server 0.0.0-next.0640aed → 0.0.0-next.0d79ab9

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.
@@ -1,3 +1,9 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
1
7
  // src/utils.ts
2
8
  function mergeContext(a, b) {
3
9
  if (!a)
@@ -23,7 +29,7 @@ function isProcedure(item) {
23
29
  if (item instanceof Procedure) {
24
30
  return true;
25
31
  }
26
- return (typeof item === "object" || typeof item === "function") && item !== null && "~type" in item && item["~type"] === "Procedure" && "~orpc" in item && typeof item["~orpc"] === "object" && item["~orpc"] !== null && "contract" in item["~orpc"] && isContractProcedure(item["~orpc"].contract) && "func" in item["~orpc"] && typeof item["~orpc"].func === "function";
32
+ return (typeof item === "object" || typeof item === "function") && item !== null && "~type" in item && item["~type"] === "Procedure" && "~orpc" in item && typeof item["~orpc"] === "object" && item["~orpc"] !== null && "contract" in item["~orpc"] && isContractProcedure(item["~orpc"].contract) && "handler" in item["~orpc"] && typeof item["~orpc"].handler === "function";
27
33
  }
28
34
 
29
35
  // src/lazy.ts
@@ -129,7 +135,7 @@ async function executeMiddlewareChain(procedure, input, context, meta) {
129
135
  });
130
136
  }
131
137
  const result = {
132
- output: await procedure["~orpc"].func(input, currentContext, meta),
138
+ output: await procedure["~orpc"].handler(input, currentContext, meta),
133
139
  context: currentContext
134
140
  };
135
141
  return result;
@@ -168,6 +174,7 @@ function getRouterChild(router, ...path) {
168
174
  }
169
175
 
170
176
  export {
177
+ __export,
171
178
  mergeContext,
172
179
  Procedure,
173
180
  isProcedure,
@@ -179,4 +186,4 @@ export {
179
186
  createProcedureClient,
180
187
  getRouterChild
181
188
  };
182
- //# sourceMappingURL=chunk-FN62GL22.js.map
189
+ //# sourceMappingURL=chunk-6A7XHEBH.js.map
package/dist/fetch.js CHANGED
@@ -1,112 +1,324 @@
1
1
  import {
2
+ __export,
2
3
  createProcedureClient,
3
4
  getRouterChild,
4
5
  isProcedure,
5
6
  unlazy
6
- } from "./chunk-FN62GL22.js";
7
+ } from "./chunk-6A7XHEBH.js";
7
8
 
8
- // src/fetch/handle-request.ts
9
+ // src/fetch/composite-handler.ts
10
+ var CompositeHandler = class {
11
+ constructor(handlers) {
12
+ this.handlers = handlers;
13
+ }
14
+ async fetch(request, ...opt) {
15
+ for (const handler of this.handlers) {
16
+ if (handler.condition(request)) {
17
+ return handler.fetch(request, ...opt);
18
+ }
19
+ }
20
+ return new Response("None of the handlers can handle the request.", {
21
+ status: 404
22
+ });
23
+ }
24
+ };
25
+
26
+ // src/fetch/orpc-handler.ts
27
+ import { executeWithHooks, ORPC_HANDLER_HEADER, ORPC_HANDLER_VALUE, trim as trim2 } from "@orpc/shared";
28
+ import { ORPCError as ORPCError2 } from "@orpc/shared/error";
29
+
30
+ // src/fetch/orpc-payload-codec.ts
31
+ import { findDeepMatches, set } from "@orpc/shared";
9
32
  import { ORPCError } from "@orpc/shared/error";
10
- async function handleFetchRequest(options) {
11
- for (const handler of options.handlers) {
12
- const response = await handler(options);
13
- if (response) {
14
- return response;
33
+
34
+ // src/fetch/super-json.ts
35
+ var super_json_exports = {};
36
+ __export(super_json_exports, {
37
+ deserialize: () => deserialize,
38
+ serialize: () => serialize
39
+ });
40
+
41
+ // ../../node_modules/.pnpm/is-what@5.0.2/node_modules/is-what/dist/getType.js
42
+ function getType(payload) {
43
+ return Object.prototype.toString.call(payload).slice(8, -1);
44
+ }
45
+
46
+ // ../../node_modules/.pnpm/is-what@5.0.2/node_modules/is-what/dist/isPlainObject.js
47
+ function isPlainObject(payload) {
48
+ if (getType(payload) !== "Object")
49
+ return false;
50
+ const prototype = Object.getPrototypeOf(payload);
51
+ return !!prototype && prototype.constructor === Object && prototype === Object.prototype;
52
+ }
53
+
54
+ // src/fetch/super-json.ts
55
+ function serialize(value, segments = [], meta = []) {
56
+ if (typeof value === "bigint") {
57
+ meta.push(["bigint", segments]);
58
+ return { data: value.toString(), meta };
59
+ }
60
+ if (value instanceof Date) {
61
+ meta.push(["date", segments]);
62
+ const data = Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString();
63
+ return { data, meta };
64
+ }
65
+ if (Number.isNaN(value)) {
66
+ meta.push(["nan", segments]);
67
+ return { data: "NaN", meta };
68
+ }
69
+ if (value instanceof RegExp) {
70
+ meta.push(["regexp", segments]);
71
+ return { data: value.toString(), meta };
72
+ }
73
+ if (value instanceof URL) {
74
+ meta.push(["url", segments]);
75
+ return { data: value.toString(), meta };
76
+ }
77
+ if (isPlainObject(value)) {
78
+ const data = {};
79
+ for (const k in value) {
80
+ data[k] = serialize(value[k], [...segments, k], meta).data;
15
81
  }
82
+ return { data, meta };
16
83
  }
17
- const error = new ORPCError({ code: "NOT_FOUND", message: "Not found" });
18
- return new Response(JSON.stringify(error.toJSON()), {
19
- status: error.status,
20
- headers: {
21
- "Content-Type": "application/json"
84
+ if (Array.isArray(value)) {
85
+ const data = value.map((v, i) => {
86
+ if (v === void 0) {
87
+ meta.push(["undefined", [...segments, i]]);
88
+ return null;
89
+ }
90
+ return serialize(v, [...segments, i], meta).data;
91
+ });
92
+ return { data, meta };
93
+ }
94
+ if (value instanceof Set) {
95
+ const result = serialize(Array.from(value), segments, meta);
96
+ meta.push(["set", segments]);
97
+ return result;
98
+ }
99
+ if (value instanceof Map) {
100
+ const result = serialize(Array.from(value.entries()), segments, meta);
101
+ meta.push(["map", segments]);
102
+ return result;
103
+ }
104
+ return { data: value, meta };
105
+ }
106
+ function deserialize({
107
+ data,
108
+ meta
109
+ }) {
110
+ if (meta.length === 0) {
111
+ return data;
112
+ }
113
+ const ref = { data };
114
+ for (const [type, segments] of meta) {
115
+ let currentRef = ref;
116
+ let preSegment = "data";
117
+ for (let i = 0; i < segments.length; i++) {
118
+ currentRef = currentRef[preSegment];
119
+ preSegment = segments[i];
120
+ }
121
+ switch (type) {
122
+ case "nan":
123
+ currentRef[preSegment] = Number.NaN;
124
+ break;
125
+ case "bigint":
126
+ currentRef[preSegment] = BigInt(currentRef[preSegment]);
127
+ break;
128
+ case "date":
129
+ currentRef[preSegment] = new Date(currentRef[preSegment]);
130
+ break;
131
+ case "regexp": {
132
+ const [, pattern, flags] = currentRef[preSegment].match(/^\/(.*)\/([a-z]*)$/);
133
+ currentRef[preSegment] = new RegExp(pattern, flags);
134
+ break;
135
+ }
136
+ case "url":
137
+ currentRef[preSegment] = new URL(currentRef[preSegment]);
138
+ break;
139
+ case "undefined":
140
+ currentRef[preSegment] = void 0;
141
+ break;
142
+ case "map":
143
+ currentRef[preSegment] = new Map(currentRef[preSegment]);
144
+ break;
145
+ case "set":
146
+ currentRef[preSegment] = new Set(currentRef[preSegment]);
147
+ break;
148
+ /* v8 ignore next 3 */
149
+ default: {
150
+ const _expected = type;
151
+ }
22
152
  }
23
- });
153
+ }
154
+ return ref.data;
24
155
  }
25
156
 
26
- // src/fetch/orpc-handler.ts
27
- import { executeWithHooks, ORPC_PROTOCOL_HEADER, ORPC_PROTOCOL_VALUE, trim, value } from "@orpc/shared";
28
- import { ORPCError as ORPCError2 } from "@orpc/shared/error";
29
- import { ORPCDeserializer, ORPCSerializer } from "@orpc/transformer";
30
- var serializer = new ORPCSerializer();
31
- var deserializer = new ORPCDeserializer();
32
- function createORPCHandler() {
33
- return async (options) => {
34
- if (!options.request.headers.get(ORPC_PROTOCOL_HEADER)?.includes(ORPC_PROTOCOL_VALUE)) {
157
+ // src/fetch/orpc-payload-codec.ts
158
+ var ORPCPayloadCodec = class {
159
+ /**
160
+ * If method is GET, the payload will be encoded as query string.
161
+ * If method is GET and payload contain file, the method will be fallback to fallbackMethod. (fallbackMethod = GET will force to use GET method)
162
+ */
163
+ encode(payload, method = "POST", fallbackMethod = "POST") {
164
+ const { data, meta } = serialize(payload);
165
+ const { maps, values } = findDeepMatches((v) => v instanceof Blob, data);
166
+ if (method === "GET" && (values.length === 0 || fallbackMethod === "GET")) {
167
+ const query = new URLSearchParams({
168
+ data: JSON.stringify(data),
169
+ meta: JSON.stringify(meta)
170
+ });
171
+ return {
172
+ query,
173
+ method: "GET"
174
+ };
175
+ }
176
+ const nonGETMethod = method === "GET" ? fallbackMethod : method;
177
+ if (values.length > 0) {
178
+ const form = new FormData();
179
+ if (data !== void 0) {
180
+ form.append("data", JSON.stringify(data));
181
+ }
182
+ form.append("meta", JSON.stringify(meta));
183
+ form.append("maps", JSON.stringify(maps));
184
+ for (const i in values) {
185
+ const value = values[i];
186
+ form.append(i, value);
187
+ }
188
+ return {
189
+ body: form,
190
+ method: nonGETMethod
191
+ };
192
+ }
193
+ return {
194
+ body: JSON.stringify({ data, meta }),
195
+ headers: new Headers({
196
+ "content-type": "application/json"
197
+ }),
198
+ method: nonGETMethod
199
+ };
200
+ }
201
+ async decode(re) {
202
+ try {
203
+ if ("method" in re && re.method === "GET") {
204
+ const url = new URL(re.url);
205
+ const query = url.searchParams;
206
+ const data = JSON.parse(query.getAll("data").at(-1));
207
+ const meta = JSON.parse(query.getAll("meta").at(-1));
208
+ return deserialize({
209
+ data,
210
+ meta
211
+ });
212
+ }
213
+ if (re.headers.get("content-type")?.startsWith("multipart/form-data")) {
214
+ const form = await re.formData();
215
+ const rawData = form.get("data");
216
+ const rawMeta = form.get("meta");
217
+ const rawMaps = form.get("maps");
218
+ let data = JSON.parse(rawData);
219
+ const meta = JSON.parse(rawMeta);
220
+ const maps = JSON.parse(rawMaps);
221
+ for (const i in maps) {
222
+ data = set(data, maps[i], form.get(i));
223
+ }
224
+ return deserialize({
225
+ data,
226
+ meta
227
+ });
228
+ }
229
+ const json = await re.json();
230
+ return deserialize(json);
231
+ } catch (e) {
232
+ throw new ORPCError({
233
+ code: "BAD_REQUEST",
234
+ message: "Cannot parse request/response. Please check the request/response body and Content-Type header.",
235
+ cause: e
236
+ });
237
+ }
238
+ }
239
+ };
240
+
241
+ // src/fetch/orpc-procedure-matcher.ts
242
+ import { trim } from "@orpc/shared";
243
+ var ORPCProcedureMatcher = class {
244
+ constructor(router) {
245
+ this.router = router;
246
+ }
247
+ async match(pathname) {
248
+ const path = trim(pathname, "/").split("/").map(decodeURIComponent);
249
+ const match = getRouterChild(this.router, ...path);
250
+ const { default: maybeProcedure } = await unlazy(match);
251
+ if (!isProcedure(maybeProcedure)) {
35
252
  return void 0;
36
253
  }
37
- const context = await value(options.context);
38
- const handler = async () => {
39
- const url = new URL(options.request.url);
40
- const pathname = `/${trim(url.pathname.replace(options.prefix ?? "", ""), "/")}`;
41
- const match = await resolveRouterMatch(options.router, pathname);
254
+ return {
255
+ procedure: maybeProcedure,
256
+ path
257
+ };
258
+ }
259
+ };
260
+
261
+ // src/fetch/orpc-handler.ts
262
+ var ORPCHandler = class {
263
+ constructor(router, options) {
264
+ this.router = router;
265
+ this.options = options;
266
+ this.procedureMatcher = options?.procedureMatcher ?? new ORPCProcedureMatcher(router);
267
+ this.payloadCodec = options?.payloadCodec ?? new ORPCPayloadCodec();
268
+ }
269
+ procedureMatcher;
270
+ payloadCodec;
271
+ condition(request) {
272
+ return Boolean(request.headers.get(ORPC_HANDLER_HEADER)?.includes(ORPC_HANDLER_VALUE));
273
+ }
274
+ async fetch(request, ...[options]) {
275
+ const context = options?.context;
276
+ const execute = async () => {
277
+ const url = new URL(request.url);
278
+ const pathname = `/${trim2(url.pathname.replace(options?.prefix ?? "", ""), "/")}`;
279
+ const match = await this.procedureMatcher.match(pathname);
42
280
  if (!match) {
43
281
  throw new ORPCError2({ code: "NOT_FOUND", message: "Not found" });
44
282
  }
45
- const input = await parseRequestInput(options.request);
46
- const caller = createProcedureClient({
283
+ const input = await this.payloadCodec.decode(request);
284
+ const client = createProcedureClient({
47
285
  context,
48
286
  procedure: match.procedure,
49
287
  path: match.path
50
288
  });
51
- const output = await caller(input, { signal: options.signal });
52
- const { body, headers } = serializer.serialize(output);
53
- return new Response(body, {
54
- status: 200,
55
- headers
56
- });
289
+ const output = await client(input, { signal: options?.signal });
290
+ const { body, headers } = this.payloadCodec.encode(output);
291
+ return new Response(body, { headers });
57
292
  };
58
293
  try {
59
294
  return await executeWithHooks({
60
- hooks: options,
61
295
  context,
62
- execute: handler,
63
- input: options.request,
296
+ execute,
297
+ input: request,
298
+ hooks: this.options,
64
299
  meta: {
65
- signal: options.signal
300
+ signal: options?.signal
66
301
  }
67
302
  });
68
- } catch (error) {
69
- return handleErrorResponse(error);
303
+ } catch (e) {
304
+ const error = e instanceof ORPCError2 ? e : new ORPCError2({
305
+ code: "INTERNAL_SERVER_ERROR",
306
+ message: "Internal server error",
307
+ cause: e
308
+ });
309
+ const { body, headers } = this.payloadCodec.encode(error.toJSON());
310
+ return new Response(body, {
311
+ headers,
312
+ status: error.status
313
+ });
70
314
  }
71
- };
72
- }
73
- async function resolveRouterMatch(router, pathname) {
74
- const pathSegments = trim(pathname, "/").split("/").map(decodeURIComponent);
75
- const match = getRouterChild(router, ...pathSegments);
76
- const { default: maybeProcedure } = await unlazy(match);
77
- if (!isProcedure(maybeProcedure)) {
78
- return void 0;
79
- }
80
- return {
81
- procedure: maybeProcedure,
82
- path: pathSegments
83
- };
84
- }
85
- async function parseRequestInput(request) {
86
- try {
87
- return await deserializer.deserialize(request);
88
- } catch (error) {
89
- throw new ORPCError2({
90
- code: "BAD_REQUEST",
91
- message: "Cannot parse request. Please check the request body and Content-Type header.",
92
- cause: error
93
- });
94
315
  }
95
- }
96
- function handleErrorResponse(error) {
97
- const orpcError = error instanceof ORPCError2 ? error : new ORPCError2({
98
- code: "INTERNAL_SERVER_ERROR",
99
- message: "Internal server error",
100
- cause: error
101
- });
102
- const { body, headers } = serializer.serialize(orpcError.toJSON());
103
- return new Response(body, {
104
- status: orpcError.status,
105
- headers
106
- });
107
- }
316
+ };
108
317
  export {
109
- createORPCHandler,
110
- handleFetchRequest
318
+ CompositeHandler,
319
+ ORPCHandler,
320
+ ORPCPayloadCodec,
321
+ ORPCProcedureMatcher,
322
+ super_json_exports as SuperJSON
111
323
  };
112
324
  //# sourceMappingURL=fetch.js.map
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ import {
9
9
  lazy,
10
10
  mergeContext,
11
11
  unlazy
12
- } from "./chunk-FN62GL22.js";
12
+ } from "./chunk-6A7XHEBH.js";
13
13
 
14
14
  // src/builder.ts
15
15
  import { ContractProcedure } from "@orpc/contract";
@@ -110,11 +110,11 @@ var ProcedureImplementer = class _ProcedureImplementer {
110
110
  middlewares: [...this["~orpc"].middlewares ?? [], mappedMiddleware]
111
111
  });
112
112
  }
113
- func(func) {
113
+ handler(handler) {
114
114
  return decorateProcedure(new Procedure({
115
115
  middlewares: this["~orpc"].middlewares,
116
116
  contract: this["~orpc"].contract,
117
- func
117
+ handler
118
118
  }));
119
119
  }
120
120
  };
@@ -358,11 +358,11 @@ var ProcedureBuilder = class _ProcedureBuilder {
358
358
  middlewares: this["~orpc"].middlewares
359
359
  }).use(middleware, mapInput);
360
360
  }
361
- func(func) {
361
+ handler(handler) {
362
362
  return decorateProcedure(new Procedure({
363
363
  middlewares: this["~orpc"].middlewares,
364
364
  contract: this["~orpc"].contract,
365
- func
365
+ handler
366
366
  }));
367
367
  }
368
368
  };
@@ -416,14 +416,14 @@ var Builder = class _Builder {
416
416
  })
417
417
  });
418
418
  }
419
- func(func) {
419
+ handler(handler) {
420
420
  return decorateProcedure(new Procedure({
421
421
  middlewares: this["~orpc"].middlewares,
422
422
  contract: new ContractProcedure({
423
423
  InputSchema: void 0,
424
424
  OutputSchema: void 0
425
425
  }),
426
- func
426
+ handler
427
427
  }));
428
428
  }
429
429
  prefix(prefix) {
@@ -23,7 +23,7 @@ export declare class Builder<TContext extends Context, TExtraContext extends Con
23
23
  route(route: RouteOptions): ProcedureBuilder<TContext, TExtraContext, undefined, undefined>;
24
24
  input<USchema extends Schema = undefined>(schema: USchema, example?: SchemaInput<USchema>): ProcedureBuilder<TContext, TExtraContext, USchema, undefined>;
25
25
  output<USchema extends Schema = undefined>(schema: USchema, example?: SchemaOutput<USchema>): ProcedureBuilder<TContext, TExtraContext, undefined, USchema>;
26
- func<UFuncOutput = undefined>(func: ProcedureFunc<TContext, TExtraContext, undefined, undefined, UFuncOutput>): DecoratedProcedure<TContext, TExtraContext, undefined, undefined, UFuncOutput>;
26
+ handler<UFuncOutput = undefined>(handler: ProcedureFunc<TContext, TExtraContext, undefined, undefined, UFuncOutput>): DecoratedProcedure<TContext, TExtraContext, undefined, undefined, UFuncOutput>;
27
27
  prefix(prefix: HTTPPath): RouterBuilder<TContext, TExtraContext>;
28
28
  tag(...tags: string[]): RouterBuilder<TContext, TExtraContext>;
29
29
  router<U extends Router<MergeContext<TContext, TExtraContext>, any>>(router: U): AdaptedRouter<TContext, U>;
@@ -0,0 +1,8 @@
1
+ import type { Context } from '../types';
2
+ import type { ConditionalFetchHandler, FetchHandler, FetchOptions } from './types';
3
+ export declare class CompositeHandler<T extends Context> implements FetchHandler<T> {
4
+ private readonly handlers;
5
+ constructor(handlers: ConditionalFetchHandler<T>[]);
6
+ fetch(request: Request, ...opt: [options: FetchOptions<T>] | (undefined extends T ? [] : never)): Promise<Response>;
7
+ }
8
+ //# sourceMappingURL=composite-handler.d.ts.map
@@ -1,4 +1,7 @@
1
- export * from './handle-request';
1
+ export * from './composite-handler';
2
2
  export * from './orpc-handler';
3
+ export * from './orpc-payload-codec';
4
+ export * from './orpc-procedure-matcher';
5
+ export * as SuperJSON from './super-json';
3
6
  export * from './types';
4
7
  //# sourceMappingURL=index.d.ts.map
@@ -1,3 +1,20 @@
1
- import type { FetchHandler } from './types';
2
- export declare function createORPCHandler(): FetchHandler;
1
+ import type { Hooks } from '@orpc/shared';
2
+ import type { Router } from '../router';
3
+ import type { Context, WithSignal } from '../types';
4
+ import type { ConditionalFetchHandler, FetchOptions } from './types';
5
+ import { type PublicORPCPayloadCodec } from './orpc-payload-codec';
6
+ import { type PublicORPCProcedureMatcher } from './orpc-procedure-matcher';
7
+ export type ORPCHandlerOptions<T extends Context> = Hooks<Request, Response, T, WithSignal> & {
8
+ procedureMatcher?: PublicORPCProcedureMatcher;
9
+ payloadCodec?: PublicORPCPayloadCodec;
10
+ };
11
+ export declare class ORPCHandler<T extends Context> implements ConditionalFetchHandler<T> {
12
+ readonly router: Router<T, any>;
13
+ readonly options?: NoInfer<ORPCHandlerOptions<T>> | undefined;
14
+ private readonly procedureMatcher;
15
+ private readonly payloadCodec;
16
+ constructor(router: Router<T, any>, options?: NoInfer<ORPCHandlerOptions<T>> | undefined);
17
+ condition(request: Request): boolean;
18
+ fetch(request: Request, ...[options]: [options: FetchOptions<T>] | (undefined extends T ? [] : never)): Promise<Response>;
19
+ }
3
20
  //# sourceMappingURL=orpc-handler.d.ts.map
@@ -0,0 +1,16 @@
1
+ import type { HTTPMethod } from '@orpc/contract';
2
+ export declare class ORPCPayloadCodec {
3
+ /**
4
+ * If method is GET, the payload will be encoded as query string.
5
+ * If method is GET and payload contain file, the method will be fallback to fallbackMethod. (fallbackMethod = GET will force to use GET method)
6
+ */
7
+ encode(payload: unknown, method?: HTTPMethod, fallbackMethod?: HTTPMethod): {
8
+ query?: URLSearchParams;
9
+ body?: FormData | string;
10
+ headers?: Headers;
11
+ method: HTTPMethod;
12
+ };
13
+ decode(re: Request | Response): Promise<unknown>;
14
+ }
15
+ export type PublicORPCPayloadCodec = Pick<ORPCPayloadCodec, keyof ORPCPayloadCodec>;
16
+ //# sourceMappingURL=orpc-payload-codec.d.ts.map
@@ -0,0 +1,12 @@
1
+ import type { ANY_PROCEDURE } from '../procedure';
2
+ import { type ANY_ROUTER } from '../router';
3
+ export declare class ORPCProcedureMatcher {
4
+ private readonly router;
5
+ constructor(router: ANY_ROUTER);
6
+ match(pathname: string): Promise<{
7
+ path: string[];
8
+ procedure: ANY_PROCEDURE;
9
+ } | undefined>;
10
+ }
11
+ export type PublicORPCProcedureMatcher = Pick<ORPCProcedureMatcher, keyof ORPCProcedureMatcher>;
12
+ //# sourceMappingURL=orpc-procedure-matcher.d.ts.map
@@ -0,0 +1,12 @@
1
+ import type { Segment } from '@orpc/shared';
2
+ export type JSONExtraType = 'bigint' | 'date' | 'nan' | 'undefined' | 'set' | 'map' | 'regexp' | 'url';
3
+ export type JSONMeta = [JSONExtraType, Segment[]][];
4
+ export declare function serialize(value: unknown, segments?: Segment[], meta?: JSONMeta): {
5
+ data: unknown;
6
+ meta: JSONMeta;
7
+ };
8
+ export declare function deserialize({ data, meta, }: {
9
+ data: unknown;
10
+ meta: JSONMeta;
11
+ }): unknown;
12
+ //# sourceMappingURL=super-json.d.ts.map
@@ -1,28 +1,16 @@
1
1
  import type { HTTPPath } from '@orpc/contract';
2
- import type { Hooks, Value } from '@orpc/shared';
3
- import type { Router } from '../router';
4
2
  import type { Context, WithSignal } from '../types';
5
- export type FetchHandlerOptions<T extends Context> = {
6
- /**
7
- * The `router` used for handling the request and routing,
8
- *
9
- */
10
- router: Router<T, any>;
11
- /**
12
- * The request need to be handled.
13
- */
14
- request: Request;
15
- /**
16
- * Remove the prefix from the request path.
17
- *
18
- * @example /orpc
19
- * @example /api
20
- */
3
+ export type FetchOptions<T extends Context> = WithSignal & {
21
4
  prefix?: HTTPPath;
22
- } & NoInfer<(undefined extends T ? {
23
- context?: Value<T>;
5
+ } & (undefined extends T ? {
6
+ context?: T;
24
7
  } : {
25
- context: Value<T>;
26
- })> & WithSignal & Hooks<Request, Response, T, WithSignal>;
27
- export type FetchHandler = <T extends Context>(options: FetchHandlerOptions<T>) => Promise<Response | undefined>;
8
+ context: T;
9
+ });
10
+ export interface FetchHandler<T extends Context> {
11
+ fetch: (request: Request, ...opt: [options: FetchOptions<T>] | (undefined extends T ? [] : never)) => Promise<Response>;
12
+ }
13
+ export interface ConditionalFetchHandler<T extends Context> extends FetchHandler<T> {
14
+ condition: (request: Request) => boolean;
15
+ }
28
16
  //# sourceMappingURL=types.d.ts.map
@@ -3,7 +3,7 @@ import type { Lazy } from './lazy';
3
3
  import type { Procedure } from './procedure';
4
4
  import type { ProcedureClient } from './procedure-client';
5
5
  import { type ANY_ROUTER } from './router';
6
- export type DecoratedLazy<T> = T extends Lazy<infer U> ? DecoratedLazy<U> : Lazy<T> & (T extends Procedure<infer UContext, any, infer UInputSchema, infer UOutputSchema, infer UFuncOutput> ? undefined extends UContext ? ProcedureClient<SchemaInput<UInputSchema>, SchemaOutput<UOutputSchema, UFuncOutput>> : unknown : {
6
+ export type DecoratedLazy<T> = T extends Lazy<infer U> ? DecoratedLazy<U> : Lazy<T> & (T extends Procedure<infer UContext, any, infer UInputSchema, infer UOutputSchema, infer UFuncOutput> ? undefined extends UContext ? ProcedureClient<SchemaInput<UInputSchema>, SchemaOutput<UOutputSchema, UFuncOutput>, unknown> : unknown : {
7
7
  [K in keyof T]: T[K] extends object ? DecoratedLazy<T[K]> : never;
8
8
  });
9
9
  export declare function decorateLazy<T extends Lazy<ANY_ROUTER | undefined>>(lazied: T): DecoratedLazy<T>;
@@ -17,6 +17,6 @@ export declare class ProcedureBuilder<TContext extends Context, TExtraContext ex
17
17
  output<U extends Schema = undefined>(schema: U, example?: SchemaOutput<U>): ProcedureBuilder<TContext, TExtraContext, TInputSchema, U>;
18
18
  use<U extends Context & Partial<MergeContext<TContext, TExtraContext>> | undefined = undefined>(middleware: Middleware<MergeContext<TContext, TExtraContext>, U, SchemaOutput<TInputSchema>, SchemaInput<TOutputSchema>>): ProcedureImplementer<TContext, MergeContext<TExtraContext, U>, TInputSchema, TOutputSchema>;
19
19
  use<UExtra extends Context & Partial<MergeContext<TContext, TExtraContext>> | undefined = undefined, UInput = unknown>(middleware: Middleware<MergeContext<TContext, TExtraContext>, UExtra, UInput, SchemaInput<TOutputSchema>>, mapInput: MapInputMiddleware<SchemaOutput<TInputSchema>, UInput>): ProcedureImplementer<TContext, MergeContext<TExtraContext, UExtra>, TInputSchema, TOutputSchema>;
20
- func<UFuncOutput extends SchemaInput<TOutputSchema>>(func: ProcedureFunc<TContext, TExtraContext, TInputSchema, TOutputSchema, UFuncOutput>): DecoratedProcedure<TContext, TExtraContext, TInputSchema, TOutputSchema, UFuncOutput>;
20
+ handler<UFuncOutput extends SchemaInput<TOutputSchema>>(handler: ProcedureFunc<TContext, TExtraContext, TInputSchema, TOutputSchema, UFuncOutput>): DecoratedProcedure<TContext, TExtraContext, TInputSchema, TOutputSchema, UFuncOutput>;
21
21
  }
22
22
  //# sourceMappingURL=procedure-builder.d.ts.map
@@ -3,14 +3,19 @@ import type { Hooks, Value } from '@orpc/shared';
3
3
  import type { Lazyable } from './lazy';
4
4
  import type { Procedure } from './procedure';
5
5
  import type { Context, Meta, WELL_CONTEXT, WithSignal } from './types';
6
- export interface ProcedureClient<TInput, TOutput> {
7
- (...opts: [input: TInput, options?: WithSignal] | (undefined extends TInput ? [] : never)): Promise<TOutput>;
6
+ export type ProcedureClientOptions<TClientContext> = WithSignal & (undefined extends TClientContext ? {
7
+ context?: TClientContext;
8
+ } : {
9
+ context: TClientContext;
10
+ });
11
+ export interface ProcedureClient<TInput, TOutput, TClientContext> {
12
+ (...opts: [input: TInput, options: ProcedureClientOptions<TClientContext>] | (undefined extends TInput & TClientContext ? [] : never) | (undefined extends TClientContext ? [input: TInput] : never)): Promise<TOutput>;
8
13
  }
9
14
  /**
10
15
  * Options for creating a procedure caller with comprehensive type safety
11
16
  */
12
- export type CreateProcedureClientOptions<TContext extends Context, TInputSchema extends Schema, TOutputSchema extends Schema, TFuncOutput extends SchemaInput<TOutputSchema>> = {
13
- procedure: Lazyable<Procedure<TContext, any, TInputSchema, TOutputSchema, TFuncOutput>>;
17
+ export type CreateProcedureClientOptions<TContext extends Context, TInputSchema extends Schema, TOutputSchema extends Schema, THandlerOutput extends SchemaInput<TOutputSchema>> = {
18
+ procedure: Lazyable<Procedure<TContext, any, TInputSchema, TOutputSchema, THandlerOutput>>;
14
19
  /**
15
20
  * This is helpful for logging and analytics.
16
21
  *
@@ -24,6 +29,6 @@ export type CreateProcedureClientOptions<TContext extends Context, TInputSchema
24
29
  context: Value<TContext>;
25
30
  } | (undefined extends TContext ? {
26
31
  context?: undefined;
27
- } : never)) & Hooks<unknown, SchemaOutput<TOutputSchema, TFuncOutput>, TContext, Meta>;
28
- export declare function createProcedureClient<TContext extends Context = WELL_CONTEXT, TInputSchema extends Schema = undefined, TOutputSchema extends Schema = undefined, TFuncOutput extends SchemaInput<TOutputSchema> = SchemaInput<TOutputSchema>>(options: CreateProcedureClientOptions<TContext, TInputSchema, TOutputSchema, TFuncOutput>): ProcedureClient<SchemaInput<TInputSchema>, SchemaOutput<TOutputSchema, TFuncOutput>>;
32
+ } : never)) & Hooks<unknown, SchemaOutput<TOutputSchema, THandlerOutput>, TContext, Meta>;
33
+ export declare function createProcedureClient<TContext extends Context = WELL_CONTEXT, TInputSchema extends Schema = undefined, TOutputSchema extends Schema = undefined, THandlerOutput extends SchemaInput<TOutputSchema> = SchemaInput<TOutputSchema>>(options: CreateProcedureClientOptions<TContext, TInputSchema, TOutputSchema, THandlerOutput>): ProcedureClient<SchemaInput<TInputSchema>, SchemaOutput<TOutputSchema, THandlerOutput>, unknown>;
29
34
  //# sourceMappingURL=procedure-client.d.ts.map
@@ -3,12 +3,12 @@ import type { MapInputMiddleware, Middleware } from './middleware';
3
3
  import type { ProcedureClient } from './procedure-client';
4
4
  import type { Context, MergeContext } from './types';
5
5
  import { Procedure } from './procedure';
6
- export type DecoratedProcedure<TContext extends Context, TExtraContext extends Context, TInputSchema extends Schema, TOutputSchema extends Schema, TFuncOutput extends SchemaInput<TOutputSchema>> = Procedure<TContext, TExtraContext, TInputSchema, TOutputSchema, TFuncOutput> & {
7
- prefix: (prefix: HTTPPath) => DecoratedProcedure<TContext, TExtraContext, TInputSchema, TOutputSchema, TFuncOutput>;
8
- route: (route: RouteOptions) => DecoratedProcedure<TContext, TExtraContext, TInputSchema, TOutputSchema, TFuncOutput>;
9
- use: (<U extends Context & Partial<MergeContext<TContext, TExtraContext>> | undefined = undefined>(middleware: Middleware<MergeContext<TContext, TExtraContext>, U, SchemaOutput<TInputSchema>, SchemaInput<TOutputSchema, TFuncOutput>>) => DecoratedProcedure<TContext, MergeContext<TExtraContext, U>, TInputSchema, TOutputSchema, TFuncOutput>) & (<UExtra extends Context & Partial<MergeContext<TContext, TExtraContext>> | undefined = undefined, UInput = unknown>(middleware: Middleware<MergeContext<TContext, TExtraContext>, UExtra, UInput, SchemaInput<TOutputSchema, TFuncOutput>>, mapInput: MapInputMiddleware<SchemaOutput<TInputSchema, TFuncOutput>, UInput>) => DecoratedProcedure<TContext, MergeContext<TExtraContext, UExtra>, TInputSchema, TOutputSchema, TFuncOutput>);
10
- unshiftTag: (...tags: string[]) => DecoratedProcedure<TContext, TExtraContext, TInputSchema, TOutputSchema, TFuncOutput>;
11
- unshiftMiddleware: <U extends Context & Partial<MergeContext<TContext, TExtraContext>> | undefined = undefined>(...middlewares: Middleware<TContext, U, SchemaOutput<TInputSchema>, SchemaInput<TOutputSchema, TFuncOutput>>[]) => DecoratedProcedure<TContext, TExtraContext, TInputSchema, TOutputSchema, TFuncOutput>;
12
- } & (undefined extends TContext ? ProcedureClient<SchemaInput<TInputSchema>, SchemaOutput<TOutputSchema, TFuncOutput>> : unknown);
13
- export declare function decorateProcedure<TContext extends Context, TExtraContext extends Context, TInputSchema extends Schema, TOutputSchema extends Schema, TFuncOutput extends SchemaInput<TOutputSchema>>(procedure: Procedure<TContext, TExtraContext, TInputSchema, TOutputSchema, TFuncOutput>): DecoratedProcedure<TContext, TExtraContext, TInputSchema, TOutputSchema, TFuncOutput>;
6
+ export type DecoratedProcedure<TContext extends Context, TExtraContext extends Context, TInputSchema extends Schema, TOutputSchema extends Schema, THandlerOutput extends SchemaInput<TOutputSchema>> = Procedure<TContext, TExtraContext, TInputSchema, TOutputSchema, THandlerOutput> & {
7
+ prefix: (prefix: HTTPPath) => DecoratedProcedure<TContext, TExtraContext, TInputSchema, TOutputSchema, THandlerOutput>;
8
+ route: (route: RouteOptions) => DecoratedProcedure<TContext, TExtraContext, TInputSchema, TOutputSchema, THandlerOutput>;
9
+ use: (<U extends Context & Partial<MergeContext<TContext, TExtraContext>> | undefined = undefined>(middleware: Middleware<MergeContext<TContext, TExtraContext>, U, SchemaOutput<TInputSchema>, SchemaInput<TOutputSchema, THandlerOutput>>) => DecoratedProcedure<TContext, MergeContext<TExtraContext, U>, TInputSchema, TOutputSchema, THandlerOutput>) & (<UExtra extends Context & Partial<MergeContext<TContext, TExtraContext>> | undefined = undefined, UInput = unknown>(middleware: Middleware<MergeContext<TContext, TExtraContext>, UExtra, UInput, SchemaInput<TOutputSchema, THandlerOutput>>, mapInput: MapInputMiddleware<SchemaOutput<TInputSchema, THandlerOutput>, UInput>) => DecoratedProcedure<TContext, MergeContext<TExtraContext, UExtra>, TInputSchema, TOutputSchema, THandlerOutput>);
10
+ unshiftTag: (...tags: string[]) => DecoratedProcedure<TContext, TExtraContext, TInputSchema, TOutputSchema, THandlerOutput>;
11
+ unshiftMiddleware: <U extends Context & Partial<MergeContext<TContext, TExtraContext>> | undefined = undefined>(...middlewares: Middleware<TContext, U, SchemaOutput<TInputSchema>, SchemaInput<TOutputSchema, THandlerOutput>>[]) => DecoratedProcedure<TContext, TExtraContext, TInputSchema, TOutputSchema, THandlerOutput>;
12
+ } & (undefined extends TContext ? ProcedureClient<SchemaInput<TInputSchema>, SchemaOutput<TOutputSchema, THandlerOutput>, unknown> : unknown);
13
+ export declare function decorateProcedure<TContext extends Context, TExtraContext extends Context, TInputSchema extends Schema, TOutputSchema extends Schema, THandlerOutput extends SchemaInput<TOutputSchema>>(procedure: Procedure<TContext, TExtraContext, TInputSchema, TOutputSchema, THandlerOutput>): DecoratedProcedure<TContext, TExtraContext, TInputSchema, TOutputSchema, THandlerOutput>;
14
14
  //# sourceMappingURL=procedure-decorated.d.ts.map
@@ -13,6 +13,6 @@ export declare class ProcedureImplementer<TContext extends Context, TExtraContex
13
13
  constructor(def: ProcedureImplementerDef<TContext, TExtraContext, TInputSchema, TOutputSchema>);
14
14
  use<U extends Context & Partial<MergeContext<TContext, TExtraContext>> | undefined = undefined>(middleware: Middleware<MergeContext<TContext, TExtraContext>, U, SchemaOutput<TInputSchema>, SchemaInput<TOutputSchema>>): ProcedureImplementer<TContext, MergeContext<TExtraContext, U>, TInputSchema, TOutputSchema>;
15
15
  use<UExtra extends Context & Partial<MergeContext<TContext, TExtraContext>> | undefined = undefined, UInput = unknown>(middleware: Middleware<MergeContext<TContext, TExtraContext>, UExtra, UInput, SchemaInput<TOutputSchema>>, mapInput: MapInputMiddleware<SchemaOutput<TInputSchema>, UInput>): ProcedureImplementer<TContext, MergeContext<TExtraContext, UExtra>, TInputSchema, TOutputSchema>;
16
- func<UFuncOutput extends SchemaInput<TOutputSchema>>(func: ProcedureFunc<TContext, TExtraContext, TInputSchema, TOutputSchema, UFuncOutput>): DecoratedProcedure<TContext, TExtraContext, TInputSchema, TOutputSchema, UFuncOutput>;
16
+ handler<UFuncOutput extends SchemaInput<TOutputSchema>>(handler: ProcedureFunc<TContext, TExtraContext, TInputSchema, TOutputSchema, UFuncOutput>): DecoratedProcedure<TContext, TExtraContext, TInputSchema, TOutputSchema, UFuncOutput>;
17
17
  }
18
18
  //# sourceMappingURL=procedure-implementer.d.ts.map
@@ -3,18 +3,18 @@ import type { Lazy } from './lazy';
3
3
  import type { Middleware } from './middleware';
4
4
  import type { Context, MergeContext, Meta } from './types';
5
5
  import { type ContractProcedure, type Schema, type SchemaInput, type SchemaOutput } from '@orpc/contract';
6
- export interface ProcedureFunc<TContext extends Context, TExtraContext extends Context, TInputSchema extends Schema, TOutputSchema extends Schema, TFuncOutput extends SchemaInput<TOutputSchema>> {
7
- (input: SchemaOutput<TInputSchema>, context: MergeContext<TContext, TExtraContext>, meta: Meta): Promisable<SchemaInput<TOutputSchema, TFuncOutput>>;
6
+ export interface ProcedureFunc<TContext extends Context, TExtraContext extends Context, TInputSchema extends Schema, TOutputSchema extends Schema, THandlerOutput extends SchemaInput<TOutputSchema>> {
7
+ (input: SchemaOutput<TInputSchema>, context: MergeContext<TContext, TExtraContext>, meta: Meta): Promisable<SchemaInput<TOutputSchema, THandlerOutput>>;
8
8
  }
9
- export interface ProcedureDef<TContext extends Context, TExtraContext extends Context, TInputSchema extends Schema, TOutputSchema extends Schema, TFuncOutput extends SchemaInput<TOutputSchema>> {
9
+ export interface ProcedureDef<TContext extends Context, TExtraContext extends Context, TInputSchema extends Schema, TOutputSchema extends Schema, THandlerOutput extends SchemaInput<TOutputSchema>> {
10
10
  middlewares?: Middleware<MergeContext<TContext, TExtraContext>, Partial<TExtraContext> | undefined, SchemaOutput<TInputSchema>, any>[];
11
11
  contract: ContractProcedure<TInputSchema, TOutputSchema>;
12
- func: ProcedureFunc<TContext, TExtraContext, TInputSchema, TOutputSchema, TFuncOutput>;
12
+ handler: ProcedureFunc<TContext, TExtraContext, TInputSchema, TOutputSchema, THandlerOutput>;
13
13
  }
14
- export declare class Procedure<TContext extends Context, TExtraContext extends Context, TInputSchema extends Schema, TOutputSchema extends Schema, TFuncOutput extends SchemaInput<TOutputSchema>> {
14
+ export declare class Procedure<TContext extends Context, TExtraContext extends Context, TInputSchema extends Schema, TOutputSchema extends Schema, THandlerOutput extends SchemaInput<TOutputSchema>> {
15
15
  '~type': "Procedure";
16
- '~orpc': ProcedureDef<TContext, TExtraContext, TInputSchema, TOutputSchema, TFuncOutput>;
17
- constructor(def: ProcedureDef<TContext, TExtraContext, TInputSchema, TOutputSchema, TFuncOutput>);
16
+ '~orpc': ProcedureDef<TContext, TExtraContext, TInputSchema, TOutputSchema, THandlerOutput>;
17
+ constructor(def: ProcedureDef<TContext, TExtraContext, TInputSchema, TOutputSchema, THandlerOutput>);
18
18
  }
19
19
  export type ANY_PROCEDURE = Procedure<any, any, any, any, any>;
20
20
  export type WELL_PROCEDURE = Procedure<Context, Context, Schema, Schema, unknown>;
@@ -5,8 +5,8 @@ import type { Procedure } from './procedure';
5
5
  import type { ProcedureClient } from './procedure-client';
6
6
  import type { Meta } from './types';
7
7
  import { type ANY_ROUTER, type Router } from './router';
8
- export type RouterClient<T extends ANY_ROUTER | ContractRouter> = T extends Lazy<infer U extends ANY_ROUTER | ContractRouter> ? RouterClient<U> : T extends ContractProcedure<infer UInputSchema, infer UOutputSchema> | Procedure<any, any, infer UInputSchema, infer UOutputSchema, infer UFuncOutput> ? ProcedureClient<SchemaInput<UInputSchema>, SchemaOutput<UOutputSchema, UFuncOutput>> : {
9
- [K in keyof T]: T[K] extends ANY_ROUTER | ContractRouter ? RouterClient<T[K]> : never;
8
+ export type RouterClient<TRouter extends ANY_ROUTER | ContractRouter, TClientContext> = TRouter extends Lazy<infer U extends ANY_ROUTER | ContractRouter> ? RouterClient<U, TClientContext> : TRouter extends ContractProcedure<infer UInputSchema, infer UOutputSchema> | Procedure<any, any, infer UInputSchema, infer UOutputSchema, infer UFuncOutput> ? ProcedureClient<SchemaInput<UInputSchema>, SchemaOutput<UOutputSchema, UFuncOutput>, TClientContext> : {
9
+ [K in keyof TRouter]: TRouter[K] extends ANY_ROUTER | ContractRouter ? RouterClient<TRouter[K], TClientContext> : never;
10
10
  };
11
11
  export type CreateRouterClientOptions<TRouter extends ANY_ROUTER> = {
12
12
  router: TRouter | Lazy<undefined>;
@@ -21,5 +21,5 @@ export type CreateRouterClientOptions<TRouter extends ANY_ROUTER> = {
21
21
  } : {
22
22
  context: Value<UContext>;
23
23
  } : never) & Hooks<unknown, unknown, TRouter extends Router<infer UContext, any> ? UContext : never, Meta>;
24
- export declare function createRouterClient<TRouter extends ANY_ROUTER>(options: CreateRouterClientOptions<TRouter>): RouterClient<TRouter>;
24
+ export declare function createRouterClient<TRouter extends ANY_ROUTER>(options: CreateRouterClientOptions<TRouter>): RouterClient<TRouter, unknown>;
25
25
  //# sourceMappingURL=router-client.d.ts.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.0640aed",
4
+ "version": "0.0.0-next.0d79ab9",
5
5
  "license": "MIT",
6
6
  "homepage": "https://orpc.unnoq.com",
7
7
  "repository": {
@@ -33,13 +33,9 @@
33
33
  "!**/*.tsbuildinfo",
34
34
  "dist"
35
35
  ],
36
- "peerDependencies": {
37
- "@orpc/zod": "0.0.0-next.0640aed"
38
- },
39
36
  "dependencies": {
40
- "@orpc/contract": "0.0.0-next.0640aed",
41
- "@orpc/shared": "0.0.0-next.0640aed",
42
- "@orpc/transformer": "0.0.0-next.0640aed"
37
+ "@orpc/contract": "0.0.0-next.0d79ab9",
38
+ "@orpc/shared": "0.0.0-next.0d79ab9"
43
39
  },
44
40
  "devDependencies": {
45
41
  "zod": "^3.24.1"
@@ -1,7 +0,0 @@
1
- import type { Context } from '../types';
2
- import type { FetchHandler, FetchHandlerOptions } from './types';
3
- export type HandleFetchRequestOptions<T extends Context> = FetchHandlerOptions<T> & {
4
- handlers: readonly [FetchHandler, ...FetchHandler[]];
5
- };
6
- export declare function handleFetchRequest<T extends Context>(options: HandleFetchRequestOptions<T>): Promise<Response>;
7
- //# sourceMappingURL=handle-request.d.ts.map