@temporary-name/server 1.9.3-alpha.e2d8d164da72fb570c2b14a4fa956c80f9e33cdc → 1.9.3-alpha.edd373b82156a10608d43b19a44b75ae72e72de7

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 (44) hide show
  1. package/dist/adapters/aws-lambda/index.d.mts +4 -6
  2. package/dist/adapters/aws-lambda/index.d.ts +4 -6
  3. package/dist/adapters/aws-lambda/index.mjs +4 -4
  4. package/dist/adapters/fetch/index.d.mts +8 -86
  5. package/dist/adapters/fetch/index.d.ts +8 -86
  6. package/dist/adapters/fetch/index.mjs +16 -155
  7. package/dist/adapters/node/index.d.mts +8 -63
  8. package/dist/adapters/node/index.d.ts +8 -63
  9. package/dist/adapters/node/index.mjs +14 -120
  10. package/dist/adapters/standard/index.d.mts +10 -7
  11. package/dist/adapters/standard/index.d.ts +10 -7
  12. package/dist/adapters/standard/index.mjs +4 -4
  13. package/dist/helpers/index.mjs +3 -29
  14. package/dist/index.d.mts +376 -242
  15. package/dist/index.d.ts +376 -242
  16. package/dist/index.mjs +482 -359
  17. package/dist/openapi/index.d.mts +18 -53
  18. package/dist/openapi/index.d.ts +18 -53
  19. package/dist/openapi/index.mjs +337 -347
  20. package/dist/shared/server.BCY45g2x.mjs +160 -0
  21. package/dist/shared/server.BETu17rq.mjs +319 -0
  22. package/dist/shared/server.B_oW_rPl.mjs +525 -0
  23. package/dist/shared/server.C1RJffw4.mjs +30 -0
  24. package/dist/shared/server.CQIFwyhc.mjs +40 -0
  25. package/dist/shared/server.CjPiuQYH.d.mts +51 -0
  26. package/dist/shared/server.CjPiuQYH.d.ts +51 -0
  27. package/dist/shared/server.Cq7SBLD5.mjs +403 -0
  28. package/dist/shared/server.DGH2Bq4t.d.mts +41 -0
  29. package/dist/shared/server.nQoUObAJ.d.ts +41 -0
  30. package/dist/shared/server.zsKBRxsz.d.mts +388 -0
  31. package/dist/shared/server.zsKBRxsz.d.ts +388 -0
  32. package/package.json +10 -28
  33. package/dist/plugins/index.d.mts +0 -160
  34. package/dist/plugins/index.d.ts +0 -160
  35. package/dist/plugins/index.mjs +0 -288
  36. package/dist/shared/server.B93y_8tj.d.mts +0 -23
  37. package/dist/shared/server.BYYf0Wn6.mjs +0 -202
  38. package/dist/shared/server.C3RuMHWl.d.mts +0 -192
  39. package/dist/shared/server.C3RuMHWl.d.ts +0 -192
  40. package/dist/shared/server.CT1xhSmE.d.mts +0 -56
  41. package/dist/shared/server.CqTex_jI.mjs +0 -265
  42. package/dist/shared/server.D_fags8X.d.ts +0 -23
  43. package/dist/shared/server.Kxw442A9.mjs +0 -247
  44. package/dist/shared/server.cjcgLdr1.d.ts +0 -56
@@ -0,0 +1,160 @@
1
+ import { resolveMaybeOptionalOptions, toArray, value, runWithSpan, isAsyncIteratorObject, overlayProxy, asyncIteratorWithSpan, ORPCError } from '@temporary-name/shared';
2
+ import { HibernationEventIterator, mapEventIterator } from '@temporary-name/standard-server';
3
+ import { safeDecodeAsync, safeEncodeAsync } from '@temporary-name/zod';
4
+ import { u as unlazy, V as ValidationError } from './server.BETu17rq.mjs';
5
+
6
+ function mergeCurrentContext(context, other) {
7
+ return { ...context, ...other };
8
+ }
9
+
10
+ function middlewareOutputFn(output) {
11
+ return { output, context: {} };
12
+ }
13
+
14
+ function createProcedureClient(lazyableProcedure, ...rest) {
15
+ const options = resolveMaybeOptionalOptions(rest);
16
+ return async (...[input, callerOptions]) => {
17
+ const path = toArray(options.path);
18
+ const { default: procedure } = await unlazy(lazyableProcedure);
19
+ const clientContext = callerOptions?.context ?? {};
20
+ const context = await value(options.context ?? {}, clientContext);
21
+ const output = await runWithSpan({ name: "call_procedure", signal: callerOptions?.signal }, (span) => {
22
+ span?.setAttribute("procedure.path", [...path]);
23
+ return executeProcedureInternal(procedure, input, {
24
+ context,
25
+ path,
26
+ procedure,
27
+ request: callerOptions?.request,
28
+ signal: callerOptions?.signal,
29
+ lastEventId: callerOptions?.lastEventId
30
+ });
31
+ });
32
+ if (isAsyncIteratorObject(output)) {
33
+ if (output instanceof HibernationEventIterator) {
34
+ return output;
35
+ }
36
+ return overlayProxy(
37
+ output,
38
+ mapEventIterator(
39
+ asyncIteratorWithSpan(
40
+ { name: "consume_event_iterator_output", signal: callerOptions?.signal },
41
+ output
42
+ ),
43
+ {
44
+ value: (v) => v,
45
+ error: async (e) => e
46
+ }
47
+ )
48
+ );
49
+ }
50
+ return output;
51
+ };
52
+ }
53
+ async function validateInput(procedure, input) {
54
+ const schemas = procedure["~orpc"].schemas;
55
+ return runWithSpan({ name: "validate_input" }, async () => {
56
+ const resultBody = await safeDecodeAsync(schemas.bodySchema, input.body, { parseType: "body" });
57
+ const resultPath = await safeDecodeAsync(schemas.pathSchema, input.path, { parseType: "path" });
58
+ const resultQuery = await safeDecodeAsync(schemas.querySchema, input.query, { parseType: "query" });
59
+ const issues = [];
60
+ if (!resultBody.success) {
61
+ issues.push(...resultBody.error.issues.map((i) => ({ ...i, path: ["body", ...i.path] })));
62
+ }
63
+ if (!resultPath.success) {
64
+ issues.push(...resultPath.error.issues.map((i) => ({ ...i, path: ["path", ...i.path] })));
65
+ }
66
+ if (!resultQuery.success) {
67
+ issues.push(...resultQuery.error.issues.map((i) => ({ ...i, path: ["query", ...i.path] })));
68
+ }
69
+ if (issues.length > 0) {
70
+ throw new ORPCError("BAD_REQUEST", {
71
+ message: "Input validation failed",
72
+ data: {
73
+ issues
74
+ },
75
+ cause: new ValidationError({
76
+ message: "Input validation failed",
77
+ issues,
78
+ data: input
79
+ })
80
+ });
81
+ }
82
+ const results = {
83
+ body: resultBody.data,
84
+ path: resultPath.data,
85
+ query: resultQuery.data
86
+ };
87
+ return results;
88
+ });
89
+ }
90
+ async function validateOutput(procedure, output) {
91
+ const schema = procedure["~orpc"].schemas.outputSchema;
92
+ if (!schema) {
93
+ return output;
94
+ }
95
+ return runWithSpan({ name: "validate_output" }, async () => {
96
+ const result = await safeEncodeAsync(schema, output, { parseType: "output" });
97
+ if (!result.success) {
98
+ throw new ORPCError("INTERNAL_SERVER_ERROR", {
99
+ message: "Output validation failed",
100
+ cause: new ValidationError({
101
+ message: "Output validation failed",
102
+ issues: result.error.issues,
103
+ data: output
104
+ })
105
+ });
106
+ }
107
+ return result.data;
108
+ });
109
+ }
110
+ async function executeProcedureInternal(procedure, input, options) {
111
+ const middlewares = procedure["~orpc"].middlewares;
112
+ const inputValidationIndex = Math.min(
113
+ Math.max(0, procedure["~orpc"].inputValidationIndex),
114
+ middlewares.length
115
+ );
116
+ const outputValidationIndex = Math.min(
117
+ Math.max(0, procedure["~orpc"].outputValidationIndex),
118
+ middlewares.length
119
+ );
120
+ const next = async (index, context, input2) => {
121
+ let currentInput = input2;
122
+ if (index === inputValidationIndex) {
123
+ currentInput = await validateInput(procedure, currentInput);
124
+ }
125
+ const mid = middlewares[index];
126
+ const output = mid ? await runWithSpan({ name: `middleware.${mid.name}`, signal: options.signal }, async (span) => {
127
+ span?.setAttribute("middleware.index", index);
128
+ span?.setAttribute("middleware.name", mid.name);
129
+ const result = await mid(
130
+ {
131
+ ...options,
132
+ context,
133
+ next: async (nextOptions) => {
134
+ const nextContext = nextOptions?.context ?? {};
135
+ return {
136
+ output: await next(index + 1, mergeCurrentContext(context, nextContext), currentInput),
137
+ // NB: Pretty sure this isn't used (or meant to be used) at runtime, it's just there
138
+ // to get type inference in the builder (via the caller returning the output of next() in
139
+ // the middleware function)
140
+ context: nextContext
141
+ };
142
+ }
143
+ },
144
+ currentInput,
145
+ middlewareOutputFn
146
+ );
147
+ return result.output;
148
+ }) : await runWithSpan(
149
+ { name: "handler", signal: options.signal },
150
+ () => procedure["~orpc"].handler(currentInput, { ...options, context })
151
+ );
152
+ if (index === outputValidationIndex) {
153
+ return await validateOutput(procedure, output);
154
+ }
155
+ return output;
156
+ };
157
+ return next(0, options.context, input);
158
+ }
159
+
160
+ export { middlewareOutputFn as a, createProcedureClient as c, mergeCurrentContext as m };
@@ -0,0 +1,319 @@
1
+ import { HTTPMethods } from '@temporary-name/shared';
2
+ import * as z from '@temporary-name/zod';
3
+
4
+ function isStartWithMiddlewares(middlewares, compare) {
5
+ if (compare.length > middlewares.length) {
6
+ return false;
7
+ }
8
+ for (let i = 0; i < middlewares.length; i++) {
9
+ if (compare[i] === void 0) {
10
+ return true;
11
+ }
12
+ if (middlewares[i] !== compare[i]) {
13
+ return false;
14
+ }
15
+ }
16
+ return true;
17
+ }
18
+ function mergeMiddlewares(first, second, options) {
19
+ if (options.dedupeLeading && isStartWithMiddlewares(second, first)) {
20
+ return second;
21
+ }
22
+ return [...first, ...second];
23
+ }
24
+ function addMiddleware(middlewares, addition) {
25
+ return [...middlewares, addition];
26
+ }
27
+
28
+ class Contract {
29
+ /**
30
+ * This property holds the defined options.
31
+ */
32
+ "~orpc";
33
+ constructor(def) {
34
+ this["~orpc"] = def;
35
+ }
36
+ }
37
+ class Procedure extends Contract {
38
+ }
39
+ function isProcedure(item) {
40
+ return item instanceof Procedure || // This is so we'll return true for Proxy-wrapped Procedures e.g. as returned by `callable`
41
+ (typeof item === "object" || typeof item === "function") && item !== null && "~orpc" in item && typeof item["~orpc"] === "object" && item["~orpc"] !== null && "route" in item["~orpc"] && "meta" in item["~orpc"] && "middlewares" in item["~orpc"] && "inputValidationIndex" in item["~orpc"] && "outputValidationIndex" in item["~orpc"] && "handler" in item["~orpc"];
42
+ }
43
+
44
+ class ValidationError extends Error {
45
+ issues;
46
+ data;
47
+ constructor(options) {
48
+ super(options.message, options);
49
+ this.issues = options.issues;
50
+ this.data = options.data;
51
+ }
52
+ }
53
+
54
+ function mergeRoute(a, b) {
55
+ return { ...a, ...b };
56
+ }
57
+ function prefixRoute(route, prefix) {
58
+ if (!route.path) {
59
+ return route;
60
+ }
61
+ return {
62
+ ...route,
63
+ path: `${prefix}${route.path}`
64
+ };
65
+ }
66
+ function unshiftTagRoute(route, tags) {
67
+ return {
68
+ ...route,
69
+ tags: [...tags, ...route.tags ?? []]
70
+ };
71
+ }
72
+ function mergePrefix(a, b) {
73
+ return a ? `${a}${b}` : b;
74
+ }
75
+ function mergeTags(a, b) {
76
+ return a ? [...a, ...b] : b;
77
+ }
78
+ function enhanceRoute(route, options) {
79
+ let router = route;
80
+ if (options.prefix) {
81
+ router = prefixRoute(router, options.prefix);
82
+ }
83
+ if (options.tags?.length) {
84
+ router = unshiftTagRoute(router, options.tags);
85
+ }
86
+ return router;
87
+ }
88
+
89
+ function getRouter(router, path) {
90
+ let current = router;
91
+ for (let i = 0; i < path.length; i++) {
92
+ const segment = path[i];
93
+ if (!current) {
94
+ return void 0;
95
+ }
96
+ if (isProcedure(current)) {
97
+ return void 0;
98
+ }
99
+ if (!isLazy(current)) {
100
+ current = current[segment];
101
+ continue;
102
+ }
103
+ const lazied = current;
104
+ const rest = path.slice(i);
105
+ return lazyInternal(async () => {
106
+ const unwrapped = await unlazy(lazied);
107
+ const next = getRouter(unwrapped.default, rest);
108
+ return unlazy(next);
109
+ }, getLazyMeta(lazied));
110
+ }
111
+ return current;
112
+ }
113
+ function createAccessibleLazyRouter(lazied) {
114
+ const recursive = new Proxy(lazied, {
115
+ get(target, key) {
116
+ if (typeof key !== "string") {
117
+ return Reflect.get(target, key);
118
+ }
119
+ const next = getRouter(lazied, [key]);
120
+ return createAccessibleLazyRouter(next);
121
+ }
122
+ });
123
+ return recursive;
124
+ }
125
+ function enhanceRouter(router, options) {
126
+ if (isLazy(router)) {
127
+ const laziedMeta = getLazyMeta(router);
128
+ const enhancedPrefix = laziedMeta?.prefix ? mergePrefix(options.prefix, laziedMeta?.prefix) : options.prefix;
129
+ const enhanced2 = lazyInternal(
130
+ async () => {
131
+ const { default: unlaziedRouter } = await unlazy(router);
132
+ const enhanced3 = enhanceRouter(unlaziedRouter, options);
133
+ return unlazy(enhanced3);
134
+ },
135
+ {
136
+ ...laziedMeta,
137
+ prefix: enhancedPrefix
138
+ }
139
+ );
140
+ const accessible = createAccessibleLazyRouter(enhanced2);
141
+ return accessible;
142
+ }
143
+ if (isProcedure(router)) {
144
+ const newMiddlewares = mergeMiddlewares(options.middlewares, router["~orpc"].middlewares, {
145
+ dedupeLeading: options.dedupeLeadingMiddlewares
146
+ });
147
+ const newMiddlewareAdded = newMiddlewares.length - router["~orpc"].middlewares.length;
148
+ const enhanced2 = new Procedure({
149
+ ...router["~orpc"],
150
+ route: enhanceRoute(router["~orpc"].route, options),
151
+ middlewares: newMiddlewares,
152
+ inputValidationIndex: router["~orpc"].inputValidationIndex + newMiddlewareAdded,
153
+ outputValidationIndex: router["~orpc"].outputValidationIndex + newMiddlewareAdded
154
+ });
155
+ return enhanced2;
156
+ }
157
+ const enhanced = {};
158
+ for (const key in router) {
159
+ enhanced[key] = enhanceRouter(router[key], options);
160
+ }
161
+ return enhanced;
162
+ }
163
+ function traverseContractProcedures(options, callback, lazyOptions = []) {
164
+ const currentRouter = options.router;
165
+ if (isLazy(currentRouter)) {
166
+ lazyOptions.push({
167
+ router: currentRouter,
168
+ path: options.path
169
+ });
170
+ } else if (currentRouter instanceof Contract) {
171
+ callback({
172
+ contract: currentRouter,
173
+ path: options.path
174
+ });
175
+ } else if (typeof currentRouter === "string") {
176
+ throw new Error("Unexpected: got string instead of router");
177
+ } else {
178
+ for (const key in currentRouter) {
179
+ traverseContractProcedures(
180
+ {
181
+ router: currentRouter[key],
182
+ path: [...options.path, key]
183
+ },
184
+ callback,
185
+ lazyOptions
186
+ );
187
+ }
188
+ }
189
+ return lazyOptions;
190
+ }
191
+ async function resolveContractProcedures(options, callback) {
192
+ const pending = [options];
193
+ for (const options2 of pending) {
194
+ const lazyOptions = traverseContractProcedures(options2, callback);
195
+ for (const options3 of lazyOptions) {
196
+ const { default: router } = await unlazy(options3.router);
197
+ pending.push({
198
+ router,
199
+ path: options3.path
200
+ });
201
+ }
202
+ }
203
+ }
204
+ async function unlazyRouter(router) {
205
+ if (isProcedure(router)) {
206
+ return router;
207
+ }
208
+ const unlazied = {};
209
+ for (const key in router) {
210
+ const item = router[key];
211
+ const { default: unlaziedRouter } = await unlazy(item);
212
+ unlazied[key] = await unlazyRouter(unlaziedRouter);
213
+ }
214
+ return unlazied;
215
+ }
216
+
217
+ const LAZY_SYMBOL = Symbol("ORPC_LAZY_SYMBOL");
218
+ function lazyInternal(loader, meta = {}) {
219
+ return {
220
+ [LAZY_SYMBOL]: {
221
+ loader,
222
+ meta
223
+ }
224
+ };
225
+ }
226
+ function lazy(prefix, loader) {
227
+ return enhanceRouter(lazyInternal(loader), {
228
+ middlewares: [],
229
+ dedupeLeadingMiddlewares: true,
230
+ prefix
231
+ });
232
+ }
233
+ function isLazy(item) {
234
+ return (typeof item === "object" || typeof item === "function") && item !== null && LAZY_SYMBOL in item;
235
+ }
236
+ function getLazyMeta(lazied) {
237
+ return lazied[LAZY_SYMBOL].meta;
238
+ }
239
+ function unlazy(lazied) {
240
+ return isLazy(lazied) ? lazied[LAZY_SYMBOL].loader() : Promise.resolve({ default: lazied });
241
+ }
242
+
243
+ const endpointRegex = new RegExp(`^(${HTTPMethods.join("|")})`);
244
+ function standardizeHTTPPath(path) {
245
+ return `/${path.replace(/\/{2,}/g, "/").replace(/^\/|\/$/g, "")}`;
246
+ }
247
+ function getDynamicParams(path) {
248
+ return path ? standardizeHTTPPath(path).match(/\/\{[^}]+\}/g)?.map((v) => ({
249
+ raw: v,
250
+ name: v.match(/\{\+?([^}]+)\}/)[1]
251
+ })) : void 0;
252
+ }
253
+ function parseEndpointDefinition(stringsOrEndpoint, values) {
254
+ let method, path, pathSchema;
255
+ if (stringsOrEndpoint instanceof Array) {
256
+ let endpoint = stringsOrEndpoint[0];
257
+ if (endpoint === void 0 || !endpointRegex.test(endpoint)) {
258
+ throw new Error(".endpoint() must start with a valid HTTP endpoint string.");
259
+ }
260
+ const shape = {};
261
+ for (let i = 1; i < stringsOrEndpoint.length; i++) {
262
+ const str = stringsOrEndpoint[i];
263
+ const value = values[i - 1];
264
+ if (typeof value !== "object" || value instanceof z.core.$ZodType) {
265
+ throw new Error(
266
+ `Each template value for .endpoint must be an object with a single key, whose value is a ZodType.`
267
+ );
268
+ }
269
+ const valueEntries = Object.entries(value);
270
+ if (valueEntries.length !== 1) {
271
+ throw new Error(
272
+ `Each template value for .endpoint must be an object with a single key, whose value is a ZodType.`
273
+ );
274
+ }
275
+ const [key, schema] = valueEntries[0];
276
+ endpoint += `{${key}}${str}`;
277
+ if (key in schema) {
278
+ throw new Error(`Duplicate path parameter name "${key}" in endpoint.`);
279
+ }
280
+ shape[key] = schema;
281
+ }
282
+ [method, path] = endpoint.split(" ", 2);
283
+ pathSchema = z.object(shape);
284
+ } else if (values.length <= 1) {
285
+ const endpoint = stringsOrEndpoint;
286
+ const schema = values[0];
287
+ [method, path] = endpoint.split(" ", 2);
288
+ const pathParamNames = getDynamicParams(path)?.map((p) => p.name) ?? [];
289
+ let schemaKeys;
290
+ if (schema instanceof z.core.$ZodType) {
291
+ if (schema instanceof z.core.$ZodObject) {
292
+ schemaKeys = Object.keys(schema._zod.def.shape);
293
+ pathSchema = schema;
294
+ } else {
295
+ throw new Error(
296
+ `Path schema for endpoint "${endpoint}" must be a ZodObject schema (or object where each value is a ZodType).`
297
+ );
298
+ }
299
+ } else if (typeof schema === "object") {
300
+ schemaKeys = Object.keys(schema);
301
+ pathSchema = z.object(schema);
302
+ } else if (schema !== void 0) {
303
+ throw new Error(
304
+ `Path schema for endpoint "${endpoint}" must be a ZodObject schema (or object where each value is a ZodType).`
305
+ );
306
+ } else {
307
+ schemaKeys = [];
308
+ pathSchema = z.object({});
309
+ }
310
+ if (pathParamNames.length !== schemaKeys.length || !pathParamNames.every((name) => schemaKeys.includes(name))) {
311
+ throw new Error(`Path schema keys do not match dynamic parameters in endpoint "${endpoint}".`);
312
+ }
313
+ } else {
314
+ throw new Error("Invalid arguments for .endpoint() method.");
315
+ }
316
+ return { method, path, pathSchema };
317
+ }
318
+
319
+ export { Contract as C, LAZY_SYMBOL as L, Procedure as P, ValidationError as V, mergeTags as a, mergeRoute as b, prefixRoute as c, addMiddleware as d, enhanceRouter as e, getLazyMeta as f, getDynamicParams as g, lazy as h, isProcedure as i, isLazy as j, isStartWithMiddlewares as k, lazyInternal as l, mergePrefix as m, mergeMiddlewares as n, getRouter as o, parseEndpointDefinition as p, createAccessibleLazyRouter as q, resolveContractProcedures as r, standardizeHTTPPath as s, traverseContractProcedures as t, unlazy as u, unlazyRouter as v, endpointRegex as w };