@orpc/server 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.
Files changed (139) hide show
  1. package/dist/adapters/aws-lambda/handler.d.ts +17 -15
  2. package/dist/adapters/aws-lambda/handler.js +23 -23
  3. package/dist/adapters/aws-lambda/index.d.ts +4 -16
  4. package/dist/adapters/aws-lambda/index.js +2 -2
  5. package/dist/adapters/aws-lambda/rpc-handler.d.ts +9 -9
  6. package/dist/adapters/aws-lambda/rpc-handler.js +20 -17
  7. package/dist/adapters/crossws/handler.d.ts +44 -42
  8. package/dist/adapters/crossws/handler.js +53 -60
  9. package/dist/adapters/crossws/index.d.ts +3 -2
  10. package/dist/adapters/crossws/index.js +2 -2
  11. package/dist/adapters/crossws/rpc-handler.d.ts +10 -10
  12. package/dist/adapters/crossws/rpc-handler.js +17 -14
  13. package/dist/adapters/fastify/handler.d.ts +17 -15
  14. package/dist/adapters/fastify/handler.js +20 -20
  15. package/dist/adapters/fastify/index.d.ts +3 -2
  16. package/dist/adapters/fastify/index.js +2 -2
  17. package/dist/adapters/fastify/rpc-handler.d.ts +9 -9
  18. package/dist/adapters/fastify/rpc-handler.js +16 -13
  19. package/dist/adapters/fetch/handler.d.ts +19 -17
  20. package/dist/adapters/fetch/handler.js +22 -22
  21. package/dist/adapters/fetch/index.d.ts +4 -7
  22. package/dist/adapters/fetch/index.js +3 -7
  23. package/dist/adapters/fetch/rpc-handler.d.ts +9 -9
  24. package/dist/adapters/fetch/rpc-handler.js +18 -15
  25. package/dist/adapters/message-port/handler.d.ts +58 -60
  26. package/dist/adapters/message-port/handler.js +72 -86
  27. package/dist/adapters/message-port/index.d.ts +3 -2
  28. package/dist/adapters/message-port/index.js +2 -2
  29. package/dist/adapters/message-port/rpc-handler.d.ts +9 -9
  30. package/dist/adapters/message-port/rpc-handler.js +17 -14
  31. package/dist/adapters/node/handler.d.ts +17 -15
  32. package/dist/adapters/node/handler.js +20 -20
  33. package/dist/adapters/node/index.d.ts +4 -7
  34. package/dist/adapters/node/index.js +3 -7
  35. package/dist/adapters/node/rpc-handler.d.ts +9 -9
  36. package/dist/adapters/node/rpc-handler.js +17 -14
  37. package/dist/adapters/standard/codec.d.ts +13 -13
  38. package/dist/adapters/standard/handler.d.ts +49 -49
  39. package/dist/adapters/standard/handler.js +205 -205
  40. package/dist/adapters/standard/index.d.ts +7 -6
  41. package/dist/adapters/standard/index.js +4 -5
  42. package/dist/adapters/standard/plugin.d.ts +25 -31
  43. package/dist/adapters/standard/plugin.js +14 -16
  44. package/dist/adapters/standard/rpc-handler-codec.d.ts +39 -43
  45. package/dist/adapters/standard/rpc-handler-codec.js +50 -51
  46. package/dist/adapters/standard/rpc-matcher.d.ts +40 -40
  47. package/dist/adapters/standard/rpc-matcher.js +103 -149
  48. package/dist/adapters/standard/utils.d.ts +8 -8
  49. package/dist/adapters/standard/utils.js +7 -5
  50. package/dist/adapters/standard-peer/index.d.ts +2 -1
  51. package/dist/adapters/standard-peer/index.js +1 -1
  52. package/dist/adapters/standard-peer/utils.d.ts +6 -4
  53. package/dist/adapters/standard-peer/utils.js +12 -6
  54. package/dist/adapters/websocket/handler.d.ts +52 -50
  55. package/dist/adapters/websocket/handler.js +75 -85
  56. package/dist/adapters/websocket/index.d.ts +3 -2
  57. package/dist/adapters/websocket/index.js +2 -2
  58. package/dist/adapters/websocket/rpc-handler.d.ts +9 -9
  59. package/dist/adapters/websocket/rpc-handler.js +17 -14
  60. package/dist/builder-variants.d.ts +195 -195
  61. package/dist/builder.d.ts +103 -104
  62. package/dist/builder.js +198 -224
  63. package/dist/constants.d.ts +1 -1
  64. package/dist/constants.js +4 -2
  65. package/dist/context.d.ts +3 -3
  66. package/dist/extensions/callable.d.ts +11 -11
  67. package/dist/extensions/callable.js +6 -5
  68. package/dist/helpers/base64url.d.ts +1 -1
  69. package/dist/helpers/base64url.js +44 -49
  70. package/dist/helpers/cookie.d.ts +10 -11
  71. package/dist/helpers/cookie.js +56 -63
  72. package/dist/helpers/encryption.d.ts +1 -1
  73. package/dist/helpers/encryption.js +80 -70
  74. package/dist/helpers/index.d.ts +5 -4
  75. package/dist/helpers/index.js +4 -4
  76. package/dist/helpers/signing.d.ts +1 -1
  77. package/dist/helpers/signing.js +72 -82
  78. package/dist/implementer-procedure.d.ts +12 -13
  79. package/dist/implementer-procedure.js +37 -44
  80. package/dist/implementer-router.d.ts +30 -36
  81. package/dist/implementer-router.js +92 -111
  82. package/dist/implementer.d.ts +8 -8
  83. package/dist/implementer.js +28 -35
  84. package/dist/index.d.ts +22 -61
  85. package/dist/index.js +16 -48
  86. package/dist/lazy.d.ts +14 -14
  87. package/dist/lazy.js +19 -30
  88. package/dist/middleware-decorated.d.ts +8 -9
  89. package/dist/middleware-decorated.js +66 -70
  90. package/dist/middleware.d.ts +34 -34
  91. package/dist/plugins/batch.d.ts +75 -75
  92. package/dist/plugins/batch.js +345 -379
  93. package/dist/plugins/cors.d.ts +60 -64
  94. package/dist/plugins/cors.js +118 -111
  95. package/dist/plugins/get-method-csrf-protection.d.ts +8 -6
  96. package/dist/plugins/get-method-csrf-protection.js +47 -63
  97. package/dist/plugins/head-method.d.ts +11 -9
  98. package/dist/plugins/head-method.js +97 -94
  99. package/dist/plugins/index.d.ts +15 -39
  100. package/dist/plugins/index.js +14 -29
  101. package/dist/plugins/method-override.d.ts +30 -28
  102. package/dist/plugins/method-override.js +53 -49
  103. package/dist/plugins/request-compression.d.ts +11 -9
  104. package/dist/plugins/request-compression.js +52 -79
  105. package/dist/plugins/request-headers.d.ts +10 -8
  106. package/dist/plugins/request-headers.js +27 -29
  107. package/dist/plugins/request-limit.d.ts +21 -19
  108. package/dist/plugins/request-limit.js +60 -67
  109. package/dist/plugins/response-compression.d.ts +42 -39
  110. package/dist/plugins/response-compression.js +150 -202
  111. package/dist/plugins/response-headers.d.ts +15 -13
  112. package/dist/plugins/response-headers.js +43 -46
  113. package/dist/plugins/rethrow.d.ts +25 -23
  114. package/dist/plugins/rethrow.js +46 -58
  115. package/dist/plugins/signal-sync.d.ts +7 -5
  116. package/dist/plugins/signal-sync.js +71 -86
  117. package/dist/plugins/timeout.d.ts +29 -27
  118. package/dist/plugins/timeout.js +61 -58
  119. package/dist/procedure-client.d.ts +14 -15
  120. package/dist/procedure-client.js +149 -166
  121. package/dist/procedure-decorated.d.ts +9 -9
  122. package/dist/procedure-decorated.js +36 -44
  123. package/dist/procedure-utils.d.ts +10 -30
  124. package/dist/procedure-utils.js +39 -40
  125. package/dist/procedure.d.ts +60 -60
  126. package/dist/procedure.js +18 -24
  127. package/dist/router-client.d.ts +9 -11
  128. package/dist/router-client.js +33 -41
  129. package/dist/router-hidden.js +10 -12
  130. package/dist/router-utils.d.ts +13 -30
  131. package/dist/router-utils.js +146 -191
  132. package/dist/router.d.ts +12 -26
  133. package/package.json +10 -10
  134. package/dist/adapters/standard/codec.js +0 -1
  135. package/dist/builder-variants.js +0 -1
  136. package/dist/context.js +0 -1
  137. package/dist/middleware.js +0 -1
  138. package/dist/router-hidden.d.ts +0 -5
  139. package/dist/router.js +0 -1
@@ -1,175 +1,158 @@
1
- import { ORPCError, wrapAsyncIteratorPreservingEventMeta } from '@orpc/client';
2
- import { createORPCErrorConstructorMap, reconcileORPCError, ValidationError } from '@orpc/contract';
3
- import { getTracer, intercept, isAsyncIteratorObject, mergeTwoLevels, override, resolveMaybeOptionalOptions, runWithSpan, toArray, traceAsyncIterator, traceReadableStream, value, } from '@orpc/shared';
4
- import { unlazy } from './lazy.js';
5
- export function createProcedureClient(lazyableProcedure, ...rest) {
6
- const options = resolveMaybeOptionalOptions(rest);
7
- return async (...[input, callerOptions]) => {
8
- const path = toArray(options.path);
9
- const { default: procedure } = await unlazy(lazyableProcedure);
10
- // callerOptions.context can be undefined when all field is optional
11
- const clientContext = callerOptions?.context ?? {};
12
- // options.context can be undefined when all field is optional
13
- const context = (await value(options.context, clientContext)) ??
14
- {};
15
- const errors = createORPCErrorConstructorMap(procedure['~orpc'].errorMap);
16
- const reconcileError = async (e) => {
17
- if (e instanceof ORPCError) {
18
- return await reconcileORPCError(procedure['~orpc'].errorMap, e);
19
- }
20
- return e;
21
- };
22
- try {
23
- const output = await runWithSpan('call_procedure', (span) => {
24
- span?.setAttribute('procedure.path', path);
25
- return intercept(options.interceptors, {
26
- context,
27
- // input can be optional if it is undefinable
28
- input: input,
29
- errors,
30
- path,
31
- procedure: procedure,
32
- signal: callerOptions?.signal,
33
- lastEventId: callerOptions?.lastEventId,
34
- }, (interceptorOptions) => executeProcedureInternal(interceptorOptions.procedure, interceptorOptions));
35
- });
36
- if (isAsyncIteratorObject(output)) {
37
- /**
38
- * traceAsyncIterator/wrapAsyncIteratorPreservingEventMeta return AsyncIteratorClass
39
- * which is backwards compatible with AsyncIteratorObject.
40
- *
41
- * @warning
42
- * If remove this return, can be breaking change
43
- * because AsyncIteratorClass convert `.throw` to `.return` (rarely used)
44
- *
45
- * @warning
46
- * Remember use `override` for AsyncIteratorObject to remain other special properties
47
- */
48
- return override(output, wrapAsyncIteratorPreservingEventMeta(getTracer()
49
- ? traceAsyncIterator('consume_async_iterator_object_output', output)
50
- : output, { mapError: reconcileError }));
51
- }
52
- else if (getTracer() && output instanceof ReadableStream) {
53
- /**
54
- * @warning
55
- * Remember use `override` for ReadableStream to remain other special properties
56
- */
57
- return override(output, traceReadableStream('consume_octet_stream_output', output));
58
- }
59
- return output;
60
- }
61
- catch (e) {
62
- throw await reconcileError(e);
63
- }
64
- };
1
+ import { unlazy } from "./lazy.js";
2
+ import { ValidationError, createORPCErrorConstructorMap, reconcileORPCError } from "@orpc/contract";
3
+ import { getTracer, intercept, isAsyncIteratorObject, mergeTwoLevels, override, resolveMaybeOptionalOptions, runWithSpan, toArray, traceAsyncIterator, traceReadableStream, value } from "@orpc/shared";
4
+ import { ORPCError, wrapAsyncIteratorPreservingEventMeta } from "@orpc/client";
5
+ // src/procedure-client.ts
6
+ function createProcedureClient(lazyableProcedure, ...rest) {
7
+ const options = resolveMaybeOptionalOptions(rest);
8
+ return async (...[input, callerOptions]) => {
9
+ const path = toArray(options.path);
10
+ const { default: procedure } = await unlazy(lazyableProcedure);
11
+ const clientContext = callerOptions?.context ?? {};
12
+ const context = await value(options.context, clientContext) ?? {};
13
+ const errors = createORPCErrorConstructorMap(procedure["~orpc"].errorMap);
14
+ const reconcileError = async (e) => {
15
+ if (e instanceof ORPCError) return await reconcileORPCError(procedure["~orpc"].errorMap, e);
16
+ return e;
17
+ };
18
+ try {
19
+ const output = await runWithSpan("call_procedure", (span) => {
20
+ span?.setAttribute("procedure.path", path);
21
+ return intercept(options.interceptors, {
22
+ context,
23
+ input,
24
+ errors,
25
+ path,
26
+ procedure,
27
+ signal: callerOptions?.signal,
28
+ lastEventId: callerOptions?.lastEventId
29
+ }, (interceptorOptions) => executeProcedureInternal(interceptorOptions.procedure, interceptorOptions));
30
+ });
31
+ if (isAsyncIteratorObject(output))
32
+ /**
33
+ * traceAsyncIterator/wrapAsyncIteratorPreservingEventMeta return AsyncIteratorClass
34
+ * which is backwards compatible with AsyncIteratorObject.
35
+ *
36
+ * @warning
37
+ * If remove this return, can be breaking change
38
+ * because AsyncIteratorClass convert `.throw` to `.return` (rarely used)
39
+ *
40
+ * @warning
41
+ * Remember use `override` for AsyncIteratorObject to remain other special properties
42
+ */
43
+ return override(output, wrapAsyncIteratorPreservingEventMeta(getTracer() ? traceAsyncIterator("consume_async_iterator_object_output", output) : output, { mapError: reconcileError }));
44
+ else if (getTracer() && output instanceof ReadableStream)
45
+ /**
46
+ * @warning
47
+ * Remember use `override` for ReadableStream to remain other special properties
48
+ */
49
+ return override(output, traceReadableStream("consume_octet_stream_output", output));
50
+ return output;
51
+ } catch (e) {
52
+ throw await reconcileError(e);
53
+ }
54
+ };
65
55
  }
66
56
  async function validateInput(i, schema, input) {
67
- return runWithSpan(`validate_input.${i}`, async (span) => {
68
- span?.setAttribute('input_schema.index', i);
69
- const result = await schema['~standard'].validate(input);
70
- if (result.issues) {
71
- throw new ORPCError('BAD_REQUEST', {
72
- message: 'Input validation failed',
73
- data: {
74
- issues: result.issues,
75
- },
76
- cause: new ValidationError({
77
- message: 'Input validation failed',
78
- issues: result.issues,
79
- invalidData: input,
80
- }),
81
- });
82
- }
83
- return result.value;
84
- });
57
+ return runWithSpan(`validate_input.${i}`, async (span) => {
58
+ span?.setAttribute("input_schema.index", i);
59
+ const result = await schema["~standard"].validate(input);
60
+ if (result.issues) throw new ORPCError("BAD_REQUEST", {
61
+ message: "Input validation failed",
62
+ data: { issues: result.issues },
63
+ cause: new ValidationError({
64
+ message: "Input validation failed",
65
+ issues: result.issues,
66
+ invalidData: input
67
+ })
68
+ });
69
+ return result.value;
70
+ });
85
71
  }
86
72
  async function validateOutput(i, schema, output) {
87
- return runWithSpan(`validate_output.${i}`, async (span) => {
88
- span?.setAttribute('output_schema.index', i);
89
- const result = await schema['~standard'].validate(output);
90
- if (result.issues) {
91
- throw new ORPCError('INTERNAL_SERVER_ERROR', {
92
- message: 'Output validation failed',
93
- cause: new ValidationError({
94
- message: 'Output validation failed',
95
- issues: result.issues,
96
- invalidData: output,
97
- }),
98
- });
99
- }
100
- return result.value;
101
- });
73
+ return runWithSpan(`validate_output.${i}`, async (span) => {
74
+ span?.setAttribute("output_schema.index", i);
75
+ const result = await schema["~standard"].validate(output);
76
+ if (result.issues) throw new ORPCError("INTERNAL_SERVER_ERROR", {
77
+ message: "Output validation failed",
78
+ cause: new ValidationError({
79
+ message: "Output validation failed",
80
+ issues: result.issues,
81
+ invalidData: output
82
+ })
83
+ });
84
+ return result.value;
85
+ });
102
86
  }
103
87
  const middlewareDone = (...rest) => {
104
- const options = resolveMaybeOptionalOptions(rest);
105
- return {
106
- output: options.output,
107
- // context can be undefined when all field is optional
108
- context: options.context ?? {},
109
- };
88
+ const options = resolveMaybeOptionalOptions(rest);
89
+ return {
90
+ output: options.output,
91
+ context: options.context ?? {}
92
+ };
110
93
  };
111
94
  async function executeProcedureInternal(procedure, options) {
112
- const inputSchemas = toArray(procedure['~orpc'].inputSchemas);
113
- const outputSchemas = toArray(procedure['~orpc'].outputSchemas);
114
- const orderedMiddlewares = procedure['~orpc'].orderedMiddlewares;
115
- const next = async (midIndex, context, input, signal) => {
116
- let currentInput = input;
117
- let middlewareInput = input;
118
- const startInputIndex = midIndex === 0 ? 0 : (orderedMiddlewares[midIndex - 1].inputSchemasLengthAtUse ?? 0);
119
- const endInputIndex = midIndex === orderedMiddlewares.length
120
- ? inputSchemas.length
121
- : (orderedMiddlewares[midIndex].inputSchemasLengthAtUse ?? 0);
122
- /**
123
- * Each schema after the first validates the original input with the results so far applied, then
124
- * its result is merged in, so no schema loses a field an earlier one stripped. Values that are not
125
- * plain objects stay piped, which keeps schemas like `asyncIteratorObject` wrapping each other.
126
- */
127
- if (!procedure['~orpc'].disableInputValidation) {
128
- for (let i = startInputIndex; i < endInputIndex; i++) {
129
- const validated = await validateInput(i, inputSchemas[i], i !== 0 ? mergeTwoLevels(options.input, currentInput) : currentInput);
130
- currentInput = i !== 0 ? mergeTwoLevels(currentInput, validated) : validated;
131
- }
132
- middlewareInput =
133
- endInputIndex > 0 && endInputIndex < inputSchemas.length
134
- ? mergeTwoLevels(options.input, currentInput)
135
- : currentInput;
136
- }
137
- let currentOutput;
138
- let currentContext = context;
139
- if (midIndex < orderedMiddlewares.length) {
140
- const { middleware } = orderedMiddlewares[midIndex];
141
- const result = await runWithSpan(`middleware.${middleware.name}`, async (span) => {
142
- span?.setAttribute('middleware.index', midIndex);
143
- return await middleware({
144
- ...options,
145
- context,
146
- signal,
147
- next: (...rest) => {
148
- const nextOptions = resolveMaybeOptionalOptions(rest);
149
- // context can be undefined when all field is optional
150
- const nextContext = nextOptions.context ?? {};
151
- return next(midIndex + 1, { ...context, ...nextContext }, currentInput, nextOptions.signal ?? signal);
152
- },
153
- lastEventId: options.lastEventId,
154
- }, middlewareInput, middlewareDone);
155
- });
156
- currentOutput = result.output;
157
- currentContext = { ...context, ...result.context };
158
- }
159
- else {
160
- currentOutput = await runWithSpan('handler', () => procedure['~orpc'].handler({ ...options, context, input: currentInput, signal }, currentInput));
161
- }
162
- const startOutputIndex = midIndex === 0 ? 0 : (orderedMiddlewares[midIndex - 1].outputSchemasLengthAtUse ?? 0);
163
- const endOutputIndex = midIndex === orderedMiddlewares.length
164
- ? outputSchemas.length
165
- : (orderedMiddlewares[midIndex].outputSchemasLengthAtUse ?? 0);
166
- if (!procedure['~orpc'].disableOutputValidation) {
167
- for (let i = endOutputIndex - 1; i >= startOutputIndex; i--) {
168
- currentOutput = await validateOutput(i, outputSchemas[i], currentOutput);
169
- }
170
- }
171
- return { output: currentOutput, context: currentContext };
172
- };
173
- const { output } = await next(0, options.context, options.input, options.signal);
174
- return output;
95
+ const inputSchemas = toArray(procedure["~orpc"].inputSchemas);
96
+ const outputSchemas = toArray(procedure["~orpc"].outputSchemas);
97
+ const orderedMiddlewares = procedure["~orpc"].orderedMiddlewares;
98
+ const next = async (midIndex, context, input, signal) => {
99
+ let currentInput = input;
100
+ let middlewareInput = input;
101
+ const startInputIndex = midIndex === 0 ? 0 : orderedMiddlewares[midIndex - 1].inputSchemasLengthAtUse ?? 0;
102
+ const endInputIndex = midIndex === orderedMiddlewares.length ? inputSchemas.length : orderedMiddlewares[midIndex].inputSchemasLengthAtUse ?? 0;
103
+ /**
104
+ * Each schema after the first validates the original input with the results so far applied, then
105
+ * its result is merged in, so no schema loses a field an earlier one stripped. Values that are not
106
+ * plain objects stay piped, which keeps schemas like `asyncIteratorObject` wrapping each other.
107
+ */
108
+ if (!procedure["~orpc"].disableInputValidation) {
109
+ for (let i = startInputIndex; i < endInputIndex; i++) {
110
+ const validated = await validateInput(i, inputSchemas[i], i !== 0 ? mergeTwoLevels(options.input, currentInput) : currentInput);
111
+ currentInput = i !== 0 ? mergeTwoLevels(currentInput, validated) : validated;
112
+ }
113
+ middlewareInput = endInputIndex > 0 && endInputIndex < inputSchemas.length ? mergeTwoLevels(options.input, currentInput) : currentInput;
114
+ }
115
+ let currentOutput;
116
+ let currentContext = context;
117
+ if (midIndex < orderedMiddlewares.length) {
118
+ const { middleware } = orderedMiddlewares[midIndex];
119
+ const result = await runWithSpan(`middleware.${middleware.name}`, async (span) => {
120
+ span?.setAttribute("middleware.index", midIndex);
121
+ return await middleware({
122
+ ...options,
123
+ context,
124
+ signal,
125
+ next: (...rest) => {
126
+ const nextOptions = resolveMaybeOptionalOptions(rest);
127
+ const nextContext = nextOptions.context ?? {};
128
+ return next(midIndex + 1, {
129
+ ...context,
130
+ ...nextContext
131
+ }, currentInput, nextOptions.signal ?? signal);
132
+ },
133
+ lastEventId: options.lastEventId
134
+ }, middlewareInput, middlewareDone);
135
+ });
136
+ currentOutput = result.output;
137
+ currentContext = {
138
+ ...context,
139
+ ...result.context
140
+ };
141
+ } else currentOutput = await runWithSpan("handler", () => procedure["~orpc"].handler({
142
+ ...options,
143
+ context,
144
+ input: currentInput,
145
+ signal
146
+ }, currentInput));
147
+ const startOutputIndex = midIndex === 0 ? 0 : orderedMiddlewares[midIndex - 1].outputSchemasLengthAtUse ?? 0;
148
+ const endOutputIndex = midIndex === orderedMiddlewares.length ? outputSchemas.length : orderedMiddlewares[midIndex].outputSchemasLengthAtUse ?? 0;
149
+ if (!procedure["~orpc"].disableOutputValidation) for (let i = endOutputIndex - 1; i >= startOutputIndex; i--) currentOutput = await validateOutput(i, outputSchemas[i], currentOutput);
150
+ return {
151
+ output: currentOutput,
152
+ context: currentContext
153
+ };
154
+ };
155
+ const { output } = await next(0, options.context, options.input, options.signal);
156
+ return output;
175
157
  }
158
+ export { createProcedureClient };
@@ -1,10 +1,10 @@
1
- import type { AnySchema, ErrorMap, InferSchemaInput, InferSchemaOutput, MergedErrorMap, MetaPlugin } from '@orpc/contract';
2
- import type { IntersectPick } from '@orpc/shared';
3
- import type { Context, MergedContext, MergedInitialContext } from './context.ts';
4
- import type { Middleware } from './middleware.ts';
5
- import { Procedure } from './procedure.ts';
1
+ import { Context, MergedContext, MergedInitialContext } from "./context.js";
2
+ import { Middleware } from "./middleware.js";
3
+ import { Procedure } from "./procedure.js";
4
+ import { AnySchema, ErrorMap, InferSchemaInput, InferSchemaOutput, MergedErrorMap, MetaPlugin } from "@orpc/contract";
5
+ import { IntersectPick } from "@orpc/shared";
6
6
  export declare class DecoratedProcedure<TInitialContext extends Context, TInjectedContext extends Context, TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> extends Procedure<TInitialContext, TInjectedContext, TInputSchema, TOutputSchema, TErrorMap> {
7
- meta(...plugins: MetaPlugin<TInputSchema, TOutputSchema, TErrorMap>[]): DecoratedProcedure<TInitialContext, TInjectedContext, TInputSchema, TOutputSchema, TErrorMap>;
8
- errors<T extends ErrorMap>(errors: T): DecoratedProcedure<TInitialContext, TInjectedContext, TInputSchema, TOutputSchema, MergedErrorMap<TErrorMap, T>>;
9
- use<$OutContext extends IntersectPick<MergedContext<TInitialContext, TInjectedContext>, $OutContext>, $InContext extends Context = MergedContext<TInitialContext, TInjectedContext>, $ErrorMap extends ErrorMap = TErrorMap>(middleware: Middleware<$InContext | MergedContext<TInitialContext, TInjectedContext>, $OutContext, InferSchemaOutput<TInputSchema>, InferSchemaInput<TOutputSchema>, $ErrorMap>): DecoratedProcedure<MergedInitialContext<TInitialContext, TInjectedContext, $InContext>, MergedContext<TInjectedContext, $OutContext>, TInputSchema, TOutputSchema, MergedErrorMap<$ErrorMap, TErrorMap>>;
10
- }
7
+ meta(...plugins: MetaPlugin<TInputSchema, TOutputSchema, TErrorMap>[]): DecoratedProcedure<TInitialContext, TInjectedContext, TInputSchema, TOutputSchema, TErrorMap>;
8
+ errors<T extends ErrorMap>(errors: T): DecoratedProcedure<TInitialContext, TInjectedContext, TInputSchema, TOutputSchema, MergedErrorMap<TErrorMap, T>>;
9
+ use<$OutContext extends IntersectPick<MergedContext<TInitialContext, TInjectedContext>, $OutContext>, $InContext extends Context = MergedContext<TInitialContext, TInjectedContext>, $ErrorMap extends ErrorMap = TErrorMap>(middleware: Middleware<$InContext | MergedContext<TInitialContext, TInjectedContext>, $OutContext, InferSchemaOutput<TInputSchema>, InferSchemaInput<TOutputSchema>, $ErrorMap>): DecoratedProcedure<MergedInitialContext<TInitialContext, TInjectedContext, $InContext>, MergedContext<TInjectedContext, $OutContext>, TInputSchema, TOutputSchema, MergedErrorMap<$ErrorMap, TErrorMap>>;
10
+ }
@@ -1,44 +1,36 @@
1
- import { getHiddenMetaPlugins, mergeErrorMap, resolveMetaPlugins } from '@orpc/contract';
2
- import { Procedure } from './procedure.js';
3
- export class DecoratedProcedure extends Procedure {
4
- meta(...plugins) {
5
- const [meta, metaPlugins] = resolveMetaPlugins(this['~orpc'].meta, this['~orpc'].metaPlugins, plugins);
6
- return new DecoratedProcedure({
7
- ...this['~orpc'],
8
- meta,
9
- metaPlugins,
10
- });
11
- }
12
- errors(errors) {
13
- let procedure = new DecoratedProcedure({
14
- ...this['~orpc'],
15
- errorMap: mergeErrorMap(this['~orpc'].errorMap, errors),
16
- });
17
- const plugins = getHiddenMetaPlugins(errors);
18
- if (plugins) {
19
- procedure = procedure.meta(...plugins);
20
- }
21
- return procedure;
22
- }
23
- use(middleware) {
24
- // Since middleware executes before the handler, we use `IntersectPick` to ensure
25
- // that the middleware's output context ($OutContext) is compatible with the
26
- // context requirements of the handler, which may have already been defined.
27
- let procedure = new DecoratedProcedure({
28
- ...this['~orpc'],
29
- errorMap: mergeErrorMap(middleware['~orpc']?.errorMap, this['~orpc'].errorMap),
30
- orderedMiddlewares: [
31
- ...this['~orpc'].orderedMiddlewares,
32
- {
33
- middleware,
34
- inputSchemasLengthAtUse: this['~orpc'].inputSchemas?.length,
35
- outputSchemasLengthAtUse: this['~orpc'].outputSchemas?.length,
36
- },
37
- ],
38
- });
39
- if (middleware['~orpc']?.metaPlugins) {
40
- procedure = procedure.meta(...middleware['~orpc']?.metaPlugins);
41
- }
42
- return procedure;
43
- }
44
- }
1
+ import { Procedure } from "./procedure.js";
2
+ import { getHiddenMetaPlugins, mergeErrorMap, resolveMetaPlugins } from "@orpc/contract";
3
+ // src/procedure-decorated.ts
4
+ var DecoratedProcedure = class DecoratedProcedure extends Procedure {
5
+ meta(...plugins) {
6
+ const [meta, metaPlugins] = resolveMetaPlugins(this["~orpc"].meta, this["~orpc"].metaPlugins, plugins);
7
+ return new DecoratedProcedure({
8
+ ...this["~orpc"],
9
+ meta,
10
+ metaPlugins
11
+ });
12
+ }
13
+ errors(errors) {
14
+ let procedure = new DecoratedProcedure({
15
+ ...this["~orpc"],
16
+ errorMap: mergeErrorMap(this["~orpc"].errorMap, errors)
17
+ });
18
+ const plugins = getHiddenMetaPlugins(errors);
19
+ if (plugins) procedure = procedure.meta(...plugins);
20
+ return procedure;
21
+ }
22
+ use(middleware) {
23
+ let procedure = new DecoratedProcedure({
24
+ ...this["~orpc"],
25
+ errorMap: mergeErrorMap(middleware["~orpc"]?.errorMap, this["~orpc"].errorMap),
26
+ orderedMiddlewares: [...this["~orpc"].orderedMiddlewares, {
27
+ middleware,
28
+ inputSchemasLengthAtUse: this["~orpc"].inputSchemas?.length,
29
+ outputSchemasLengthAtUse: this["~orpc"].outputSchemas?.length
30
+ }]
31
+ });
32
+ if (middleware["~orpc"]?.metaPlugins) procedure = procedure.meta(...middleware["~orpc"]?.metaPlugins);
33
+ return procedure;
34
+ }
35
+ };
36
+ export { DecoratedProcedure };
@@ -1,32 +1,12 @@
1
- import type { ClientOptions } from '@orpc/client';
2
- import type { AnySchema, ErrorMap, InferSchemaInput, InferSchemaOutput, ORPCErrorFromErrorMap, ProcedureContract } from '@orpc/contract';
3
- import type { PromiseWithError, ThrowableError } from '@orpc/shared';
4
- import type { Context } from './context.ts';
5
- import type { Lazyable } from './lazy.ts';
6
- import { Lazy } from './lazy.ts';
7
- import type { ProcedureClientOptions } from './procedure-client.ts';
8
- import type { AnyProcedure } from './procedure.ts';
9
- import { Procedure } from './procedure.ts';
10
- export declare function createGuardedProcedureLazy(lazy: Lazy<unknown>): Lazy<AnyProcedure>;
11
- /**
12
- * Create a new procedure that ensure the contract is applied to the procedure.
13
- *
14
- * .input/.output/.handler mismatches are already caught by the `implementer.router`,
15
- * but .errors (in case implemented procedure error map is more than enough) and .meta cannot be
16
- * validated that way - so they must be overridden here to ensure the client always sees what the contract defines.
17
- */
18
- export declare function createContractProcedure<TInitialContext extends Context, TInjectedContext extends Context, TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap>(procedure: Procedure<TInitialContext, TInjectedContext, TInputSchema, TOutputSchema, any>, contract: ProcedureContract<any, any, TErrorMap>): Procedure<TInitialContext, TInjectedContext, TInputSchema, TOutputSchema, TErrorMap>;
19
- export type CallOptions<TInitialContext extends Context, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> = ProcedureClientOptions<TInitialContext, TOutputSchema, TErrorMap, object> & Omit<ClientOptions<object>, 'context'>;
20
- export type CallRest<TInitialContext extends Context, TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> = object extends CallOptions<TInitialContext, TOutputSchema, TErrorMap> ? undefined extends InferSchemaInput<TInputSchema> ? [
21
- input?: InferSchemaInput<TInputSchema>,
22
- options?: CallOptions<TInitialContext, TOutputSchema, TErrorMap>
23
- ] : [
24
- input: InferSchemaInput<TInputSchema>,
25
- options?: CallOptions<TInitialContext, TOutputSchema, TErrorMap>
26
- ] : [
27
- input: InferSchemaInput<TInputSchema>,
28
- options: CallOptions<TInitialContext, TOutputSchema, TErrorMap>
29
- ];
1
+ import { Context } from "./context.js";
2
+ import { Lazyable } from "./lazy.js";
3
+ import { Procedure } from "./procedure.js";
4
+ import { ProcedureClientOptions } from "./procedure-client.js";
5
+ import { AnySchema, ErrorMap, InferSchemaInput, InferSchemaOutput, ORPCErrorFromErrorMap } from "@orpc/contract";
6
+ import { PromiseWithError, ThrowableError as ThrowableError$1 } from "@orpc/shared";
7
+ import { ClientOptions } from "@orpc/client";
8
+ export type CallOptions<TInitialContext extends Context, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> = ProcedureClientOptions<TInitialContext, TOutputSchema, TErrorMap, object> & Omit<ClientOptions<object>, "context">;
9
+ export type CallRest<TInitialContext extends Context, TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> = object extends CallOptions<TInitialContext, TOutputSchema, TErrorMap> ? undefined extends InferSchemaInput<TInputSchema> ? [input?: InferSchemaInput<TInputSchema>, options?: CallOptions<TInitialContext, TOutputSchema, TErrorMap>] : [input: InferSchemaInput<TInputSchema>, options?: CallOptions<TInitialContext, TOutputSchema, TErrorMap>] : [input: InferSchemaInput<TInputSchema>, options: CallOptions<TInitialContext, TOutputSchema, TErrorMap>];
30
10
  /**
31
11
  * Quickly call a procedure without creating a client.
32
12
  *
@@ -38,4 +18,4 @@ export type CallRest<TInitialContext extends Context, TInputSchema extends AnySc
38
18
  *
39
19
  * @see {@link https://orpc.dev/docs/client/server-side#one-off-calls | Server-Side Clients - One-Off Calls}
40
20
  */
41
- export declare function call<TInitialContext extends Context, TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap>(lazyableProcedure: Lazyable<Procedure<TInitialContext, any, TInputSchema, TOutputSchema, TErrorMap>>, ...[input, options,]: CallRest<TInitialContext, TInputSchema, TOutputSchema, TErrorMap>): PromiseWithError<InferSchemaOutput<TOutputSchema>, ORPCErrorFromErrorMap<TErrorMap> | ThrowableError>;
21
+ export declare function call<TInitialContext extends Context, TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap>(lazyableProcedure: Lazyable<Procedure<TInitialContext, any, TInputSchema, TOutputSchema, TErrorMap>>, ...[input, options]: CallRest<TInitialContext, TInputSchema, TOutputSchema, TErrorMap>): PromiseWithError<InferSchemaOutput<TOutputSchema>, ORPCErrorFromErrorMap<TErrorMap> | ThrowableError$1>;
@@ -1,49 +1,48 @@
1
- import { Lazy, unlazy } from './lazy.js';
2
- import { createProcedureClient } from './procedure-client.js';
3
- import { Procedure } from './procedure.js';
4
- export function createGuardedProcedureLazy(lazy) {
5
- const guarded = new Lazy({
6
- ...lazy['~orpc'],
7
- async loader() {
8
- const { default: maybeProcedure } = await unlazy(lazy);
9
- if (!(maybeProcedure instanceof Procedure)) {
10
- throw new TypeError(`
1
+ import { Lazy, unlazy } from "./lazy.js";
2
+ import { Procedure } from "./procedure.js";
3
+ import { createProcedureClient } from "./procedure-client.js";
4
+ // src/procedure-utils.ts
5
+ function createGuardedProcedureLazy(lazy) {
6
+ return new Lazy({
7
+ ...lazy["~orpc"],
8
+ async loader() {
9
+ const { default: maybeProcedure } = await unlazy(lazy);
10
+ if (!(maybeProcedure instanceof Procedure)) throw new TypeError(`
11
11
  Expected a lazy<procedure> but got lazy<unknown>.
12
12
  This should be caught by TypeScript compilation.
13
13
  Please report this issue if you think this is a bug.
14
14
  `);
15
- }
16
- return { default: maybeProcedure };
17
- },
18
- });
19
- return guarded;
15
+ return { default: maybeProcedure };
16
+ }
17
+ });
20
18
  }
21
19
  /**
22
- * Create a new procedure that ensure the contract is applied to the procedure.
23
- *
24
- * .input/.output/.handler mismatches are already caught by the `implementer.router`,
25
- * but .errors (in case implemented procedure error map is more than enough) and .meta cannot be
26
- * validated that way - so they must be overridden here to ensure the client always sees what the contract defines.
27
- */
28
- export function createContractProcedure(procedure, contract) {
29
- return new Procedure({
30
- ...procedure['~orpc'],
31
- errorMap: contract['~orpc'].errorMap,
32
- meta: contract['~orpc'].meta,
33
- metaPlugins: contract['~orpc'].metaPlugins,
34
- });
20
+ * Create a new procedure that ensure the contract is applied to the procedure.
21
+ *
22
+ * .input/.output/.handler mismatches are already caught by the `implementer.router`,
23
+ * but .errors (in case implemented procedure error map is more than enough) and .meta cannot be
24
+ * validated that way - so they must be overridden here to ensure the client always sees what the contract defines.
25
+ */
26
+ function createContractProcedure(procedure, contract) {
27
+ return new Procedure({
28
+ ...procedure["~orpc"],
29
+ errorMap: contract["~orpc"].errorMap,
30
+ meta: contract["~orpc"].meta,
31
+ metaPlugins: contract["~orpc"].metaPlugins
32
+ });
35
33
  }
36
34
  /**
37
- * Quickly call a procedure without creating a client.
38
- *
39
- * @example
40
- * ```ts
41
- * const output = await call(getting, 'input')
42
- * const output = await call(getting, 'input', { context: { db: 'postgres' } })
43
- * ```
44
- *
45
- * @see {@link https://orpc.dev/docs/client/server-side#one-off-calls | Server-Side Clients - One-Off Calls}
46
- */
47
- export function call(lazyableProcedure, ...[input = undefined, options = {},]) {
48
- return createProcedureClient(lazyableProcedure, options)(input, options);
35
+ * Quickly call a procedure without creating a client.
36
+ *
37
+ * @example
38
+ * ```ts
39
+ * const output = await call(getting, 'input')
40
+ * const output = await call(getting, 'input', { context: { db: 'postgres' } })
41
+ * ```
42
+ *
43
+ * @see {@link https://orpc.dev/docs/client/server-side#one-off-calls | Server-Side Clients - One-Off Calls}
44
+ */
45
+ function call(lazyableProcedure, ...[input = void 0, options = {}]) {
46
+ return createProcedureClient(lazyableProcedure, options)(input, options);
49
47
  }
48
+ export { call, createContractProcedure, createGuardedProcedureLazy };