@orpc/nest 2.0.0-beta.49 → 2.0.0-beta.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,8 @@
1
+ // \0@oxc-project+runtime@0.157.0/helpers/esm/decorate.js
2
+ function __decorate(decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ }
8
+ export { __decorate as default };
@@ -0,0 +1,5 @@
1
+ // \0@oxc-project+runtime@0.157.0/helpers/esm/decorateMetadata.js
2
+ function __decorateMetadata(k, v) {
3
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
4
+ }
5
+ export { __decorateMetadata as default };
@@ -0,0 +1,7 @@
1
+ // \0@oxc-project+runtime@0.157.0/helpers/esm/decorateParam.js
2
+ function __decorateParam(paramIndex, decorator) {
3
+ return function(target, key) {
4
+ decorator(target, key, paramIndex);
5
+ };
6
+ }
7
+ export { __decorateParam as default };
@@ -1 +1 @@
1
- export declare const ORPC_MODULE_CONFIG_SYMBOL: unique symbol;
1
+ export declare const ORPC_MODULE_CONFIG_SYMBOL: unique symbol;
package/dist/constants.js CHANGED
@@ -1,2 +1,3 @@
1
- export const ORPC_MODULE_CONFIG_SYMBOL =
2
- /* @__PURE__ */ Symbol.for('ORPC_NEST_MODULE_CONFIG');
1
+ // src/constants.ts
2
+ const ORPC_MODULE_CONFIG_SYMBOL = /* @__PURE__ */ Symbol.for("ORPC_NEST_MODULE_CONFIG");
3
+ export { ORPC_MODULE_CONFIG_SYMBOL };
@@ -1,10 +1,10 @@
1
- import type { CallHandler, ExecutionContext, NestInterceptor } from '@nestjs/common';
2
- import { HttpAdapterHost } from '@nestjs/core';
3
- import type { RouterContract } from '@orpc/contract';
4
- import type { ContractedRouter, DefaultInitialContext } from '@orpc/server';
5
- import type { Promisable } from '@orpc/shared';
6
- import type { Observable } from 'rxjs';
7
- import type { ORPCModuleConfig } from './module.ts';
1
+ import { ORPCModuleConfig } from "./module.js";
2
+ import { CallHandler, ExecutionContext, NestInterceptor } from "@nestjs/common";
3
+ import { HttpAdapterHost } from "@nestjs/core";
4
+ import { RouterContract } from "@orpc/contract";
5
+ import { ContractedRouter, DefaultInitialContext } from "@orpc/server";
6
+ import { Promisable } from "@orpc/shared";
7
+ import { Observable } from "rxjs";
8
8
  /**
9
9
  * Decorator that implements an oRPC contract (procedure or router contract)
10
10
  * on a NestJS controller method. It registers the corresponding NestJS routes
@@ -19,11 +19,11 @@ import type { ORPCModuleConfig } from './module.ts';
19
19
  */
20
20
  export declare function Implement<T extends RouterContract>(contract: T): <U extends Promisable<ContractedRouter<T, DefaultInitialContext>>>(target: Record<PropertyKey, any>, propertyKey: string, descriptor: TypedPropertyDescriptor<(...args: any[]) => U>) => void;
21
21
  export declare class ImplementInterceptor implements NestInterceptor {
22
- private readonly config;
23
- private readonly codec;
24
- private readonly handler;
25
- private readonly toNestStandardLazyRequest;
26
- private readonly httpAdapterHost;
27
- constructor(config: ORPCModuleConfig | undefined, httpAdapterHost: HttpAdapterHost);
28
- intercept(ctx: ExecutionContext, next: CallHandler): Observable<any>;
29
- }
22
+ private readonly config;
23
+ private readonly codec;
24
+ private readonly handler;
25
+ private readonly toNestStandardLazyRequest;
26
+ private readonly httpAdapterHost;
27
+ constructor(config: ORPCModuleConfig | undefined, httpAdapterHost: HttpAdapterHost);
28
+ intercept(ctx: ExecutionContext, next: CallHandler): Observable<any>;
29
+ }
package/dist/implement.js CHANGED
@@ -1,323 +1,253 @@
1
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
- return c > 3 && r && Object.defineProperty(target, key, r), r;
6
- };
7
- var __metadata = (this && this.__metadata) || function (k, v) {
8
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
- };
10
- var __param = (this && this.__param) || function (paramIndex, decorator) {
11
- return function (target, key) { decorator(target, key, paramIndex); }
12
- };
13
- import { Readable } from 'node:stream';
14
- import * as NestCommon from '@nestjs/common';
15
- import { applyDecorators, Delete, Get, Head, HttpCode, HttpException, Inject, Injectable, Optional, Options, Patch, Post, Put, StreamableFile, UseInterceptors, } from '@nestjs/common';
16
- import { HttpAdapterHost } from '@nestjs/core';
17
- import { getPathMeta, ProcedureContract } from '@orpc/contract';
18
- import { DEFAULT_OPENAPI_METHOD, getDynamicPathParams, getOpenAPIMeta } from '@orpc/openapi';
19
- import { OpenAPIHandlerCodecCore } from '@orpc/openapi/standard';
20
- import { DEFAULT_SUCCESS_STATUS, getRouter, Procedure, unlazy } from '@orpc/server';
21
- import { StandardHandler } from '@orpc/server/standard';
22
- import { isAsyncIteratorObject, mergeHttpPath, NullProtoObj, stringifyJSON, toArray, value, } from '@orpc/shared';
23
- import { flattenStandardHeader, generateContentDisposition, getRequiredStandardBodyHint, } from '@standard-server/core';
24
- import { toEventStream, toStandardLazyRequest } from '@standard-server/node';
25
- import { mergeMap } from 'rxjs';
26
- import { ORPC_MODULE_CONFIG_SYMBOL } from './constants.js';
27
- // Namespace access so NestJS < 11.2 (no QueryMethod export) loads without a SyntaxError
1
+ import { ORPC_MODULE_CONFIG_SYMBOL } from "./constants.js";
2
+ import __decorateMetadata from "./_virtual/_@oxc-project_runtime@0.157.0/helpers/esm/decorateMetadata.js";
3
+ import __decorateParam from "./_virtual/_@oxc-project_runtime@0.157.0/helpers/esm/decorateParam.js";
4
+ import __decorate from "./_virtual/_@oxc-project_runtime@0.157.0/helpers/esm/decorate.js";
5
+ import { Readable } from "node:stream";
6
+ import * as NestCommon from "@nestjs/common";
7
+ import { Delete, Get, Head, HttpCode, HttpException, Inject, Injectable, Optional, Options, Patch, Post, Put, StreamableFile, UseInterceptors, applyDecorators } from "@nestjs/common";
8
+ import { HttpAdapterHost } from "@nestjs/core";
9
+ import { ProcedureContract, getPathMeta } from "@orpc/contract";
10
+ import { DEFAULT_OPENAPI_METHOD, getDynamicPathParams, getOpenAPIMeta } from "@orpc/openapi";
11
+ import { OpenAPIHandlerCodecCore } from "@orpc/openapi/standard";
12
+ import { DEFAULT_SUCCESS_STATUS, Procedure, getRouter, unlazy } from "@orpc/server";
13
+ import { StandardHandler } from "@orpc/server/standard";
14
+ import { NullProtoObj, isAsyncIteratorObject, listenAbort, mergeHttpPath, stringifyJSON, toArray, value } from "@orpc/shared";
15
+ import { flattenStandardHeader, generateContentDisposition, getRequiredStandardBodyHint } from "@standard-server/core";
16
+ import { toEventStream, toStandardLazyRequest } from "@standard-server/node";
17
+ import { mergeMap } from "rxjs";
18
+ // src/implement.ts
28
19
  const QueryMethod = NestCommon.QueryMethod;
29
20
  const MethodDecoratorMap = {
30
- HEAD: Head,
31
- GET: Get,
32
- POST: Post,
33
- PUT: Put,
34
- PATCH: Patch,
35
- DELETE: Delete,
36
- OPTIONS: Options,
21
+ HEAD: Head,
22
+ GET: Get,
23
+ POST: Post,
24
+ PUT: Put,
25
+ PATCH: Patch,
26
+ DELETE: Delete,
27
+ OPTIONS: Options
37
28
  };
38
29
  /**
39
- * Decorator that implements an oRPC contract (procedure or router contract)
40
- * on a NestJS controller method. It registers the corresponding NestJS routes
41
- * and handles request decoding and response encoding for you.
42
- *
43
- * @remarks
44
- * **Note**: Every procedure contract must define an `openapi.path` meta;
45
- * use `populateRouterContractOpenAPIPaths` from `@orpc/openapi` to fill in missing paths.
46
- * **Note**: The HTTP `QUERY` method requires NestJS v11.2+ (`QueryMethod`). Older NestJS versions throw; use `GET` instead.
47
- *
48
- * @see {@link https://orpc.dev/docs/integrations/nest#implement-your-contract | Implement oRPC contract with NestJS - Implement Your Contract}
49
- */
50
- export function Implement(contract) {
51
- if (contract instanceof ProcedureContract) {
52
- return (target, propertyKey, descriptor) => {
53
- applyDecorators(toNestRouteDecorator(contract), UseInterceptors(ImplementInterceptor))(target, propertyKey, descriptor);
54
- };
55
- }
56
- return (target, propertyKey, descriptor) => {
57
- // applied at the decorated method level so interceptor order follows decorator order,
58
- // and synthesized methods inherit the full ordered list through the prototype chain
59
- UseInterceptors(ImplementInterceptor)(target, propertyKey, descriptor);
60
- implementRouterContract(contract, target, propertyKey, descriptor);
61
- };
30
+ * Decorator that implements an oRPC contract (procedure or router contract)
31
+ * on a NestJS controller method. It registers the corresponding NestJS routes
32
+ * and handles request decoding and response encoding for you.
33
+ *
34
+ * @remarks
35
+ * **Note**: Every procedure contract must define an `openapi.path` meta;
36
+ * use `populateRouterContractOpenAPIPaths` from `@orpc/openapi` to fill in missing paths.
37
+ * **Note**: The HTTP `QUERY` method requires NestJS v11.2+ (`QueryMethod`). Older NestJS versions throw; use `GET` instead.
38
+ *
39
+ * @see {@link https://orpc.dev/docs/integrations/nest#implement-your-contract | Implement oRPC contract with NestJS - Implement Your Contract}
40
+ */
41
+ function Implement(contract) {
42
+ if (contract instanceof ProcedureContract) return (target, propertyKey, descriptor) => {
43
+ applyDecorators(toNestRouteDecorator(contract), UseInterceptors(ImplementInterceptor))(target, propertyKey, descriptor);
44
+ };
45
+ return (target, propertyKey, descriptor) => {
46
+ UseInterceptors(ImplementInterceptor)(target, propertyKey, descriptor);
47
+ implementRouterContract(contract, target, propertyKey, descriptor);
48
+ };
62
49
  }
63
50
  function toNestRouteDecorator(contract) {
64
- const meta = getOpenAPIMeta(contract);
65
- if (meta?.path === undefined) {
66
- throw new TypeError(`
51
+ const meta = getOpenAPIMeta(contract);
52
+ if (meta?.path === void 0) throw new TypeError(`
67
53
  @Implement decorator requires contract to have a 'openapi.path' meta.
68
54
  Please define one using '.meta(openapi({ path: '/example' }))'.
69
55
  Or use "populateRouterContractOpenAPIPaths" from "@orpc/openapi" utility to automatically fill in any missing paths.
70
56
  `);
71
- }
72
- const method = meta.method ?? DEFAULT_OPENAPI_METHOD;
73
- const path = toNestPattern(meta.prefix ? mergeHttpPath(meta.prefix, meta.path) : meta.path);
74
- const successStatus = meta.successStatus ?? DEFAULT_SUCCESS_STATUS;
75
- if (method === 'QUERY') {
76
- if (!QueryMethod) {
77
- throw new TypeError(`
57
+ const method = meta.method ?? DEFAULT_OPENAPI_METHOD;
58
+ const path = toNestPattern(meta.prefix ? mergeHttpPath(meta.prefix, meta.path) : meta.path);
59
+ const successStatus = meta.successStatus ?? DEFAULT_SUCCESS_STATUS;
60
+ if (method === "QUERY") {
61
+ if (!QueryMethod) throw new TypeError(`
78
62
  @Implement decorator does not support the 'QUERY' HTTP method because the installed version of NestJS does not support it.
79
63
  The 'QUERY' HTTP method requires NestJS v11.2 or later. Alternatively, use 'GET' method.
80
64
  `);
81
- }
82
- return applyDecorators(QueryMethod(path), HttpCode(successStatus));
83
- }
84
- return applyDecorators(MethodDecoratorMap[method](path), HttpCode(successStatus));
65
+ return applyDecorators(QueryMethod(path), HttpCode(successStatus));
66
+ }
67
+ return applyDecorators(MethodDecoratorMap[method](path), HttpCode(successStatus));
85
68
  }
86
69
  function implementRouterContract(contract, target, propertyKey, descriptor) {
87
- for (const [key, childContract] of Object.entries(contract)) {
88
- let methodName = `${propertyKey}_${key}`;
89
- let i = 0;
90
- while (methodName in target) {
91
- methodName = `${propertyKey}_${key}_${i++}`;
92
- }
93
- target[methodName] = async function (...args) {
94
- const router = await descriptor.value.apply(this, args);
95
- return getRouter(router, [key]);
96
- };
97
- Object.setPrototypeOf(target[methodName], descriptor.value);
98
- queueMicrotask(() => {
99
- for (const p of Reflect.getOwnMetadataKeys(target, propertyKey)) {
100
- Reflect.defineMetadata(p, Reflect.getOwnMetadata(p, target, propertyKey), target, methodName);
101
- }
102
- for (const p of Reflect.getOwnMetadataKeys(target.constructor, propertyKey)) {
103
- Reflect.defineMetadata(p, Reflect.getOwnMetadata(p, target.constructor, propertyKey), target.constructor, methodName);
104
- }
105
- });
106
- const childDescriptor = Object.getOwnPropertyDescriptor(target, methodName);
107
- if (childContract instanceof ProcedureContract) {
108
- const routeDecorator = toNestRouteDecorator(childContract);
109
- // applied after the deferred metadata copies so route metadata cannot be overridden
110
- queueMicrotask(() => {
111
- routeDecorator(target, methodName, childDescriptor);
112
- });
113
- }
114
- else {
115
- implementRouterContract(childContract, target, methodName, childDescriptor);
116
- }
117
- }
70
+ for (const [key, childContract] of Object.entries(contract)) {
71
+ let methodName = `${propertyKey}_${key}`;
72
+ let i = 0;
73
+ while (methodName in target) methodName = `${propertyKey}_${key}_${i++}`;
74
+ target[methodName] = async function(...args) {
75
+ const router = await descriptor.value.apply(this, args);
76
+ return getRouter(router, [key]);
77
+ };
78
+ Object.setPrototypeOf(target[methodName], descriptor.value);
79
+ queueMicrotask(() => {
80
+ for (const p of Reflect.getOwnMetadataKeys(target, propertyKey)) Reflect.defineMetadata(p, Reflect.getOwnMetadata(p, target, propertyKey), target, methodName);
81
+ for (const p of Reflect.getOwnMetadataKeys(target.constructor, propertyKey)) Reflect.defineMetadata(p, Reflect.getOwnMetadata(p, target.constructor, propertyKey), target.constructor, methodName);
82
+ });
83
+ const childDescriptor = Object.getOwnPropertyDescriptor(target, methodName);
84
+ if (childContract instanceof ProcedureContract) {
85
+ const routeDecorator = toNestRouteDecorator(childContract);
86
+ queueMicrotask(() => {
87
+ routeDecorator(target, methodName, childDescriptor);
88
+ });
89
+ } else implementRouterContract(childContract, target, methodName, childDescriptor);
90
+ }
118
91
  }
119
92
  let ImplementInterceptor = class ImplementInterceptor {
120
- config;
121
- codec;
122
- handler;
123
- toNestStandardLazyRequest;
124
- httpAdapterHost;
125
- constructor(config, httpAdapterHost) {
126
- // @Optional() does not allow set default value so we need to do it here
127
- this.config = config ?? {};
128
- this.httpAdapterHost = httpAdapterHost;
129
- this.codec = new NestHandlerCodec(this.config);
130
- this.handler = new StandardHandler(this.codec, this.config);
131
- this.toNestStandardLazyRequest =
132
- this.config.toNestStandardLazyRequest ??
133
- ((req, res) => {
134
- const standardRequest = toStandardLazyRequest('raw' in req ? req.raw : req, 'raw' in res ? res.raw : res);
135
- // if body already parsed by NestJS
136
- if (req.body !== undefined) {
137
- standardRequest.resolveBody = () => Promise.resolve(req.body);
138
- }
139
- standardRequest.params = req.params;
140
- return standardRequest;
141
- });
142
- }
143
- intercept(ctx, next) {
144
- return next.handle().pipe(mergeMap(async (impl) => {
145
- const { default: procedure } = await unlazy(impl);
146
- if (!(procedure instanceof Procedure)) {
147
- throw new TypeError(`
93
+ config;
94
+ codec;
95
+ handler;
96
+ toNestStandardLazyRequest;
97
+ httpAdapterHost;
98
+ constructor(config, httpAdapterHost) {
99
+ this.config = config ?? {};
100
+ this.httpAdapterHost = httpAdapterHost;
101
+ this.codec = new NestHandlerCodec(this.config);
102
+ this.handler = new StandardHandler(this.codec, this.config);
103
+ this.toNestStandardLazyRequest = this.config.toNestStandardLazyRequest ?? ((req, res) => {
104
+ const standardRequest = toStandardLazyRequest("raw" in req ? req.raw : req, "raw" in res ? res.raw : res);
105
+ if (req.body !== void 0) standardRequest.resolveBody = () => Promise.resolve(req.body);
106
+ standardRequest.params = req.params;
107
+ return standardRequest;
108
+ });
109
+ }
110
+ intercept(ctx, next) {
111
+ return next.handle().pipe(mergeMap(async (impl) => {
112
+ const { default: procedure } = await unlazy(impl);
113
+ if (!(procedure instanceof Procedure)) throw new TypeError(`
148
114
  The return value of the @Implement controller handler must be a corresponding implemented router or procedure.
149
115
  `);
150
- }
151
- const req = ctx.switchToHttp().getRequest();
152
- const res = ctx.switchToHttp().getResponse();
153
- const standardRequest = this.toNestStandardLazyRequest(req, res);
154
- const context = await value(this.config.context ?? {}, ctx);
155
- const result = await this.handler.handle(standardRequest, {
156
- context: this.codec.withMatch(context, { procedure, params: standardRequest.params }),
157
- });
158
- if (!result.matched) {
159
- throw new TypeError('oRPC NestJS handler returned an unmatched result, which should never happen. Please check your plugins/interceptors or report a bug.');
160
- }
161
- const [nestBody, headers] = toNestHttpBody(result.response, standardRequest.signal, this.config.toNestResponse);
162
- const httpAdapter = this.httpAdapterHost.httpAdapter;
163
- httpAdapter.status(res, result.response.status);
164
- for (const key of Object.keys(headers)) {
165
- toArray(headers[key]).forEach((value, index) => {
166
- if (index === 0) {
167
- httpAdapter.setHeader(res, key, value);
168
- }
169
- else {
170
- httpAdapter.appendHeader(res, key, value);
171
- }
172
- });
173
- }
174
- if (nestBody instanceof HttpException) {
175
- throw nestBody;
176
- }
177
- return nestBody;
178
- }));
179
- }
116
+ const req = ctx.switchToHttp().getRequest();
117
+ const res = ctx.switchToHttp().getResponse();
118
+ const standardRequest = this.toNestStandardLazyRequest(req, res);
119
+ const context = await value(this.config.context ?? {}, ctx);
120
+ const result = await this.handler.handle(standardRequest, { context: this.codec.withMatch(context, {
121
+ procedure,
122
+ params: standardRequest.params
123
+ }) });
124
+ if (!result.matched) throw new TypeError("oRPC NestJS handler returned an unmatched result, which should never happen. Please check your plugins/interceptors or report a bug.");
125
+ const [nestBody, headers] = toNestHttpBody(result.response, standardRequest.signal, this.config.toNestResponse);
126
+ const httpAdapter = this.httpAdapterHost.httpAdapter;
127
+ httpAdapter.status(res, result.response.status);
128
+ for (const key of Object.keys(headers)) toArray(headers[key]).forEach((value, index) => {
129
+ if (index === 0) httpAdapter.setHeader(res, key, value);
130
+ else httpAdapter.appendHeader(res, key, value);
131
+ });
132
+ if (nestBody instanceof HttpException) throw nestBody;
133
+ return nestBody;
134
+ }));
135
+ }
180
136
  };
181
137
  ImplementInterceptor = __decorate([
182
- Injectable(),
183
- __param(0, Inject(ORPC_MODULE_CONFIG_SYMBOL)),
184
- __param(0, Optional()),
185
- __param(1, Inject(HttpAdapterHost)),
186
- __metadata("design:paramtypes", [Object, HttpAdapterHost])
138
+ Injectable(),
139
+ __decorateParam(0, Inject(ORPC_MODULE_CONFIG_SYMBOL)),
140
+ __decorateParam(0, Optional()),
141
+ __decorateParam(1, Inject(HttpAdapterHost)),
142
+ __decorateMetadata("design:paramtypes", [Object, typeof HttpAdapterHost === "undefined" ? Object : HttpAdapterHost])
187
143
  ], ImplementInterceptor);
188
- export { ImplementInterceptor };
189
144
  /**
190
- * Mirrors `toNodeHttpBody` from `@standard-server/node`, but returns a body NestJS can respond with.
191
- */
145
+ * Mirrors `toNodeHttpBody` from `@standard-server/node`, but returns a body NestJS can respond with.
146
+ */
192
147
  function toNestHttpBody(response, signal, options) {
193
- const { status, body } = response;
194
- const headers = { ...response.headers };
195
- if (body instanceof ReadableStream) {
196
- headers['standard-server'] ??= 'octet-stream';
197
- headers['content-type'] ??= 'application/octet-stream';
198
- return [toStreamableFile(Readable.fromWeb(body), headers, signal), headers];
199
- }
200
- if (body instanceof Blob) {
201
- headers['standard-server'] ??= 'file';
202
- headers['content-type'] ??= body.type;
203
- headers['content-disposition'] ??= generateContentDisposition(body instanceof File ? body.name : 'blob');
204
- // BunS3 can use NaN for the size
205
- if (Number.isFinite(body.size)) {
206
- headers['content-length'] = body.size.toString();
207
- }
208
- return [toStreamableFile(Readable.fromWeb(body.stream()), headers, signal), headers];
209
- }
210
- headers['standard-server'] = undefined;
211
- headers['content-length'] = undefined;
212
- if (body === undefined) {
213
- headers['content-type'] = undefined;
214
- return [undefined, headers];
215
- }
216
- if (body instanceof FormData) {
217
- const response = new Response(body);
218
- headers['content-type'] = response.headers.get('content-type');
219
- return [toStreamableFile(Readable.fromWeb(response.body), headers, signal), headers];
220
- }
221
- if (body instanceof URLSearchParams) {
222
- headers['content-type'] ??= 'application/x-www-form-urlencoded';
223
- headers['standard-server'] = getRequiredStandardBodyHint('url-search-params', headers);
224
- return [body.toString(), headers];
225
- }
226
- if (isAsyncIteratorObject(body)) {
227
- headers['content-type'] ??= 'text/event-stream';
228
- headers['standard-server'] = getRequiredStandardBodyHint('event-stream', headers);
229
- return [toStreamableFile(toEventStream(body, options?.eventStream), headers, signal), headers];
230
- }
231
- // Prefer throwing an HttpException for more native error handling in NestJS.
232
- if (status >= 300 && typeof body === 'object' && body !== null && !Array.isArray(body)) {
233
- if (headers['content-type'] !== undefined) {
234
- headers['standard-server'] = getRequiredStandardBodyHint('json', headers);
235
- }
236
- return [new HttpException(body, status), headers];
237
- }
238
- headers['content-type'] ??= 'application/json';
239
- headers['standard-server'] = getRequiredStandardBodyHint('json', headers);
240
- return [
241
- typeof body === 'string' || body === null || headers['standard-server'] !== undefined
242
- ? stringifyJSON(body)
243
- : body,
244
- headers,
245
- ];
246
- }
247
- class NestHandlerCodec extends OpenAPIHandlerCodecCore {
248
- CONTEXT_SYMBOL = Symbol('ORPC_NEST_HANDLER_CODEC_CONTEXT');
249
- withMatch(context, match) {
250
- return { ...context, [this.CONTEXT_SYMBOL]: match };
251
- }
252
- resolveProcedure(request, options) {
253
- const match = options.context[this.CONTEXT_SYMBOL];
254
- if (!match) {
255
- return undefined;
256
- }
257
- const { procedure, params } = match;
258
- return {
259
- path: getPathMeta(procedure) ?? [],
260
- procedure,
261
- decodeInput: () => this.decodeInput({
262
- procedure,
263
- params: toORPCOpenAPIParams(procedure, params),
264
- }, request),
265
- };
266
- }
148
+ const { status, body } = response;
149
+ const headers = { ...response.headers };
150
+ if (body instanceof ReadableStream) {
151
+ headers["standard-server"] ??= "octet-stream";
152
+ headers["content-type"] ??= "application/octet-stream";
153
+ return [toStreamableFile(Readable.fromWeb(body), headers, signal), headers];
154
+ }
155
+ if (body instanceof Blob) {
156
+ headers["standard-server"] ??= "file";
157
+ headers["content-type"] ??= body.type;
158
+ headers["content-disposition"] ??= generateContentDisposition(body instanceof File ? body.name : "blob");
159
+ if (Number.isFinite(body.size)) headers["content-length"] = body.size.toString();
160
+ return [toStreamableFile(Readable.fromWeb(body.stream()), headers, signal), headers];
161
+ }
162
+ headers["standard-server"] = void 0;
163
+ headers["content-length"] = void 0;
164
+ if (body === void 0) {
165
+ headers["content-type"] = void 0;
166
+ return [void 0, headers];
167
+ }
168
+ if (body instanceof FormData) {
169
+ const response = new Response(body);
170
+ headers["content-type"] = response.headers.get("content-type");
171
+ return [toStreamableFile(Readable.fromWeb(response.body), headers, signal), headers];
172
+ }
173
+ if (body instanceof URLSearchParams) {
174
+ headers["content-type"] ??= "application/x-www-form-urlencoded";
175
+ headers["standard-server"] = getRequiredStandardBodyHint("url-search-params", headers);
176
+ return [body.toString(), headers];
177
+ }
178
+ if (isAsyncIteratorObject(body)) {
179
+ headers["content-type"] ??= "text/event-stream";
180
+ headers["standard-server"] = getRequiredStandardBodyHint("event-stream", headers);
181
+ return [toStreamableFile(toEventStream(body, options?.eventStream), headers, signal), headers];
182
+ }
183
+ if (status >= 300 && typeof body === "object" && body !== null && !Array.isArray(body)) {
184
+ if (headers["content-type"] !== void 0) headers["standard-server"] = getRequiredStandardBodyHint("json", headers);
185
+ return [new HttpException(body, status), headers];
186
+ }
187
+ headers["content-type"] ??= "application/json";
188
+ headers["standard-server"] = getRequiredStandardBodyHint("json", headers);
189
+ return [typeof body === "string" || body === null || headers["standard-server"] !== void 0 ? stringifyJSON(body) : body, headers];
267
190
  }
191
+ var NestHandlerCodec = class extends OpenAPIHandlerCodecCore {
192
+ CONTEXT_SYMBOL = Symbol("ORPC_NEST_HANDLER_CODEC_CONTEXT");
193
+ withMatch(context, match) {
194
+ return {
195
+ ...context,
196
+ [this.CONTEXT_SYMBOL]: match
197
+ };
198
+ }
199
+ resolveProcedure(request, options) {
200
+ const match = options.context[this.CONTEXT_SYMBOL];
201
+ if (!match) return;
202
+ const { procedure, params } = match;
203
+ return {
204
+ path: getPathMeta(procedure) ?? [],
205
+ procedure,
206
+ decodeInput: () => this.decodeInput({
207
+ procedure,
208
+ params: toORPCOpenAPIParams(procedure, params)
209
+ }, request)
210
+ };
211
+ }
212
+ };
268
213
  /**
269
- * Destroys the stream once the request is aborted, because Nest's Express adapter only pipes a StreamableFile
270
- * and never destroys it on client disconnect, which would leave the underlying event iterator or stream uncanceled.
271
- */
214
+ * Destroys the stream once the request is aborted, because Nest's Express adapter only pipes a StreamableFile
215
+ * and never destroys it on client disconnect, which would leave the underlying event iterator or stream uncanceled.
216
+ */
272
217
  function toStreamableFile(stream, headers, signal) {
273
- const type = flattenStandardHeader(headers['content-type']);
274
- headers['content-type'] = undefined;
275
- if (signal?.aborted) {
276
- stream.destroy();
277
- }
278
- else {
279
- signal?.addEventListener('abort', () => stream.destroy(), { once: true });
280
- }
281
- return new StreamableFile(stream, { type });
218
+ const type = flattenStandardHeader(headers["content-type"]);
219
+ headers["content-type"] = void 0;
220
+ listenAbort(signal, () => stream.destroy());
221
+ return new StreamableFile(stream, { type });
282
222
  }
283
223
  function flattenParamValue(value) {
284
- return Array.isArray(value) ? value.join('/') : value;
224
+ return Array.isArray(value) ? value.join("/") : value;
285
225
  }
286
226
  function toORPCOpenAPIParams(contract, params) {
287
- const meta = getOpenAPIMeta(contract);
288
- if (!params || meta?.path === undefined || Object.keys(params).length === 0) {
289
- return undefined;
290
- }
291
- // NullProtoObj prevents prototype injection when a param is named like `__proto__`
292
- const orpcParams = new NullProtoObj();
293
- // express and node use `path` while fastify uses `*` for rest matching
294
- const restKey = Object.hasOwn(params, '*') ? '*' : 'path';
295
- for (const [key, value] of Object.entries(params)) {
296
- if (key === restKey) {
297
- const restParams = getDynamicPathParams(meta.prefix ? mergeHttpPath(meta.prefix, meta.path) : meta.path)?.filter((c) => c.allowsSlash);
298
- if (restParams?.length) {
299
- for (const c of restParams) {
300
- orpcParams[c.parameterName] = flattenParamValue(value);
301
- }
302
- continue;
303
- }
304
- }
305
- orpcParams[key] = flattenParamValue(value);
306
- }
307
- return orpcParams;
227
+ const meta = getOpenAPIMeta(contract);
228
+ if (!params || meta?.path === void 0 || Object.keys(params).length === 0) return;
229
+ const orpcParams = new NullProtoObj();
230
+ const restKey = Object.hasOwn(params, "*") ? "*" : "path";
231
+ for (const [key, value] of Object.entries(params)) {
232
+ if (key === restKey) {
233
+ const restParams = getDynamicPathParams(meta.prefix ? mergeHttpPath(meta.prefix, meta.path) : meta.path)?.filter((c) => c.allowsSlash);
234
+ if (restParams?.length) {
235
+ for (const c of restParams) orpcParams[c.parameterName] = flattenParamValue(value);
236
+ continue;
237
+ }
238
+ }
239
+ orpcParams[key] = flattenParamValue(value);
240
+ }
241
+ return orpcParams;
308
242
  }
309
243
  function toNestPattern(path) {
310
- const params = getDynamicPathParams(path);
311
- if (!params?.length) {
312
- return path;
313
- }
314
- for (let i = params.length - 1; i >= 0; i--) {
315
- const param = params[i];
316
- const pattern = param.allowsSlash ? `*` : `:${param.parameterName}`;
317
- path =
318
- path.slice(0, param.startIndex) +
319
- pattern +
320
- path.slice(param.startIndex + param.segment.length);
321
- }
322
- return path;
244
+ const params = getDynamicPathParams(path);
245
+ if (!params?.length) return path;
246
+ for (let i = params.length - 1; i >= 0; i--) {
247
+ const param = params[i];
248
+ const pattern = param.allowsSlash ? `*` : `:${param.parameterName}`;
249
+ path = path.slice(0, param.startIndex) + pattern + path.slice(param.startIndex + param.segment.length);
250
+ }
251
+ return path;
323
252
  }
253
+ export { Implement, ImplementInterceptor };
package/dist/index.d.ts CHANGED
@@ -1,8 +1,4 @@
1
- export * from './constants.ts';
2
- export * from './implement.ts';
3
- export {
4
- /**
5
- * @alias Implement
6
- */
7
- Implement as Impl, } from './implement.ts';
8
- export * from './module.ts';
1
+ import { ORPC_MODULE_CONFIG_SYMBOL } from "./constants.js";
2
+ import { Implement, ImplementInterceptor } from "./implement.js";
3
+ import { NestStandardLazyRequest, ORPCModule, ORPCModuleConfig } from "./module.js";
4
+ export { Implement as Impl, Implement, ImplementInterceptor, NestStandardLazyRequest, ORPCModule, ORPCModuleConfig, ORPC_MODULE_CONFIG_SYMBOL };
package/dist/index.js CHANGED
@@ -1,8 +1,3 @@
1
- export * from './constants.js';
2
- export * from './implement.js';
3
- export {
4
- /**
5
- * @alias Implement
6
- */
7
- Implement as Impl, } from './implement.js';
8
- export * from './module.js';
1
+ export { ORPC_MODULE_CONFIG_SYMBOL } from "./constants.js";
2
+ export { Implement as Impl, Implement, ImplementInterceptor } from "./implement.js";
3
+ export { ORPCModule } from "./module.js";
package/dist/module.d.ts CHANGED
@@ -1,10 +1,10 @@
1
- import type { DynamicModule, ExecutionContext } from '@nestjs/common';
2
- import type { OpenAPIHandlerCodecCoreOptions } from '@orpc/openapi/standard';
3
- import type { DefaultInitialContext } from '@orpc/server';
4
- import type { StandardHandlerOptions } from '@orpc/server/standard';
5
- import type { Promisable, Value } from '@orpc/shared';
6
- import type { StandardLazyRequest } from '@standard-server/core';
7
- import type { ToEventStreamOptions } from '@standard-server/node';
1
+ import { DynamicModule, ExecutionContext } from "@nestjs/common";
2
+ import { OpenAPIHandlerCodecCoreOptions } from "@orpc/openapi/standard";
3
+ import { DefaultInitialContext } from "@orpc/server";
4
+ import { StandardHandlerOptions } from "@orpc/server/standard";
5
+ import { Promisable, Value } from "@orpc/shared";
6
+ import { StandardLazyRequest } from "@standard-server/core";
7
+ import { ToEventStreamOptions } from "@standard-server/node";
8
8
  /**
9
9
  * A standard lazy request extended with NestJS route parameters,
10
10
  * used as the request representation inside the `@orpc/nest` integration.
@@ -12,30 +12,30 @@ import type { ToEventStreamOptions } from '@standard-server/node';
12
12
  * @see {@link https://orpc.dev/docs/integrations/nest#toneststandardlazyrequest-option | Implement oRPC contract with NestJS - toNestStandardLazyRequest option}
13
13
  */
14
14
  export interface NestStandardLazyRequest extends StandardLazyRequest {
15
- /**
16
- * Route parameters extracted from the request path.
17
- */
18
- params?: Record<string, string | string[]> | undefined;
15
+ /**
16
+ * Route parameters extracted from the request path.
17
+ */
18
+ params?: Record<string, string | string[]> | undefined;
19
19
  }
20
20
  export type ORPCModuleConfig = OpenAPIHandlerCodecCoreOptions<DefaultInitialContext> & StandardHandlerOptions<DefaultInitialContext> & (object extends DefaultInitialContext ? {
21
- context?: Value<Promisable<DefaultInitialContext>, [ctx: ExecutionContext]> | undefined;
21
+ context?: Value<Promisable<DefaultInitialContext>, [ctx: ExecutionContext]> | undefined;
22
22
  } : {
23
- context: Value<Promisable<DefaultInitialContext>, [ctx: ExecutionContext]>;
23
+ context: Value<Promisable<DefaultInitialContext>, [ctx: ExecutionContext]>;
24
24
  }) & {
25
+ /**
26
+ * Customize how to convert NestJS `req` and `res` to {@link NestStandardLazyRequest}.
27
+ * You might need to define this if you are not using the express, fastify or node adapters.
28
+ */
29
+ toNestStandardLazyRequest?: ((req: any, res: any) => NestStandardLazyRequest) | undefined;
30
+ /**
31
+ * Options for how to convert the Standard Response to a Nest Response (returning value), like event stream options, etc.
32
+ */
33
+ toNestResponse?: {
25
34
  /**
26
- * Customize how to convert NestJS `req` and `res` to {@link NestStandardLazyRequest}.
27
- * You might need to define this if you are not using the express, fastify or node adapters.
35
+ * Options for the event stream, like keep-alive settings, initial comment, etc.
28
36
  */
29
- toNestStandardLazyRequest?: ((req: any, res: any) => NestStandardLazyRequest) | undefined;
30
- /**
31
- * Options for how to convert the Standard Response to a Nest Response (returning value), like event stream options, etc.
32
- */
33
- toNestResponse?: {
34
- /**
35
- * Options for the event stream, like keep-alive settings, initial comment, etc.
36
- */
37
- eventStream?: ToEventStreamOptions | undefined;
38
- } | undefined;
37
+ eventStream?: ToEventStreamOptions | undefined;
38
+ } | undefined;
39
39
  };
40
40
  /**
41
41
  * NestJS module that configures the `@orpc/nest` integration via `forRoot`
@@ -45,10 +45,10 @@ export type ORPCModuleConfig = OpenAPIHandlerCodecCoreOptions<DefaultInitialCont
45
45
  * @see {@link https://orpc.dev/docs/integrations/nest#configuration | Implement oRPC contract with NestJS - Configuration}
46
46
  */
47
47
  export declare class ORPCModule {
48
- static forRoot(config: ORPCModuleConfig): DynamicModule;
49
- static forRootAsync(options: {
50
- imports?: any[] | undefined;
51
- useFactory: (...args: any[]) => Promise<ORPCModuleConfig> | ORPCModuleConfig;
52
- inject?: any[] | undefined;
53
- }): DynamicModule;
54
- }
48
+ static forRoot(config: ORPCModuleConfig): DynamicModule;
49
+ static forRootAsync(options: {
50
+ imports?: any[] | undefined;
51
+ useFactory: (...args: any[]) => Promise<ORPCModuleConfig> | ORPCModuleConfig;
52
+ inject?: any[] | undefined;
53
+ }): DynamicModule;
54
+ }
package/dist/module.js CHANGED
@@ -1,54 +1,34 @@
1
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1
+ import { ORPC_MODULE_CONFIG_SYMBOL } from "./constants.js";
2
+ import { ImplementInterceptor } from "./implement.js";
3
+ import __decorate from "./_virtual/_@oxc-project_runtime@0.157.0/helpers/esm/decorate.js";
4
+ import { Module } from "@nestjs/common";
5
+ // src/module.ts
6
+ var _ORPCModule;
7
+ let ORPCModule = _ORPCModule = class ORPCModule {
8
+ static forRoot(config) {
9
+ return {
10
+ module: _ORPCModule,
11
+ providers: [{
12
+ provide: ORPC_MODULE_CONFIG_SYMBOL,
13
+ useValue: config
14
+ }, ImplementInterceptor],
15
+ exports: [ORPC_MODULE_CONFIG_SYMBOL, ImplementInterceptor],
16
+ global: true
17
+ };
18
+ }
19
+ static forRootAsync(options) {
20
+ return {
21
+ module: _ORPCModule,
22
+ imports: options.imports,
23
+ providers: [{
24
+ provide: ORPC_MODULE_CONFIG_SYMBOL,
25
+ useFactory: options.useFactory,
26
+ inject: options.inject
27
+ }, ImplementInterceptor],
28
+ exports: [ORPC_MODULE_CONFIG_SYMBOL, ImplementInterceptor],
29
+ global: true
30
+ };
31
+ }
6
32
  };
7
- var ORPCModule_1;
8
- import { Module } from '@nestjs/common';
9
- import { ORPC_MODULE_CONFIG_SYMBOL } from './constants.js';
10
- import { ImplementInterceptor } from './implement.js';
11
- /**
12
- * NestJS module that configures the `@orpc/nest` integration via `forRoot`
13
- * or `forRootAsync`, providing options such as initial context, plugins,
14
- * and interceptors to `@Implement` handlers.
15
- *
16
- * @see {@link https://orpc.dev/docs/integrations/nest#configuration | Implement oRPC contract with NestJS - Configuration}
17
- */
18
- let ORPCModule = ORPCModule_1 = class ORPCModule {
19
- static forRoot(config) {
20
- return {
21
- module: ORPCModule_1,
22
- providers: [
23
- {
24
- provide: ORPC_MODULE_CONFIG_SYMBOL,
25
- useValue: config,
26
- },
27
- ImplementInterceptor,
28
- ],
29
- exports: [ORPC_MODULE_CONFIG_SYMBOL, ImplementInterceptor],
30
- global: true,
31
- };
32
- }
33
- static forRootAsync(options) {
34
- return {
35
- module: ORPCModule_1,
36
- imports: options.imports,
37
- providers: [
38
- {
39
- provide: ORPC_MODULE_CONFIG_SYMBOL,
40
- useFactory: options.useFactory,
41
- inject: options.inject,
42
- },
43
- ImplementInterceptor,
44
- ],
45
- exports: [ORPC_MODULE_CONFIG_SYMBOL, ImplementInterceptor],
46
- global: true,
47
- };
48
- }
49
- };
50
- ORPCModule = ORPCModule_1 = __decorate([
51
- Module({})
52
- // oxlint-disable-next-line typescript/no-extraneous-class
53
- ], ORPCModule);
33
+ ORPCModule = _ORPCModule = __decorate([Module({})], ORPCModule);
54
34
  export { ORPCModule };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orpc/nest",
3
- "version": "2.0.0-beta.49",
3
+ "version": "2.0.0-beta.50",
4
4
  "description": "NestJS integration for oRPC: implement typesafe contracts in NestJS controllers",
5
5
  "keywords": [
6
6
  "contract-first",
@@ -37,14 +37,14 @@
37
37
  }
38
38
  },
39
39
  "dependencies": {
40
- "@orpc/client": "2.0.0-beta.49",
41
- "@orpc/contract": "2.0.0-beta.49",
42
- "@orpc/openapi": "2.0.0-beta.49",
43
- "@orpc/server": "2.0.0-beta.49",
44
- "@orpc/shared": "2.0.0-beta.49",
45
- "@oxc-project/runtime": "^0.155.0",
46
- "@standard-server/core": "~0.15.0",
47
- "@standard-server/node": "~0.15.0"
40
+ "@orpc/client": "2.0.0-beta.50",
41
+ "@orpc/contract": "2.0.0-beta.50",
42
+ "@orpc/openapi": "2.0.0-beta.50",
43
+ "@orpc/server": "2.0.0-beta.50",
44
+ "@orpc/shared": "2.0.0-beta.50",
45
+ "@oxc-project/runtime": "^0.157.0",
46
+ "@standard-server/core": "~0.16.0",
47
+ "@standard-server/node": "~0.16.0"
48
48
  },
49
49
  "devDependencies": {
50
50
  "@fastify/cookie": "^11.1.5",