@orpc/server 0.0.0-next.ccd4e42 → 0.0.0-next.d0e429d

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 (50) hide show
  1. package/README.md +118 -0
  2. package/dist/chunk-AJXRPY6I.js +32 -0
  3. package/dist/{chunk-NOA3GBJQ.js → chunk-MHVECKBC.js} +64 -23
  4. package/dist/chunk-NTHCS5CK.js +182 -0
  5. package/dist/chunk-TXHKQO7N.js +120 -0
  6. package/dist/fetch.js +6 -13
  7. package/dist/hono.js +18 -16
  8. package/dist/index.js +16 -7
  9. package/dist/next.js +6 -13
  10. package/dist/node.js +9 -151
  11. package/dist/plugins.js +11 -0
  12. package/dist/src/adapters/fetch/index.d.ts +0 -1
  13. package/dist/src/adapters/fetch/rpc-handler.d.ts +4 -2
  14. package/dist/src/adapters/fetch/types.d.ts +4 -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 +4 -2
  19. package/dist/src/adapters/node/types.d.ts +4 -2
  20. package/dist/src/adapters/standard/handler.d.ts +30 -10
  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 +11 -0
  35. package/dist/src/plugins/cors.d.ts +19 -0
  36. package/dist/src/plugins/index.d.ts +4 -0
  37. package/dist/src/plugins/response-headers.d.ts +10 -0
  38. package/dist/src/procedure-client.d.ts +21 -8
  39. package/dist/src/procedure-decorated.d.ts +7 -4
  40. package/dist/src/procedure-utils.d.ts +5 -3
  41. package/dist/src/procedure.d.ts +5 -3
  42. package/dist/src/router-client.d.ts +7 -17
  43. package/dist/src/router.d.ts +1 -0
  44. package/dist/standard.js +5 -8
  45. package/package.json +12 -4
  46. package/dist/chunk-6RSW63UJ.js +0 -136
  47. package/dist/chunk-JHLUGXCM.js +0 -294
  48. package/dist/src/adapters/fetch/utils.d.ts +0 -6
  49. package/dist/src/adapters/node/utils.d.ts +0 -5
  50. package/dist/src/adapters/standard/rpc-serializer.d.ts +0 -16
package/README.md ADDED
@@ -0,0 +1,118 @@
1
+ <div align="center">
2
+ <image align="center" src="https://orpc.unnoq.com/logo.webp" width=280 />
3
+ </div>
4
+
5
+ <h1></h1>
6
+
7
+ <div align="center">
8
+ <a href="https://codecov.io/gh/unnoq/orpc">
9
+ <img alt="codecov" src="https://codecov.io/gh/unnoq/orpc/branch/main/graph/badge.svg">
10
+ </a>
11
+ <a href="https://www.npmjs.com/package/@orpc/server">
12
+ <img alt="weekly downloads" src="https://img.shields.io/npm/dw/%40orpc%2Fserver?logo=npm" />
13
+ </a>
14
+ <a href="https://github.com/unnoq/orpc/blob/main/LICENSE">
15
+ <img alt="MIT License" src="https://img.shields.io/github/license/unnoq/orpc?logo=open-source-initiative" />
16
+ </a>
17
+ <a href="https://discord.gg/TXEbwRBvQn">
18
+ <img alt="Discord" src="https://img.shields.io/discord/1308966753044398161?color=7389D8&label&logo=discord&logoColor=ffffff" />
19
+ </a>
20
+ </div>
21
+
22
+ <h3 align="center">Typesafe APIs Made Simple 🪄</h3>
23
+
24
+ **oRPC is a powerful combination of RPC and OpenAPI**, makes it easy to build APIs that are end-to-end type-safe and adhere to OpenAPI standards, ensuring a smooth and enjoyable developer experience.
25
+
26
+ ---
27
+
28
+ ## Highlights
29
+
30
+ - **End-to-End Type Safety 🔒**: Ensure complete type safety from inputs to outputs and errors, bridging server and client seamlessly.
31
+ - **First-Class OpenAPI 📄**: Adheres to the OpenAPI standard out of the box, ensuring seamless integration and comprehensive API documentation.
32
+ - **Contract-First Development 📜**: (Optional) Define your API contract upfront and implement it with confidence.
33
+ - **Exceptional Developer Experience ✨**: Enjoy a streamlined workflow with robust typing and clear, in-code documentation.
34
+ - **Multi-Runtime Support 🌍**: Run your code seamlessly on Cloudflare, Deno, Bun, Node.js, and more.
35
+ - **Framework Integrations 🧩**: Supports Tanstack Query (React, Vue), Pinia Colada, and more.
36
+ - **Server Actions ⚡️**: Fully compatible with React Server Actions on Next.js, TanStack Start, and more.
37
+ - **Standard Schema Support 🗂️**: Effortlessly work with Zod, Valibot, ArkType, and others right out of the box.
38
+ - **Fast & Lightweight 💨**: Built on native APIs across all runtimes – optimized for speed and efficiency.
39
+ - **Native Types 📦**: Enjoy built-in support for Date, File, Blob, BigInt, URL and more with no extra setup.
40
+ - **Lazy Router ⏱️**: Improve cold start times with our lazy routing feature.
41
+ - **SSE & Streaming 📡**: Provides SSE and streaming features – perfect for real-time notifications and AI-powered streaming responses.
42
+ - **Reusability 🔄**: Write once and reuse your code across multiple purposes effortlessly.
43
+ - **Extendability 🔌**: Easily enhance oRPC with plugins, middleware, and interceptors.
44
+ - **Reliability 🛡️**: Well-tested, fully TypeScript, production-ready, and MIT licensed for peace of mind.
45
+ - **Simplicity 💡**: Enjoy straightforward, clean code with no hidden magic.
46
+
47
+ ## Documentation
48
+
49
+ You can find the full documentation [here](https://orpc.unnoq.com).
50
+
51
+ ## Packages
52
+
53
+ - [@orpc/contract](https://www.npmjs.com/package/@orpc/contract): Build your API contract.
54
+ - [@orpc/server](https://www.npmjs.com/package/@orpc/server): Build your API or implement API contract.
55
+ - [@orpc/client](https://www.npmjs.com/package/@orpc/client): Consume your API on the client with type-safety.
56
+ - [@orpc/react-query](https://www.npmjs.com/package/@orpc/react-query): Integration with [React Query](https://tanstack.com/query/latest/docs/framework/react/overview).
57
+ - [@orpc/vue-query](https://www.npmjs.com/package/@orpc/vue-query): Integration with [Vue Query](https://tanstack.com/query/latest/docs/framework/vue/overview).
58
+ - [@orpc/vue-colada](https://www.npmjs.com/package/@orpc/vue-colada): Integration with [Pinia Colada](https://pinia-colada.esm.dev/).
59
+ - [@orpc/openapi](https://www.npmjs.com/package/@orpc/openapi): Generate OpenAPI specs and handle OpenAPI requests.
60
+ - [@orpc/zod](https://www.npmjs.com/package/@orpc/zod): More schemas that [Zod](https://zod.dev/) doesn't support yet.
61
+
62
+ ## `@orpc/server`
63
+
64
+ Build your API or implement API contract. Read the [documentation](https://orpc.unnoq.com/docs/getting-started) for more information.
65
+
66
+ ```ts
67
+ import type { IncomingHttpHeaders } from 'node:http'
68
+ import { ORPCError, os } from '@orpc/server'
69
+ import { z } from 'zod'
70
+
71
+ const PlanetSchema = z.object({
72
+ id: z.number().int().min(1),
73
+ name: z.string(),
74
+ description: z.string().optional(),
75
+ })
76
+
77
+ export const listPlanet = os
78
+ .input(
79
+ z.object({
80
+ limit: z.number().int().min(1).max(100).optional(),
81
+ cursor: z.number().int().min(0).default(0),
82
+ }),
83
+ )
84
+ .handler(async ({ input }) => {
85
+ // your list code here
86
+ return [{ id: 1, name: 'name' }]
87
+ })
88
+
89
+ export const findPlanet = os
90
+ .input(PlanetSchema.pick({ id: true }))
91
+ .handler(async ({ input }) => {
92
+ // your find code here
93
+ return { id: 1, name: 'name' }
94
+ })
95
+
96
+ export const createPlanet = os
97
+ .$context<{ headers: IncomingHttpHeaders }>()
98
+ .use(({ context, next }) => {
99
+ const user = parseJWT(context.headers.authorization?.split(' ')[1])
100
+
101
+ if (user) {
102
+ return next({ context: { user } })
103
+ }
104
+
105
+ throw new ORPCError('UNAUTHORIZED')
106
+ })
107
+ .input(PlanetSchema.omit({ id: true }))
108
+ .handler(async ({ input, context }) => {
109
+ // your create code here
110
+ return { id: 1, name: 'name' }
111
+ })
112
+
113
+ export const router = { planet: { list: listPlanet, find: findPlanet, create: createPlanet } }
114
+ ```
115
+
116
+ ## License
117
+
118
+ Distributed under the MIT License. See [LICENSE](https://github.com/unnoq/orpc/blob/main/LICENSE) for more information.
@@ -0,0 +1,32 @@
1
+ import {
2
+ RPCCodec,
3
+ RPCMatcher,
4
+ StandardHandler
5
+ } from "./chunk-NTHCS5CK.js";
6
+
7
+ // src/adapters/fetch/rpc-handler.ts
8
+ import { toFetchResponse, toStandardRequest } from "@orpc/standard-server-fetch";
9
+ var RPCHandler = class {
10
+ standardHandler;
11
+ constructor(router, options) {
12
+ const matcher = options?.matcher ?? new RPCMatcher();
13
+ const codec = options?.codec ?? new RPCCodec();
14
+ this.standardHandler = new StandardHandler(router, matcher, codec, options);
15
+ }
16
+ async handle(request, ...[options]) {
17
+ const standardRequest = toStandardRequest(request);
18
+ const result = await this.standardHandler.handle(standardRequest, options);
19
+ if (!result.matched) {
20
+ return result;
21
+ }
22
+ return {
23
+ matched: true,
24
+ response: toFetchResponse(result.response, options)
25
+ };
26
+ }
27
+ };
28
+
29
+ export {
30
+ RPCHandler
31
+ };
32
+ //# sourceMappingURL=chunk-AJXRPY6I.js.map
@@ -62,33 +62,74 @@ function middlewareOutputFn(output) {
62
62
  }
63
63
 
64
64
  // src/procedure-client.ts
65
- import { createORPCErrorConstructorMap, ORPCError, validateORPCError, ValidationError } from "@orpc/contract";
66
- import { executeWithHooks, toError, value } from "@orpc/shared";
65
+ import { ORPCError as ORPCError2 } from "@orpc/client";
66
+ import { ValidationError } from "@orpc/contract";
67
+ import { intercept, toError, value } from "@orpc/shared";
68
+
69
+ // src/error.ts
70
+ import { fallbackORPCErrorStatus, ORPCError } from "@orpc/client";
71
+ function createORPCErrorConstructorMap(errors) {
72
+ const proxy = new Proxy(errors, {
73
+ get(target, code) {
74
+ if (typeof code !== "string") {
75
+ return Reflect.get(target, code);
76
+ }
77
+ const item = (...[options]) => {
78
+ const config = errors[code];
79
+ return new ORPCError(code, {
80
+ defined: Boolean(config),
81
+ status: config?.status,
82
+ message: options?.message ?? config?.message,
83
+ data: options?.data,
84
+ cause: options?.cause
85
+ });
86
+ };
87
+ return item;
88
+ }
89
+ });
90
+ return proxy;
91
+ }
92
+ async function validateORPCError(map, error) {
93
+ const { code, status, message, data, cause, defined } = error;
94
+ const config = map?.[error.code];
95
+ if (!config || fallbackORPCErrorStatus(error.code, config.status) !== error.status) {
96
+ return defined ? new ORPCError(code, { defined: false, status, message, data, cause }) : error;
97
+ }
98
+ if (!config.data) {
99
+ return defined ? error : new ORPCError(code, { defined: true, status, message, data, cause });
100
+ }
101
+ const validated = await config.data["~standard"].validate(error.data);
102
+ if (validated.issues) {
103
+ return defined ? new ORPCError(code, { defined: false, status, message, data, cause }) : error;
104
+ }
105
+ return new ORPCError(code, { defined: true, status, message, data: validated.value, cause });
106
+ }
107
+
108
+ // src/procedure-client.ts
67
109
  function createProcedureClient(lazyableProcedure, ...[options]) {
68
110
  return async (...[input, callerOptions]) => {
69
111
  const path = options?.path ?? [];
70
112
  const { default: procedure } = await unlazy(lazyableProcedure);
71
- const context = await value(options?.context ?? {}, callerOptions?.context);
113
+ const clientContext = callerOptions?.context ?? {};
114
+ const context = await value(options?.context ?? {}, clientContext);
72
115
  const errors = createORPCErrorConstructorMap(procedure["~orpc"].errorMap);
73
- const executeOptions = {
74
- input,
75
- context,
76
- errors,
77
- path,
78
- procedure,
79
- signal: callerOptions?.signal
80
- };
81
116
  try {
82
- const output = await executeWithHooks({
83
- hooks: options,
84
- input,
85
- context,
86
- meta: executeOptions,
87
- execute: () => executeProcedureInternal(procedure, executeOptions)
88
- });
89
- return output;
117
+ return await intercept(
118
+ options?.interceptors ?? [],
119
+ {
120
+ context,
121
+ input,
122
+ // input only optional when it undefinable so we can safely cast it
123
+ errors,
124
+ path,
125
+ procedure,
126
+ signal: callerOptions?.signal,
127
+ lastEventId: callerOptions?.lastEventId
128
+ },
129
+ (interceptorOptions) => executeProcedureInternal(interceptorOptions.procedure, interceptorOptions)
130
+ );
90
131
  } catch (e) {
91
- if (!(e instanceof ORPCError)) {
132
+ if (!(e instanceof ORPCError2)) {
92
133
  throw toError(e);
93
134
  }
94
135
  const validated = await validateORPCError(procedure["~orpc"].errorMap, e);
@@ -103,7 +144,7 @@ async function validateInput(procedure, input) {
103
144
  }
104
145
  const result = await schema["~standard"].validate(input);
105
146
  if (result.issues) {
106
- throw new ORPCError("BAD_REQUEST", {
147
+ throw new ORPCError2("BAD_REQUEST", {
107
148
  message: "Input validation failed",
108
149
  data: {
109
150
  issues: result.issues
@@ -120,7 +161,7 @@ async function validateOutput(procedure, output) {
120
161
  }
121
162
  const result = await schema["~standard"].validate(output);
122
163
  if (result.issues) {
123
- throw new ORPCError("INTERNAL_SERVER_ERROR", {
164
+ throw new ORPCError2("INTERNAL_SERVER_ERROR", {
124
165
  message: "Output validation failed",
125
166
  cause: new ValidationError({ message: "Output validation failed", issues: result.issues })
126
167
  });
@@ -377,4 +418,4 @@ export {
377
418
  convertPathToHttpPath,
378
419
  createContractedProcedure
379
420
  };
380
- //# sourceMappingURL=chunk-NOA3GBJQ.js.map
421
+ //# sourceMappingURL=chunk-MHVECKBC.js.map
@@ -0,0 +1,182 @@
1
+ import {
2
+ convertPathToHttpPath,
3
+ createContractedProcedure,
4
+ createProcedureClient,
5
+ eachContractProcedure,
6
+ getRouterChild,
7
+ isProcedure,
8
+ unlazy
9
+ } from "./chunk-MHVECKBC.js";
10
+ import {
11
+ CompositePlugin
12
+ } from "./chunk-TXHKQO7N.js";
13
+
14
+ // src/adapters/standard/handler.ts
15
+ import { ORPCError, toORPCError } from "@orpc/client";
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.rootInterceptors ?? [],
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
+ let isDecoding = false;
38
+ try {
39
+ return await intercept(
40
+ this.options.interceptors ?? [],
41
+ interceptorOptions,
42
+ async (interceptorOptions2) => {
43
+ const method = interceptorOptions2.request.method;
44
+ const url = interceptorOptions2.request.url;
45
+ const pathname = `/${trim(url.pathname.replace(interceptorOptions2.prefix ?? "", ""), "/")}`;
46
+ const match = await this.matcher.match(method, pathname);
47
+ if (!match) {
48
+ return { matched: false, response: void 0 };
49
+ }
50
+ const client = createProcedureClient(match.procedure, {
51
+ context: interceptorOptions2.context,
52
+ path: match.path,
53
+ interceptors: this.options.clientInterceptors
54
+ });
55
+ isDecoding = true;
56
+ const input = await this.codec.decode(request, match.params, match.procedure);
57
+ isDecoding = false;
58
+ const lastEventId = Array.isArray(request.headers["last-event-id"]) ? request.headers["last-event-id"].at(-1) : request.headers["last-event-id"];
59
+ const output = await client(input, { signal: request.signal, lastEventId });
60
+ const response = this.codec.encode(output, match.procedure);
61
+ return {
62
+ matched: true,
63
+ response
64
+ };
65
+ }
66
+ );
67
+ } catch (e) {
68
+ const error = isDecoding ? new ORPCError("BAD_REQUEST", {
69
+ message: `Malformed request. Ensure the request body is properly formatted and the 'Content-Type' header is set correctly.`,
70
+ cause: e
71
+ }) : toORPCError(e);
72
+ const response = this.codec.encodeError(error);
73
+ return {
74
+ matched: true,
75
+ response
76
+ };
77
+ }
78
+ }
79
+ );
80
+ }
81
+ };
82
+
83
+ // src/adapters/standard/rpc-codec.ts
84
+ import { RPCSerializer } from "@orpc/client/rpc";
85
+ import { parseEmptyableJSON } from "@orpc/shared";
86
+ var RPCCodec = class {
87
+ serializer;
88
+ constructor(options = {}) {
89
+ this.serializer = options.serializer ?? new RPCSerializer();
90
+ }
91
+ async decode(request, _params, _procedure) {
92
+ const serialized = request.method === "GET" ? parseEmptyableJSON(request.url.searchParams.getAll("data").at(-1)) : await request.body();
93
+ return this.serializer.deserialize(serialized);
94
+ }
95
+ encode(output, _procedure) {
96
+ return {
97
+ status: 200,
98
+ headers: {},
99
+ body: this.serializer.serialize(output)
100
+ };
101
+ }
102
+ encodeError(error) {
103
+ return {
104
+ status: error.status,
105
+ headers: {},
106
+ body: this.serializer.serialize(error.toJSON())
107
+ };
108
+ }
109
+ };
110
+
111
+ // src/adapters/standard/rpc-matcher.ts
112
+ var RPCMatcher = class {
113
+ tree = {};
114
+ pendingRouters = [];
115
+ init(router, path = []) {
116
+ const laziedOptions = eachContractProcedure({
117
+ router,
118
+ path
119
+ }, ({ path: path2, contract }) => {
120
+ const httpPath = convertPathToHttpPath(path2);
121
+ if (isProcedure(contract)) {
122
+ this.tree[httpPath] = {
123
+ path: path2,
124
+ contract,
125
+ procedure: contract,
126
+ // this mean dev not used contract-first so we can used contract as procedure directly
127
+ router
128
+ };
129
+ } else {
130
+ this.tree[httpPath] = {
131
+ path: path2,
132
+ contract,
133
+ procedure: void 0,
134
+ router
135
+ };
136
+ }
137
+ });
138
+ this.pendingRouters.push(...laziedOptions.map((option) => ({
139
+ ...option,
140
+ httpPathPrefix: convertPathToHttpPath(option.path)
141
+ })));
142
+ }
143
+ async match(_method, pathname) {
144
+ if (this.pendingRouters.length) {
145
+ const newPendingRouters = [];
146
+ for (const pendingRouter of this.pendingRouters) {
147
+ if (pathname.startsWith(pendingRouter.httpPathPrefix)) {
148
+ const { default: router } = await unlazy(pendingRouter.lazied);
149
+ this.init(router, pendingRouter.path);
150
+ } else {
151
+ newPendingRouters.push(pendingRouter);
152
+ }
153
+ }
154
+ this.pendingRouters = newPendingRouters;
155
+ }
156
+ const match = this.tree[pathname];
157
+ if (!match) {
158
+ return void 0;
159
+ }
160
+ if (!match.procedure) {
161
+ const { default: maybeProcedure } = await unlazy(getRouterChild(match.router, ...match.path));
162
+ if (!isProcedure(maybeProcedure)) {
163
+ throw new Error(`
164
+ [Contract-First] Missing or invalid implementation for procedure at path: ${convertPathToHttpPath(match.path)}.
165
+ Ensure that the procedure is correctly defined and matches the expected contract.
166
+ `);
167
+ }
168
+ match.procedure = createContractedProcedure(match.contract, maybeProcedure);
169
+ }
170
+ return {
171
+ path: match.path,
172
+ procedure: match.procedure
173
+ };
174
+ }
175
+ };
176
+
177
+ export {
178
+ StandardHandler,
179
+ RPCCodec,
180
+ RPCMatcher
181
+ };
182
+ //# sourceMappingURL=chunk-NTHCS5CK.js.map
@@ -0,0 +1,120 @@
1
+ // src/plugins/base.ts
2
+ var CompositePlugin = class {
3
+ constructor(plugins = []) {
4
+ this.plugins = plugins;
5
+ }
6
+ init(options) {
7
+ for (const plugin of this.plugins) {
8
+ plugin.init?.(options);
9
+ }
10
+ }
11
+ };
12
+
13
+ // src/plugins/cors.ts
14
+ import { value } from "@orpc/shared";
15
+ var CORSPlugin = class {
16
+ options;
17
+ constructor(options) {
18
+ const defaults = {
19
+ origin: (origin) => origin,
20
+ allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"]
21
+ };
22
+ this.options = {
23
+ ...defaults,
24
+ ...options
25
+ };
26
+ }
27
+ init(options) {
28
+ options.rootInterceptors ??= [];
29
+ options.rootInterceptors.unshift(async (interceptorOptions) => {
30
+ if (interceptorOptions.request.method === "OPTIONS") {
31
+ const resHeaders = {};
32
+ if (this.options.maxAge !== void 0) {
33
+ resHeaders["access-control-max-age"] = this.options.maxAge.toString();
34
+ }
35
+ if (this.options.allowMethods?.length) {
36
+ resHeaders["access-control-allow-methods"] = this.options.allowMethods.join(",");
37
+ }
38
+ const allowHeaders = this.options.allowHeaders ?? interceptorOptions.request.headers["access-control-request-headers"];
39
+ if (Array.isArray(allowHeaders) && allowHeaders.length) {
40
+ resHeaders["access-control-allow-headers"] = allowHeaders.join(",");
41
+ } else if (typeof allowHeaders === "string") {
42
+ resHeaders["access-control-allow-headers"] = allowHeaders;
43
+ }
44
+ return {
45
+ matched: true,
46
+ response: {
47
+ status: 204,
48
+ headers: resHeaders,
49
+ body: void 0
50
+ }
51
+ };
52
+ }
53
+ return interceptorOptions.next();
54
+ });
55
+ options.rootInterceptors.unshift(async (interceptorOptions) => {
56
+ const result = await interceptorOptions.next();
57
+ if (!result.matched) {
58
+ return result;
59
+ }
60
+ const origin = Array.isArray(interceptorOptions.request.headers.origin) ? interceptorOptions.request.headers.origin.join(",") : interceptorOptions.request.headers.origin || "";
61
+ const allowedOrigin = await value(this.options.origin, origin, interceptorOptions);
62
+ const allowedOriginArr = Array.isArray(allowedOrigin) ? allowedOrigin : [allowedOrigin];
63
+ if (allowedOriginArr.includes("*")) {
64
+ result.response.headers["access-control-allow-origin"] = "*";
65
+ } else {
66
+ if (allowedOriginArr.includes(origin)) {
67
+ result.response.headers["access-control-allow-origin"] = origin;
68
+ }
69
+ result.response.headers.vary = interceptorOptions.request.headers.vary ?? "origin";
70
+ }
71
+ const allowedTimingOrigin = await value(this.options.timingOrigin, origin, interceptorOptions);
72
+ const allowedTimingOriginArr = Array.isArray(allowedTimingOrigin) ? allowedTimingOrigin : [allowedTimingOrigin];
73
+ if (allowedTimingOriginArr.includes("*")) {
74
+ result.response.headers["timing-allow-origin"] = "*";
75
+ } else if (allowedTimingOriginArr.includes(origin)) {
76
+ result.response.headers["timing-allow-origin"] = origin;
77
+ }
78
+ if (this.options.credentials) {
79
+ result.response.headers["access-control-allow-credentials"] = "true";
80
+ }
81
+ if (this.options.exposeHeaders?.length) {
82
+ result.response.headers["access-control-expose-headers"] = this.options.exposeHeaders.join(",");
83
+ }
84
+ return result;
85
+ });
86
+ }
87
+ };
88
+
89
+ // src/plugins/response-headers.ts
90
+ var ResponseHeadersPlugin = class {
91
+ init(options) {
92
+ options.rootInterceptors ??= [];
93
+ options.rootInterceptors.push(async (interceptorOptions) => {
94
+ const headers = new Headers();
95
+ interceptorOptions.context.resHeaders = headers;
96
+ const result = await interceptorOptions.next();
97
+ if (!result.matched) {
98
+ return result;
99
+ }
100
+ const responseHeaders = result.response.headers;
101
+ for (const [key, value2] of headers) {
102
+ if (Array.isArray(responseHeaders[key])) {
103
+ responseHeaders[key].push(value2);
104
+ } else if (responseHeaders[key] !== void 0) {
105
+ responseHeaders[key] = [responseHeaders[key], value2];
106
+ } else {
107
+ responseHeaders[key] = value2;
108
+ }
109
+ }
110
+ return result;
111
+ });
112
+ }
113
+ };
114
+
115
+ export {
116
+ CompositePlugin,
117
+ CORSPlugin,
118
+ ResponseHeadersPlugin
119
+ };
120
+ //# sourceMappingURL=chunk-TXHKQO7N.js.map
package/dist/fetch.js CHANGED
@@ -1,17 +1,10 @@
1
1
  import {
2
- RPCHandler,
3
- fetchReToStandardBody,
4
- fetchRequestToStandardRequest,
5
- standardBodyToFetchBody,
6
- standardResponseToFetchResponse
7
- } from "./chunk-6RSW63UJ.js";
8
- import "./chunk-JHLUGXCM.js";
9
- import "./chunk-NOA3GBJQ.js";
2
+ RPCHandler
3
+ } from "./chunk-AJXRPY6I.js";
4
+ import "./chunk-NTHCS5CK.js";
5
+ import "./chunk-MHVECKBC.js";
6
+ import "./chunk-TXHKQO7N.js";
10
7
  export {
11
- RPCHandler,
12
- fetchReToStandardBody,
13
- fetchRequestToStandardRequest,
14
- standardBodyToFetchBody,
15
- standardResponseToFetchResponse
8
+ RPCHandler
16
9
  };
17
10
  //# sourceMappingURL=fetch.js.map
package/dist/hono.js CHANGED
@@ -1,32 +1,34 @@
1
1
  import {
2
- RPCHandler,
3
- fetchReToStandardBody,
4
- fetchRequestToStandardRequest,
5
- standardBodyToFetchBody,
6
- standardResponseToFetchResponse
7
- } from "./chunk-6RSW63UJ.js";
8
- import "./chunk-JHLUGXCM.js";
9
- import "./chunk-NOA3GBJQ.js";
2
+ RPCHandler
3
+ } from "./chunk-AJXRPY6I.js";
4
+ import "./chunk-NTHCS5CK.js";
5
+ import "./chunk-MHVECKBC.js";
6
+ import "./chunk-TXHKQO7N.js";
10
7
 
11
8
  // src/adapters/hono/middleware.ts
12
9
  import { value } from "@orpc/shared";
13
10
  function createMiddleware(handler, ...[options]) {
14
11
  return async (c, next) => {
12
+ const bodyProps = /* @__PURE__ */ new Set(["arrayBuffer", "blob", "formData", "json", "text"]);
13
+ const request = c.req.method === "GET" || c.req.method === "HEAD" ? c.req.raw : new Proxy(c.req.raw, {
14
+ // https://github.com/honojs/middleware/blob/main/packages/trpc-server/src/index.ts#L39
15
+ get(target, prop) {
16
+ if (bodyProps.has(prop)) {
17
+ return () => c.req[prop]();
18
+ }
19
+ return Reflect.get(target, prop, target);
20
+ }
21
+ });
15
22
  const context = await value(options?.context ?? {}, c);
16
- const { matched, response } = await handler.handle(c.req.raw, { ...options, context });
23
+ const { matched, response } = await handler.handle(request, { ...options, context });
17
24
  if (matched) {
18
- c.res = response;
19
- return;
25
+ return c.newResponse(response.body, response);
20
26
  }
21
27
  await next();
22
28
  };
23
29
  }
24
30
  export {
25
31
  RPCHandler,
26
- createMiddleware,
27
- fetchReToStandardBody,
28
- fetchRequestToStandardRequest,
29
- standardBodyToFetchBody,
30
- standardResponseToFetchResponse
32
+ createMiddleware
31
33
  };
32
34
  //# sourceMappingURL=hono.js.map