@orpc/nest 2.0.0-beta.47 → 2.0.0-beta.48

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.
package/README.md CHANGED
@@ -191,15 +191,14 @@ Like what we build over at [middleapi](https://github.com/middleapi)? You can he
191
191
  <td align="center"><a href="https://kellychan.im/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Kelly Peilin Chan"><img src="https://avatars.githubusercontent.com/u/520852?u=6b0f7105f694e7b5cacf410a3f04c7044b469dc8&amp;v=4" width="139" alt="Kelly Peilin Chan"/><br />Kelly Peilin Chan</a></td>
192
192
  <td align="center"><a href="https://guyariely.com/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Guy Ariely"><img src="https://avatars.githubusercontent.com/u/42813496?u=edb6b7f563bf28e160a290832e7da57c0506f8ca&amp;v=4" width="139" alt="Guy Ariely"/><br />Guy Ariely</a></td>
193
193
  <td align="center"><a href="https://paulsenon.com/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="PaulSenon"><img src="https://avatars.githubusercontent.com/u/19531087?u=6385741eb91d200b8c513ec6045482e301767ca6&amp;v=4" width="139" alt="PaulSenon"/><br />PaulSenon</a></td>
194
- <td align="center"><a href="https://nakasyou.how/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Shotaro Nakamura"><img src="https://avatars.githubusercontent.com/u/79000684?u=f644df3f29f0e8677a90967115774564f1d9d6ab&amp;v=4" width="139" alt="Shotaro Nakamura"/><br />Shotaro Nakamura</a></td>
194
+ <td align="center"><a href="https://piscis.dev/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Alex"><img src="https://avatars.githubusercontent.com/u/326163?u=b245f368bd940cf51d08c0b6bf55f8257f359437&amp;v=4" width="139" alt="Alex"/><br />Alex</a></td>
195
195
  </tr>
196
196
  <tr>
197
- <td align="center"><a href="https://piscis.dev/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Alex"><img src="https://avatars.githubusercontent.com/u/326163?u=b245f368bd940cf51d08c0b6bf55f8257f359437&amp;v=4" width="139" alt="Alex"/><br />Alex</a></td>
198
197
  <td align="center"><a href="https://opensource.gubanov.eu/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Andrey Gubanov"><img src="https://avatars.githubusercontent.com/u/1082083?u=c5f2daf7ebece498e85c83367bb37b4e10e2649d&amp;v=4" width="139" alt="Andrey Gubanov"/><br />Andrey Gubanov</a></td>
199
198
  </tr>
200
199
  </table>
201
200
 
202
- With thanks to [39 past sponsors](https://orpc.dev/sponsors#past-sponsors) who helped get oRPC here.
201
+ With thanks to [40 past sponsors](https://orpc.dev/sponsors#past-sponsors) who helped get oRPC here.
203
202
 
204
203
  ## Open Source Programs
205
204
 
@@ -0,0 +1 @@
1
+ export declare const ORPC_MODULE_CONFIG_SYMBOL: unique symbol;
@@ -0,0 +1 @@
1
+ export const ORPC_MODULE_CONFIG_SYMBOL = /* @__PURE__ */ Symbol.for("ORPC_NEST_MODULE_CONFIG");
@@ -0,0 +1,29 @@
1
+ import type { CallHandler, ExecutionContext, NestInterceptor } from "@nestjs/common";
2
+ import type { RouterContract } from "@orpc/contract";
3
+ import type { ContractedRouter, DefaultInitialContext } from "@orpc/server";
4
+ import type { Promisable } from "@orpc/shared";
5
+ import type { Observable } from "rxjs";
6
+ import type { ORPCModuleConfig } from "./module.mjs";
7
+ import { HttpAdapterHost } from "@nestjs/core";
8
+ /**
9
+ * Decorator that implements an oRPC contract (procedure or router contract)
10
+ * on a NestJS controller method. It registers the corresponding NestJS routes
11
+ * and handles request decoding and response encoding for you.
12
+ *
13
+ * @remarks
14
+ * **Note**: Every procedure contract must define an `openapi.path` meta;
15
+ * use `populateRouterContractOpenAPIPaths` from `@orpc/openapi` to fill in missing paths.
16
+ * **Note**: The HTTP `QUERY` method requires NestJS v11.2+ (`QueryMethod`). Older NestJS versions throw; use `GET` instead.
17
+ *
18
+ * @see {@link https://orpc.dev/docs/integrations/nest#implement-your-contract | Implement oRPC contract with NestJS - Implement Your Contract}
19
+ */
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
+ 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<any>): Observable<any>;
29
+ }
@@ -0,0 +1,287 @@
1
+ import { Readable } from "node:stream";
2
+ import * as NestCommon from "@nestjs/common";
3
+ import { applyDecorators, Delete, Get, Head, HttpCode, HttpException, Inject, Injectable, Optional, Options, Patch, Post, Put, StreamableFile, UseInterceptors } from "@nestjs/common";
4
+ import { HttpAdapterHost } from "@nestjs/core";
5
+ import { getPathMeta, ProcedureContract } from "@orpc/contract";
6
+ import { DEFAULT_OPENAPI_METHOD, getDynamicPathParams, getOpenAPIMeta } from "@orpc/openapi";
7
+ import { OpenAPIHandlerCodecCore } from "@orpc/openapi/standard";
8
+ import { DEFAULT_SUCCESS_STATUS, getRouter, Procedure, unlazy } from "@orpc/server";
9
+ import { StandardHandler } from "@orpc/server/standard";
10
+ import { isAsyncIteratorObject, mergeHttpPath, NullProtoObj, stringifyJSON, toArray, value } from "@orpc/shared";
11
+ import { flattenStandardHeader, generateContentDisposition, getRequiredStandardBodyHint } from "@standard-server/core";
12
+ import { toEventStream, toStandardLazyRequest } from "@standard-server/node";
13
+ import { mergeMap } from "rxjs";
14
+ import { ORPC_MODULE_CONFIG_SYMBOL } from "./constants.mjs";
15
+ import _decorateParam from "@oxc-project/runtime/helpers/decorateParam";
16
+ import _decorate from "@oxc-project/runtime/helpers/decorate";
17
+
18
+ const QueryMethod = NestCommon.QueryMethod;
19
+ const MethodDecoratorMap = {
20
+ HEAD: Head,
21
+ GET: Get,
22
+ POST: Post,
23
+ PUT: Put,
24
+ PATCH: Patch,
25
+ DELETE: Delete,
26
+ OPTIONS: Options
27
+ };
28
+
29
+ export function Implement(contract) {
30
+ if (contract instanceof ProcedureContract) {
31
+ return (target, propertyKey, descriptor) => {
32
+ applyDecorators(toNestRouteDecorator(contract), UseInterceptors(ImplementInterceptor))(target, propertyKey, descriptor);
33
+ };
34
+ }
35
+ return (target, propertyKey, descriptor) => {
36
+
37
+
38
+ UseInterceptors(ImplementInterceptor)(target, propertyKey, descriptor);
39
+ implementRouterContract(contract, target, propertyKey, descriptor);
40
+ };
41
+ }
42
+ function toNestRouteDecorator(contract) {
43
+ const meta = getOpenAPIMeta(contract);
44
+ if (meta?.path === undefined) {
45
+ throw new TypeError(`
46
+ @Implement decorator requires contract to have a 'openapi.path' meta.
47
+ Please define one using '.meta(openapi({ path: '/example' }))'.
48
+ Or use "populateRouterContractOpenAPIPaths" from "@orpc/openapi" utility to automatically fill in any missing paths.
49
+ `);
50
+ }
51
+ const method = meta.method ?? DEFAULT_OPENAPI_METHOD;
52
+ const path = toNestPattern(meta.prefix ? mergeHttpPath(meta.prefix, meta.path) : meta.path);
53
+ const successStatus = meta.successStatus ?? DEFAULT_SUCCESS_STATUS;
54
+ if (method === "QUERY") {
55
+ if (!QueryMethod) {
56
+ throw new TypeError(`
57
+ @Implement decorator does not support the 'QUERY' HTTP method because the installed version of NestJS does not support it.
58
+ The 'QUERY' HTTP method requires NestJS v11.2 or later. Alternatively, use 'GET' method.
59
+ `);
60
+ }
61
+ return applyDecorators(QueryMethod(path), HttpCode(successStatus));
62
+ }
63
+ return applyDecorators(MethodDecoratorMap[method](path), HttpCode(successStatus));
64
+ }
65
+ function implementRouterContract(contract, target, propertyKey, descriptor) {
66
+ for (const [key, childContract] of Object.entries(contract)) {
67
+ let methodName = `${propertyKey}_${key}`;
68
+ let i = 0;
69
+ while (methodName in target) {
70
+ methodName = `${propertyKey}_${key}_${i++}`;
71
+ }
72
+ target[methodName] = async function(...args) {
73
+ const router = await descriptor.value.apply(this, args);
74
+ return getRouter(router, [key]);
75
+ };
76
+ Object.setPrototypeOf(target[methodName], descriptor.value);
77
+ queueMicrotask(() => {
78
+ for (const p of Reflect.getOwnMetadataKeys(target, propertyKey)) {
79
+ Reflect.defineMetadata(p, Reflect.getOwnMetadata(p, target, propertyKey), target, methodName);
80
+ }
81
+ for (const p of Reflect.getOwnMetadataKeys(target.constructor, propertyKey)) {
82
+ Reflect.defineMetadata(p, Reflect.getOwnMetadata(p, target.constructor, propertyKey), target.constructor, methodName);
83
+ }
84
+ });
85
+ const childDescriptor = Object.getOwnPropertyDescriptor(target, methodName);
86
+ if (childContract instanceof ProcedureContract) {
87
+ const routeDecorator = toNestRouteDecorator(childContract);
88
+
89
+ queueMicrotask(() => {
90
+ routeDecorator(target, methodName, childDescriptor);
91
+ });
92
+ } else {
93
+ implementRouterContract(childContract, target, methodName, childDescriptor);
94
+ }
95
+ }
96
+ }
97
+ let ImplementInterceptor = class ImplementInterceptor {
98
+ config;
99
+ codec;
100
+ handler;
101
+ toNestStandardLazyRequest;
102
+ httpAdapterHost;
103
+ constructor(config, httpAdapterHost) {
104
+ // @Optional() does not allow set default value so we need to do it here
105
+ this.config = config ?? {};
106
+ this.httpAdapterHost = httpAdapterHost;
107
+ this.codec = new NestHandlerCodec(this.config);
108
+ this.handler = new StandardHandler(this.codec, this.config);
109
+ this.toNestStandardLazyRequest = this.config.toNestStandardLazyRequest ?? ((req, res) => {
110
+ const standardRequest = toStandardLazyRequest("raw" in req ? req.raw : req, "raw" in res ? res.raw : res);
111
+
112
+ if (req.body !== undefined) {
113
+ standardRequest.resolveBody = () => Promise.resolve(req.body);
114
+ }
115
+ standardRequest.params = req.params;
116
+ return standardRequest;
117
+ });
118
+ }
119
+ intercept(ctx, next) {
120
+ return next.handle().pipe(mergeMap(async (impl) => {
121
+ const { default: procedure } = await unlazy(impl);
122
+ if (!(procedure instanceof Procedure)) {
123
+ throw new TypeError(`
124
+ The return value of the @Implement controller handler must be a corresponding implemented router or procedure.
125
+ `);
126
+ }
127
+ const req = ctx.switchToHttp().getRequest();
128
+ const res = ctx.switchToHttp().getResponse();
129
+ const standardRequest = this.toNestStandardLazyRequest(req, res);
130
+ const context = await value(this.config.context ?? {}, ctx);
131
+ const result = await this.handler.handle(standardRequest, { context: this.codec.withMatch(context, {
132
+ procedure,
133
+ params: standardRequest.params
134
+ }) });
135
+ if (!result.matched) {
136
+ throw new TypeError("oRPC NestJS handler returned an unmatched result, which should never happen. Please check your plugins/interceptors or report a bug.");
137
+ }
138
+ const [nestBody, headers] = toNestHttpBody(result.response, standardRequest.signal, this.config.toNestResponse);
139
+ const httpAdapter = this.httpAdapterHost.httpAdapter;
140
+ httpAdapter.status(res, result.response.status);
141
+ for (const key of Object.keys(headers)) {
142
+ toArray(headers[key]).forEach((value, index) => {
143
+ if (index === 0) {
144
+ httpAdapter.setHeader(res, key, value);
145
+ } else {
146
+ httpAdapter.appendHeader(res, key, value);
147
+ }
148
+ });
149
+ }
150
+ if (nestBody instanceof HttpException) {
151
+ throw nestBody;
152
+ }
153
+ return nestBody;
154
+ }));
155
+ }
156
+ };
157
+ ImplementInterceptor = _decorate([
158
+ Injectable(),
159
+ _decorateParam(0, Inject(ORPC_MODULE_CONFIG_SYMBOL)),
160
+ _decorateParam(0, Optional()),
161
+ _decorateParam(1, Inject(HttpAdapterHost))
162
+ ], ImplementInterceptor);
163
+ export { ImplementInterceptor };
164
+
165
+ function toNestHttpBody(response, signal, options) {
166
+ const { status, body } = response;
167
+ const headers = { ...response.headers };
168
+ if (body instanceof ReadableStream) {
169
+ headers["standard-server"] ??= "octet-stream";
170
+ headers["content-type"] ??= "application/octet-stream";
171
+ return [toStreamableFile(Readable.fromWeb(body), headers, signal), headers];
172
+ }
173
+ if (body instanceof Blob) {
174
+ headers["standard-server"] ??= "file";
175
+ headers["content-type"] ??= body.type;
176
+ headers["content-disposition"] ??= generateContentDisposition(body instanceof File ? body.name : "blob");
177
+
178
+ if (Number.isFinite(body.size)) {
179
+ headers["content-length"] = body.size.toString();
180
+ }
181
+ return [toStreamableFile(Readable.fromWeb(body.stream()), headers, signal), headers];
182
+ }
183
+ headers["standard-server"] = undefined;
184
+ headers["content-length"] = undefined;
185
+ if (body === undefined) {
186
+ headers["content-type"] = undefined;
187
+ return [undefined, headers];
188
+ }
189
+ if (body instanceof FormData) {
190
+ const response = new Response(body);
191
+ headers["content-type"] = response.headers.get("content-type");
192
+ return [toStreamableFile(Readable.fromWeb(response.body), headers, signal), headers];
193
+ }
194
+ if (body instanceof URLSearchParams) {
195
+ headers["content-type"] ??= "application/x-www-form-urlencoded";
196
+ headers["standard-server"] = getRequiredStandardBodyHint("url-search-params", headers);
197
+ return [body.toString(), headers];
198
+ }
199
+ if (isAsyncIteratorObject(body)) {
200
+ headers["content-type"] ??= "text/event-stream";
201
+ headers["standard-server"] = getRequiredStandardBodyHint("event-stream", headers);
202
+ return [toStreamableFile(toEventStream(body, options?.eventStream), headers, signal), headers];
203
+ }
204
+
205
+ if (status >= 300 && typeof body === "object" && body !== null && !Array.isArray(body)) {
206
+ if (headers["content-type"] !== undefined) {
207
+ headers["standard-server"] = getRequiredStandardBodyHint("json", headers);
208
+ }
209
+ return [new HttpException(body, status), headers];
210
+ }
211
+ headers["content-type"] ??= "application/json";
212
+ headers["standard-server"] = getRequiredStandardBodyHint("json", headers);
213
+ return [typeof body === "string" || body === null || headers["standard-server"] !== undefined ? stringifyJSON(body) : body, headers];
214
+ }
215
+ class NestHandlerCodec extends OpenAPIHandlerCodecCore {
216
+ CONTEXT_SYMBOL = Symbol("ORPC_NEST_HANDLER_CODEC_CONTEXT");
217
+ withMatch(context, match) {
218
+ return {
219
+ ...context,
220
+ [this.CONTEXT_SYMBOL]: match
221
+ };
222
+ }
223
+ resolveProcedure(request, options) {
224
+ const match = options.context[this.CONTEXT_SYMBOL];
225
+ if (!match) {
226
+ return undefined;
227
+ }
228
+ const { procedure, params } = match;
229
+ return {
230
+ path: getPathMeta(procedure) ?? [],
231
+ procedure,
232
+ decodeInput: () => this.decodeInput({
233
+ procedure,
234
+ params: toORPCOpenAPIParams(procedure, params)
235
+ }, request)
236
+ };
237
+ }
238
+ }
239
+
240
+ function toStreamableFile(stream, headers, signal) {
241
+ const type = flattenStandardHeader(headers["content-type"]);
242
+ headers["content-type"] = undefined;
243
+ if (signal?.aborted) {
244
+ stream.destroy();
245
+ } else {
246
+ signal?.addEventListener("abort", () => stream.destroy(), { once: true });
247
+ }
248
+ return new StreamableFile(stream, { type });
249
+ }
250
+ function flattenParamValue(value) {
251
+ return Array.isArray(value) ? value.join("/") : value;
252
+ }
253
+ function toORPCOpenAPIParams(contract, params) {
254
+ const meta = getOpenAPIMeta(contract);
255
+ if (!params || meta?.path === undefined || Object.keys(params).length === 0) {
256
+ return undefined;
257
+ }
258
+
259
+ const orpcParams = new NullProtoObj();
260
+
261
+ const restKey = Object.hasOwn(params, "*") ? "*" : "path";
262
+ for (const [key, value] of Object.entries(params)) {
263
+ if (key === restKey) {
264
+ const restParams = getDynamicPathParams(meta.prefix ? mergeHttpPath(meta.prefix, meta.path) : meta.path)?.filter((c) => c.allowsSlash);
265
+ if (restParams?.length) {
266
+ for (const c of restParams) {
267
+ orpcParams[c.parameterName] = flattenParamValue(value);
268
+ }
269
+ continue;
270
+ }
271
+ }
272
+ orpcParams[key] = flattenParamValue(value);
273
+ }
274
+ return orpcParams;
275
+ }
276
+ function toNestPattern(path) {
277
+ const params = getDynamicPathParams(path);
278
+ if (!params?.length) {
279
+ return path;
280
+ }
281
+ for (let i = params.length - 1; i >= 0; i--) {
282
+ const param = params[i];
283
+ const pattern = param.allowsSlash ? `*` : `:${param.parameterName}`;
284
+ path = path.slice(0, param.startIndex) + pattern + path.slice(param.startIndex + param.segment.length);
285
+ }
286
+ return path;
287
+ }
package/dist/index.d.mts CHANGED
@@ -1,85 +1,8 @@
1
- import { ExecutionContext, DynamicModule, NestInterceptor, CallHandler } from '@nestjs/common';
2
- import { RouterContract } from '@orpc/contract';
3
- import { DefaultInitialContext, ContractedRouter } from '@orpc/server';
4
- import { Value, Promisable } from '@orpc/shared';
5
- import { Observable } from 'rxjs';
6
- import { OpenAPIHandlerCodecCoreOptions } from '@orpc/openapi/standard';
7
- import { StandardHandlerOptions } from '@orpc/server/standard';
8
- import { StandardLazyRequest } from '@standard-server/core';
9
- import { ToEventStreamOptions } from '@standard-server/node';
10
- import { HttpAdapterHost } from '@nestjs/core';
11
-
12
- declare const ORPC_MODULE_CONFIG_SYMBOL: unique symbol;
1
+ export * from "./constants.mjs";
2
+ export * from "./implement.mjs";
3
+ export {
13
4
  /**
14
- * A standard lazy request extended with NestJS route parameters,
15
- * used as the request representation inside the `@orpc/nest` integration.
16
- *
17
- * @see {@link https://orpc.dev/docs/integrations/nest#toneststandardlazyrequest-option | Implement oRPC contract with NestJS - toNestStandardLazyRequest option}
18
- */
19
- interface NestStandardLazyRequest extends StandardLazyRequest {
20
- /**
21
- * Route parameters extracted from the request path.
22
- */
23
- params?: Record<string, string | string[]> | undefined;
24
- }
25
- type ORPCModuleConfig = OpenAPIHandlerCodecCoreOptions<DefaultInitialContext> & StandardHandlerOptions<DefaultInitialContext> & (object extends DefaultInitialContext ? {
26
- context?: Value<Promisable<DefaultInitialContext>, [ctx: ExecutionContext]> | undefined;
27
- } : {
28
- context: Value<Promisable<DefaultInitialContext>, [ctx: ExecutionContext]>;
29
- }) & {
30
- /**
31
- * Customize how to convert NestJS `req` and `res` to {@link NestStandardLazyRequest}.
32
- * You might need to define this if you are not using express or fastify adapters.
33
- */
34
- toNestStandardLazyRequest?: ((req: any, res: any) => NestStandardLazyRequest) | undefined;
35
- /**
36
- * Options for how to convert the Standard Response to a Nest Response (returning value), like event stream options, etc.
37
- */
38
- toNestResponse?: {
39
- /**
40
- * Options for the event stream, like keep-alive settings, initial comment, etc.
41
- */
42
- eventStream?: ToEventStreamOptions | undefined;
43
- } | undefined;
44
- };
45
- /**
46
- * NestJS module that configures the `@orpc/nest` integration via `forRoot`
47
- * or `forRootAsync`, providing options such as initial context, plugins,
48
- * and interceptors to `@Implement` handlers.
49
- *
50
- * @see {@link https://orpc.dev/docs/integrations/nest#configuration | Implement oRPC contract with NestJS - Configuration}
51
- */
52
- declare class ORPCModule {
53
- static forRoot(config: ORPCModuleConfig): DynamicModule;
54
- static forRootAsync(options: {
55
- imports?: any[] | undefined;
56
- useFactory: (...args: any[]) => Promise<ORPCModuleConfig> | ORPCModuleConfig;
57
- inject?: any[] | undefined;
58
- }): DynamicModule;
59
- }
60
-
61
- /**
62
- * Decorator that implements an oRPC contract (procedure or router contract)
63
- * on a NestJS controller method. It registers the corresponding NestJS routes
64
- * and handles request decoding and response encoding for you.
65
- *
66
- * @remarks
67
- * **Note**: Every procedure contract must define an `openapi.path` meta;
68
- * use `populateRouterContractOpenAPIPaths` from `@orpc/openapi` to fill in missing paths.
69
- * **Note**: The HTTP `QUERY` method requires NestJS v11.2+ (`QueryMethod`). Older NestJS versions throw; use `GET` instead.
70
- *
71
- * @see {@link https://orpc.dev/docs/integrations/nest#implement-your-contract | Implement oRPC contract with NestJS - Implement Your Contract}
72
- */
73
- 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;
74
- declare class ImplementInterceptor implements NestInterceptor {
75
- private readonly config;
76
- private readonly codec;
77
- private readonly handler;
78
- private readonly toNestStandardLazyRequest;
79
- private readonly httpAdapterHost;
80
- constructor(config: ORPCModuleConfig | undefined, httpAdapterHost: HttpAdapterHost);
81
- intercept(ctx: ExecutionContext, next: CallHandler<any>): Observable<any>;
82
- }
83
-
84
- export { Implement as Impl, Implement, ImplementInterceptor, ORPCModule, ORPC_MODULE_CONFIG_SYMBOL };
85
- export type { NestStandardLazyRequest, ORPCModuleConfig };
5
+ * @alias Implement
6
+ */
7
+ Implement as Impl } from "./implement.mjs";
8
+ export * from "./module.mjs";
package/dist/index.mjs CHANGED
@@ -1,341 +1,6 @@
1
- import { Readable } from 'node:stream';
2
- import * as NestCommon from '@nestjs/common';
3
- import { Module, applyDecorators, UseInterceptors, HttpException, HttpCode, Options, Delete, Patch, Put, Post, Get, Head, StreamableFile, Injectable, Inject, Optional } from '@nestjs/common';
4
- import { HttpAdapterHost } from '@nestjs/core';
5
- import { ProcedureContract, getPathMeta } from '@orpc/contract';
6
- import { getOpenAPIMeta, DEFAULT_OPENAPI_METHOD, getDynamicPathParams } from '@orpc/openapi';
7
- import { OpenAPIHandlerCodecCore } from '@orpc/openapi/standard';
8
- import { unlazy, Procedure, DEFAULT_SUCCESS_STATUS, getRouter } from '@orpc/server';
9
- import { StandardHandler } from '@orpc/server/standard';
10
- import { value, toArray, mergeHttpPath, isAsyncIteratorObject, stringifyJSON, NullProtoObj } from '@orpc/shared';
11
- import { generateContentDisposition, getRequiredStandardBodyHint, flattenStandardHeader } from '@standard-server/core';
12
- import { toStandardLazyRequest, toEventStream } from '@standard-server/node';
13
- import { mergeMap } from 'rxjs';
1
+ export * from "./constants.mjs";
2
+ export * from "./implement.mjs";
3
+ export {
14
4
 
15
- var __getOwnPropDesc$1 = Object.getOwnPropertyDescriptor;
16
- var __decorateClass$1 = (decorators, target, key, kind) => {
17
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$1(target, key) : target;
18
- for (var i = decorators.length - 1, decorator; i >= 0; i--)
19
- if (decorator = decorators[i])
20
- result = (decorator(result)) || result;
21
- return result;
22
- };
23
- const ORPC_MODULE_CONFIG_SYMBOL = Symbol.for("ORPC_NEST_MODULE_CONFIG");
24
- let ORPCModule = class {
25
- static forRoot(config) {
26
- return {
27
- module: ORPCModule,
28
- providers: [
29
- {
30
- provide: ORPC_MODULE_CONFIG_SYMBOL,
31
- useValue: config
32
- },
33
- ImplementInterceptor
34
- ],
35
- exports: [ORPC_MODULE_CONFIG_SYMBOL, ImplementInterceptor],
36
- global: true
37
- };
38
- }
39
- static forRootAsync(options) {
40
- return {
41
- module: ORPCModule,
42
- imports: options.imports,
43
- providers: [
44
- {
45
- provide: ORPC_MODULE_CONFIG_SYMBOL,
46
- useFactory: options.useFactory,
47
- inject: options.inject
48
- },
49
- ImplementInterceptor
50
- ],
51
- exports: [ORPC_MODULE_CONFIG_SYMBOL, ImplementInterceptor],
52
- global: true
53
- };
54
- }
55
- };
56
- ORPCModule = __decorateClass$1([
57
- Module({})
58
- ], ORPCModule);
59
-
60
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
61
- var __decorateClass = (decorators, target, key, kind) => {
62
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
63
- for (var i = decorators.length - 1, decorator; i >= 0; i--)
64
- if (decorator = decorators[i])
65
- result = (decorator(result)) || result;
66
- return result;
67
- };
68
- var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
69
- const QueryMethod = NestCommon.QueryMethod;
70
- const MethodDecoratorMap = {
71
- HEAD: Head,
72
- GET: Get,
73
- POST: Post,
74
- PUT: Put,
75
- PATCH: Patch,
76
- DELETE: Delete,
77
- OPTIONS: Options
78
- };
79
- function Implement(contract) {
80
- if (contract instanceof ProcedureContract) {
81
- return (target, propertyKey, descriptor) => {
82
- applyDecorators(
83
- toNestRouteDecorator(contract),
84
- UseInterceptors(ImplementInterceptor)
85
- )(target, propertyKey, descriptor);
86
- };
87
- }
88
- return (target, propertyKey, descriptor) => {
89
- UseInterceptors(ImplementInterceptor)(target, propertyKey, descriptor);
90
- implementRouterContract(contract, target, propertyKey, descriptor);
91
- };
92
- }
93
- function toNestRouteDecorator(contract) {
94
- const meta = getOpenAPIMeta(contract);
95
- if (meta?.path === void 0) {
96
- throw new TypeError(`
97
- @Implement decorator requires contract to have a 'openapi.path' meta.
98
- Please define one using '.meta(openapi({ path: '/example' }))'.
99
- Or use "populateRouterContractOpenAPIPaths" from "@orpc/openapi" utility to automatically fill in any missing paths.
100
- `);
101
- }
102
- const method = meta.method ?? DEFAULT_OPENAPI_METHOD;
103
- const path = toNestPattern(meta.prefix ? mergeHttpPath(meta.prefix, meta.path) : meta.path);
104
- const successStatus = meta.successStatus ?? DEFAULT_SUCCESS_STATUS;
105
- if (method === "QUERY") {
106
- if (!QueryMethod) {
107
- throw new TypeError(`
108
- @Implement decorator does not support the 'QUERY' HTTP method because the installed version of NestJS does not support it.
109
- The 'QUERY' HTTP method requires NestJS v11.2 or later. Alternatively, use 'GET' method.
110
- `);
111
- }
112
- return applyDecorators(
113
- QueryMethod(path),
114
- HttpCode(successStatus)
115
- );
116
- }
117
- return applyDecorators(
118
- MethodDecoratorMap[method](path),
119
- HttpCode(successStatus)
120
- );
121
- }
122
- function implementRouterContract(contract, target, propertyKey, descriptor) {
123
- for (const [key, childContract] of Object.entries(contract)) {
124
- let methodName = `${propertyKey}_${key}`;
125
- let i = 0;
126
- while (methodName in target) {
127
- methodName = `${propertyKey}_${key}_${i++}`;
128
- }
129
- target[methodName] = async function(...args) {
130
- const router = await descriptor.value.apply(this, args);
131
- return getRouter(router, [key]);
132
- };
133
- Object.setPrototypeOf(target[methodName], descriptor.value);
134
- queueMicrotask(() => {
135
- for (const p of Reflect.getOwnMetadataKeys(target, propertyKey)) {
136
- Reflect.defineMetadata(p, Reflect.getOwnMetadata(p, target, propertyKey), target, methodName);
137
- }
138
- for (const p of Reflect.getOwnMetadataKeys(target.constructor, propertyKey)) {
139
- Reflect.defineMetadata(p, Reflect.getOwnMetadata(p, target.constructor, propertyKey), target.constructor, methodName);
140
- }
141
- });
142
- const childDescriptor = Object.getOwnPropertyDescriptor(target, methodName);
143
- if (childContract instanceof ProcedureContract) {
144
- const routeDecorator = toNestRouteDecorator(childContract);
145
- queueMicrotask(() => {
146
- routeDecorator(target, methodName, childDescriptor);
147
- });
148
- } else {
149
- implementRouterContract(childContract, target, methodName, childDescriptor);
150
- }
151
- }
152
- }
153
- let ImplementInterceptor = class {
154
- config;
155
- codec;
156
- handler;
157
- toNestStandardLazyRequest;
158
- httpAdapterHost;
159
- constructor(config, httpAdapterHost) {
160
- this.config = config ?? {};
161
- this.httpAdapterHost = httpAdapterHost;
162
- this.codec = new NestHandlerCodec(this.config);
163
- this.handler = new StandardHandler(this.codec, this.config);
164
- this.toNestStandardLazyRequest = this.config.toNestStandardLazyRequest ?? ((req, res) => {
165
- const standardRequest = toStandardLazyRequest(
166
- "raw" in req ? req.raw : req,
167
- "raw" in res ? res.raw : res
168
- );
169
- if (req.body !== void 0) {
170
- standardRequest.resolveBody = () => Promise.resolve(req.body);
171
- }
172
- standardRequest.params = req.params;
173
- return standardRequest;
174
- });
175
- }
176
- intercept(ctx, next) {
177
- return next.handle().pipe(
178
- mergeMap(async (impl) => {
179
- const { default: procedure } = await unlazy(impl);
180
- if (!(procedure instanceof Procedure)) {
181
- throw new TypeError(`
182
- The return value of the @Implement controller handler must be a corresponding implemented router or procedure.
183
- `);
184
- }
185
- const req = ctx.switchToHttp().getRequest();
186
- const res = ctx.switchToHttp().getResponse();
187
- const standardRequest = this.toNestStandardLazyRequest(req, res);
188
- const context = await value(this.config.context ?? {}, ctx);
189
- const result = await this.handler.handle(standardRequest, {
190
- context: this.codec.withMatch(context, { procedure, params: standardRequest.params })
191
- });
192
- if (!result.matched) {
193
- throw new TypeError(
194
- "oRPC NestJS handler returned an unmatched result, which should never happen. Please check your plugins/interceptors or report a bug."
195
- );
196
- }
197
- const [nestBody, headers] = toNestHttpBody(result.response, standardRequest.signal, this.config.toNestResponse);
198
- const httpAdapter = this.httpAdapterHost.httpAdapter;
199
- httpAdapter.status(res, result.response.status);
200
- for (const key of Object.keys(headers)) {
201
- toArray(headers[key]).forEach((value2, index) => {
202
- if (index === 0) {
203
- httpAdapter.setHeader(res, key, value2);
204
- } else {
205
- httpAdapter.appendHeader(res, key, value2);
206
- }
207
- });
208
- }
209
- if (nestBody instanceof HttpException) {
210
- throw nestBody;
211
- }
212
- return nestBody;
213
- })
214
- );
215
- }
216
- };
217
- ImplementInterceptor = __decorateClass([
218
- Injectable(),
219
- __decorateParam(0, Inject(ORPC_MODULE_CONFIG_SYMBOL)),
220
- __decorateParam(0, Optional()),
221
- __decorateParam(1, Inject(HttpAdapterHost))
222
- ], ImplementInterceptor);
223
- function toNestHttpBody(response, signal, options) {
224
- const { status, body } = response;
225
- const headers = { ...response.headers };
226
- if (body instanceof ReadableStream) {
227
- headers["standard-server"] ??= "octet-stream";
228
- headers["content-type"] ??= "application/octet-stream";
229
- return [toStreamableFile(Readable.fromWeb(body), headers, signal), headers];
230
- }
231
- if (body instanceof Blob) {
232
- headers["standard-server"] ??= "file";
233
- headers["content-type"] ??= body.type;
234
- headers["content-disposition"] ??= generateContentDisposition(body instanceof File ? body.name : "blob");
235
- if (Number.isFinite(body.size)) {
236
- headers["content-length"] = body.size.toString();
237
- }
238
- return [toStreamableFile(Readable.fromWeb(body.stream()), headers, signal), headers];
239
- }
240
- headers["standard-server"] = void 0;
241
- headers["content-length"] = void 0;
242
- if (body === void 0) {
243
- headers["standard-server"] = getRequiredStandardBodyHint("none", headers);
244
- return [void 0, headers];
245
- }
246
- if (body instanceof FormData) {
247
- const response2 = new Response(body);
248
- headers["content-type"] = response2.headers.get("content-type");
249
- return [toStreamableFile(Readable.fromWeb(response2.body), headers, signal), headers];
250
- }
251
- if (body instanceof URLSearchParams) {
252
- headers["content-type"] ??= "application/x-www-form-urlencoded";
253
- headers["standard-server"] = getRequiredStandardBodyHint("url-search-params", headers);
254
- return [body.toString(), headers];
255
- }
256
- if (isAsyncIteratorObject(body)) {
257
- headers["content-type"] ??= "text/event-stream";
258
- headers["standard-server"] = getRequiredStandardBodyHint("event-stream", headers);
259
- return [toStreamableFile(toEventStream(body, options?.eventStream), headers, signal), headers];
260
- }
261
- if (status >= 300 && typeof body === "object" && body !== null && !Array.isArray(body)) {
262
- if (headers["content-type"] !== void 0) {
263
- headers["standard-server"] = getRequiredStandardBodyHint("json", headers);
264
- }
265
- return [new HttpException(body, status), headers];
266
- }
267
- headers["content-type"] ??= "application/json";
268
- headers["standard-server"] = getRequiredStandardBodyHint("json", headers);
269
- return [typeof body === "string" || body === null || headers["standard-server"] !== void 0 ? stringifyJSON(body) : body, headers];
270
- }
271
- class NestHandlerCodec extends OpenAPIHandlerCodecCore {
272
- CONTEXT_SYMBOL = Symbol("ORPC_NEST_HANDLER_CODEC_CONTEXT");
273
- withMatch(context, match) {
274
- return { ...context, [this.CONTEXT_SYMBOL]: match };
275
- }
276
- resolveProcedure(request, options) {
277
- const match = options.context[this.CONTEXT_SYMBOL];
278
- if (!match) {
279
- return void 0;
280
- }
281
- const { procedure, params } = match;
282
- return {
283
- path: getPathMeta(procedure) ?? [],
284
- procedure,
285
- decodeInput: () => this.decodeInput({
286
- procedure,
287
- params: toORPCOpenAPIParams(procedure, params)
288
- }, request)
289
- };
290
- }
291
- }
292
- function toStreamableFile(stream, headers, signal) {
293
- const type = flattenStandardHeader(headers["content-type"]);
294
- headers["content-type"] = void 0;
295
- if (signal?.aborted) {
296
- stream.destroy();
297
- } else {
298
- signal?.addEventListener("abort", () => stream.destroy(), { once: true });
299
- }
300
- return new StreamableFile(stream, { type });
301
- }
302
- function flattenParamValue(value2) {
303
- return Array.isArray(value2) ? value2.join("/") : value2;
304
- }
305
- function toORPCOpenAPIParams(contract, params) {
306
- const meta = getOpenAPIMeta(contract);
307
- if (!params || meta?.path === void 0 || Object.keys(params).length === 0) {
308
- return void 0;
309
- }
310
- const orpcParams = new NullProtoObj();
311
- const restKey = Object.hasOwn(params, "*") ? "*" : "path";
312
- for (const [key, value2] of Object.entries(params)) {
313
- if (key === restKey) {
314
- const restParams = getDynamicPathParams(
315
- meta.prefix ? mergeHttpPath(meta.prefix, meta.path) : meta.path
316
- )?.filter((c) => c.allowsSlash);
317
- if (restParams?.length) {
318
- for (const c of restParams) {
319
- orpcParams[c.parameterName] = flattenParamValue(value2);
320
- }
321
- continue;
322
- }
323
- }
324
- orpcParams[key] = flattenParamValue(value2);
325
- }
326
- return orpcParams;
327
- }
328
- function toNestPattern(path) {
329
- const params = getDynamicPathParams(path);
330
- if (!params?.length) {
331
- return path;
332
- }
333
- for (let i = params.length - 1; i >= 0; i--) {
334
- const param = params[i];
335
- const pattern = param.allowsSlash ? `*` : `:${param.parameterName}`;
336
- path = path.slice(0, param.startIndex) + pattern + path.slice(param.startIndex + param.segment.length);
337
- }
338
- return path;
339
- }
340
-
341
- export { Implement as Impl, Implement, ImplementInterceptor, ORPCModule, ORPC_MODULE_CONFIG_SYMBOL };
5
+ Implement as Impl } from "./implement.mjs";
6
+ export * from "./module.mjs";
@@ -0,0 +1,47 @@
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";
8
+ /**
9
+ * A standard lazy request extended with NestJS route parameters,
10
+ * used as the request representation inside the `@orpc/nest` integration.
11
+ *
12
+ * @see {@link https://orpc.dev/docs/integrations/nest#toneststandardlazyrequest-option | Implement oRPC contract with NestJS - toNestStandardLazyRequest option}
13
+ */
14
+ export interface NestStandardLazyRequest extends StandardLazyRequest {
15
+ /**
16
+ * Route parameters extracted from the request path.
17
+ */
18
+ params?: Record<string, string | string[]> | undefined;
19
+ }
20
+ export type ORPCModuleConfig = OpenAPIHandlerCodecCoreOptions<DefaultInitialContext> & StandardHandlerOptions<DefaultInitialContext> & (object extends DefaultInitialContext ? {
21
+ context?: Value<Promisable<DefaultInitialContext>, [ctx: ExecutionContext]> | undefined;
22
+ } : {
23
+ context: Value<Promisable<DefaultInitialContext>, [ctx: ExecutionContext]>;
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?: {
34
+ /**
35
+ * Options for the event stream, like keep-alive settings, initial comment, etc.
36
+ */
37
+ eventStream?: ToEventStreamOptions | undefined;
38
+ } | undefined;
39
+ };
40
+ export declare class ORPCModule {
41
+ static forRoot(config: ORPCModuleConfig): DynamicModule;
42
+ static forRootAsync(options: {
43
+ imports?: any[] | undefined;
44
+ useFactory: (...args: any[]) => Promise<ORPCModuleConfig> | ORPCModuleConfig;
45
+ inject?: any[] | undefined;
46
+ }): DynamicModule;
47
+ }
@@ -0,0 +1,33 @@
1
+ import { Module } from "@nestjs/common";
2
+ import { ORPC_MODULE_CONFIG_SYMBOL } from "./constants.mjs";
3
+ import { ImplementInterceptor } from "./implement.mjs";
4
+ import _decorate from "@oxc-project/runtime/helpers/decorate";
5
+ var _ORPCModule;
6
+ let ORPCModule = _ORPCModule = class ORPCModule {
7
+ static forRoot(config) {
8
+ return {
9
+ module: _ORPCModule,
10
+ providers: [{
11
+ provide: ORPC_MODULE_CONFIG_SYMBOL,
12
+ useValue: config
13
+ }, ImplementInterceptor],
14
+ exports: [ORPC_MODULE_CONFIG_SYMBOL, ImplementInterceptor],
15
+ global: true
16
+ };
17
+ }
18
+ static forRootAsync(options) {
19
+ return {
20
+ module: _ORPCModule,
21
+ imports: options.imports,
22
+ providers: [{
23
+ provide: ORPC_MODULE_CONFIG_SYMBOL,
24
+ useFactory: options.useFactory,
25
+ inject: options.inject
26
+ }, ImplementInterceptor],
27
+ exports: [ORPC_MODULE_CONFIG_SYMBOL, ImplementInterceptor],
28
+ global: true
29
+ };
30
+ }
31
+ };
32
+ ORPCModule = _ORPCModule = _decorate([Module({})], ORPCModule);
33
+ export { ORPCModule };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@orpc/nest",
3
3
  "type": "module",
4
- "version": "2.0.0-beta.47",
4
+ "version": "2.0.0-beta.48",
5
5
  "description": "NestJS integration for oRPC: implement typesafe contracts in NestJS controllers",
6
6
  "license": "MIT",
7
7
  "funding": [
@@ -39,11 +39,15 @@
39
39
  "peerDependencies": {
40
40
  "@nestjs/common": ">=11.1.27",
41
41
  "@nestjs/core": ">=11.1.27",
42
+ "@nestjs/platform-node": ">=12.3.0",
42
43
  "express": ">=5.2.1",
43
44
  "fastify": ">=5.8.5",
44
45
  "rxjs": ">=7.8.2"
45
46
  },
46
47
  "peerDependenciesMeta": {
48
+ "@nestjs/platform-node": {
49
+ "optional": true
50
+ },
47
51
  "express": {
48
52
  "optional": true
49
53
  },
@@ -52,21 +56,23 @@
52
56
  }
53
57
  },
54
58
  "dependencies": {
55
- "@orpc/client": "2.0.0-beta.47",
56
- "@orpc/contract": "2.0.0-beta.47",
57
- "@orpc/openapi": "2.0.0-beta.47",
58
- "@orpc/server": "2.0.0-beta.47",
59
- "@orpc/shared": "2.0.0-beta.47",
60
- "@standard-server/core": "~0.13.0",
61
- "@standard-server/node": "~0.13.0"
59
+ "@orpc/client": "2.0.0-beta.48",
60
+ "@orpc/contract": "2.0.0-beta.48",
61
+ "@orpc/openapi": "2.0.0-beta.48",
62
+ "@orpc/server": "2.0.0-beta.48",
63
+ "@orpc/shared": "2.0.0-beta.48",
64
+ "@oxc-project/runtime": "^0.155.0",
65
+ "@standard-server/core": "~0.14.0",
66
+ "@standard-server/node": "~0.14.0"
62
67
  },
63
68
  "devDependencies": {
64
- "@fastify/cookie": "^11.1.3",
65
- "@nestjs/common": "^12.1.3",
66
- "@nestjs/core": "^12.1.3",
67
- "@nestjs/platform-express": "^12.1.3",
68
- "@nestjs/platform-fastify": "^12.1.3",
69
- "@nestjs/testing": "^12.1.3",
69
+ "@fastify/cookie": "^11.1.5",
70
+ "@nestjs/common": "^12.3.2",
71
+ "@nestjs/core": "^12.3.2",
72
+ "@nestjs/platform-express": "^12.3.2",
73
+ "@nestjs/platform-fastify": "^12.3.2",
74
+ "@nestjs/platform-node": "^12.3.2",
75
+ "@nestjs/testing": "^12.3.2",
70
76
  "@types/express": "^5.0.6",
71
77
  "express": "^5.3.0",
72
78
  "fastify": "^5.12.7",
package/dist/index.d.ts DELETED
@@ -1,85 +0,0 @@
1
- import { ExecutionContext, DynamicModule, NestInterceptor, CallHandler } from '@nestjs/common';
2
- import { RouterContract } from '@orpc/contract';
3
- import { DefaultInitialContext, ContractedRouter } from '@orpc/server';
4
- import { Value, Promisable } from '@orpc/shared';
5
- import { Observable } from 'rxjs';
6
- import { OpenAPIHandlerCodecCoreOptions } from '@orpc/openapi/standard';
7
- import { StandardHandlerOptions } from '@orpc/server/standard';
8
- import { StandardLazyRequest } from '@standard-server/core';
9
- import { ToEventStreamOptions } from '@standard-server/node';
10
- import { HttpAdapterHost } from '@nestjs/core';
11
-
12
- declare const ORPC_MODULE_CONFIG_SYMBOL: unique symbol;
13
- /**
14
- * A standard lazy request extended with NestJS route parameters,
15
- * used as the request representation inside the `@orpc/nest` integration.
16
- *
17
- * @see {@link https://orpc.dev/docs/integrations/nest#toneststandardlazyrequest-option | Implement oRPC contract with NestJS - toNestStandardLazyRequest option}
18
- */
19
- interface NestStandardLazyRequest extends StandardLazyRequest {
20
- /**
21
- * Route parameters extracted from the request path.
22
- */
23
- params?: Record<string, string | string[]> | undefined;
24
- }
25
- type ORPCModuleConfig = OpenAPIHandlerCodecCoreOptions<DefaultInitialContext> & StandardHandlerOptions<DefaultInitialContext> & (object extends DefaultInitialContext ? {
26
- context?: Value<Promisable<DefaultInitialContext>, [ctx: ExecutionContext]> | undefined;
27
- } : {
28
- context: Value<Promisable<DefaultInitialContext>, [ctx: ExecutionContext]>;
29
- }) & {
30
- /**
31
- * Customize how to convert NestJS `req` and `res` to {@link NestStandardLazyRequest}.
32
- * You might need to define this if you are not using express or fastify adapters.
33
- */
34
- toNestStandardLazyRequest?: ((req: any, res: any) => NestStandardLazyRequest) | undefined;
35
- /**
36
- * Options for how to convert the Standard Response to a Nest Response (returning value), like event stream options, etc.
37
- */
38
- toNestResponse?: {
39
- /**
40
- * Options for the event stream, like keep-alive settings, initial comment, etc.
41
- */
42
- eventStream?: ToEventStreamOptions | undefined;
43
- } | undefined;
44
- };
45
- /**
46
- * NestJS module that configures the `@orpc/nest` integration via `forRoot`
47
- * or `forRootAsync`, providing options such as initial context, plugins,
48
- * and interceptors to `@Implement` handlers.
49
- *
50
- * @see {@link https://orpc.dev/docs/integrations/nest#configuration | Implement oRPC contract with NestJS - Configuration}
51
- */
52
- declare class ORPCModule {
53
- static forRoot(config: ORPCModuleConfig): DynamicModule;
54
- static forRootAsync(options: {
55
- imports?: any[] | undefined;
56
- useFactory: (...args: any[]) => Promise<ORPCModuleConfig> | ORPCModuleConfig;
57
- inject?: any[] | undefined;
58
- }): DynamicModule;
59
- }
60
-
61
- /**
62
- * Decorator that implements an oRPC contract (procedure or router contract)
63
- * on a NestJS controller method. It registers the corresponding NestJS routes
64
- * and handles request decoding and response encoding for you.
65
- *
66
- * @remarks
67
- * **Note**: Every procedure contract must define an `openapi.path` meta;
68
- * use `populateRouterContractOpenAPIPaths` from `@orpc/openapi` to fill in missing paths.
69
- * **Note**: The HTTP `QUERY` method requires NestJS v11.2+ (`QueryMethod`). Older NestJS versions throw; use `GET` instead.
70
- *
71
- * @see {@link https://orpc.dev/docs/integrations/nest#implement-your-contract | Implement oRPC contract with NestJS - Implement Your Contract}
72
- */
73
- 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;
74
- declare class ImplementInterceptor implements NestInterceptor {
75
- private readonly config;
76
- private readonly codec;
77
- private readonly handler;
78
- private readonly toNestStandardLazyRequest;
79
- private readonly httpAdapterHost;
80
- constructor(config: ORPCModuleConfig | undefined, httpAdapterHost: HttpAdapterHost);
81
- intercept(ctx: ExecutionContext, next: CallHandler<any>): Observable<any>;
82
- }
83
-
84
- export { Implement as Impl, Implement, ImplementInterceptor, ORPCModule, ORPC_MODULE_CONFIG_SYMBOL };
85
- export type { NestStandardLazyRequest, ORPCModuleConfig };