@temporary-name/shared 1.9.3-alpha.0d2fa3247b6b23bbc2e3097a95f631b86740e4d8

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 ADDED
@@ -0,0 +1,897 @@
1
+ import { resolveMaybeOptionalOptions as resolveMaybeOptionalOptions$1, getConstructor as getConstructor$1, isObject as isObject$1 } from '@temporary-name/shared';
2
+ export { group, guard, mapEntries, mapValues, omit, retry, sleep } from 'radash';
3
+
4
+ function resolveMaybeOptionalOptions(rest) {
5
+ return rest[0] ?? {};
6
+ }
7
+
8
+ function toArray(value) {
9
+ return Array.isArray(value) ? value : value === void 0 || value === null ? [] : [value];
10
+ }
11
+ function splitInHalf(arr) {
12
+ const half = Math.ceil(arr.length / 2);
13
+ return [arr.slice(0, half), arr.slice(half)];
14
+ }
15
+
16
+ function readAsBuffer(source) {
17
+ if (typeof source.bytes === "function") {
18
+ return source.bytes();
19
+ }
20
+ return source.arrayBuffer();
21
+ }
22
+
23
+ const ORPC_NAME = "orpc";
24
+ const ORPC_SHARED_PACKAGE_NAME = "@temporary-name/shared";
25
+ const ORPC_SHARED_PACKAGE_VERSION = "1.9.3-alpha.0d2fa3247b6b23bbc2e3097a95f631b86740e4d8";
26
+
27
+ const ORPC_CLIENT_PACKAGE_NAME = "__ORPC_CLIENT_PACKAGE_NAME_PLACEHOLDER__";
28
+ const ORPC_CLIENT_PACKAGE_VERSION = "__ORPC_CLIENT_PACKAGE_VERSION_PLACEHOLDER__";
29
+ const COMMON_ORPC_ERROR_DEFS = {
30
+ BAD_REQUEST: {
31
+ status: 400,
32
+ message: "Bad Request"
33
+ },
34
+ UNAUTHORIZED: {
35
+ status: 401,
36
+ message: "Unauthorized"
37
+ },
38
+ FORBIDDEN: {
39
+ status: 403,
40
+ message: "Forbidden"
41
+ },
42
+ NOT_FOUND: {
43
+ status: 404,
44
+ message: "Not Found"
45
+ },
46
+ METHOD_NOT_SUPPORTED: {
47
+ status: 405,
48
+ message: "Method Not Supported"
49
+ },
50
+ NOT_ACCEPTABLE: {
51
+ status: 406,
52
+ message: "Not Acceptable"
53
+ },
54
+ TIMEOUT: {
55
+ status: 408,
56
+ message: "Request Timeout"
57
+ },
58
+ CONFLICT: {
59
+ status: 409,
60
+ message: "Conflict"
61
+ },
62
+ PRECONDITION_FAILED: {
63
+ status: 412,
64
+ message: "Precondition Failed"
65
+ },
66
+ PAYLOAD_TOO_LARGE: {
67
+ status: 413,
68
+ message: "Payload Too Large"
69
+ },
70
+ UNSUPPORTED_MEDIA_TYPE: {
71
+ status: 415,
72
+ message: "Unsupported Media Type"
73
+ },
74
+ UNPROCESSABLE_CONTENT: {
75
+ status: 422,
76
+ message: "Unprocessable Content"
77
+ },
78
+ TOO_MANY_REQUESTS: {
79
+ status: 429,
80
+ message: "Too Many Requests"
81
+ },
82
+ CLIENT_CLOSED_REQUEST: {
83
+ status: 499,
84
+ message: "Client Closed Request"
85
+ },
86
+ INTERNAL_SERVER_ERROR: {
87
+ status: 500,
88
+ message: "Internal Server Error"
89
+ },
90
+ NOT_IMPLEMENTED: {
91
+ status: 501,
92
+ message: "Not Implemented"
93
+ },
94
+ BAD_GATEWAY: {
95
+ status: 502,
96
+ message: "Bad Gateway"
97
+ },
98
+ SERVICE_UNAVAILABLE: {
99
+ status: 503,
100
+ message: "Service Unavailable"
101
+ },
102
+ GATEWAY_TIMEOUT: {
103
+ status: 504,
104
+ message: "Gateway Timeout"
105
+ }
106
+ };
107
+ function fallbackORPCErrorStatus(code, status) {
108
+ return status ?? COMMON_ORPC_ERROR_DEFS[code]?.status ?? 500;
109
+ }
110
+ function fallbackORPCErrorMessage(code, message) {
111
+ return message || COMMON_ORPC_ERROR_DEFS[code]?.message || code;
112
+ }
113
+ const GLOBAL_ORPC_ERROR_CONSTRUCTORS_SYMBOL = Symbol.for(
114
+ `__${ORPC_CLIENT_PACKAGE_NAME}@${ORPC_CLIENT_PACKAGE_VERSION}/error/ORPC_ERROR_CONSTRUCTORS__`
115
+ );
116
+ void (globalThis[GLOBAL_ORPC_ERROR_CONSTRUCTORS_SYMBOL] ??= /* @__PURE__ */ new WeakSet());
117
+ const globalORPCErrorConstructors = globalThis[GLOBAL_ORPC_ERROR_CONSTRUCTORS_SYMBOL];
118
+ class ORPCError extends Error {
119
+ defined;
120
+ code;
121
+ status;
122
+ data;
123
+ constructor(code, ...rest) {
124
+ const options = resolveMaybeOptionalOptions$1(rest);
125
+ if (options.status !== void 0 && !isORPCErrorStatus(options.status)) {
126
+ throw new Error("[ORPCError] Invalid error status code.");
127
+ }
128
+ const message = fallbackORPCErrorMessage(code, options.message);
129
+ super(message, options);
130
+ this.code = code;
131
+ this.status = fallbackORPCErrorStatus(code, options.status);
132
+ this.defined = options.defined ?? false;
133
+ this.data = options.data;
134
+ }
135
+ toJSON() {
136
+ return {
137
+ defined: this.defined,
138
+ code: this.code,
139
+ status: this.status,
140
+ message: this.message,
141
+ data: this.data
142
+ };
143
+ }
144
+ /**
145
+ * Workaround for Next.js where different contexts use separate
146
+ * dependency graphs, causing multiple ORPCError constructors existing and breaking
147
+ * `instanceof` checks across contexts.
148
+ *
149
+ * This is particularly problematic with "Optimized SSR", where orpc-client
150
+ * executes in one context but is invoked from another. When an error is thrown
151
+ * in the execution context, `instanceof ORPCError` checks fail in the
152
+ * invocation context due to separate class constructors.
153
+ *
154
+ * @todo Remove this and related code if Next.js resolves the multiple dependency graph issue.
155
+ */
156
+ static [Symbol.hasInstance](instance) {
157
+ if (globalORPCErrorConstructors.has(this)) {
158
+ const constructor = getConstructor$1(instance);
159
+ if (constructor && globalORPCErrorConstructors.has(constructor)) {
160
+ return true;
161
+ }
162
+ }
163
+ return super[Symbol.hasInstance](instance);
164
+ }
165
+ }
166
+ globalORPCErrorConstructors.add(ORPCError);
167
+ function isDefinedError(error) {
168
+ return error instanceof ORPCError && error.defined;
169
+ }
170
+ function toORPCError(error) {
171
+ return error instanceof ORPCError ? error : new ORPCError("INTERNAL_SERVER_ERROR", {
172
+ message: "Internal server error",
173
+ cause: error
174
+ });
175
+ }
176
+ function isORPCErrorStatus(status) {
177
+ return status < 200 || status >= 400;
178
+ }
179
+ function isORPCErrorJson(json) {
180
+ if (!isObject$1(json)) {
181
+ return false;
182
+ }
183
+ const validKeys = ["defined", "code", "status", "message", "data"];
184
+ if (Object.keys(json).some((k) => !validKeys.includes(k))) {
185
+ return false;
186
+ }
187
+ return "defined" in json && typeof json.defined === "boolean" && "code" in json && typeof json.code === "string" && "status" in json && typeof json.status === "number" && isORPCErrorStatus(json.status) && "message" in json && typeof json.message === "string";
188
+ }
189
+ function createORPCErrorFromJson(json, options = {}) {
190
+ return new ORPCError(json.code, {
191
+ ...options,
192
+ ...json
193
+ });
194
+ }
195
+ class AbortError extends Error {
196
+ constructor(...rest) {
197
+ super(...rest);
198
+ this.name = "AbortError";
199
+ }
200
+ }
201
+
202
+ function once(fn) {
203
+ let cached;
204
+ return () => {
205
+ if (cached) {
206
+ return cached.result;
207
+ }
208
+ const result = fn();
209
+ cached = { result };
210
+ return result;
211
+ };
212
+ }
213
+ function sequential(fn) {
214
+ let lastOperationPromise = Promise.resolve();
215
+ return (...args) => {
216
+ return lastOperationPromise = lastOperationPromise.catch(() => {
217
+ }).then(() => {
218
+ return fn(...args);
219
+ });
220
+ };
221
+ }
222
+ function defer(callback) {
223
+ if (typeof setTimeout === "function") {
224
+ setTimeout(callback, 0);
225
+ } else {
226
+ Promise.resolve().then(() => Promise.resolve().then(() => Promise.resolve().then(callback)));
227
+ }
228
+ }
229
+
230
+ const SPAN_ERROR_STATUS = 2;
231
+ const GLOBAL_OTEL_CONFIG_KEY = `__${ORPC_SHARED_PACKAGE_NAME}@${ORPC_SHARED_PACKAGE_VERSION}/otel/config__`;
232
+ function setGlobalOtelConfig(config) {
233
+ globalThis[GLOBAL_OTEL_CONFIG_KEY] = config;
234
+ }
235
+ function getGlobalOtelConfig() {
236
+ return globalThis[GLOBAL_OTEL_CONFIG_KEY];
237
+ }
238
+ function startSpan(name, options = {}, context) {
239
+ const tracer = getGlobalOtelConfig()?.tracer;
240
+ return tracer?.startSpan(name, options, context);
241
+ }
242
+ function setSpanError(span, error, options = {}) {
243
+ if (!span) {
244
+ return;
245
+ }
246
+ const exception = toOtelException(error);
247
+ span.recordException(exception);
248
+ if (!options.signal?.aborted || options.signal.reason !== error) {
249
+ span.setStatus({
250
+ code: SPAN_ERROR_STATUS,
251
+ message: exception.message
252
+ });
253
+ }
254
+ }
255
+ function setSpanAttribute(span, key, value) {
256
+ if (!span || value === void 0) {
257
+ return;
258
+ }
259
+ span.setAttribute(key, value);
260
+ }
261
+ function toOtelException(error) {
262
+ if (error instanceof Error) {
263
+ const exception = {
264
+ message: error.message,
265
+ name: error.name,
266
+ stack: error.stack
267
+ };
268
+ if ("code" in error && (typeof error.code === "string" || typeof error.code === "number")) {
269
+ exception.code = error.code;
270
+ }
271
+ return exception;
272
+ }
273
+ return { message: String(error) };
274
+ }
275
+ function toSpanAttributeValue(data) {
276
+ if (data === void 0) {
277
+ return "undefined";
278
+ }
279
+ try {
280
+ return JSON.stringify(data, (_, value) => {
281
+ if (typeof value === "bigint") {
282
+ return value.toString();
283
+ }
284
+ if (value instanceof Map || value instanceof Set) {
285
+ return Array.from(value);
286
+ }
287
+ return value;
288
+ });
289
+ } catch {
290
+ return String(data);
291
+ }
292
+ }
293
+ async function runWithSpan({ name, context, ...options }, fn) {
294
+ const tracer = getGlobalOtelConfig()?.tracer;
295
+ if (!tracer) {
296
+ return fn();
297
+ }
298
+ const callback = async (span) => {
299
+ try {
300
+ return await fn(span);
301
+ } catch (e) {
302
+ setSpanError(span, e, options);
303
+ throw e;
304
+ } finally {
305
+ span.end();
306
+ }
307
+ };
308
+ if (context) {
309
+ return tracer.startActiveSpan(name, options, context, callback);
310
+ } else {
311
+ return tracer.startActiveSpan(name, options, callback);
312
+ }
313
+ }
314
+ async function runInSpanContext(span, fn) {
315
+ const otelConfig = getGlobalOtelConfig();
316
+ if (!span || !otelConfig) {
317
+ return fn();
318
+ }
319
+ const ctx = otelConfig.trace.setSpan(otelConfig.context.active(), span);
320
+ return otelConfig.context.with(ctx, fn);
321
+ }
322
+
323
+ class AsyncIdQueue {
324
+ openIds = /* @__PURE__ */ new Set();
325
+ queues = /* @__PURE__ */ new Map();
326
+ waiters = /* @__PURE__ */ new Map();
327
+ get length() {
328
+ return this.openIds.size;
329
+ }
330
+ get waiterIds() {
331
+ return Array.from(this.waiters.keys());
332
+ }
333
+ hasBufferedItems(id) {
334
+ return Boolean(this.queues.get(id)?.length);
335
+ }
336
+ open(id) {
337
+ this.openIds.add(id);
338
+ }
339
+ isOpen(id) {
340
+ return this.openIds.has(id);
341
+ }
342
+ push(id, item) {
343
+ this.assertOpen(id);
344
+ const pending = this.waiters.get(id);
345
+ if (pending?.length) {
346
+ pending.shift()[0](item);
347
+ if (pending.length === 0) {
348
+ this.waiters.delete(id);
349
+ }
350
+ } else {
351
+ const items = this.queues.get(id);
352
+ if (items) {
353
+ items.push(item);
354
+ } else {
355
+ this.queues.set(id, [item]);
356
+ }
357
+ }
358
+ }
359
+ async pull(id) {
360
+ this.assertOpen(id);
361
+ const items = this.queues.get(id);
362
+ if (items?.length) {
363
+ const item = items.shift();
364
+ if (items.length === 0) {
365
+ this.queues.delete(id);
366
+ }
367
+ return item;
368
+ }
369
+ return new Promise((resolve, reject) => {
370
+ const waitingPulls = this.waiters.get(id);
371
+ const pending = [resolve, reject];
372
+ if (waitingPulls) {
373
+ waitingPulls.push(pending);
374
+ } else {
375
+ this.waiters.set(id, [pending]);
376
+ }
377
+ });
378
+ }
379
+ close({ id, reason } = {}) {
380
+ if (id === void 0) {
381
+ this.waiters.forEach((pendingPulls, id2) => {
382
+ const error2 = reason ?? new AbortError(`[AsyncIdQueue] Queue[${id2}] was closed or aborted while waiting for pulling.`);
383
+ pendingPulls.forEach(([, reject]) => reject(error2));
384
+ });
385
+ this.waiters.clear();
386
+ this.openIds.clear();
387
+ this.queues.clear();
388
+ return;
389
+ }
390
+ const error = reason ?? new AbortError(`[AsyncIdQueue] Queue[${id}] was closed or aborted while waiting for pulling.`);
391
+ this.waiters.get(id)?.forEach(([, reject]) => reject(error));
392
+ this.waiters.delete(id);
393
+ this.openIds.delete(id);
394
+ this.queues.delete(id);
395
+ }
396
+ assertOpen(id) {
397
+ if (!this.isOpen(id)) {
398
+ throw new Error(`[AsyncIdQueue] Cannot access queue[${id}] because it is not open or aborted.`);
399
+ }
400
+ }
401
+ }
402
+
403
+ function isAsyncIteratorObject(maybe) {
404
+ if (!maybe || typeof maybe !== "object") {
405
+ return false;
406
+ }
407
+ return "next" in maybe && typeof maybe.next === "function" && Symbol.asyncIterator in maybe && typeof maybe[Symbol.asyncIterator] === "function";
408
+ }
409
+ const fallbackAsyncDisposeSymbol = Symbol.for("asyncDispose");
410
+ const asyncDisposeSymbol = Symbol.asyncDispose ?? fallbackAsyncDisposeSymbol;
411
+ class AsyncIteratorClass {
412
+ #isDone = false;
413
+ #isExecuteComplete = false;
414
+ #cleanup;
415
+ #next;
416
+ constructor(next, cleanup) {
417
+ this.#cleanup = cleanup;
418
+ this.#next = sequential(async () => {
419
+ if (this.#isDone) {
420
+ return { done: true, value: void 0 };
421
+ }
422
+ try {
423
+ const result = await next();
424
+ if (result.done) {
425
+ this.#isDone = true;
426
+ }
427
+ return result;
428
+ } catch (err) {
429
+ this.#isDone = true;
430
+ throw err;
431
+ } finally {
432
+ if (this.#isDone && !this.#isExecuteComplete) {
433
+ this.#isExecuteComplete = true;
434
+ await this.#cleanup("next");
435
+ }
436
+ }
437
+ });
438
+ }
439
+ next() {
440
+ return this.#next();
441
+ }
442
+ async return(value) {
443
+ this.#isDone = true;
444
+ if (!this.#isExecuteComplete) {
445
+ this.#isExecuteComplete = true;
446
+ await this.#cleanup("return");
447
+ }
448
+ return { done: true, value };
449
+ }
450
+ async throw(err) {
451
+ this.#isDone = true;
452
+ if (!this.#isExecuteComplete) {
453
+ this.#isExecuteComplete = true;
454
+ await this.#cleanup("throw");
455
+ }
456
+ throw err;
457
+ }
458
+ /**
459
+ * asyncDispose symbol only available in esnext, we should fallback to Symbol.for('asyncDispose')
460
+ */
461
+ async [asyncDisposeSymbol]() {
462
+ this.#isDone = true;
463
+ if (!this.#isExecuteComplete) {
464
+ this.#isExecuteComplete = true;
465
+ await this.#cleanup("dispose");
466
+ }
467
+ }
468
+ [Symbol.asyncIterator]() {
469
+ return this;
470
+ }
471
+ }
472
+ function replicateAsyncIterator(source, count) {
473
+ const queue = new AsyncIdQueue();
474
+ const ids = Array.from({ length: count }, (_, i) => i.toString());
475
+ let isSourceFinished = false;
476
+ const start = once(async () => {
477
+ try {
478
+ while (true) {
479
+ const item = await source.next();
480
+ ids.forEach((id) => {
481
+ if (queue.isOpen(id)) {
482
+ queue.push(id, { next: item });
483
+ }
484
+ });
485
+ if (item.done) {
486
+ break;
487
+ }
488
+ }
489
+ } catch (error) {
490
+ ids.forEach((id) => {
491
+ if (queue.isOpen(id)) {
492
+ queue.push(id, { error });
493
+ }
494
+ });
495
+ } finally {
496
+ isSourceFinished = true;
497
+ }
498
+ });
499
+ const replicated = ids.map((id) => {
500
+ queue.open(id);
501
+ return new AsyncIteratorClass(
502
+ async () => {
503
+ start();
504
+ const item = await queue.pull(id);
505
+ if (item.next) {
506
+ return item.next;
507
+ }
508
+ throw item.error;
509
+ },
510
+ async (reason) => {
511
+ queue.close({ id });
512
+ if (reason !== "next" && !queue.length && !isSourceFinished) {
513
+ isSourceFinished = true;
514
+ await source?.return?.();
515
+ }
516
+ }
517
+ );
518
+ });
519
+ return replicated;
520
+ }
521
+ function asyncIteratorWithSpan({ name, ...options }, iterator) {
522
+ let span;
523
+ return new AsyncIteratorClass(
524
+ async () => {
525
+ span ??= startSpan(name);
526
+ try {
527
+ const result = await runInSpanContext(span, () => iterator.next());
528
+ span?.addEvent(result.done ? "completed" : "yielded");
529
+ return result;
530
+ } catch (err) {
531
+ setSpanError(span, err, options);
532
+ throw err;
533
+ }
534
+ },
535
+ async (reason) => {
536
+ try {
537
+ if (reason !== "next") {
538
+ await runInSpanContext(span, () => iterator.return?.());
539
+ }
540
+ } catch (err) {
541
+ setSpanError(span, err, options);
542
+ throw err;
543
+ } finally {
544
+ span?.end();
545
+ }
546
+ }
547
+ );
548
+ }
549
+
550
+ class EventPublisher {
551
+ #listenersMap = /* @__PURE__ */ new Map();
552
+ #maxBufferedEvents;
553
+ constructor(options = {}) {
554
+ this.#maxBufferedEvents = options.maxBufferedEvents ?? 100;
555
+ }
556
+ get size() {
557
+ return this.#listenersMap.size;
558
+ }
559
+ /**
560
+ * Emits an event and delivers the payload to all subscribed listeners.
561
+ */
562
+ publish(event, payload) {
563
+ const listeners = this.#listenersMap.get(event);
564
+ if (!listeners) {
565
+ return;
566
+ }
567
+ for (const listener of listeners) {
568
+ listener(payload);
569
+ }
570
+ }
571
+ subscribe(event, listenerOrOptions) {
572
+ if (typeof listenerOrOptions === "function") {
573
+ let listeners = this.#listenersMap.get(event);
574
+ if (!listeners) {
575
+ this.#listenersMap.set(event, listeners = /* @__PURE__ */ new Set());
576
+ }
577
+ listeners.add(listenerOrOptions);
578
+ return () => {
579
+ listeners.delete(listenerOrOptions);
580
+ if (listeners.size === 0) {
581
+ this.#listenersMap.delete(event);
582
+ }
583
+ };
584
+ }
585
+ const signal = listenerOrOptions?.signal;
586
+ const maxBufferedEvents = listenerOrOptions?.maxBufferedEvents ?? this.#maxBufferedEvents;
587
+ signal?.throwIfAborted();
588
+ const bufferedEvents = [];
589
+ const pullResolvers = [];
590
+ const unsubscribe = this.subscribe(event, (payload) => {
591
+ const resolver = pullResolvers.shift();
592
+ if (resolver) {
593
+ resolver[0]({ done: false, value: payload });
594
+ } else {
595
+ bufferedEvents.push(payload);
596
+ if (bufferedEvents.length > maxBufferedEvents) {
597
+ bufferedEvents.shift();
598
+ }
599
+ }
600
+ });
601
+ const abortListener = (event2) => {
602
+ unsubscribe();
603
+ pullResolvers.forEach((resolver) => resolver[1](event2.target.reason));
604
+ pullResolvers.length = 0;
605
+ bufferedEvents.length = 0;
606
+ };
607
+ signal?.addEventListener("abort", abortListener, { once: true });
608
+ return new AsyncIteratorClass(
609
+ async () => {
610
+ if (signal?.aborted) {
611
+ throw signal.reason;
612
+ }
613
+ if (bufferedEvents.length > 0) {
614
+ return { done: false, value: bufferedEvents.shift() };
615
+ }
616
+ return new Promise((resolve, reject) => {
617
+ pullResolvers.push([resolve, reject]);
618
+ });
619
+ },
620
+ async () => {
621
+ unsubscribe();
622
+ signal?.removeEventListener("abort", abortListener);
623
+ pullResolvers.forEach((resolver) => resolver[0]({ done: true, value: void 0 }));
624
+ pullResolvers.length = 0;
625
+ bufferedEvents.length = 0;
626
+ }
627
+ );
628
+ }
629
+ }
630
+
631
+ class SequentialIdGenerator {
632
+ index = BigInt(0);
633
+ generate() {
634
+ const id = this.index.toString(32);
635
+ this.index++;
636
+ return id;
637
+ }
638
+ }
639
+
640
+ function onStart(callback) {
641
+ return async (options, ...rest) => {
642
+ await callback(options, ...rest);
643
+ return await options.next();
644
+ };
645
+ }
646
+ function onSuccess(callback) {
647
+ return async (options, ...rest) => {
648
+ const result = await options.next();
649
+ await callback(result, options, ...rest);
650
+ return result;
651
+ };
652
+ }
653
+ function onError(callback) {
654
+ return async (options, ...rest) => {
655
+ try {
656
+ return await options.next();
657
+ } catch (error) {
658
+ await callback(error, options, ...rest);
659
+ throw error;
660
+ }
661
+ };
662
+ }
663
+ function onFinish(callback) {
664
+ let state;
665
+ return async (options, ...rest) => {
666
+ try {
667
+ const result = await options.next();
668
+ state = [null, result, true];
669
+ return result;
670
+ } catch (error) {
671
+ state = [error, void 0, false];
672
+ throw error;
673
+ } finally {
674
+ await callback(state, options, ...rest);
675
+ }
676
+ };
677
+ }
678
+ function intercept(interceptors, options, main) {
679
+ const next = (options2, index) => {
680
+ const interceptor = interceptors[index];
681
+ if (!interceptor) {
682
+ return main(options2);
683
+ }
684
+ return interceptor({
685
+ ...options2,
686
+ next: (newOptions = options2) => next(newOptions, index + 1)
687
+ });
688
+ };
689
+ return next(options, 0);
690
+ }
691
+
692
+ function parseEmptyableJSON(text) {
693
+ if (!text) {
694
+ return void 0;
695
+ }
696
+ return JSON.parse(text);
697
+ }
698
+ function stringifyJSON(value) {
699
+ return JSON.stringify(value);
700
+ }
701
+
702
+ function findDeepMatches(check, payload, segments = [], maps = [], values = []) {
703
+ if (check(payload)) {
704
+ maps.push(segments);
705
+ values.push(payload);
706
+ } else if (Array.isArray(payload)) {
707
+ payload.forEach((v, i) => {
708
+ findDeepMatches(check, v, [...segments, i], maps, values);
709
+ });
710
+ } else if (isObject(payload)) {
711
+ for (const key in payload) {
712
+ findDeepMatches(check, payload[key], [...segments, key], maps, values);
713
+ }
714
+ }
715
+ return { maps, values };
716
+ }
717
+ function getConstructor(value) {
718
+ if (!isTypescriptObject(value)) {
719
+ return null;
720
+ }
721
+ return Object.getPrototypeOf(value)?.constructor;
722
+ }
723
+ function isObject(value) {
724
+ if (!value || typeof value !== "object") {
725
+ return false;
726
+ }
727
+ const proto = Object.getPrototypeOf(value);
728
+ return proto === Object.prototype || !proto || !proto.constructor;
729
+ }
730
+ function isTypescriptObject(value) {
731
+ return !!value && (typeof value === "object" || typeof value === "function");
732
+ }
733
+ function clone(value) {
734
+ if (Array.isArray(value)) {
735
+ return value.map(clone);
736
+ }
737
+ if (isObject(value)) {
738
+ const result = {};
739
+ for (const key in value) {
740
+ result[key] = clone(value[key]);
741
+ }
742
+ return result;
743
+ }
744
+ return value;
745
+ }
746
+ function get(object, path) {
747
+ let current = object;
748
+ for (const key of path) {
749
+ if (!isTypescriptObject(current)) {
750
+ return void 0;
751
+ }
752
+ current = current[key];
753
+ }
754
+ return current;
755
+ }
756
+ function isPropertyKey(value) {
757
+ const type = typeof value;
758
+ return type === "string" || type === "number" || type === "symbol";
759
+ }
760
+ const NullProtoObj = /* @__PURE__ */ (() => {
761
+ const e = function() {
762
+ };
763
+ e.prototype = /* @__PURE__ */ Object.create(null);
764
+ Object.freeze(e.prototype);
765
+ return e;
766
+ })();
767
+
768
+ function value(value2, ...args) {
769
+ if (typeof value2 === "function") {
770
+ return value2(...args);
771
+ }
772
+ return value2;
773
+ }
774
+ function fallback(value2, fallback2) {
775
+ return value2 === void 0 ? fallback2 : value2;
776
+ }
777
+
778
+ function preventNativeAwait(target) {
779
+ return new Proxy(target, {
780
+ get(target2, prop, receiver) {
781
+ const value2 = Reflect.get(target2, prop, receiver);
782
+ if (prop !== "then" || typeof value2 !== "function") {
783
+ return value2;
784
+ }
785
+ return new Proxy(value2, {
786
+ apply(targetFn, thisArg, args) {
787
+ if (args.length !== 2 || args.some((arg) => !isNativeFunction(arg))) {
788
+ return Reflect.apply(targetFn, thisArg, args);
789
+ }
790
+ let shouldOmit = true;
791
+ args[0].call(
792
+ thisArg,
793
+ preventNativeAwait(
794
+ new Proxy(target2, {
795
+ get: (target3, prop2, receiver2) => {
796
+ if (shouldOmit && prop2 === "then") {
797
+ shouldOmit = false;
798
+ return void 0;
799
+ }
800
+ return Reflect.get(target3, prop2, receiver2);
801
+ }
802
+ })
803
+ )
804
+ );
805
+ }
806
+ });
807
+ }
808
+ });
809
+ }
810
+ const NATIVE_FUNCTION_REGEX = /^\s*function\s*\(\)\s*\{\s*\[native code\]\s*\}\s*$/;
811
+ function isNativeFunction(fn) {
812
+ return typeof fn === "function" && NATIVE_FUNCTION_REGEX.test(fn.toString());
813
+ }
814
+ function overlayProxy(target, partial) {
815
+ const proxy = new Proxy(typeof target === "function" ? partial : target, {
816
+ get(_, prop) {
817
+ const targetValue = prop in partial ? partial : value(target);
818
+ const v = Reflect.get(targetValue, prop);
819
+ return typeof v === "function" ? v.bind(targetValue) : v;
820
+ },
821
+ has(_, prop) {
822
+ return Reflect.has(partial, prop) || Reflect.has(value(target), prop);
823
+ }
824
+ });
825
+ return proxy;
826
+ }
827
+
828
+ function streamToAsyncIteratorClass(stream) {
829
+ const reader = stream.getReader();
830
+ return new AsyncIteratorClass(
831
+ async () => {
832
+ return reader.read();
833
+ },
834
+ async () => {
835
+ await reader.cancel();
836
+ }
837
+ );
838
+ }
839
+ function asyncIteratorToStream(iterator) {
840
+ return new ReadableStream({
841
+ async pull(controller) {
842
+ const { done, value } = await iterator.next();
843
+ if (done) {
844
+ controller.close();
845
+ } else {
846
+ controller.enqueue(value);
847
+ }
848
+ },
849
+ async cancel() {
850
+ await iterator.return?.();
851
+ }
852
+ });
853
+ }
854
+
855
+ function tryDecodeURIComponent(value) {
856
+ try {
857
+ return decodeURIComponent(value);
858
+ } catch {
859
+ return value;
860
+ }
861
+ }
862
+
863
+ async function safe(promise) {
864
+ try {
865
+ const output = await promise;
866
+ return Object.assign([null, output, false, true], {
867
+ error: null,
868
+ data: output,
869
+ isDefined: false,
870
+ isSuccess: true
871
+ });
872
+ } catch (e) {
873
+ const error = e;
874
+ if (isDefinedError(error)) {
875
+ return Object.assign([error, void 0, true, false], {
876
+ error,
877
+ data: void 0,
878
+ isDefined: true,
879
+ isSuccess: false
880
+ });
881
+ }
882
+ return Object.assign(
883
+ [error, void 0, false, false],
884
+ {
885
+ error,
886
+ data: void 0,
887
+ isDefined: false,
888
+ isSuccess: false
889
+ }
890
+ );
891
+ }
892
+ }
893
+ function toHttpPath(path) {
894
+ return `/${path.map(encodeURIComponent).join("/")}`;
895
+ }
896
+
897
+ export { AbortError, AsyncIdQueue, AsyncIteratorClass, COMMON_ORPC_ERROR_DEFS, EventPublisher, NullProtoObj, ORPCError, ORPC_CLIENT_PACKAGE_NAME, ORPC_CLIENT_PACKAGE_VERSION, ORPC_NAME, ORPC_SHARED_PACKAGE_NAME, ORPC_SHARED_PACKAGE_VERSION, SequentialIdGenerator, asyncIteratorToStream, asyncIteratorWithSpan, clone, createORPCErrorFromJson, defer, fallback, fallbackORPCErrorMessage, fallbackORPCErrorStatus, findDeepMatches, get, getConstructor, getGlobalOtelConfig, intercept, isAsyncIteratorObject, isDefinedError, isORPCErrorJson, isORPCErrorStatus, isObject, isPropertyKey, isTypescriptObject, onError, onFinish, onStart, onSuccess, once, overlayProxy, parseEmptyableJSON, preventNativeAwait, readAsBuffer, replicateAsyncIterator, resolveMaybeOptionalOptions, runInSpanContext, runWithSpan, safe, sequential, setGlobalOtelConfig, setSpanAttribute, setSpanError, splitInHalf, startSpan, streamToAsyncIteratorClass, stringifyJSON, toArray, toHttpPath, toORPCError, toOtelException, toSpanAttributeValue, tryDecodeURIComponent, value };