@temporary-name/server 1.9.3-alpha.afd18ec2afa743b08cf1b5c2eb6252ded18a1f43 → 1.9.3-alpha.bb3867758271e7fcf8c191f9693365d655697e7f

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 (35) hide show
  1. package/dist/adapters/aws-lambda/index.d.mts +3 -4
  2. package/dist/adapters/aws-lambda/index.d.ts +3 -4
  3. package/dist/adapters/aws-lambda/index.mjs +5 -7
  4. package/dist/adapters/fetch/index.d.mts +3 -4
  5. package/dist/adapters/fetch/index.d.ts +3 -4
  6. package/dist/adapters/fetch/index.mjs +5 -7
  7. package/dist/adapters/node/index.d.mts +3 -4
  8. package/dist/adapters/node/index.d.ts +3 -4
  9. package/dist/adapters/node/index.mjs +5 -7
  10. package/dist/adapters/standard/index.d.mts +20 -78
  11. package/dist/adapters/standard/index.d.ts +20 -78
  12. package/dist/adapters/standard/index.mjs +5 -7
  13. package/dist/index.d.mts +69 -339
  14. package/dist/index.d.ts +69 -339
  15. package/dist/index.mjs +132 -357
  16. package/dist/openapi/index.d.mts +1 -2
  17. package/dist/openapi/index.d.ts +1 -2
  18. package/dist/openapi/index.mjs +63 -88
  19. package/dist/plugins/index.d.mts +4 -80
  20. package/dist/plugins/index.d.ts +4 -80
  21. package/dist/plugins/index.mjs +17 -189
  22. package/dist/shared/{server.BeuTpcmO.d.mts → server.7aL9gcoU.d.mts} +2 -2
  23. package/dist/shared/server.BL2R5jcp.d.mts +228 -0
  24. package/dist/shared/server.BL2R5jcp.d.ts +228 -0
  25. package/dist/shared/server.C61o1Zch.mjs +413 -0
  26. package/dist/shared/{server.CQyYNJ1H.d.ts → server.D6Qs_UcF.d.mts} +2 -4
  27. package/dist/shared/{server.SLLuK6_v.d.ts → server.DFptr1Nz.d.ts} +2 -2
  28. package/dist/shared/{server.C1fnTLq0.d.mts → server.DpoO_ER_.d.ts} +2 -4
  29. package/dist/shared/{server._YqJjI50.mjs → server.DwbIdsnK.mjs} +58 -101
  30. package/dist/shared/server.JtIZ8YG7.mjs +237 -0
  31. package/package.json +10 -9
  32. package/dist/shared/server.BKSOrA6h.d.mts +0 -192
  33. package/dist/shared/server.BKSOrA6h.d.ts +0 -192
  34. package/dist/shared/server.BKh8I1Ny.mjs +0 -239
  35. package/dist/shared/server.DhdDYN-Z.mjs +0 -261
@@ -1,239 +0,0 @@
1
- import { validateORPCError, ValidationError } from '@temporary-name/contract';
2
- import { resolveMaybeOptionalOptions, ORPCError, toArray, value, runWithSpan, intercept, isAsyncIteratorObject, overlayProxy, asyncIteratorWithSpan } from '@temporary-name/shared';
3
- import { HibernationEventIterator, mapEventIterator } from '@temporary-name/standard-server';
4
- import { AsyncLocalStorage } from 'node:async_hooks';
5
- import 'zod';
6
- import * as z4 from 'zod/v4/core';
7
-
8
- const gatingContext = new AsyncLocalStorage();
9
- function withoutGatedFields(data, schema, isGateEnabled) {
10
- const filtered = { ...data };
11
- const gatedFields = getGatedFields(schema);
12
- for (const [fieldName, gate] of gatedFields) {
13
- if (!isGateEnabled(gate)) {
14
- delete filtered[fieldName];
15
- }
16
- }
17
- return filtered;
18
- }
19
- function getGatedFields(schema) {
20
- if (!schema || schema["~standard"].vendor !== "zod") {
21
- return [];
22
- }
23
- const gatedFields = [];
24
- const zodDef = schema._zod.def;
25
- if (zodDef.type === "object") {
26
- const shape = zodDef.shape;
27
- for (const fieldName in shape) {
28
- const fieldSchema = shape[fieldName];
29
- const gate = z4.globalRegistry.get(fieldSchema)?.gate;
30
- if (gate) {
31
- gatedFields.push([fieldName, gate]);
32
- }
33
- }
34
- }
35
- return gatedFields;
36
- }
37
-
38
- const LAZY_SYMBOL = Symbol("ORPC_LAZY_SYMBOL");
39
- function lazy(loader, meta = {}) {
40
- return {
41
- [LAZY_SYMBOL]: {
42
- loader,
43
- meta
44
- }
45
- };
46
- }
47
- function isLazy(item) {
48
- return (typeof item === "object" || typeof item === "function") && item !== null && LAZY_SYMBOL in item;
49
- }
50
- function getLazyMeta(lazied) {
51
- return lazied[LAZY_SYMBOL].meta;
52
- }
53
- function unlazy(lazied) {
54
- return isLazy(lazied) ? lazied[LAZY_SYMBOL].loader() : Promise.resolve({ default: lazied });
55
- }
56
-
57
- function mergeCurrentContext(context, other) {
58
- return { ...context, ...other };
59
- }
60
-
61
- function createORPCErrorConstructorMap(errors) {
62
- const proxy = new Proxy(errors, {
63
- get(target, code) {
64
- if (typeof code !== "string") {
65
- return Reflect.get(target, code);
66
- }
67
- const item = (...rest) => {
68
- const options = resolveMaybeOptionalOptions(rest);
69
- const config = errors[code];
70
- return new ORPCError(code, {
71
- defined: Boolean(config),
72
- status: config?.status,
73
- message: options.message ?? config?.message,
74
- data: options.data,
75
- cause: options.cause
76
- });
77
- };
78
- return item;
79
- }
80
- });
81
- return proxy;
82
- }
83
-
84
- function middlewareOutputFn(output) {
85
- return { output, context: {} };
86
- }
87
-
88
- function createProcedureClient(lazyableProcedure, ...rest) {
89
- const options = resolveMaybeOptionalOptions(rest);
90
- return async (...[input, callerOptions]) => {
91
- const path = toArray(options.path);
92
- const { default: procedure } = await unlazy(lazyableProcedure);
93
- const clientContext = callerOptions?.context ?? {};
94
- const context = await value(options.context ?? {}, clientContext);
95
- const errors = createORPCErrorConstructorMap(procedure["~orpc"].errorMap);
96
- const validateError = async (e) => {
97
- if (e instanceof ORPCError) {
98
- return await validateORPCError(procedure["~orpc"].errorMap, e);
99
- }
100
- return e;
101
- };
102
- try {
103
- const output = await runWithSpan({ name: "call_procedure", signal: callerOptions?.signal }, (span) => {
104
- span?.setAttribute("procedure.path", [...path]);
105
- return intercept(
106
- toArray(options.interceptors),
107
- {
108
- context,
109
- input,
110
- // input only optional when it undefinable so we can safely cast it
111
- errors,
112
- path,
113
- procedure,
114
- signal: callerOptions?.signal,
115
- lastEventId: callerOptions?.lastEventId
116
- },
117
- (interceptorOptions) => executeProcedureInternal(interceptorOptions.procedure, interceptorOptions)
118
- );
119
- });
120
- if (isAsyncIteratorObject(output)) {
121
- if (output instanceof HibernationEventIterator) {
122
- return output;
123
- }
124
- return overlayProxy(
125
- output,
126
- mapEventIterator(
127
- asyncIteratorWithSpan(
128
- { name: "consume_event_iterator_output", signal: callerOptions?.signal },
129
- output
130
- ),
131
- {
132
- value: (v) => v,
133
- error: (e) => validateError(e)
134
- }
135
- )
136
- );
137
- }
138
- return output;
139
- } catch (e) {
140
- throw await validateError(e);
141
- }
142
- };
143
- }
144
- async function validateInput(procedure, input) {
145
- const schema = procedure["~orpc"].inputSchema;
146
- if (!schema) {
147
- return input;
148
- }
149
- return runWithSpan({ name: "validate_input" }, async () => {
150
- const result = await schema["~standard"].validate(input);
151
- if (result.issues) {
152
- throw new ORPCError("BAD_REQUEST", {
153
- message: "Input validation failed",
154
- data: {
155
- issues: result.issues
156
- },
157
- cause: new ValidationError({
158
- message: "Input validation failed",
159
- issues: result.issues,
160
- data: input
161
- })
162
- });
163
- }
164
- return result.value;
165
- });
166
- }
167
- async function validateOutput(schema, output) {
168
- return runWithSpan({ name: "validate_output" }, async () => {
169
- const result = await schema["~standard"].validate(output);
170
- if (result.issues) {
171
- throw new ORPCError("INTERNAL_SERVER_ERROR", {
172
- message: "Output validation failed",
173
- cause: new ValidationError({
174
- message: "Output validation failed",
175
- issues: result.issues,
176
- data: output
177
- })
178
- });
179
- }
180
- return result.value;
181
- });
182
- }
183
- async function executeProcedureInternal(procedure, options) {
184
- const middlewares = procedure["~orpc"].middlewares;
185
- const inputValidationIndex = Math.min(
186
- Math.max(0, procedure["~orpc"].inputValidationIndex),
187
- middlewares.length
188
- );
189
- const outputValidationIndex = Math.min(
190
- Math.max(0, procedure["~orpc"].outputValidationIndex),
191
- middlewares.length
192
- );
193
- const next = async (index, context, input) => {
194
- let currentInput = input;
195
- if (index === inputValidationIndex) {
196
- currentInput = await validateInput(procedure, currentInput);
197
- }
198
- const mid = middlewares[index];
199
- const output = mid ? await runWithSpan({ name: `middleware.${mid.name}`, signal: options.signal }, async (span) => {
200
- span?.setAttribute("middleware.index", index);
201
- span?.setAttribute("middleware.name", mid.name);
202
- const result = await mid(
203
- {
204
- ...options,
205
- context,
206
- next: async (...[nextOptions]) => {
207
- const nextContext = nextOptions?.context ?? {};
208
- return {
209
- output: await next(index + 1, mergeCurrentContext(context, nextContext), currentInput),
210
- context: nextContext
211
- };
212
- }
213
- },
214
- currentInput,
215
- middlewareOutputFn
216
- );
217
- return result.output;
218
- }) : await runWithSpan(
219
- { name: "handler", signal: options.signal },
220
- () => procedure["~orpc"].handler({ ...options, context, input: currentInput })
221
- );
222
- if (index === outputValidationIndex) {
223
- const schema = procedure["~orpc"].outputSchema;
224
- if (!schema) {
225
- return output;
226
- }
227
- const validated = await validateOutput(schema, output);
228
- const isGateEnabled = gatingContext.getStore();
229
- if (!validated || !isGateEnabled) {
230
- return validated;
231
- }
232
- return withoutGatedFields(validated, schema, isGateEnabled);
233
- }
234
- return output;
235
- };
236
- return next(0, options.context, options.input);
237
- }
238
-
239
- export { LAZY_SYMBOL as L, gatingContext as a, createORPCErrorConstructorMap as b, createProcedureClient as c, middlewareOutputFn as d, getLazyMeta as g, isLazy as i, lazy as l, mergeCurrentContext as m, unlazy as u };
@@ -1,261 +0,0 @@
1
- import { isObject, NullProtoObj, isAsyncIteratorObject, toORPCError, isORPCErrorJson, createORPCErrorFromJson } from '@temporary-name/shared';
2
- import { mapEventIterator, ErrorEvent } from '@temporary-name/standard-server';
3
-
4
- class StandardBracketNotationSerializer {
5
- maxArrayIndex;
6
- constructor(options = {}) {
7
- this.maxArrayIndex = options.maxBracketNotationArrayIndex ?? 9999;
8
- }
9
- serialize(data, segments = [], result = []) {
10
- if (Array.isArray(data)) {
11
- data.forEach((item, i) => {
12
- this.serialize(item, [...segments, i], result);
13
- });
14
- } else if (isObject(data)) {
15
- for (const key in data) {
16
- this.serialize(data[key], [...segments, key], result);
17
- }
18
- } else {
19
- result.push([this.stringifyPath(segments), data]);
20
- }
21
- return result;
22
- }
23
- deserialize(serialized) {
24
- if (serialized.length === 0) {
25
- return {};
26
- }
27
- const arrayPushStyles = /* @__PURE__ */ new WeakSet();
28
- const ref = { value: [] };
29
- for (const [path, value] of serialized) {
30
- const segments = this.parsePath(path);
31
- let currentRef = ref;
32
- let nextSegment = "value";
33
- segments.forEach((segment, i) => {
34
- if (!Array.isArray(currentRef[nextSegment]) && !isObject(currentRef[nextSegment])) {
35
- currentRef[nextSegment] = [];
36
- }
37
- if (i !== segments.length - 1) {
38
- if (Array.isArray(currentRef[nextSegment]) && !isValidArrayIndex(segment, this.maxArrayIndex)) {
39
- if (arrayPushStyles.has(currentRef[nextSegment])) {
40
- arrayPushStyles.delete(currentRef[nextSegment]);
41
- currentRef[nextSegment] = pushStyleArrayToObject(currentRef[nextSegment]);
42
- } else {
43
- currentRef[nextSegment] = arrayToObject(currentRef[nextSegment]);
44
- }
45
- }
46
- } else {
47
- if (Array.isArray(currentRef[nextSegment])) {
48
- if (segment === "") {
49
- if (currentRef[nextSegment].length && !arrayPushStyles.has(currentRef[nextSegment])) {
50
- currentRef[nextSegment] = arrayToObject(currentRef[nextSegment]);
51
- }
52
- } else {
53
- if (arrayPushStyles.has(currentRef[nextSegment])) {
54
- arrayPushStyles.delete(currentRef[nextSegment]);
55
- currentRef[nextSegment] = pushStyleArrayToObject(currentRef[nextSegment]);
56
- } else if (!isValidArrayIndex(segment, this.maxArrayIndex)) {
57
- currentRef[nextSegment] = arrayToObject(currentRef[nextSegment]);
58
- }
59
- }
60
- }
61
- }
62
- currentRef = currentRef[nextSegment];
63
- nextSegment = segment;
64
- });
65
- if (Array.isArray(currentRef) && nextSegment === "") {
66
- arrayPushStyles.add(currentRef);
67
- currentRef.push(value);
68
- } else if (nextSegment in currentRef) {
69
- if (Array.isArray(currentRef[nextSegment])) {
70
- currentRef[nextSegment].push(value);
71
- } else {
72
- currentRef[nextSegment] = [currentRef[nextSegment], value];
73
- }
74
- } else {
75
- currentRef[nextSegment] = value;
76
- }
77
- }
78
- return ref.value;
79
- }
80
- stringifyPath(segments) {
81
- return segments.map((segment) => {
82
- return segment.toString().replace(/[\\[\]]/g, (match) => {
83
- switch (match) {
84
- case "\\":
85
- return "\\\\";
86
- case "[":
87
- return "\\[";
88
- case "]":
89
- return "\\]";
90
- /* v8 ignore next 2 */
91
- default:
92
- return match;
93
- }
94
- });
95
- }).reduce((result, segment, i) => {
96
- if (i === 0) {
97
- return segment;
98
- }
99
- return `${result}[${segment}]`;
100
- }, "");
101
- }
102
- parsePath(path) {
103
- const segments = [];
104
- let inBrackets = false;
105
- let currentSegment = "";
106
- let backslashCount = 0;
107
- for (let i = 0; i < path.length; i++) {
108
- const char = path[i];
109
- const nextChar = path[i + 1];
110
- if (inBrackets && char === "]" && (nextChar === void 0 || nextChar === "[") && backslashCount % 2 === 0) {
111
- if (nextChar === void 0) {
112
- inBrackets = false;
113
- }
114
- segments.push(currentSegment);
115
- currentSegment = "";
116
- i++;
117
- } else if (segments.length === 0 && char === "[" && backslashCount % 2 === 0) {
118
- inBrackets = true;
119
- segments.push(currentSegment);
120
- currentSegment = "";
121
- } else if (char === "\\") {
122
- backslashCount++;
123
- } else {
124
- currentSegment += "\\".repeat(backslashCount / 2) + char;
125
- backslashCount = 0;
126
- }
127
- }
128
- return inBrackets || segments.length === 0 ? [path] : segments;
129
- }
130
- }
131
- function isValidArrayIndex(value, maxIndex) {
132
- return /^0$|^[1-9]\d*$/.test(value) && Number(value) <= maxIndex;
133
- }
134
- function arrayToObject(array) {
135
- const obj = new NullProtoObj();
136
- array.forEach((item, i) => {
137
- obj[i] = item;
138
- });
139
- return obj;
140
- }
141
- function pushStyleArrayToObject(array) {
142
- const obj = new NullProtoObj();
143
- obj[""] = array.length === 1 ? array[0] : array;
144
- return obj;
145
- }
146
-
147
- class StandardOpenAPIJsonSerializer {
148
- serialize(data, hasBlobRef = { value: false }) {
149
- if (data instanceof Blob) {
150
- hasBlobRef.value = true;
151
- return [data, hasBlobRef.value];
152
- }
153
- if (data instanceof Set) {
154
- return this.serialize(Array.from(data), hasBlobRef);
155
- }
156
- if (data instanceof Map) {
157
- return this.serialize(Array.from(data.entries()), hasBlobRef);
158
- }
159
- if (Array.isArray(data)) {
160
- const json = data.map((v) => v === void 0 ? null : this.serialize(v, hasBlobRef)[0]);
161
- return [json, hasBlobRef.value];
162
- }
163
- if (isObject(data)) {
164
- const json = {};
165
- for (const k in data) {
166
- if (k === "toJSON" && typeof data[k] === "function") {
167
- continue;
168
- }
169
- json[k] = this.serialize(data[k], hasBlobRef)[0];
170
- }
171
- return [json, hasBlobRef.value];
172
- }
173
- if (typeof data === "bigint" || data instanceof RegExp || data instanceof URL) {
174
- return [data.toString(), hasBlobRef.value];
175
- }
176
- if (data instanceof Date) {
177
- return [Number.isNaN(data.getTime()) ? null : data.toISOString(), hasBlobRef.value];
178
- }
179
- if (Number.isNaN(data)) {
180
- return [null, hasBlobRef.value];
181
- }
182
- return [data, hasBlobRef.value];
183
- }
184
- }
185
-
186
- class StandardOpenAPISerializer {
187
- constructor(jsonSerializer, bracketNotation) {
188
- this.jsonSerializer = jsonSerializer;
189
- this.bracketNotation = bracketNotation;
190
- }
191
- serialize(data, options = {}) {
192
- if (isAsyncIteratorObject(data) && !options.outputFormat) {
193
- return mapEventIterator(data, {
194
- value: async (value) => this.#serialize(value, { outputFormat: "plain" }),
195
- error: async (e) => {
196
- return new ErrorEvent({
197
- data: this.#serialize(toORPCError(e).toJSON(), { outputFormat: "plain" }),
198
- cause: e
199
- });
200
- }
201
- });
202
- }
203
- return this.#serialize(data, options);
204
- }
205
- #serialize(data, options) {
206
- const [json, hasBlob] = this.jsonSerializer.serialize(data);
207
- if (options.outputFormat === "plain") {
208
- return json;
209
- }
210
- if (options.outputFormat === "URLSearchParams") {
211
- const params = new URLSearchParams();
212
- for (const [path, value] of this.bracketNotation.serialize(json)) {
213
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
214
- params.append(path, value.toString());
215
- }
216
- }
217
- return params;
218
- }
219
- if (json instanceof Blob || json === void 0 || !hasBlob) {
220
- return json;
221
- }
222
- const form = new FormData();
223
- for (const [path, value] of this.bracketNotation.serialize(json)) {
224
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
225
- form.append(path, value.toString());
226
- } else if (value instanceof Blob) {
227
- form.append(path, value);
228
- }
229
- }
230
- return form;
231
- }
232
- deserialize(data) {
233
- if (data instanceof URLSearchParams || data instanceof FormData) {
234
- return this.bracketNotation.deserialize(Array.from(data.entries()));
235
- }
236
- if (isAsyncIteratorObject(data)) {
237
- return mapEventIterator(data, {
238
- value: async (value) => value,
239
- error: async (e) => {
240
- if (e instanceof ErrorEvent && isORPCErrorJson(e.data)) {
241
- return createORPCErrorFromJson(e.data, { cause: e });
242
- }
243
- return e;
244
- }
245
- });
246
- }
247
- return data;
248
- }
249
- }
250
-
251
- function standardizeHTTPPath(path) {
252
- return `/${path.replace(/\/{2,}/g, "/").replace(/^\/|\/$/g, "")}`;
253
- }
254
- function getDynamicParams(path) {
255
- return path ? standardizeHTTPPath(path).match(/\/\{[^}]+\}/g)?.map((v) => ({
256
- raw: v,
257
- name: v.match(/\{\+?([^}]+)\}/)[1]
258
- })) : void 0;
259
- }
260
-
261
- export { StandardBracketNotationSerializer as S, StandardOpenAPISerializer as a, StandardOpenAPIJsonSerializer as b, getDynamicParams as g, standardizeHTTPPath as s };