@orpc/shared 2.0.0-beta.4 → 2.0.0-beta.41

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/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { AbortError, AsyncIteratorClass, isTypescriptObject, getOrBind } from '@standardserver/shared';
2
- export { AbortError, AsyncIteratorClass, SequentialIdGenerator, getOrBind, isAsyncIteratorObject, isTypescriptObject, parseEmptyableJSON, sleep, stringifyJSON, toArray } from '@standardserver/shared';
1
+ import { safeDecodeURIComponent, safeEncodeURIComponent, AbortError, AsyncIteratorClass, getOrBind, isTypescriptObject, isAsyncIteratorObject, throwIfAborted } from '@standard-server/shared';
2
+ export { AbortError, AsyncIteratorClass, SequentialIdGenerator, getOrBind, isAsyncIteratorObject, isTypescriptObject, parseEmptyableJSON, safeDecodeURIComponent, safeEncodeURIComponent, sequential, sleep, stringifyJSON, throwIfAborted, toArray } from '@standard-server/shared';
3
3
 
4
4
  function resolveMaybeOptionalOptions(rest) {
5
5
  return rest[0] ?? {};
@@ -16,24 +16,44 @@ async function loadBytes(source) {
16
16
  }
17
17
  return new Uint8Array(await source.arrayBuffer());
18
18
  }
19
- async function toStringOrBytes(source) {
19
+ function toStringOrBytes(source) {
20
20
  if (typeof source === "string") {
21
21
  return source;
22
22
  }
23
23
  if (source instanceof ArrayBuffer) {
24
24
  return new Uint8Array(source);
25
25
  }
26
- if (source instanceof Blob) {
27
- return loadBytes(source);
28
- }
29
26
  if (Array.isArray(source)) {
30
- return loadBytes(new Blob(source));
27
+ return concatBytes(source);
31
28
  }
32
29
  if (source instanceof Uint8Array) {
33
30
  return source;
34
31
  }
35
32
  return new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
36
33
  }
34
+ function toBytes(item) {
35
+ if (typeof item === "string") {
36
+ return new TextEncoder().encode(item);
37
+ }
38
+ if (item instanceof ArrayBuffer) {
39
+ return new Uint8Array(item);
40
+ }
41
+ if (item instanceof Uint8Array) {
42
+ return item;
43
+ }
44
+ return new Uint8Array(item.buffer, item.byteOffset, item.byteLength);
45
+ }
46
+ function concatBytes(items) {
47
+ const chunks = items.map(toBytes);
48
+ const totalLength = chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0);
49
+ const result = new Uint8Array(totalLength);
50
+ let offset = 0;
51
+ for (const chunk of chunks) {
52
+ result.set(chunk, offset);
53
+ offset += chunk.byteLength;
54
+ }
55
+ return result;
56
+ }
37
57
 
38
58
  function isDeepEqual(a, b) {
39
59
  return isDeepEqualInternal(a, b, /* @__PURE__ */ new WeakMap());
@@ -91,6 +111,11 @@ function isAbortError(error) {
91
111
  return error instanceof Error && error.name.includes("Abort");
92
112
  }
93
113
 
114
+ const AsyncGeneratorFunction = Object.getPrototypeOf(async function* () {
115
+ }).constructor;
116
+ function isAsyncGeneratorFunction(value) {
117
+ return value instanceof AsyncGeneratorFunction;
118
+ }
94
119
  function once(fn) {
95
120
  let cached;
96
121
  return () => {
@@ -102,9 +127,9 @@ function once(fn) {
102
127
  return result;
103
128
  };
104
129
  }
105
- function defer(callback) {
130
+ function defer(callback, delay = 0) {
106
131
  if (typeof setTimeout === "function") {
107
- setTimeout(callback, 0);
132
+ setTimeout(callback, delay);
108
133
  } else {
109
134
  Promise.resolve().then(() => Promise.resolve().then(() => Promise.resolve().then(callback)));
110
135
  }
@@ -117,23 +142,15 @@ function tryOrUndefined(fn) {
117
142
  }
118
143
  }
119
144
 
120
- function tryDecodeURIComponent(value) {
121
- try {
122
- return decodeURIComponent(value);
123
- } catch {
124
- return value;
125
- }
126
- }
127
-
128
145
  function pathToHttpPath(path) {
129
- return `/${path.map(encodeURIComponent).join("/")}`;
146
+ return `/${path.map(safeEncodeURIComponent).join("/")}`;
130
147
  }
131
148
  function normalizeHttpPath(path) {
132
149
  const paths = path.split("/");
133
150
  if (paths.at(0) === "") {
134
151
  paths.shift();
135
152
  }
136
- return pathToHttpPath(paths.map(tryDecodeURIComponent));
153
+ return pathToHttpPath(paths.map(safeDecodeURIComponent));
137
154
  }
138
155
  function mergeHttpPath(a, b) {
139
156
  return `${a.endsWith("/") ? a.slice(0, -1) : a}${b}`;
@@ -156,167 +173,54 @@ function matchesHttpPath(url, path) {
156
173
  }
157
174
  return charAfterPrefix === void 0 || charAfterPrefix === "?" || charAfterPrefix === "#";
158
175
  }
159
-
160
- function compareSequentialIds(a, b) {
161
- if (a.length !== b.length) {
162
- return a.length - b.length;
163
- }
164
- return a < b ? -1 : a > b ? 1 : 0;
165
- }
166
-
167
- function onStart(callback) {
168
- return async (options, ...rest) => {
169
- await callback(options, ...rest);
170
- return await options.next();
171
- };
172
- }
173
- function onSuccess(callback) {
174
- return async (options, ...rest) => {
175
- const result = await options.next();
176
- await callback(result, options, ...rest);
177
- return result;
178
- };
179
- }
180
- function onError(callback) {
181
- return async (options, ...rest) => {
182
- try {
183
- return await options.next();
184
- } catch (error) {
185
- await callback(error, options, ...rest);
186
- throw error;
187
- }
188
- };
189
- }
190
- function onFinish(callback) {
191
- let state;
192
- return async (options, ...rest) => {
193
- try {
194
- const result = await options.next();
195
- state = [null, result, true];
196
- return result;
197
- } catch (error) {
198
- state = [error, void 0, false];
199
- throw error;
200
- } finally {
201
- await callback(state, options, ...rest);
202
- }
203
- };
204
- }
205
- function intercept(interceptors, options, main) {
206
- if (!interceptors?.length) {
207
- return main(options);
208
- }
209
- const next = (options2, index) => {
210
- const interceptor = interceptors[index];
211
- if (!interceptor) {
212
- return main(options2);
176
+ const ACCEPT_ENCODING_QUALITY_REGEX = /^\s*q=([\d.]+)\s*$/i;
177
+ function parseAcceptEncodingQualities(header) {
178
+ const qualities = /* @__PURE__ */ new Map();
179
+ for (const part of header?.split(",") ?? []) {
180
+ const [rawCoding, ...params] = part.split(";");
181
+ const coding = rawCoding.trim().toLowerCase();
182
+ if (coding === "") {
183
+ continue;
213
184
  }
214
- return interceptor({
215
- ...options2,
216
- next: (newOptions = options2) => next(newOptions, index + 1)
217
- });
218
- };
219
- return next(options, 0);
220
- }
221
-
222
- const SPAN_ERROR_STATUS = 2;
223
- const OPENTELEMETRY_CONFIG_SYMBOL = Symbol.for("ORPC_OPENTELEMETRY_CONFIG");
224
- function setOpenTelemetryConfig(config) {
225
- globalThis[OPENTELEMETRY_CONFIG_SYMBOL] = config;
226
- }
227
- function getOpenTelemetryConfig() {
228
- return globalThis[OPENTELEMETRY_CONFIG_SYMBOL];
229
- }
230
- function startSpan(options) {
231
- const tracer = getOpenTelemetryConfig()?.tracer;
232
- if (!tracer) {
233
- return void 0;
234
- }
235
- const { name, context, ...spanOptions } = typeof options === "string" ? { name: options } : options;
236
- return tracer.startSpan(name, spanOptions, context);
237
- }
238
- function recordSpanError(span, error) {
239
- if (!span) {
240
- return;
241
- }
242
- const exception = toOtelException(error);
243
- span.recordException(exception);
244
- if (!isAbortError(error)) {
245
- span.setStatus({
246
- code: SPAN_ERROR_STATUS,
247
- message: exception.message
248
- });
185
+ const quality = params.map((param) => ACCEPT_ENCODING_QUALITY_REGEX.exec(param)?.[1]).find((value) => value !== void 0);
186
+ qualities.set(coding, quality === void 0 ? 1 : Number(quality));
249
187
  }
188
+ return qualities;
250
189
  }
251
- function setSpanAttributeIfDefined(span, key, value) {
252
- if (!span || value === void 0) {
253
- return;
254
- }
255
- span.setAttribute(key, value);
190
+ function isAcceptableEncoding(qualities, coding) {
191
+ return (qualities.get(coding) ?? qualities.get("*") ?? 0) > 0;
256
192
  }
257
- function toOtelException(error) {
258
- if (error instanceof Error) {
259
- const exception = {
260
- message: error.message,
261
- name: error.name,
262
- stack: error.stack
263
- };
264
- if ("code" in error && (typeof error.code === "string" || typeof error.code === "number")) {
265
- exception.code = error.code;
266
- }
267
- return exception;
193
+ function varyByAcceptEncoding(vary) {
194
+ if (vary === void 0) {
195
+ return "accept-encoding";
268
196
  }
269
- return { message: String(error) };
197
+ const fields = vary.split(",").map((field) => field.trim().toLowerCase());
198
+ return fields.includes("accept-encoding") || fields.includes("*") ? vary : `${vary}, accept-encoding`;
270
199
  }
271
- function toSpanAttributeValue(data) {
272
- if (data === void 0) {
273
- return "undefined";
274
- }
275
- try {
276
- return JSON.stringify(data, (_, value) => {
277
- if (typeof value === "bigint") {
278
- return value.toString();
279
- }
280
- if (value instanceof Map || value instanceof Set) {
281
- return Array.from(value);
282
- }
283
- return value;
284
- });
285
- } catch {
286
- return String(data);
200
+ const CACHE_CONTROL_NO_TRANSFORM_REGEX = /(?:^|,)\s*no-transform\s*(?:,|$)/i;
201
+ function isNoTransformCacheControl(cacheControl) {
202
+ if (cacheControl === void 0) {
203
+ return false;
287
204
  }
205
+ return CACHE_CONTROL_NO_TRANSFORM_REGEX.test(cacheControl);
288
206
  }
289
- async function runWithSpan(options, fn) {
290
- const tracer = getOpenTelemetryConfig()?.tracer;
291
- if (!tracer) {
292
- return fn();
293
- }
294
- if (typeof options === "string") {
295
- options = { name: options };
207
+ const COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;
208
+ const MAX_COMPRESSIBLE_CONTENT_TYPE_LENGTH = 1024;
209
+ function isCompressibleContentType(contentType) {
210
+ if (contentType === null || contentType === void 0) {
211
+ return false;
296
212
  }
297
- const callback = async (span) => {
298
- try {
299
- return await fn(span);
300
- } catch (e) {
301
- recordSpanError(span, e);
302
- throw e;
303
- } finally {
304
- span.end();
305
- }
306
- };
307
- if (options.context) {
308
- return tracer.startActiveSpan(options.name, options, options.context, callback);
309
- } else {
310
- return tracer.startActiveSpan(options.name, options, callback);
213
+ if (contentType.length > MAX_COMPRESSIBLE_CONTENT_TYPE_LENGTH) {
214
+ return false;
311
215
  }
216
+ return COMPRESSIBLE_CONTENT_TYPE_REGEX.test(contentType);
312
217
  }
313
- async function runInSpanContext(span, fn) {
314
- const otelConfig = getOpenTelemetryConfig();
315
- if (!span || !otelConfig) {
316
- return fn();
218
+
219
+ function compareSequentialIds(a, b) {
220
+ if (a.length !== b.length) {
221
+ return a.length - b.length;
317
222
  }
318
- const ctx = otelConfig.trace.setSpan(otelConfig.context.active(), span);
319
- return otelConfig.context.with(ctx, fn);
223
+ return a < b ? -1 : a > b ? 1 : 0;
320
224
  }
321
225
 
322
226
  class AsyncIdQueue {
@@ -393,6 +297,93 @@ class AsyncIdQueue {
393
297
  }
394
298
  }
395
299
 
300
+ const TRACER_SYMBOL = Symbol.for("ORPC_TRACER");
301
+ function setTracer(tracer) {
302
+ globalThis[TRACER_SYMBOL] = tracer;
303
+ }
304
+ function getTracer() {
305
+ return globalThis[TRACER_SYMBOL];
306
+ }
307
+ function startSpan(options) {
308
+ const tracer = getTracer();
309
+ if (!tracer) {
310
+ return void 0;
311
+ }
312
+ if (typeof options === "string") {
313
+ return tracer.startSpan(options);
314
+ }
315
+ return tracer.startSpan(options.name, options.parent);
316
+ }
317
+ function recordSpanError(span, error) {
318
+ if (!span) {
319
+ return;
320
+ }
321
+ span.recordException(isAbortError(error) ? "info" : "error", toTracingException(error));
322
+ }
323
+ function setSpanAttributeIfDefined(span, key, value) {
324
+ if (!span || value === void 0) {
325
+ return;
326
+ }
327
+ span.setAttribute(key, value);
328
+ }
329
+ function toTracingException(error) {
330
+ if (error instanceof Error) {
331
+ const exception = {
332
+ message: error.message,
333
+ name: error.name,
334
+ stack: error.stack
335
+ };
336
+ if ("code" in error && (typeof error.code === "string" || typeof error.code === "number")) {
337
+ exception.code = error.code;
338
+ }
339
+ return exception;
340
+ }
341
+ return { message: String(error) };
342
+ }
343
+ function toSpanAttributeValue(data) {
344
+ if (data === void 0) {
345
+ return "undefined";
346
+ }
347
+ try {
348
+ return JSON.stringify(data, (_, value) => {
349
+ if (typeof value === "bigint") {
350
+ return value.toString();
351
+ }
352
+ if (value instanceof Map || value instanceof Set) {
353
+ return Array.from(value);
354
+ }
355
+ return value;
356
+ });
357
+ } catch {
358
+ return String(data);
359
+ }
360
+ }
361
+ async function runWithSpan(options, fn) {
362
+ const tracer = getTracer();
363
+ if (!tracer) {
364
+ return fn();
365
+ }
366
+ const name = typeof options === "string" ? options : options.name;
367
+ const parent = typeof options === "string" ? void 0 : options.parent;
368
+ return tracer.startActiveSpan(name, parent, async (span) => {
369
+ try {
370
+ return await fn(span);
371
+ } catch (e) {
372
+ recordSpanError(span, e);
373
+ throw e;
374
+ } finally {
375
+ span.end();
376
+ }
377
+ });
378
+ }
379
+ function runInSpanContext(span, fn) {
380
+ const tracer = getTracer();
381
+ if (!span || !tracer) {
382
+ return fn();
383
+ }
384
+ return tracer.withActiveSpan(span, fn);
385
+ }
386
+
396
387
  function wrapAsyncIterator(iterator, { runWith, mapResult, mapError, onError, onFinish }) {
397
388
  runWith ??= (run) => run();
398
389
  let isDone;
@@ -491,6 +482,57 @@ function replicateAsyncIterator(source, count) {
491
482
  });
492
483
  return replicated;
493
484
  }
485
+ function consumeAsyncIterator(iterator, options) {
486
+ void (async () => {
487
+ let onFinishState;
488
+ try {
489
+ const resolvedIterator = await iterator;
490
+ while (true) {
491
+ const { done, value } = await resolvedIterator.next();
492
+ if (done) {
493
+ const realValue = value;
494
+ onFinishState = [null, realValue, true];
495
+ options.onSuccess?.(realValue);
496
+ break;
497
+ }
498
+ try {
499
+ options.onEvent(value);
500
+ } catch (error) {
501
+ await resolvedIterator.return?.();
502
+ throw error;
503
+ }
504
+ }
505
+ } catch (error) {
506
+ onFinishState = [error, void 0, false];
507
+ options.onError?.(error);
508
+ } finally {
509
+ options.onFinish?.(onFinishState);
510
+ }
511
+ })();
512
+ return async () => {
513
+ await (await iterator)?.return?.();
514
+ };
515
+ }
516
+
517
+ function value(value2, ...args) {
518
+ if (typeof value2 === "function") {
519
+ return value2(...args);
520
+ }
521
+ return value2;
522
+ }
523
+
524
+ function override(target, partial) {
525
+ const proxy = new Proxy(typeof target === "function" ? partial : target, {
526
+ get(_, prop) {
527
+ const targetValue = prop in partial ? partial : value(target);
528
+ return getOrBind(targetValue, prop);
529
+ },
530
+ has(_, prop) {
531
+ return Reflect.has(partial, prop) || Reflect.has(value(target), prop);
532
+ }
533
+ });
534
+ return proxy;
535
+ }
494
536
 
495
537
  function findDeepMatches(check, payload, segments = [], maps = [], values = []) {
496
538
  if (check(payload)) {
@@ -501,7 +543,7 @@ function findDeepMatches(check, payload, segments = [], maps = [], values = [])
501
543
  findDeepMatches(check, v, [...segments, i], maps, values);
502
544
  });
503
545
  } else if (isPlainObject(payload)) {
504
- for (const key in payload) {
546
+ for (const key of Object.keys(payload)) {
505
547
  findDeepMatches(check, payload[key], [...segments, key], maps, values);
506
548
  }
507
549
  }
@@ -513,6 +555,18 @@ function getConstructor(value) {
513
555
  }
514
556
  return Object.getPrototypeOf(value)?.constructor;
515
557
  }
558
+ function* getConstructors(value) {
559
+ if (!isTypescriptObject(value)) {
560
+ return;
561
+ }
562
+ let proto = Object.getPrototypeOf(value);
563
+ while (proto != null) {
564
+ if (proto.constructor) {
565
+ yield proto.constructor;
566
+ }
567
+ proto = Object.getPrototypeOf(proto);
568
+ }
569
+ }
516
570
  function isPlainObject(value) {
517
571
  if (!value || typeof value !== "object") {
518
572
  return false;
@@ -520,13 +574,16 @@ function isPlainObject(value) {
520
574
  const proto = Object.getPrototypeOf(value);
521
575
  return proto === Object.prototype || !proto || !proto.constructor;
522
576
  }
577
+ function getOwn(object, key) {
578
+ return Object.hasOwn(object, key) ? object[key] : void 0;
579
+ }
523
580
  function get(object, path) {
524
581
  let current = object;
525
582
  for (const key of path) {
526
583
  if (!isTypescriptObject(current)) {
527
584
  return void 0;
528
585
  }
529
- current = current[key];
586
+ current = getOwn(current, key);
530
587
  }
531
588
  return current;
532
589
  }
@@ -534,37 +591,111 @@ function set(root, path, value) {
534
591
  let current = root;
535
592
  for (let i = 0; i < path.length - 1; i++) {
536
593
  const key = path[i];
537
- const next = current[key];
594
+ const next = getOwn(current, key);
538
595
  if (!isTypescriptObject(next)) {
539
- current[key] = {};
596
+ const child = {};
597
+ setOwn(current, key, child);
598
+ current = child;
599
+ } else {
600
+ current = next;
540
601
  }
541
- current = current[key];
542
602
  }
543
- current[path.at(-1)] = value;
603
+ setOwn(current, path.at(-1), value);
544
604
  }
545
- function omit(obj, keys) {
605
+ function setOwn(object, key, value) {
606
+ if (key === "__proto__") {
607
+ Object.defineProperty(object, key, {
608
+ value,
609
+ writable: true,
610
+ enumerable: true,
611
+ configurable: true
612
+ });
613
+ } else {
614
+ object[key] = value;
615
+ }
616
+ }
617
+ function mergeTwoLevels(first, second) {
618
+ if (!isPlainObject(first) || !isPlainObject(second)) {
619
+ return second;
620
+ }
621
+ const result = { ...first, ...second };
622
+ for (const key of Object.keys(second)) {
623
+ if (!Object.hasOwn(first, key)) {
624
+ continue;
625
+ }
626
+ const firstValue = first[key];
627
+ const secondValue = second[key];
628
+ if (isPlainObject(firstValue) && isPlainObject(secondValue)) {
629
+ result[key] = { ...firstValue, ...secondValue };
630
+ }
631
+ }
632
+ return result;
633
+ }
634
+ function omit(obj, keys) {
546
635
  const result = { ...obj };
547
636
  for (const key of keys) {
548
637
  delete result[key];
549
638
  }
550
639
  return result;
551
640
  }
641
+ function pick(obj, keys) {
642
+ const result = {};
643
+ for (const key of keys) {
644
+ if (Object.hasOwn(obj, key)) {
645
+ result[key] = obj[key];
646
+ }
647
+ }
648
+ return result;
649
+ }
552
650
  function clone(value) {
651
+ return cloneWithVisited(value, /* @__PURE__ */ new WeakMap());
652
+ }
653
+ function cloneWithVisited(value, visited) {
553
654
  if (Array.isArray(value)) {
554
- return value.map(clone);
655
+ const existing = visited.get(value);
656
+ if (existing) {
657
+ return existing;
658
+ }
659
+ const result = [];
660
+ visited.set(value, result);
661
+ for (const item of value) {
662
+ result.push(cloneWithVisited(item, visited));
663
+ }
664
+ return result;
555
665
  }
556
666
  if (isPlainObject(value)) {
667
+ const existing = visited.get(value);
668
+ if (existing) {
669
+ return existing;
670
+ }
557
671
  const result = {};
558
- for (const key in value) {
559
- result[key] = clone(value[key]);
672
+ visited.set(value, result);
673
+ for (const key of Object.keys(value)) {
674
+ setOwn(result, key, cloneWithVisited(value[key], visited));
560
675
  }
561
676
  for (const sym of Object.getOwnPropertySymbols(value)) {
562
- result[sym] = clone(value[sym]);
677
+ setOwn(result, sym, cloneWithVisited(value[sym], visited));
563
678
  }
564
679
  return result;
565
680
  }
566
681
  return value;
567
682
  }
683
+ function copyOnWrite(parent, key, original) {
684
+ const value = parent[key];
685
+ if (value !== original) {
686
+ return value;
687
+ }
688
+ let copy;
689
+ if (Array.isArray(value)) {
690
+ copy = value.slice();
691
+ } else if (isPlainObject(value)) {
692
+ copy = { ...value };
693
+ } else {
694
+ return value;
695
+ }
696
+ setOwn(parent, key, copy);
697
+ return copy;
698
+ }
568
699
  function isPropertyKey(value) {
569
700
  const type = typeof value;
570
701
  return type === "string" || type === "number" || type === "symbol";
@@ -576,7 +707,8 @@ const NullProtoObj = /* @__PURE__ */ (() => {
576
707
  Object.freeze(e.prototype);
577
708
  return e;
578
709
  })();
579
- function bindMethods(obj) {
710
+ function bindMethods(obj, options = {}) {
711
+ const unbound = new Set(options.unbound);
580
712
  const methods = new NullProtoObj();
581
713
  let current = obj;
582
714
  while (current && current !== Object.prototype) {
@@ -584,18 +716,18 @@ function bindMethods(obj) {
584
716
  if (key === "constructor" || key in methods) {
585
717
  continue;
586
718
  }
587
- const val = obj[key];
719
+ const val = getOrBind(obj, key, { bind: !unbound.has(key) });
588
720
  if (typeof val === "function") {
589
- methods[key] = val.bind(obj);
721
+ methods[key] = val;
590
722
  }
591
723
  }
592
724
  for (const sym of Object.getOwnPropertySymbols(current)) {
593
725
  if (sym in methods) {
594
726
  continue;
595
727
  }
596
- const val = obj[sym];
728
+ const val = getOrBind(obj, sym, { bind: !unbound.has(sym) });
597
729
  if (typeof val === "function") {
598
- methods[sym] = val.bind(obj);
730
+ methods[sym] = val;
599
731
  }
600
732
  }
601
733
  current = Object.getPrototypeOf(current);
@@ -603,84 +735,6 @@ function bindMethods(obj) {
603
735
  return methods;
604
736
  }
605
737
 
606
- function sortPlugins(plugins) {
607
- const pluginCount = plugins.length;
608
- const pluginIdToIndices = /* @__PURE__ */ new Map();
609
- for (let i = 0; i < pluginCount; i++) {
610
- const plugin = plugins[i];
611
- const indices = pluginIdToIndices.get(plugin.name);
612
- if (indices === void 0) {
613
- pluginIdToIndices.set(plugin.name, [i]);
614
- } else {
615
- indices.push(i);
616
- }
617
- }
618
- const graph = Array.from(
619
- { length: pluginCount },
620
- () => /* @__PURE__ */ new Set()
621
- );
622
- for (let i = 0; i < pluginCount; i++) {
623
- const plugin = plugins[i];
624
- const beforeList = plugin.before;
625
- if (beforeList !== void 0) {
626
- for (const beforeId of beforeList) {
627
- const beforeIndices = pluginIdToIndices.get(beforeId);
628
- if (beforeIndices === void 0)
629
- continue;
630
- for (const beforeIndex of beforeIndices) {
631
- const beforeGraph = graph[beforeIndex];
632
- if (beforeGraph !== void 0) {
633
- beforeGraph.add(i);
634
- }
635
- }
636
- }
637
- }
638
- const afterList = plugin.after;
639
- if (afterList !== void 0) {
640
- const currentGraph = graph[i];
641
- if (currentGraph !== void 0) {
642
- for (const afterId of afterList) {
643
- const afterIndices = pluginIdToIndices.get(afterId);
644
- if (afterIndices === void 0)
645
- continue;
646
- for (const afterIndex of afterIndices) {
647
- currentGraph.add(afterIndex);
648
- }
649
- }
650
- }
651
- }
652
- }
653
- const sorted = [];
654
- const visiting = /* @__PURE__ */ new Set();
655
- const visited = /* @__PURE__ */ new Set();
656
- function visit(index) {
657
- if (visited.has(index))
658
- return;
659
- if (visiting.has(index)) {
660
- const plugin2 = plugins[index];
661
- const pluginId = plugin2 !== void 0 ? plugin2.name : "unknown";
662
- throw new Error(`Circular dependency detected involving plugin "${pluginId}"`);
663
- }
664
- visiting.add(index);
665
- const deps = graph[index];
666
- if (deps !== void 0) {
667
- for (const depIndex of deps) {
668
- visit(depIndex);
669
- }
670
- }
671
- visiting.delete(index);
672
- visited.add(index);
673
- const plugin = plugins[index];
674
- if (plugin !== void 0) {
675
- sorted.push(plugin);
676
- }
677
- }
678
- for (let i = 0; i < pluginCount; i++) {
679
- visit(i);
680
- }
681
- return sorted;
682
- }
683
-
684
738
  function promiseWithResolvers() {
685
739
  const result = {};
686
740
  result.promise = new Promise((resolve, reject) => {
@@ -689,68 +743,18 @@ function promiseWithResolvers() {
689
743
  });
690
744
  return result;
691
745
  }
692
-
693
- function value(value2, ...args) {
694
- if (typeof value2 === "function") {
695
- return value2(...args);
696
- }
697
- return value2;
698
- }
699
-
700
- function override(target, partial) {
701
- const proxy = new Proxy(typeof target === "function" ? partial : target, {
702
- get(_, prop) {
703
- const targetValue = prop in partial ? partial : value(target);
704
- return getOrBind(targetValue, prop);
705
- },
706
- has(_, prop) {
707
- return Reflect.has(partial, prop) || Reflect.has(value(target), prop);
708
- }
709
- });
710
- return proxy;
711
- }
712
-
713
- function allAbortSignal(signals) {
714
- const realSignals = signals.filter((signal) => signal !== void 0);
715
- if (realSignals.length === 0 || realSignals.length !== signals.length) {
716
- return void 0;
717
- }
718
- const controller = new AbortController();
719
- const abortIfAllAborted = () => {
720
- if (realSignals.every((signal) => signal.aborted)) {
721
- controller.abort();
746
+ function captureAsyncContext() {
747
+ const { promise, resolve } = promiseWithResolvers();
748
+ const result = promise.then((callback) => callback());
749
+ let called = false;
750
+ return (callback) => {
751
+ if (called) {
752
+ return Promise.reject(new Error("A captured async context can be run only once."));
722
753
  }
754
+ called = true;
755
+ resolve(callback);
756
+ return result;
723
757
  };
724
- abortIfAllAborted();
725
- for (const signal of realSignals) {
726
- signal.addEventListener("abort", () => {
727
- abortIfAllAborted();
728
- }, {
729
- once: true,
730
- signal: controller.signal
731
- });
732
- }
733
- return controller.signal;
734
- }
735
- async function runWithSignal(signal, fn) {
736
- if (!signal) {
737
- return fn();
738
- }
739
- signal.throwIfAborted();
740
- const { promise, reject, resolve } = promiseWithResolvers();
741
- let abortListener;
742
- signal.addEventListener("abort", abortListener = () => {
743
- reject(signal.reason);
744
- abortListener = void 0;
745
- });
746
- try {
747
- fn().then(resolve, reject);
748
- return await promise;
749
- } finally {
750
- if (abortListener) {
751
- signal.removeEventListener("abort", abortListener);
752
- }
753
- }
754
758
  }
755
759
 
756
760
  function replicateReadableStream(stream, count) {
@@ -823,7 +827,7 @@ function traceReadableStream(options, stream) {
823
827
  }
824
828
  });
825
829
  }
826
- function streamToAsyncIteratorClass(stream, { signal } = {}) {
830
+ function streamToAsyncIteratorObject(stream, { signal } = {}) {
827
831
  const reader = stream.getReader();
828
832
  let cancelledBySignal = false;
829
833
  return new AsyncIteratorClass(
@@ -889,4 +893,208 @@ function asyncIteratorToUnproxiedDataStream(iterator) {
889
893
  });
890
894
  }
891
895
 
892
- export { AsyncIdQueue, NullProtoObj, ORPC_NAME, allAbortSignal, asyncIteratorToStream, asyncIteratorToUnproxiedDataStream, bindMethods, clone, compareSequentialIds, defer, findDeepMatches, get, getConstructor, getOpenTelemetryConfig, intercept, isAbortError, isDeepEqual, isPlainObject, isPropertyKey, loadBytes, matchesHttpPath, matchesHttpPathPrefix, mergeHttpPath, normalizeHttpPath, omit, onError, onFinish, onStart, onSuccess, once, override, pathToHttpPath, promiseWithResolvers, recordSpanError, replicateAsyncIterator, replicateReadableStream, resolveMaybeOptionalOptions, runInSpanContext, runWithSignal, runWithSpan, set, setOpenTelemetryConfig, setSpanAttributeIfDefined, sortPlugins, splitInHalf, startSpan, streamToAsyncIteratorClass, toOtelException, toSpanAttributeValue, toStringOrBytes, traceAsyncIterator, traceReadableStream, tryDecodeURIComponent, tryOrUndefined, value, wrapAsyncIterator, wrapReadableStream };
896
+ function onStart(callback) {
897
+ return async (options, ...rest) => {
898
+ await callback(options, ...rest);
899
+ return await options.next();
900
+ };
901
+ }
902
+ function onSuccess(callback) {
903
+ return async (options, ...rest) => {
904
+ const result = await options.next();
905
+ await callback(result, options, ...rest);
906
+ return result;
907
+ };
908
+ }
909
+ function onError(callback) {
910
+ return async (options, ...rest) => {
911
+ try {
912
+ return await options.next();
913
+ } catch (error) {
914
+ await callback(error, options, ...rest);
915
+ throw error;
916
+ }
917
+ };
918
+ }
919
+ function onFinish(callback) {
920
+ return async (options, ...rest) => {
921
+ let state;
922
+ try {
923
+ const result = await options.next();
924
+ state = [null, result, true];
925
+ return result;
926
+ } catch (error) {
927
+ state = [error, void 0, false];
928
+ throw error;
929
+ } finally {
930
+ await callback(state, options, ...rest);
931
+ }
932
+ };
933
+ }
934
+ function onAsyncIteratorObjectError(callback) {
935
+ return async (options, ...rest) => {
936
+ const output = await options.next();
937
+ if (!isAsyncIteratorObject(output)) {
938
+ return output;
939
+ }
940
+ return override(output, wrapAsyncIterator(output, {
941
+ onError: (error) => callback(error, options, ...rest)
942
+ }));
943
+ };
944
+ }
945
+ function onReadableStreamError(callback) {
946
+ return async (options, ...rest) => {
947
+ const output = await options.next();
948
+ if (!(output instanceof ReadableStream)) {
949
+ return output;
950
+ }
951
+ return override(output, wrapReadableStream(output, {
952
+ onError: (error) => callback(error, options, ...rest)
953
+ }));
954
+ };
955
+ }
956
+ function intercept(interceptors, options, main) {
957
+ if (!interceptors?.length) {
958
+ return main(options);
959
+ }
960
+ const next = (options2, index) => {
961
+ const interceptor = interceptors[index];
962
+ if (!interceptor) {
963
+ return main(options2);
964
+ }
965
+ return interceptor({
966
+ ...options2,
967
+ next: (newOptions = options2) => next(newOptions, index + 1)
968
+ });
969
+ };
970
+ return next(options, 0);
971
+ }
972
+
973
+ function sortPlugins(plugins) {
974
+ const pluginCount = plugins.length;
975
+ const pluginIdToIndices = /* @__PURE__ */ new Map();
976
+ for (let i = 0; i < pluginCount; i++) {
977
+ const plugin = plugins[i];
978
+ const indices = pluginIdToIndices.get(plugin.name);
979
+ if (indices === void 0) {
980
+ pluginIdToIndices.set(plugin.name, [i]);
981
+ } else {
982
+ indices.push(i);
983
+ }
984
+ }
985
+ const dependencies = Array.from({ length: pluginCount }, () => []);
986
+ for (let i = 0; i < pluginCount; i++) {
987
+ const plugin = plugins[i];
988
+ if (plugin.before !== void 0) {
989
+ for (const beforeId of plugin.before) {
990
+ const beforeIndices = pluginIdToIndices.get(beforeId);
991
+ if (beforeIndices !== void 0) {
992
+ for (const beforeIndex of beforeIndices) {
993
+ dependencies[beforeIndex].push(i);
994
+ }
995
+ }
996
+ }
997
+ }
998
+ if (plugin.after !== void 0) {
999
+ for (const afterId of plugin.after) {
1000
+ const afterIndices = pluginIdToIndices.get(afterId);
1001
+ if (afterIndices !== void 0) {
1002
+ for (const afterIndex of afterIndices) {
1003
+ dependencies[i].push(afterIndex);
1004
+ }
1005
+ }
1006
+ }
1007
+ }
1008
+ }
1009
+ const sorted = [];
1010
+ const placed = /* @__PURE__ */ new Set();
1011
+ while (sorted.length < pluginCount) {
1012
+ const next = plugins.findIndex((_, i) => !placed.has(i) && dependencies[i].every((dependency) => placed.has(dependency)));
1013
+ if (next === -1) {
1014
+ throw new Error(`Circular dependency detected involving plugin "${findCyclicPlugin(plugins, dependencies, placed).name}"`);
1015
+ }
1016
+ placed.add(next);
1017
+ sorted.push(plugins[next]);
1018
+ }
1019
+ return sorted;
1020
+ }
1021
+ function findCyclicPlugin(plugins, dependencies, placed) {
1022
+ const seen = /* @__PURE__ */ new Set();
1023
+ let current = plugins.findIndex((_, i) => !placed.has(i));
1024
+ while (!seen.has(current)) {
1025
+ seen.add(current);
1026
+ current = dependencies[current].find((dependency) => !placed.has(dependency));
1027
+ }
1028
+ return plugins[current];
1029
+ }
1030
+
1031
+ function allAbortSignal(signals) {
1032
+ const realSignals = signals.filter((signal) => signal !== void 0);
1033
+ if (realSignals.length === 0 || realSignals.length !== signals.length) {
1034
+ return void 0;
1035
+ }
1036
+ const controller = new AbortController();
1037
+ const abortIfAllAborted = () => {
1038
+ if (realSignals.every((signal) => signal.aborted)) {
1039
+ controller.abort();
1040
+ }
1041
+ };
1042
+ abortIfAllAborted();
1043
+ for (const signal of realSignals) {
1044
+ signal.addEventListener("abort", () => {
1045
+ abortIfAllAborted();
1046
+ }, {
1047
+ once: true,
1048
+ signal: controller.signal
1049
+ });
1050
+ }
1051
+ return controller.signal;
1052
+ }
1053
+ function anyAbortSignal(signals) {
1054
+ const realSignals = signals.filter((signal) => signal !== void 0);
1055
+ if (realSignals.length === 0) {
1056
+ return void 0;
1057
+ }
1058
+ if (realSignals.length === 1) {
1059
+ return realSignals[0];
1060
+ }
1061
+ if (typeof AbortSignal !== "undefined" && typeof AbortSignal.any === "function") {
1062
+ return AbortSignal.any(realSignals);
1063
+ }
1064
+ const controller = new AbortController();
1065
+ for (const signal of realSignals) {
1066
+ if (signal.aborted) {
1067
+ controller.abort(signal.reason);
1068
+ break;
1069
+ }
1070
+ signal.addEventListener("abort", () => {
1071
+ controller.abort(signal.reason);
1072
+ }, {
1073
+ once: true,
1074
+ signal: controller.signal
1075
+ });
1076
+ }
1077
+ return controller.signal;
1078
+ }
1079
+ async function runWithSignal(signal, fn) {
1080
+ if (!signal) {
1081
+ return fn();
1082
+ }
1083
+ throwIfAborted(signal);
1084
+ const { promise, reject, resolve } = promiseWithResolvers();
1085
+ let abortListener;
1086
+ signal.addEventListener("abort", abortListener = () => {
1087
+ reject(signal.reason);
1088
+ abortListener = void 0;
1089
+ });
1090
+ try {
1091
+ fn().then(resolve, reject);
1092
+ return await promise;
1093
+ } finally {
1094
+ if (abortListener) {
1095
+ signal.removeEventListener("abort", abortListener);
1096
+ }
1097
+ }
1098
+ }
1099
+
1100
+ export { AsyncIdQueue, NullProtoObj, ORPC_NAME, allAbortSignal, anyAbortSignal, asyncIteratorToStream, asyncIteratorToUnproxiedDataStream, bindMethods, captureAsyncContext, clone, compareSequentialIds, consumeAsyncIterator, copyOnWrite, defer, findDeepMatches, get, getConstructor, getConstructors, getOwn, getTracer, intercept, isAbortError, isAcceptableEncoding, isAsyncGeneratorFunction, isCompressibleContentType, isDeepEqual, isNoTransformCacheControl, isPlainObject, isPropertyKey, loadBytes, matchesHttpPath, matchesHttpPathPrefix, mergeHttpPath, mergeTwoLevels, normalizeHttpPath, omit, onAsyncIteratorObjectError, onError, onFinish, onReadableStreamError, onStart, onSuccess, once, override, parseAcceptEncodingQualities, pathToHttpPath, pick, promiseWithResolvers, recordSpanError, replicateAsyncIterator, replicateReadableStream, resolveMaybeOptionalOptions, runInSpanContext, runWithSignal, runWithSpan, set, setOwn, setSpanAttributeIfDefined, setTracer, sortPlugins, splitInHalf, startSpan, streamToAsyncIteratorObject, toSpanAttributeValue, toStringOrBytes, toTracingException, traceAsyncIterator, traceReadableStream, tryOrUndefined, value, varyByAcceptEncoding, wrapAsyncIterator, wrapReadableStream };