@swirls/sdk 0.0.6 → 0.0.7

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.
@@ -1,16 +1,1749 @@
1
+ // ../../node_modules/.bun/@orpc+shared@1.13.4+460773ef8ff1e07c/node_modules/@orpc/shared/dist/index.mjs
2
+ function resolveMaybeOptionalOptions(rest) {
3
+ return rest[0] ?? {};
4
+ }
5
+ function toArray(value2) {
6
+ return Array.isArray(value2) ? value2 : value2 === void 0 || value2 === null ? [] : [value2];
7
+ }
8
+ var ORPC_NAME = "orpc";
9
+ var ORPC_SHARED_PACKAGE_NAME = "@orpc/shared";
10
+ var ORPC_SHARED_PACKAGE_VERSION = "1.13.4";
11
+ var AbortError = class extends Error {
12
+ constructor(...rest) {
13
+ super(...rest);
14
+ this.name = "AbortError";
15
+ }
16
+ };
17
+ function once(fn) {
18
+ let cached;
19
+ return () => {
20
+ if (cached) {
21
+ return cached.result;
22
+ }
23
+ const result = fn();
24
+ cached = { result };
25
+ return result;
26
+ };
27
+ }
28
+ function sequential(fn) {
29
+ let lastOperationPromise = Promise.resolve();
30
+ return (...args) => {
31
+ return lastOperationPromise = lastOperationPromise.catch(() => {
32
+ }).then(() => {
33
+ return fn(...args);
34
+ });
35
+ };
36
+ }
37
+ var SPAN_ERROR_STATUS = 2;
38
+ var GLOBAL_OTEL_CONFIG_KEY = `__${ORPC_SHARED_PACKAGE_NAME}@${ORPC_SHARED_PACKAGE_VERSION}/otel/config__`;
39
+ function getGlobalOtelConfig() {
40
+ return globalThis[GLOBAL_OTEL_CONFIG_KEY];
41
+ }
42
+ function startSpan(name, options = {}, context) {
43
+ const tracer = getGlobalOtelConfig()?.tracer;
44
+ return tracer?.startSpan(name, options, context);
45
+ }
46
+ function setSpanError(span, error, options = {}) {
47
+ if (!span) {
48
+ return;
49
+ }
50
+ const exception = toOtelException(error);
51
+ span.recordException(exception);
52
+ if (!options.signal?.aborted || options.signal.reason !== error) {
53
+ span.setStatus({
54
+ code: SPAN_ERROR_STATUS,
55
+ message: exception.message
56
+ });
57
+ }
58
+ }
59
+ function toOtelException(error) {
60
+ if (error instanceof Error) {
61
+ const exception = {
62
+ message: error.message,
63
+ name: error.name,
64
+ stack: error.stack
65
+ };
66
+ if ("code" in error && (typeof error.code === "string" || typeof error.code === "number")) {
67
+ exception.code = error.code;
68
+ }
69
+ return exception;
70
+ }
71
+ return { message: String(error) };
72
+ }
73
+ async function runWithSpan({ name, context, ...options }, fn) {
74
+ const tracer = getGlobalOtelConfig()?.tracer;
75
+ if (!tracer) {
76
+ return fn();
77
+ }
78
+ const callback = async (span) => {
79
+ try {
80
+ return await fn(span);
81
+ } catch (e) {
82
+ setSpanError(span, e, options);
83
+ throw e;
84
+ } finally {
85
+ span.end();
86
+ }
87
+ };
88
+ if (context) {
89
+ return tracer.startActiveSpan(name, options, context, callback);
90
+ } else {
91
+ return tracer.startActiveSpan(name, options, callback);
92
+ }
93
+ }
94
+ async function runInSpanContext(span, fn) {
95
+ const otelConfig = getGlobalOtelConfig();
96
+ if (!span || !otelConfig) {
97
+ return fn();
98
+ }
99
+ const ctx = otelConfig.trace.setSpan(otelConfig.context.active(), span);
100
+ return otelConfig.context.with(ctx, fn);
101
+ }
102
+ function isAsyncIteratorObject(maybe) {
103
+ if (!maybe || typeof maybe !== "object") {
104
+ return false;
105
+ }
106
+ return "next" in maybe && typeof maybe.next === "function" && Symbol.asyncIterator in maybe && typeof maybe[Symbol.asyncIterator] === "function";
107
+ }
108
+ var fallbackAsyncDisposeSymbol = /* @__PURE__ */ Symbol.for("asyncDispose");
109
+ var asyncDisposeSymbol = Symbol.asyncDispose ?? fallbackAsyncDisposeSymbol;
110
+ var AsyncIteratorClass = class {
111
+ #isDone = false;
112
+ #isExecuteComplete = false;
113
+ #cleanup;
114
+ #next;
115
+ constructor(next, cleanup) {
116
+ this.#cleanup = cleanup;
117
+ this.#next = sequential(async () => {
118
+ if (this.#isDone) {
119
+ return { done: true, value: void 0 };
120
+ }
121
+ try {
122
+ const result = await next();
123
+ if (result.done) {
124
+ this.#isDone = true;
125
+ }
126
+ return result;
127
+ } catch (err) {
128
+ this.#isDone = true;
129
+ throw err;
130
+ } finally {
131
+ if (this.#isDone && !this.#isExecuteComplete) {
132
+ this.#isExecuteComplete = true;
133
+ await this.#cleanup("next");
134
+ }
135
+ }
136
+ });
137
+ }
138
+ next() {
139
+ return this.#next();
140
+ }
141
+ async return(value2) {
142
+ this.#isDone = true;
143
+ if (!this.#isExecuteComplete) {
144
+ this.#isExecuteComplete = true;
145
+ await this.#cleanup("return");
146
+ }
147
+ return { done: true, value: value2 };
148
+ }
149
+ async throw(err) {
150
+ this.#isDone = true;
151
+ if (!this.#isExecuteComplete) {
152
+ this.#isExecuteComplete = true;
153
+ await this.#cleanup("throw");
154
+ }
155
+ throw err;
156
+ }
157
+ /**
158
+ * asyncDispose symbol only available in esnext, we should fallback to Symbol.for('asyncDispose')
159
+ */
160
+ async [asyncDisposeSymbol]() {
161
+ this.#isDone = true;
162
+ if (!this.#isExecuteComplete) {
163
+ this.#isExecuteComplete = true;
164
+ await this.#cleanup("dispose");
165
+ }
166
+ }
167
+ [Symbol.asyncIterator]() {
168
+ return this;
169
+ }
170
+ };
171
+ function asyncIteratorWithSpan({ name, ...options }, iterator) {
172
+ let span;
173
+ return new AsyncIteratorClass(
174
+ async () => {
175
+ span ??= startSpan(name);
176
+ try {
177
+ const result = await runInSpanContext(span, () => iterator.next());
178
+ span?.addEvent(result.done ? "completed" : "yielded");
179
+ return result;
180
+ } catch (err) {
181
+ setSpanError(span, err, options);
182
+ throw err;
183
+ }
184
+ },
185
+ async (reason) => {
186
+ try {
187
+ if (reason !== "next") {
188
+ await runInSpanContext(span, () => iterator.return?.());
189
+ }
190
+ } catch (err) {
191
+ setSpanError(span, err, options);
192
+ throw err;
193
+ } finally {
194
+ span?.end();
195
+ }
196
+ }
197
+ );
198
+ }
199
+ function intercept(interceptors, options, main) {
200
+ const next = (options2, index) => {
201
+ const interceptor = interceptors[index];
202
+ if (!interceptor) {
203
+ return main(options2);
204
+ }
205
+ return interceptor({
206
+ ...options2,
207
+ next: (newOptions = options2) => next(newOptions, index + 1)
208
+ });
209
+ };
210
+ return next(options, 0);
211
+ }
212
+ function parseEmptyableJSON(text) {
213
+ if (!text) {
214
+ return void 0;
215
+ }
216
+ return JSON.parse(text);
217
+ }
218
+ function stringifyJSON(value2) {
219
+ return JSON.stringify(value2);
220
+ }
221
+ function getConstructor(value2) {
222
+ if (!isTypescriptObject(value2)) {
223
+ return null;
224
+ }
225
+ return Object.getPrototypeOf(value2)?.constructor;
226
+ }
227
+ function isObject(value2) {
228
+ if (!value2 || typeof value2 !== "object") {
229
+ return false;
230
+ }
231
+ const proto = Object.getPrototypeOf(value2);
232
+ return proto === Object.prototype || !proto || !proto.constructor;
233
+ }
234
+ function isTypescriptObject(value2) {
235
+ return !!value2 && (typeof value2 === "object" || typeof value2 === "function");
236
+ }
237
+ function get(object, path) {
238
+ let current = object;
239
+ for (const key of path) {
240
+ if (!isTypescriptObject(current)) {
241
+ return void 0;
242
+ }
243
+ current = current[key];
244
+ }
245
+ return current;
246
+ }
247
+ function value(value2, ...args) {
248
+ if (typeof value2 === "function") {
249
+ return value2(...args);
250
+ }
251
+ return value2;
252
+ }
253
+ function preventNativeAwait(target) {
254
+ return new Proxy(target, {
255
+ get(target2, prop, receiver) {
256
+ const value2 = Reflect.get(target2, prop, receiver);
257
+ if (prop !== "then" || typeof value2 !== "function") {
258
+ return value2;
259
+ }
260
+ return new Proxy(value2, {
261
+ apply(targetFn, thisArg, args) {
262
+ if (args.length !== 2 || args.some((arg) => !isNativeFunction(arg))) {
263
+ return Reflect.apply(targetFn, thisArg, args);
264
+ }
265
+ let shouldOmit = true;
266
+ args[0].call(thisArg, preventNativeAwait(new Proxy(target2, {
267
+ get: (target3, prop2, receiver2) => {
268
+ if (shouldOmit && prop2 === "then") {
269
+ shouldOmit = false;
270
+ return void 0;
271
+ }
272
+ return Reflect.get(target3, prop2, receiver2);
273
+ }
274
+ })));
275
+ }
276
+ });
277
+ }
278
+ });
279
+ }
280
+ var NATIVE_FUNCTION_REGEX = /^\s*function\s*\(\)\s*\{\s*\[native code\]\s*\}\s*$/;
281
+ function isNativeFunction(fn) {
282
+ return typeof fn === "function" && NATIVE_FUNCTION_REGEX.test(fn.toString());
283
+ }
284
+ function tryDecodeURIComponent(value2) {
285
+ try {
286
+ return decodeURIComponent(value2);
287
+ } catch {
288
+ return value2;
289
+ }
290
+ }
291
+
292
+ // ../../node_modules/.bun/@orpc+client@1.13.4+460773ef8ff1e07c/node_modules/@orpc/client/dist/shared/client.BwSYEMrK.mjs
293
+ var ORPC_CLIENT_PACKAGE_NAME = "@orpc/client";
294
+ var ORPC_CLIENT_PACKAGE_VERSION = "1.13.4";
295
+ var COMMON_ORPC_ERROR_DEFS = {
296
+ BAD_REQUEST: {
297
+ status: 400,
298
+ message: "Bad Request"
299
+ },
300
+ UNAUTHORIZED: {
301
+ status: 401,
302
+ message: "Unauthorized"
303
+ },
304
+ FORBIDDEN: {
305
+ status: 403,
306
+ message: "Forbidden"
307
+ },
308
+ NOT_FOUND: {
309
+ status: 404,
310
+ message: "Not Found"
311
+ },
312
+ METHOD_NOT_SUPPORTED: {
313
+ status: 405,
314
+ message: "Method Not Supported"
315
+ },
316
+ NOT_ACCEPTABLE: {
317
+ status: 406,
318
+ message: "Not Acceptable"
319
+ },
320
+ TIMEOUT: {
321
+ status: 408,
322
+ message: "Request Timeout"
323
+ },
324
+ CONFLICT: {
325
+ status: 409,
326
+ message: "Conflict"
327
+ },
328
+ PRECONDITION_FAILED: {
329
+ status: 412,
330
+ message: "Precondition Failed"
331
+ },
332
+ PAYLOAD_TOO_LARGE: {
333
+ status: 413,
334
+ message: "Payload Too Large"
335
+ },
336
+ UNSUPPORTED_MEDIA_TYPE: {
337
+ status: 415,
338
+ message: "Unsupported Media Type"
339
+ },
340
+ UNPROCESSABLE_CONTENT: {
341
+ status: 422,
342
+ message: "Unprocessable Content"
343
+ },
344
+ TOO_MANY_REQUESTS: {
345
+ status: 429,
346
+ message: "Too Many Requests"
347
+ },
348
+ CLIENT_CLOSED_REQUEST: {
349
+ status: 499,
350
+ message: "Client Closed Request"
351
+ },
352
+ INTERNAL_SERVER_ERROR: {
353
+ status: 500,
354
+ message: "Internal Server Error"
355
+ },
356
+ NOT_IMPLEMENTED: {
357
+ status: 501,
358
+ message: "Not Implemented"
359
+ },
360
+ BAD_GATEWAY: {
361
+ status: 502,
362
+ message: "Bad Gateway"
363
+ },
364
+ SERVICE_UNAVAILABLE: {
365
+ status: 503,
366
+ message: "Service Unavailable"
367
+ },
368
+ GATEWAY_TIMEOUT: {
369
+ status: 504,
370
+ message: "Gateway Timeout"
371
+ }
372
+ };
373
+ function fallbackORPCErrorStatus(code, status) {
374
+ return status ?? COMMON_ORPC_ERROR_DEFS[code]?.status ?? 500;
375
+ }
376
+ function fallbackORPCErrorMessage(code, message) {
377
+ return message || COMMON_ORPC_ERROR_DEFS[code]?.message || code;
378
+ }
379
+ var GLOBAL_ORPC_ERROR_CONSTRUCTORS_SYMBOL = /* @__PURE__ */ Symbol.for(`__${ORPC_CLIENT_PACKAGE_NAME}@${ORPC_CLIENT_PACKAGE_VERSION}/error/ORPC_ERROR_CONSTRUCTORS__`);
380
+ void (globalThis[GLOBAL_ORPC_ERROR_CONSTRUCTORS_SYMBOL] ??= /* @__PURE__ */ new WeakSet());
381
+ var globalORPCErrorConstructors = globalThis[GLOBAL_ORPC_ERROR_CONSTRUCTORS_SYMBOL];
382
+ var ORPCError = class extends Error {
383
+ defined;
384
+ code;
385
+ status;
386
+ data;
387
+ constructor(code, ...rest) {
388
+ const options = resolveMaybeOptionalOptions(rest);
389
+ if (options.status !== void 0 && !isORPCErrorStatus(options.status)) {
390
+ throw new Error("[ORPCError] Invalid error status code.");
391
+ }
392
+ const message = fallbackORPCErrorMessage(code, options.message);
393
+ super(message, options);
394
+ this.code = code;
395
+ this.status = fallbackORPCErrorStatus(code, options.status);
396
+ this.defined = options.defined ?? false;
397
+ this.data = options.data;
398
+ }
399
+ toJSON() {
400
+ return {
401
+ defined: this.defined,
402
+ code: this.code,
403
+ status: this.status,
404
+ message: this.message,
405
+ data: this.data
406
+ };
407
+ }
408
+ /**
409
+ * Workaround for Next.js where different contexts use separate
410
+ * dependency graphs, causing multiple ORPCError constructors existing and breaking
411
+ * `instanceof` checks across contexts.
412
+ *
413
+ * This is particularly problematic with "Optimized SSR", where orpc-client
414
+ * executes in one context but is invoked from another. When an error is thrown
415
+ * in the execution context, `instanceof ORPCError` checks fail in the
416
+ * invocation context due to separate class constructors.
417
+ *
418
+ * @todo Remove this and related code if Next.js resolves the multiple dependency graph issue.
419
+ */
420
+ static [Symbol.hasInstance](instance) {
421
+ if (globalORPCErrorConstructors.has(this)) {
422
+ const constructor = getConstructor(instance);
423
+ if (constructor && globalORPCErrorConstructors.has(constructor)) {
424
+ return true;
425
+ }
426
+ }
427
+ return super[Symbol.hasInstance](instance);
428
+ }
429
+ };
430
+ globalORPCErrorConstructors.add(ORPCError);
431
+ function toORPCError(error) {
432
+ return error instanceof ORPCError ? error : new ORPCError("INTERNAL_SERVER_ERROR", {
433
+ message: "Internal server error",
434
+ cause: error
435
+ });
436
+ }
437
+ function isORPCErrorStatus(status) {
438
+ return status < 200 || status >= 400;
439
+ }
440
+ function isORPCErrorJson(json) {
441
+ if (!isObject(json)) {
442
+ return false;
443
+ }
444
+ const validKeys = ["defined", "code", "status", "message", "data"];
445
+ if (Object.keys(json).some((k) => !validKeys.includes(k))) {
446
+ return false;
447
+ }
448
+ 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";
449
+ }
450
+ function createORPCErrorFromJson(json, options = {}) {
451
+ return new ORPCError(json.code, {
452
+ ...options,
453
+ ...json
454
+ });
455
+ }
456
+
457
+ // ../../node_modules/.bun/@orpc+standard-server@1.13.4+460773ef8ff1e07c/node_modules/@orpc/standard-server/dist/index.mjs
458
+ var EventEncoderError = class extends TypeError {
459
+ };
460
+ var EventDecoderError = class extends TypeError {
461
+ };
462
+ var ErrorEvent = class extends Error {
463
+ data;
464
+ constructor(options) {
465
+ super(options?.message ?? "An error event was received", options);
466
+ this.data = options?.data;
467
+ }
468
+ };
469
+ function decodeEventMessage(encoded) {
470
+ const lines = encoded.replace(/\n+$/, "").split(/\n/);
471
+ const message = {
472
+ data: void 0,
473
+ event: void 0,
474
+ id: void 0,
475
+ retry: void 0,
476
+ comments: []
477
+ };
478
+ for (const line of lines) {
479
+ const index = line.indexOf(":");
480
+ const key = index === -1 ? line : line.slice(0, index);
481
+ const value2 = index === -1 ? "" : line.slice(index + 1).replace(/^\s/, "");
482
+ if (index === 0) {
483
+ message.comments.push(value2);
484
+ } else if (key === "data") {
485
+ message.data ??= "";
486
+ message.data += `${value2}
487
+ `;
488
+ } else if (key === "event") {
489
+ message.event = value2;
490
+ } else if (key === "id") {
491
+ message.id = value2;
492
+ } else if (key === "retry") {
493
+ const maybeInteger = Number.parseInt(value2);
494
+ if (Number.isInteger(maybeInteger) && maybeInteger >= 0 && maybeInteger.toString() === value2) {
495
+ message.retry = maybeInteger;
496
+ }
497
+ }
498
+ }
499
+ message.data = message.data?.replace(/\n$/, "");
500
+ return message;
501
+ }
502
+ var EventDecoder = class {
503
+ constructor(options = {}) {
504
+ this.options = options;
505
+ }
506
+ incomplete = "";
507
+ feed(chunk) {
508
+ this.incomplete += chunk;
509
+ const lastCompleteIndex = this.incomplete.lastIndexOf("\n\n");
510
+ if (lastCompleteIndex === -1) {
511
+ return;
512
+ }
513
+ const completes = this.incomplete.slice(0, lastCompleteIndex).split(/\n\n/);
514
+ this.incomplete = this.incomplete.slice(lastCompleteIndex + 2);
515
+ for (const encoded of completes) {
516
+ const message = decodeEventMessage(`${encoded}
517
+
518
+ `);
519
+ if (this.options.onEvent) {
520
+ this.options.onEvent(message);
521
+ }
522
+ }
523
+ }
524
+ end() {
525
+ if (this.incomplete) {
526
+ throw new EventDecoderError("Event Iterator ended before complete");
527
+ }
528
+ }
529
+ };
530
+ var EventDecoderStream = class extends TransformStream {
531
+ constructor() {
532
+ let decoder;
533
+ super({
534
+ start(controller) {
535
+ decoder = new EventDecoder({
536
+ onEvent: (event) => {
537
+ controller.enqueue(event);
538
+ }
539
+ });
540
+ },
541
+ transform(chunk) {
542
+ decoder.feed(chunk);
543
+ },
544
+ flush() {
545
+ decoder.end();
546
+ }
547
+ });
548
+ }
549
+ };
550
+ function assertEventId(id) {
551
+ if (id.includes("\n")) {
552
+ throw new EventEncoderError("Event's id must not contain a newline character");
553
+ }
554
+ }
555
+ function assertEventName(event) {
556
+ if (event.includes("\n")) {
557
+ throw new EventEncoderError("Event's event must not contain a newline character");
558
+ }
559
+ }
560
+ function assertEventRetry(retry) {
561
+ if (!Number.isInteger(retry) || retry < 0) {
562
+ throw new EventEncoderError("Event's retry must be a integer and >= 0");
563
+ }
564
+ }
565
+ function assertEventComment(comment) {
566
+ if (comment.includes("\n")) {
567
+ throw new EventEncoderError("Event's comment must not contain a newline character");
568
+ }
569
+ }
570
+ function encodeEventData(data) {
571
+ const lines = data?.split(/\n/) ?? [];
572
+ let output = "";
573
+ for (const line of lines) {
574
+ output += `data: ${line}
575
+ `;
576
+ }
577
+ return output;
578
+ }
579
+ function encodeEventComments(comments) {
580
+ let output = "";
581
+ for (const comment of comments ?? []) {
582
+ assertEventComment(comment);
583
+ output += `: ${comment}
584
+ `;
585
+ }
586
+ return output;
587
+ }
588
+ function encodeEventMessage(message) {
589
+ let output = "";
590
+ output += encodeEventComments(message.comments);
591
+ if (message.event !== void 0) {
592
+ assertEventName(message.event);
593
+ output += `event: ${message.event}
594
+ `;
595
+ }
596
+ if (message.retry !== void 0) {
597
+ assertEventRetry(message.retry);
598
+ output += `retry: ${message.retry}
599
+ `;
600
+ }
601
+ if (message.id !== void 0) {
602
+ assertEventId(message.id);
603
+ output += `id: ${message.id}
604
+ `;
605
+ }
606
+ output += encodeEventData(message.data);
607
+ output += "\n";
608
+ return output;
609
+ }
610
+ var EVENT_SOURCE_META_SYMBOL = /* @__PURE__ */ Symbol("ORPC_EVENT_SOURCE_META");
611
+ function withEventMeta(container, meta) {
612
+ if (meta.id === void 0 && meta.retry === void 0 && !meta.comments?.length) {
613
+ return container;
614
+ }
615
+ if (meta.id !== void 0) {
616
+ assertEventId(meta.id);
617
+ }
618
+ if (meta.retry !== void 0) {
619
+ assertEventRetry(meta.retry);
620
+ }
621
+ if (meta.comments !== void 0) {
622
+ for (const comment of meta.comments) {
623
+ assertEventComment(comment);
624
+ }
625
+ }
626
+ return new Proxy(container, {
627
+ get(target, prop, receiver) {
628
+ if (prop === EVENT_SOURCE_META_SYMBOL) {
629
+ return meta;
630
+ }
631
+ return Reflect.get(target, prop, receiver);
632
+ }
633
+ });
634
+ }
635
+ function getEventMeta(container) {
636
+ return isTypescriptObject(container) ? Reflect.get(container, EVENT_SOURCE_META_SYMBOL) : void 0;
637
+ }
638
+ function generateContentDisposition(filename) {
639
+ const escapedFileName = filename.replace(/"/g, '\\"');
640
+ const encodedFilenameStar = encodeURIComponent(filename).replace(/['()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%(7C|60|5E)/g, (str, hex) => String.fromCharCode(Number.parseInt(hex, 16)));
641
+ return `inline; filename="${escapedFileName}"; filename*=utf-8''${encodedFilenameStar}`;
642
+ }
643
+ function getFilenameFromContentDisposition(contentDisposition) {
644
+ const encodedFilenameStarMatch = contentDisposition.match(/filename\*=(UTF-8'')?([^;]*)/i);
645
+ if (encodedFilenameStarMatch && typeof encodedFilenameStarMatch[2] === "string") {
646
+ return tryDecodeURIComponent(encodedFilenameStarMatch[2]);
647
+ }
648
+ const encodedFilenameMatch = contentDisposition.match(/filename="((?:\\"|[^"])*)"/i);
649
+ if (encodedFilenameMatch && typeof encodedFilenameMatch[1] === "string") {
650
+ return encodedFilenameMatch[1].replace(/\\"/g, '"');
651
+ }
652
+ }
653
+ function mergeStandardHeaders(a, b) {
654
+ const merged = { ...a };
655
+ for (const key in b) {
656
+ if (Array.isArray(b[key])) {
657
+ merged[key] = [...toArray(merged[key]), ...b[key]];
658
+ } else if (b[key] !== void 0) {
659
+ if (Array.isArray(merged[key])) {
660
+ merged[key] = [...merged[key], b[key]];
661
+ } else if (merged[key] !== void 0) {
662
+ merged[key] = [merged[key], b[key]];
663
+ } else {
664
+ merged[key] = b[key];
665
+ }
666
+ }
667
+ }
668
+ return merged;
669
+ }
670
+
671
+ // ../../node_modules/.bun/@orpc+client@1.13.4+460773ef8ff1e07c/node_modules/@orpc/client/dist/shared/client.BLtwTQUg.mjs
672
+ function mapEventIterator(iterator, maps) {
673
+ const mapError = async (error) => {
674
+ let mappedError = await maps.error(error);
675
+ if (mappedError !== error) {
676
+ const meta = getEventMeta(error);
677
+ if (meta && isTypescriptObject(mappedError)) {
678
+ mappedError = withEventMeta(mappedError, meta);
679
+ }
680
+ }
681
+ return mappedError;
682
+ };
683
+ return new AsyncIteratorClass(async () => {
684
+ const { done, value: value2 } = await (async () => {
685
+ try {
686
+ return await iterator.next();
687
+ } catch (error) {
688
+ throw await mapError(error);
689
+ }
690
+ })();
691
+ let mappedValue = await maps.value(value2, done);
692
+ if (mappedValue !== value2) {
693
+ const meta = getEventMeta(value2);
694
+ if (meta && isTypescriptObject(mappedValue)) {
695
+ mappedValue = withEventMeta(mappedValue, meta);
696
+ }
697
+ }
698
+ return { done, value: mappedValue };
699
+ }, async () => {
700
+ try {
701
+ await iterator.return?.();
702
+ } catch (error) {
703
+ throw await mapError(error);
704
+ }
705
+ });
706
+ }
707
+
708
+ // ../../node_modules/.bun/@orpc+client@1.13.4+460773ef8ff1e07c/node_modules/@orpc/client/dist/index.mjs
709
+ function resolveFriendlyClientOptions(options) {
710
+ return {
711
+ ...options,
712
+ context: options.context ?? {}
713
+ // Context only optional if all fields are optional
714
+ };
715
+ }
716
+ function createORPCClient(link, options = {}) {
717
+ const path = options.path ?? [];
718
+ const procedureClient = async (...[input, options2 = {}]) => {
719
+ return await link.call(path, input, resolveFriendlyClientOptions(options2));
720
+ };
721
+ const recursive = new Proxy(procedureClient, {
722
+ get(target, key) {
723
+ if (typeof key !== "string") {
724
+ return Reflect.get(target, key);
725
+ }
726
+ return createORPCClient(link, {
727
+ ...options,
728
+ path: [...path, key]
729
+ });
730
+ }
731
+ });
732
+ return preventNativeAwait(recursive);
733
+ }
734
+
735
+ // ../../node_modules/.bun/@orpc+standard-server-fetch@1.13.4+460773ef8ff1e07c/node_modules/@orpc/standard-server-fetch/dist/index.mjs
736
+ function toEventIterator(stream, options = {}) {
737
+ const eventStream = stream?.pipeThrough(new TextDecoderStream()).pipeThrough(new EventDecoderStream());
738
+ const reader = eventStream?.getReader();
739
+ let span;
740
+ let isCancelled = false;
741
+ return new AsyncIteratorClass(async () => {
742
+ span ??= startSpan("consume_event_iterator_stream");
743
+ try {
744
+ while (true) {
745
+ if (reader === void 0) {
746
+ return { done: true, value: void 0 };
747
+ }
748
+ const { done, value: value2 } = await runInSpanContext(span, () => reader.read());
749
+ if (done) {
750
+ if (isCancelled) {
751
+ throw new AbortError("Stream was cancelled");
752
+ }
753
+ return { done: true, value: void 0 };
754
+ }
755
+ switch (value2.event) {
756
+ case "message": {
757
+ let message = parseEmptyableJSON(value2.data);
758
+ if (isTypescriptObject(message)) {
759
+ message = withEventMeta(message, value2);
760
+ }
761
+ span?.addEvent("message");
762
+ return { done: false, value: message };
763
+ }
764
+ case "error": {
765
+ let error = new ErrorEvent({
766
+ data: parseEmptyableJSON(value2.data)
767
+ });
768
+ error = withEventMeta(error, value2);
769
+ span?.addEvent("error");
770
+ throw error;
771
+ }
772
+ case "done": {
773
+ let done2 = parseEmptyableJSON(value2.data);
774
+ if (isTypescriptObject(done2)) {
775
+ done2 = withEventMeta(done2, value2);
776
+ }
777
+ span?.addEvent("done");
778
+ return { done: true, value: done2 };
779
+ }
780
+ default: {
781
+ span?.addEvent("maybe_keepalive");
782
+ }
783
+ }
784
+ }
785
+ } catch (e) {
786
+ if (!(e instanceof ErrorEvent)) {
787
+ setSpanError(span, e, options);
788
+ }
789
+ throw e;
790
+ }
791
+ }, async (reason) => {
792
+ try {
793
+ if (reason !== "next") {
794
+ isCancelled = true;
795
+ span?.addEvent("cancelled");
796
+ }
797
+ await runInSpanContext(span, () => reader?.cancel());
798
+ } catch (e) {
799
+ setSpanError(span, e, options);
800
+ throw e;
801
+ } finally {
802
+ span?.end();
803
+ }
804
+ });
805
+ }
806
+ function toEventStream(iterator, options = {}) {
807
+ const keepAliveEnabled = options.eventIteratorKeepAliveEnabled ?? true;
808
+ const keepAliveInterval = options.eventIteratorKeepAliveInterval ?? 5e3;
809
+ const keepAliveComment = options.eventIteratorKeepAliveComment ?? "";
810
+ const initialCommentEnabled = options.eventIteratorInitialCommentEnabled ?? true;
811
+ const initialComment = options.eventIteratorInitialComment ?? "";
812
+ let cancelled = false;
813
+ let timeout;
814
+ let span;
815
+ const stream = new ReadableStream({
816
+ start(controller) {
817
+ span = startSpan("stream_event_iterator");
818
+ if (initialCommentEnabled) {
819
+ controller.enqueue(encodeEventMessage({
820
+ comments: [initialComment]
821
+ }));
822
+ }
823
+ },
824
+ async pull(controller) {
825
+ try {
826
+ if (keepAliveEnabled) {
827
+ timeout = setInterval(() => {
828
+ controller.enqueue(encodeEventMessage({
829
+ comments: [keepAliveComment]
830
+ }));
831
+ span?.addEvent("keepalive");
832
+ }, keepAliveInterval);
833
+ }
834
+ const value2 = await runInSpanContext(span, () => iterator.next());
835
+ clearInterval(timeout);
836
+ if (cancelled) {
837
+ return;
838
+ }
839
+ const meta = getEventMeta(value2.value);
840
+ if (!value2.done || value2.value !== void 0 || meta !== void 0) {
841
+ const event = value2.done ? "done" : "message";
842
+ controller.enqueue(encodeEventMessage({
843
+ ...meta,
844
+ event,
845
+ data: stringifyJSON(value2.value)
846
+ }));
847
+ span?.addEvent(event);
848
+ }
849
+ if (value2.done) {
850
+ controller.close();
851
+ span?.end();
852
+ }
853
+ } catch (err) {
854
+ clearInterval(timeout);
855
+ if (cancelled) {
856
+ return;
857
+ }
858
+ if (err instanceof ErrorEvent) {
859
+ controller.enqueue(encodeEventMessage({
860
+ ...getEventMeta(err),
861
+ event: "error",
862
+ data: stringifyJSON(err.data)
863
+ }));
864
+ span?.addEvent("error");
865
+ controller.close();
866
+ } else {
867
+ setSpanError(span, err);
868
+ controller.error(err);
869
+ }
870
+ span?.end();
871
+ }
872
+ },
873
+ async cancel() {
874
+ try {
875
+ cancelled = true;
876
+ clearInterval(timeout);
877
+ span?.addEvent("cancelled");
878
+ await runInSpanContext(span, () => iterator.return?.());
879
+ } catch (e) {
880
+ setSpanError(span, e);
881
+ throw e;
882
+ } finally {
883
+ span?.end();
884
+ }
885
+ }
886
+ }).pipeThrough(new TextEncoderStream());
887
+ return stream;
888
+ }
889
+ function toStandardBody(re, options = {}) {
890
+ return runWithSpan(
891
+ { name: "parse_standard_body", signal: options.signal },
892
+ async () => {
893
+ const contentDisposition = re.headers.get("content-disposition");
894
+ if (typeof contentDisposition === "string") {
895
+ const fileName = getFilenameFromContentDisposition(contentDisposition) ?? "blob";
896
+ const blob2 = await re.blob();
897
+ return new File([blob2], fileName, {
898
+ type: blob2.type
899
+ });
900
+ }
901
+ const contentType = re.headers.get("content-type");
902
+ if (!contentType || contentType.startsWith("application/json")) {
903
+ const text = await re.text();
904
+ return parseEmptyableJSON(text);
905
+ }
906
+ if (contentType.startsWith("multipart/form-data")) {
907
+ return await re.formData();
908
+ }
909
+ if (contentType.startsWith("application/x-www-form-urlencoded")) {
910
+ const text = await re.text();
911
+ return new URLSearchParams(text);
912
+ }
913
+ if (contentType.startsWith("text/event-stream")) {
914
+ return toEventIterator(re.body, options);
915
+ }
916
+ if (contentType.startsWith("text/plain")) {
917
+ return await re.text();
918
+ }
919
+ const blob = await re.blob();
920
+ return new File([blob], "blob", {
921
+ type: blob.type
922
+ });
923
+ }
924
+ );
925
+ }
926
+ function toFetchBody(body, headers, options = {}) {
927
+ const currentContentDisposition = headers.get("content-disposition");
928
+ headers.delete("content-type");
929
+ headers.delete("content-disposition");
930
+ if (body === void 0) {
931
+ return void 0;
932
+ }
933
+ if (body instanceof Blob) {
934
+ headers.set("content-type", body.type);
935
+ headers.set("content-length", body.size.toString());
936
+ headers.set(
937
+ "content-disposition",
938
+ currentContentDisposition ?? generateContentDisposition(body instanceof File ? body.name : "blob")
939
+ );
940
+ return body;
941
+ }
942
+ if (body instanceof FormData) {
943
+ return body;
944
+ }
945
+ if (body instanceof URLSearchParams) {
946
+ return body;
947
+ }
948
+ if (isAsyncIteratorObject(body)) {
949
+ headers.set("content-type", "text/event-stream");
950
+ return toEventStream(body, options);
951
+ }
952
+ headers.set("content-type", "application/json");
953
+ return stringifyJSON(body);
954
+ }
955
+ function toStandardHeaders(headers, standardHeaders = {}) {
956
+ headers.forEach((value2, key) => {
957
+ if (Array.isArray(standardHeaders[key])) {
958
+ standardHeaders[key].push(value2);
959
+ } else if (standardHeaders[key] !== void 0) {
960
+ standardHeaders[key] = [standardHeaders[key], value2];
961
+ } else {
962
+ standardHeaders[key] = value2;
963
+ }
964
+ });
965
+ return standardHeaders;
966
+ }
967
+ function toFetchHeaders(headers, fetchHeaders = new Headers()) {
968
+ for (const [key, value2] of Object.entries(headers)) {
969
+ if (Array.isArray(value2)) {
970
+ for (const v of value2) {
971
+ fetchHeaders.append(key, v);
972
+ }
973
+ } else if (value2 !== void 0) {
974
+ fetchHeaders.append(key, value2);
975
+ }
976
+ }
977
+ return fetchHeaders;
978
+ }
979
+ function toFetchRequest(request, options = {}) {
980
+ const headers = toFetchHeaders(request.headers);
981
+ const body = toFetchBody(request.body, headers, options);
982
+ return new Request(request.url, {
983
+ signal: request.signal,
984
+ method: request.method,
985
+ headers,
986
+ body
987
+ });
988
+ }
989
+ function toStandardLazyResponse(response, options = {}) {
990
+ return {
991
+ body: once(() => toStandardBody(response, options)),
992
+ status: response.status,
993
+ get headers() {
994
+ const headers = toStandardHeaders(response.headers);
995
+ Object.defineProperty(this, "headers", { value: headers, writable: true });
996
+ return headers;
997
+ },
998
+ set headers(value2) {
999
+ Object.defineProperty(this, "headers", { value: value2, writable: true });
1000
+ }
1001
+ };
1002
+ }
1003
+
1004
+ // ../../node_modules/.bun/@orpc+client@1.13.4+460773ef8ff1e07c/node_modules/@orpc/client/dist/shared/client.CRfRve1v.mjs
1005
+ var CompositeStandardLinkPlugin = class {
1006
+ plugins;
1007
+ constructor(plugins = []) {
1008
+ this.plugins = [...plugins].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
1009
+ }
1010
+ init(options) {
1011
+ for (const plugin of this.plugins) {
1012
+ plugin.init?.(options);
1013
+ }
1014
+ }
1015
+ };
1016
+ var StandardLink = class {
1017
+ constructor(codec, sender, options = {}) {
1018
+ this.codec = codec;
1019
+ this.sender = sender;
1020
+ const plugin = new CompositeStandardLinkPlugin(options.plugins);
1021
+ plugin.init(options);
1022
+ this.interceptors = toArray(options.interceptors);
1023
+ this.clientInterceptors = toArray(options.clientInterceptors);
1024
+ }
1025
+ interceptors;
1026
+ clientInterceptors;
1027
+ call(path, input, options) {
1028
+ return runWithSpan(
1029
+ { name: `${ORPC_NAME}.${path.join("/")}`, signal: options.signal },
1030
+ (span) => {
1031
+ span?.setAttribute("rpc.system", ORPC_NAME);
1032
+ span?.setAttribute("rpc.method", path.join("."));
1033
+ if (isAsyncIteratorObject(input)) {
1034
+ input = asyncIteratorWithSpan(
1035
+ { name: "consume_event_iterator_input", signal: options.signal },
1036
+ input
1037
+ );
1038
+ }
1039
+ return intercept(this.interceptors, { ...options, path, input }, async ({ path: path2, input: input2, ...options2 }) => {
1040
+ const otelConfig = getGlobalOtelConfig();
1041
+ let otelContext;
1042
+ const currentSpan = otelConfig?.trace.getActiveSpan() ?? span;
1043
+ if (currentSpan && otelConfig) {
1044
+ otelContext = otelConfig?.trace.setSpan(otelConfig.context.active(), currentSpan);
1045
+ }
1046
+ const request = await runWithSpan(
1047
+ { name: "encode_request", context: otelContext },
1048
+ () => this.codec.encode(path2, input2, options2)
1049
+ );
1050
+ const response = await intercept(
1051
+ this.clientInterceptors,
1052
+ { ...options2, input: input2, path: path2, request },
1053
+ ({ input: input3, path: path3, request: request2, ...options3 }) => {
1054
+ return runWithSpan(
1055
+ { name: "send_request", signal: options3.signal, context: otelContext },
1056
+ () => this.sender.call(request2, options3, path3, input3)
1057
+ );
1058
+ }
1059
+ );
1060
+ const output = await runWithSpan(
1061
+ { name: "decode_response", context: otelContext },
1062
+ () => this.codec.decode(response, options2, path2, input2)
1063
+ );
1064
+ if (isAsyncIteratorObject(output)) {
1065
+ return asyncIteratorWithSpan(
1066
+ { name: "consume_event_iterator_output", signal: options2.signal },
1067
+ output
1068
+ );
1069
+ }
1070
+ return output;
1071
+ });
1072
+ }
1073
+ );
1074
+ }
1075
+ };
1076
+ var STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES = {
1077
+ BIGINT: 0,
1078
+ DATE: 1,
1079
+ NAN: 2,
1080
+ UNDEFINED: 3,
1081
+ URL: 4,
1082
+ REGEXP: 5,
1083
+ SET: 6,
1084
+ MAP: 7
1085
+ };
1086
+ var StandardRPCJsonSerializer = class {
1087
+ customSerializers;
1088
+ constructor(options = {}) {
1089
+ this.customSerializers = options.customJsonSerializers ?? [];
1090
+ if (this.customSerializers.length !== new Set(this.customSerializers.map((custom) => custom.type)).size) {
1091
+ throw new Error("Custom serializer type must be unique.");
1092
+ }
1093
+ }
1094
+ serialize(data, segments = [], meta = [], maps = [], blobs = []) {
1095
+ for (const custom of this.customSerializers) {
1096
+ if (custom.condition(data)) {
1097
+ const result = this.serialize(custom.serialize(data), segments, meta, maps, blobs);
1098
+ meta.push([custom.type, ...segments]);
1099
+ return result;
1100
+ }
1101
+ }
1102
+ if (data instanceof Blob) {
1103
+ maps.push(segments);
1104
+ blobs.push(data);
1105
+ return [data, meta, maps, blobs];
1106
+ }
1107
+ if (typeof data === "bigint") {
1108
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.BIGINT, ...segments]);
1109
+ return [data.toString(), meta, maps, blobs];
1110
+ }
1111
+ if (data instanceof Date) {
1112
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.DATE, ...segments]);
1113
+ if (Number.isNaN(data.getTime())) {
1114
+ return [null, meta, maps, blobs];
1115
+ }
1116
+ return [data.toISOString(), meta, maps, blobs];
1117
+ }
1118
+ if (Number.isNaN(data)) {
1119
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.NAN, ...segments]);
1120
+ return [null, meta, maps, blobs];
1121
+ }
1122
+ if (data instanceof URL) {
1123
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.URL, ...segments]);
1124
+ return [data.toString(), meta, maps, blobs];
1125
+ }
1126
+ if (data instanceof RegExp) {
1127
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.REGEXP, ...segments]);
1128
+ return [data.toString(), meta, maps, blobs];
1129
+ }
1130
+ if (data instanceof Set) {
1131
+ const result = this.serialize(Array.from(data), segments, meta, maps, blobs);
1132
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.SET, ...segments]);
1133
+ return result;
1134
+ }
1135
+ if (data instanceof Map) {
1136
+ const result = this.serialize(Array.from(data.entries()), segments, meta, maps, blobs);
1137
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.MAP, ...segments]);
1138
+ return result;
1139
+ }
1140
+ if (Array.isArray(data)) {
1141
+ const json = data.map((v, i) => {
1142
+ if (v === void 0) {
1143
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.UNDEFINED, ...segments, i]);
1144
+ return v;
1145
+ }
1146
+ return this.serialize(v, [...segments, i], meta, maps, blobs)[0];
1147
+ });
1148
+ return [json, meta, maps, blobs];
1149
+ }
1150
+ if (isObject(data)) {
1151
+ const json = {};
1152
+ for (const k in data) {
1153
+ if (k === "toJSON" && typeof data[k] === "function") {
1154
+ continue;
1155
+ }
1156
+ json[k] = this.serialize(data[k], [...segments, k], meta, maps, blobs)[0];
1157
+ }
1158
+ return [json, meta, maps, blobs];
1159
+ }
1160
+ return [data, meta, maps, blobs];
1161
+ }
1162
+ deserialize(json, meta, maps, getBlob) {
1163
+ const ref = { data: json };
1164
+ if (maps && getBlob) {
1165
+ maps.forEach((segments, i) => {
1166
+ let currentRef = ref;
1167
+ let preSegment = "data";
1168
+ segments.forEach((segment) => {
1169
+ currentRef = currentRef[preSegment];
1170
+ preSegment = segment;
1171
+ });
1172
+ currentRef[preSegment] = getBlob(i);
1173
+ });
1174
+ }
1175
+ for (const item of meta) {
1176
+ const type = item[0];
1177
+ let currentRef = ref;
1178
+ let preSegment = "data";
1179
+ for (let i = 1; i < item.length; i++) {
1180
+ currentRef = currentRef[preSegment];
1181
+ preSegment = item[i];
1182
+ }
1183
+ for (const custom of this.customSerializers) {
1184
+ if (custom.type === type) {
1185
+ currentRef[preSegment] = custom.deserialize(currentRef[preSegment]);
1186
+ break;
1187
+ }
1188
+ }
1189
+ switch (type) {
1190
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.BIGINT:
1191
+ currentRef[preSegment] = BigInt(currentRef[preSegment]);
1192
+ break;
1193
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.DATE:
1194
+ currentRef[preSegment] = new Date(currentRef[preSegment] ?? "Invalid Date");
1195
+ break;
1196
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.NAN:
1197
+ currentRef[preSegment] = Number.NaN;
1198
+ break;
1199
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.UNDEFINED:
1200
+ currentRef[preSegment] = void 0;
1201
+ break;
1202
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.URL:
1203
+ currentRef[preSegment] = new URL(currentRef[preSegment]);
1204
+ break;
1205
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.REGEXP: {
1206
+ const [, pattern, flags] = currentRef[preSegment].match(/^\/(.*)\/([a-z]*)$/);
1207
+ currentRef[preSegment] = new RegExp(pattern, flags);
1208
+ break;
1209
+ }
1210
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.SET:
1211
+ currentRef[preSegment] = new Set(currentRef[preSegment]);
1212
+ break;
1213
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.MAP:
1214
+ currentRef[preSegment] = new Map(currentRef[preSegment]);
1215
+ break;
1216
+ }
1217
+ }
1218
+ return ref.data;
1219
+ }
1220
+ };
1221
+ function toHttpPath(path) {
1222
+ return `/${path.map(encodeURIComponent).join("/")}`;
1223
+ }
1224
+ function toStandardHeaders2(headers) {
1225
+ if (typeof headers.forEach === "function") {
1226
+ return toStandardHeaders(headers);
1227
+ }
1228
+ return headers;
1229
+ }
1230
+ function getMalformedResponseErrorCode(status) {
1231
+ return Object.entries(COMMON_ORPC_ERROR_DEFS).find(([, def]) => def.status === status)?.[0] ?? "MALFORMED_ORPC_ERROR_RESPONSE";
1232
+ }
1233
+ var StandardRPCLinkCodec = class {
1234
+ constructor(serializer, options) {
1235
+ this.serializer = serializer;
1236
+ this.baseUrl = options.url;
1237
+ this.maxUrlLength = options.maxUrlLength ?? 2083;
1238
+ this.fallbackMethod = options.fallbackMethod ?? "POST";
1239
+ this.expectedMethod = options.method ?? this.fallbackMethod;
1240
+ this.headers = options.headers ?? {};
1241
+ }
1242
+ baseUrl;
1243
+ maxUrlLength;
1244
+ fallbackMethod;
1245
+ expectedMethod;
1246
+ headers;
1247
+ async encode(path, input, options) {
1248
+ let headers = toStandardHeaders2(await value(this.headers, options, path, input));
1249
+ if (options.lastEventId !== void 0) {
1250
+ headers = mergeStandardHeaders(headers, { "last-event-id": options.lastEventId });
1251
+ }
1252
+ const expectedMethod = await value(this.expectedMethod, options, path, input);
1253
+ const baseUrl = await value(this.baseUrl, options, path, input);
1254
+ const url = new URL(baseUrl);
1255
+ url.pathname = `${url.pathname.replace(/\/$/, "")}${toHttpPath(path)}`;
1256
+ const serialized = this.serializer.serialize(input);
1257
+ if (expectedMethod === "GET" && !(serialized instanceof FormData) && !isAsyncIteratorObject(serialized)) {
1258
+ const maxUrlLength = await value(this.maxUrlLength, options, path, input);
1259
+ const getUrl = new URL(url);
1260
+ getUrl.searchParams.append("data", stringifyJSON(serialized));
1261
+ if (getUrl.toString().length <= maxUrlLength) {
1262
+ return {
1263
+ body: void 0,
1264
+ method: expectedMethod,
1265
+ headers,
1266
+ url: getUrl,
1267
+ signal: options.signal
1268
+ };
1269
+ }
1270
+ }
1271
+ return {
1272
+ url,
1273
+ method: expectedMethod === "GET" ? this.fallbackMethod : expectedMethod,
1274
+ headers,
1275
+ body: serialized,
1276
+ signal: options.signal
1277
+ };
1278
+ }
1279
+ async decode(response) {
1280
+ const isOk = !isORPCErrorStatus(response.status);
1281
+ const deserialized = await (async () => {
1282
+ let isBodyOk = false;
1283
+ try {
1284
+ const body = await response.body();
1285
+ isBodyOk = true;
1286
+ return this.serializer.deserialize(body);
1287
+ } catch (error) {
1288
+ if (!isBodyOk) {
1289
+ throw new Error("Cannot parse response body, please check the response body and content-type.", {
1290
+ cause: error
1291
+ });
1292
+ }
1293
+ throw new Error("Invalid RPC response format.", {
1294
+ cause: error
1295
+ });
1296
+ }
1297
+ })();
1298
+ if (!isOk) {
1299
+ if (isORPCErrorJson(deserialized)) {
1300
+ throw createORPCErrorFromJson(deserialized);
1301
+ }
1302
+ throw new ORPCError(getMalformedResponseErrorCode(response.status), {
1303
+ status: response.status,
1304
+ data: { ...response, body: deserialized }
1305
+ });
1306
+ }
1307
+ return deserialized;
1308
+ }
1309
+ };
1310
+ var StandardRPCSerializer = class {
1311
+ constructor(jsonSerializer) {
1312
+ this.jsonSerializer = jsonSerializer;
1313
+ }
1314
+ serialize(data) {
1315
+ if (isAsyncIteratorObject(data)) {
1316
+ return mapEventIterator(data, {
1317
+ value: async (value2) => this.#serialize(value2, false),
1318
+ error: async (e) => {
1319
+ return new ErrorEvent({
1320
+ data: this.#serialize(toORPCError(e).toJSON(), false),
1321
+ cause: e
1322
+ });
1323
+ }
1324
+ });
1325
+ }
1326
+ return this.#serialize(data, true);
1327
+ }
1328
+ #serialize(data, enableFormData) {
1329
+ const [json, meta_, maps, blobs] = this.jsonSerializer.serialize(data);
1330
+ const meta = meta_.length === 0 ? void 0 : meta_;
1331
+ if (!enableFormData || blobs.length === 0) {
1332
+ return {
1333
+ json,
1334
+ meta
1335
+ };
1336
+ }
1337
+ const form = new FormData();
1338
+ form.set("data", stringifyJSON({ json, meta, maps }));
1339
+ blobs.forEach((blob, i) => {
1340
+ form.set(i.toString(), blob);
1341
+ });
1342
+ return form;
1343
+ }
1344
+ deserialize(data) {
1345
+ if (isAsyncIteratorObject(data)) {
1346
+ return mapEventIterator(data, {
1347
+ value: async (value2) => this.#deserialize(value2),
1348
+ error: async (e) => {
1349
+ if (!(e instanceof ErrorEvent)) {
1350
+ return e;
1351
+ }
1352
+ const deserialized = this.#deserialize(e.data);
1353
+ if (isORPCErrorJson(deserialized)) {
1354
+ return createORPCErrorFromJson(deserialized, { cause: e });
1355
+ }
1356
+ return new ErrorEvent({
1357
+ data: deserialized,
1358
+ cause: e
1359
+ });
1360
+ }
1361
+ });
1362
+ }
1363
+ return this.#deserialize(data);
1364
+ }
1365
+ #deserialize(data) {
1366
+ if (data === void 0) {
1367
+ return void 0;
1368
+ }
1369
+ if (!(data instanceof FormData)) {
1370
+ return this.jsonSerializer.deserialize(data.json, data.meta ?? []);
1371
+ }
1372
+ const serialized = JSON.parse(data.get("data"));
1373
+ return this.jsonSerializer.deserialize(
1374
+ serialized.json,
1375
+ serialized.meta ?? [],
1376
+ serialized.maps,
1377
+ (i) => data.get(i.toString())
1378
+ );
1379
+ }
1380
+ };
1381
+ var StandardRPCLink = class extends StandardLink {
1382
+ constructor(linkClient, options) {
1383
+ const jsonSerializer = new StandardRPCJsonSerializer(options);
1384
+ const serializer = new StandardRPCSerializer(jsonSerializer);
1385
+ const linkCodec = new StandardRPCLinkCodec(serializer, options);
1386
+ super(linkCodec, linkClient, options);
1387
+ }
1388
+ };
1389
+
1390
+ // ../../node_modules/.bun/@orpc+client@1.13.4+460773ef8ff1e07c/node_modules/@orpc/client/dist/adapters/fetch/index.mjs
1391
+ var CompositeLinkFetchPlugin = class extends CompositeStandardLinkPlugin {
1392
+ initRuntimeAdapter(options) {
1393
+ for (const plugin of this.plugins) {
1394
+ plugin.initRuntimeAdapter?.(options);
1395
+ }
1396
+ }
1397
+ };
1398
+ var LinkFetchClient = class {
1399
+ fetch;
1400
+ toFetchRequestOptions;
1401
+ adapterInterceptors;
1402
+ constructor(options) {
1403
+ const plugin = new CompositeLinkFetchPlugin(options.plugins);
1404
+ plugin.initRuntimeAdapter(options);
1405
+ this.fetch = options.fetch ?? globalThis.fetch.bind(globalThis);
1406
+ this.toFetchRequestOptions = options;
1407
+ this.adapterInterceptors = toArray(options.adapterInterceptors);
1408
+ }
1409
+ async call(standardRequest, options, path, input) {
1410
+ const request = toFetchRequest(standardRequest, this.toFetchRequestOptions);
1411
+ const fetchResponse = await intercept(
1412
+ this.adapterInterceptors,
1413
+ { ...options, request, path, input, init: { redirect: "manual" } },
1414
+ ({ request: request2, path: path2, input: input2, init, ...options2 }) => this.fetch(request2, init, options2, path2, input2)
1415
+ );
1416
+ const lazyResponse = toStandardLazyResponse(fetchResponse, { signal: request.signal });
1417
+ return lazyResponse;
1418
+ }
1419
+ };
1420
+ var RPCLink = class extends StandardRPCLink {
1421
+ constructor(options) {
1422
+ const linkClient = new LinkFetchClient(options);
1423
+ super(linkClient, options);
1424
+ }
1425
+ };
1426
+
1427
+ // ../../node_modules/.bun/@tanstack+query-core@5.90.10/node_modules/@tanstack/query-core/build/modern/utils.js
1428
+ var isServer = typeof window === "undefined" || "Deno" in globalThis;
1429
+ var skipToken = /* @__PURE__ */ Symbol();
1430
+
1431
+ // ../../node_modules/.bun/@orpc+tanstack-query@1.13.4+951a70f6a2b70cf3/node_modules/@orpc/tanstack-query/dist/index.mjs
1432
+ function generateOperationKey(path, state = {}) {
1433
+ return [path, {
1434
+ ...state.input !== void 0 ? { input: state.input } : {},
1435
+ ...state.type !== void 0 ? { type: state.type } : {},
1436
+ ...state.fnOptions !== void 0 ? { fnOptions: state.fnOptions } : {}
1437
+ }];
1438
+ }
1439
+ function createGeneralUtils(path) {
1440
+ return {
1441
+ key(options) {
1442
+ return generateOperationKey(path, options);
1443
+ }
1444
+ };
1445
+ }
1446
+ function experimental_liveQuery(queryFn) {
1447
+ return async (context) => {
1448
+ const stream = await queryFn(context);
1449
+ let last;
1450
+ for await (const chunk of stream) {
1451
+ if (context.signal.aborted) {
1452
+ throw context.signal.reason;
1453
+ }
1454
+ last = { chunk };
1455
+ context.client.setQueryData(context.queryKey, chunk);
1456
+ }
1457
+ if (!last) {
1458
+ throw new Error(
1459
+ `Live query for ${stringifyJSON(context.queryKey)} did not yield any data. Ensure the query function returns an AsyncIterable with at least one chunk.`
1460
+ );
1461
+ }
1462
+ return last.chunk;
1463
+ };
1464
+ }
1465
+ function experimental_serializableStreamedQuery(queryFn, { refetchMode = "reset", maxChunks = Number.POSITIVE_INFINITY } = {}) {
1466
+ return async (context) => {
1467
+ const query = context.client.getQueryCache().find({ queryKey: context.queryKey, exact: true });
1468
+ const hasPreviousData = !!query && query.state.data !== void 0;
1469
+ if (hasPreviousData) {
1470
+ if (refetchMode === "reset") {
1471
+ query.setState({
1472
+ status: "pending",
1473
+ data: void 0,
1474
+ error: null,
1475
+ fetchStatus: "fetching"
1476
+ });
1477
+ } else {
1478
+ context.client.setQueryData(
1479
+ context.queryKey,
1480
+ (prev = []) => limitArraySize(prev, maxChunks)
1481
+ );
1482
+ }
1483
+ }
1484
+ let result = [];
1485
+ const stream = await queryFn(context);
1486
+ const shouldUpdateCacheDuringStream = !hasPreviousData || refetchMode !== "replace";
1487
+ context.client.setQueryData(
1488
+ context.queryKey,
1489
+ (prev = []) => limitArraySize(prev, maxChunks)
1490
+ );
1491
+ for await (const chunk of stream) {
1492
+ if (context.signal.aborted) {
1493
+ throw context.signal.reason;
1494
+ }
1495
+ result.push(chunk);
1496
+ result = limitArraySize(result, maxChunks);
1497
+ if (shouldUpdateCacheDuringStream) {
1498
+ context.client.setQueryData(
1499
+ context.queryKey,
1500
+ (prev = []) => limitArraySize([...prev, chunk], maxChunks)
1501
+ );
1502
+ }
1503
+ }
1504
+ if (!shouldUpdateCacheDuringStream) {
1505
+ context.client.setQueryData(context.queryKey, result);
1506
+ }
1507
+ const cachedData = context.client.getQueryData(context.queryKey);
1508
+ if (cachedData) {
1509
+ return limitArraySize(cachedData, maxChunks);
1510
+ }
1511
+ return result;
1512
+ };
1513
+ }
1514
+ function limitArraySize(items, maxSize) {
1515
+ if (items.length <= maxSize) {
1516
+ return items;
1517
+ }
1518
+ return items.slice(items.length - maxSize);
1519
+ }
1520
+ var OPERATION_CONTEXT_SYMBOL = /* @__PURE__ */ Symbol("ORPC_OPERATION_CONTEXT");
1521
+ function createProcedureUtils(client, options) {
1522
+ const utils = {
1523
+ call: client,
1524
+ queryKey(...[optionsIn = {}]) {
1525
+ optionsIn = { ...options.experimental_defaults?.queryKey, ...optionsIn };
1526
+ const queryKey = optionsIn.queryKey ?? generateOperationKey(options.path, { type: "query", input: optionsIn.input });
1527
+ return queryKey;
1528
+ },
1529
+ queryOptions(...[optionsIn = {}]) {
1530
+ optionsIn = { ...options.experimental_defaults?.queryOptions, ...optionsIn };
1531
+ const queryKey = utils.queryKey(optionsIn);
1532
+ return {
1533
+ queryFn: ({ signal }) => {
1534
+ if (optionsIn.input === skipToken) {
1535
+ throw new Error("queryFn should not be called with skipToken used as input");
1536
+ }
1537
+ return client(optionsIn.input, {
1538
+ signal,
1539
+ context: {
1540
+ [OPERATION_CONTEXT_SYMBOL]: {
1541
+ key: queryKey,
1542
+ type: "query"
1543
+ },
1544
+ ...optionsIn.context
1545
+ }
1546
+ });
1547
+ },
1548
+ ...optionsIn.input === skipToken ? { enabled: false } : {},
1549
+ ...optionsIn,
1550
+ queryKey
1551
+ };
1552
+ },
1553
+ experimental_streamedKey(...[optionsIn = {}]) {
1554
+ optionsIn = { ...options.experimental_defaults?.experimental_streamedKey, ...optionsIn };
1555
+ const queryKey = optionsIn.queryKey ?? generateOperationKey(options.path, { type: "streamed", input: optionsIn.input, fnOptions: optionsIn.queryFnOptions });
1556
+ return queryKey;
1557
+ },
1558
+ experimental_streamedOptions(...[optionsIn = {}]) {
1559
+ optionsIn = { ...options.experimental_defaults?.experimental_streamedOptions, ...optionsIn };
1560
+ const queryKey = utils.experimental_streamedKey(optionsIn);
1561
+ return {
1562
+ queryFn: experimental_serializableStreamedQuery(
1563
+ async ({ signal }) => {
1564
+ if (optionsIn.input === skipToken) {
1565
+ throw new Error("queryFn should not be called with skipToken used as input");
1566
+ }
1567
+ const output = await client(optionsIn.input, {
1568
+ signal,
1569
+ context: {
1570
+ [OPERATION_CONTEXT_SYMBOL]: {
1571
+ key: queryKey,
1572
+ type: "streamed"
1573
+ },
1574
+ ...optionsIn.context
1575
+ }
1576
+ });
1577
+ if (!isAsyncIteratorObject(output)) {
1578
+ throw new Error("streamedQuery requires an event iterator output");
1579
+ }
1580
+ return output;
1581
+ },
1582
+ optionsIn.queryFnOptions
1583
+ ),
1584
+ ...optionsIn.input === skipToken ? { enabled: false } : {},
1585
+ ...optionsIn,
1586
+ queryKey
1587
+ };
1588
+ },
1589
+ experimental_liveKey(...[optionsIn = {}]) {
1590
+ optionsIn = { ...options.experimental_defaults?.experimental_liveKey, ...optionsIn };
1591
+ const queryKey = optionsIn.queryKey ?? generateOperationKey(options.path, { type: "live", input: optionsIn.input });
1592
+ return queryKey;
1593
+ },
1594
+ experimental_liveOptions(...[optionsIn = {}]) {
1595
+ optionsIn = { ...options.experimental_defaults?.experimental_liveOptions, ...optionsIn };
1596
+ const queryKey = utils.experimental_liveKey(optionsIn);
1597
+ return {
1598
+ queryFn: experimental_liveQuery(async ({ signal }) => {
1599
+ if (optionsIn.input === skipToken) {
1600
+ throw new Error("queryFn should not be called with skipToken used as input");
1601
+ }
1602
+ const output = await client(optionsIn.input, {
1603
+ signal,
1604
+ context: {
1605
+ [OPERATION_CONTEXT_SYMBOL]: {
1606
+ key: queryKey,
1607
+ type: "live"
1608
+ },
1609
+ ...optionsIn.context
1610
+ }
1611
+ });
1612
+ if (!isAsyncIteratorObject(output)) {
1613
+ throw new Error("liveQuery requires an event iterator output");
1614
+ }
1615
+ return output;
1616
+ }),
1617
+ ...optionsIn.input === skipToken ? { enabled: false } : {},
1618
+ ...optionsIn,
1619
+ queryKey
1620
+ };
1621
+ },
1622
+ infiniteKey(optionsIn) {
1623
+ optionsIn = { ...options.experimental_defaults?.infiniteKey, ...optionsIn };
1624
+ const queryKey = optionsIn.queryKey ?? generateOperationKey(options.path, {
1625
+ type: "infinite",
1626
+ input: optionsIn.input === skipToken ? skipToken : optionsIn.input(optionsIn.initialPageParam)
1627
+ });
1628
+ return queryKey;
1629
+ },
1630
+ infiniteOptions(optionsIn) {
1631
+ optionsIn = { ...options.experimental_defaults?.infiniteOptions, ...optionsIn };
1632
+ const queryKey = utils.infiniteKey(optionsIn);
1633
+ return {
1634
+ queryFn: ({ pageParam, signal }) => {
1635
+ if (optionsIn.input === skipToken) {
1636
+ throw new Error("queryFn should not be called with skipToken used as input");
1637
+ }
1638
+ return client(optionsIn.input(pageParam), {
1639
+ signal,
1640
+ context: {
1641
+ [OPERATION_CONTEXT_SYMBOL]: {
1642
+ key: queryKey,
1643
+ type: "infinite"
1644
+ },
1645
+ ...optionsIn.context
1646
+ }
1647
+ });
1648
+ },
1649
+ ...optionsIn.input === skipToken ? { enabled: false } : {},
1650
+ ...optionsIn,
1651
+ queryKey
1652
+ };
1653
+ },
1654
+ mutationKey(...[optionsIn = {}]) {
1655
+ optionsIn = { ...options.experimental_defaults?.mutationKey, ...optionsIn };
1656
+ const mutationKey = optionsIn.mutationKey ?? generateOperationKey(options.path, { type: "mutation" });
1657
+ return mutationKey;
1658
+ },
1659
+ mutationOptions(...[optionsIn = {}]) {
1660
+ optionsIn = { ...options.experimental_defaults?.mutationOptions, ...optionsIn };
1661
+ const mutationKey = utils.mutationKey(optionsIn);
1662
+ return {
1663
+ mutationFn: (input) => client(input, {
1664
+ context: {
1665
+ [OPERATION_CONTEXT_SYMBOL]: {
1666
+ key: mutationKey,
1667
+ type: "mutation"
1668
+ },
1669
+ ...optionsIn.context
1670
+ }
1671
+ }),
1672
+ ...optionsIn,
1673
+ mutationKey
1674
+ };
1675
+ }
1676
+ };
1677
+ return utils;
1678
+ }
1679
+ function createRouterUtils(client, options = {}) {
1680
+ const path = toArray(options.path);
1681
+ const generalUtils = createGeneralUtils(path);
1682
+ const procedureUtils = createProcedureUtils(client, {
1683
+ path,
1684
+ experimental_defaults: options.experimental_defaults
1685
+ });
1686
+ const recursive = new Proxy({
1687
+ ...generalUtils,
1688
+ ...procedureUtils
1689
+ }, {
1690
+ get(target, prop) {
1691
+ const value2 = Reflect.get(target, prop);
1692
+ if (typeof prop !== "string") {
1693
+ return value2;
1694
+ }
1695
+ const nextUtils = createRouterUtils(client[prop], {
1696
+ ...options,
1697
+ path: [...path, prop],
1698
+ experimental_defaults: get(options.experimental_defaults, [prop])
1699
+ });
1700
+ if (typeof value2 !== "function") {
1701
+ return nextUtils;
1702
+ }
1703
+ return new Proxy(value2, {
1704
+ get(_, prop2) {
1705
+ return Reflect.get(nextUtils, prop2);
1706
+ }
1707
+ });
1708
+ }
1709
+ });
1710
+ return recursive;
1711
+ }
1712
+
1713
+ // ../core/src/client.ts
1714
+ function createSwirlsClient(options) {
1715
+ const link = new RPCLink({
1716
+ url: `${options.apiUrl.replace(/\/$/, "")}/rpc`,
1717
+ headers: () => ({
1718
+ Authorization: `Bearer ${options.apiKey}`
1719
+ })
1720
+ });
1721
+ return createORPCClient(link);
1722
+ }
1723
+ function createSwirlsQueryUtils(client) {
1724
+ return createRouterUtils(client);
1725
+ }
1726
+
1
1727
  // src/client/client.ts
2
- import { createSwirlsClient, createSwirlsQueryUtils } from "@swirls/core/client";
3
1728
  var DEFAULT_SWIRLS_API_URL = "https://swirls.ai/api";
4
1729
  var Swirls = class {
5
1730
  apiKey;
6
1731
  apiUrl;
1732
+ /**
1733
+ * Create a new Swirls SDK instance.
1734
+ *
1735
+ * @param options.apiKey - Your Swirls API key.
1736
+ * @param options.apiUrl - Override the API base URL (defaults to `https://swirls.ai/api`).
1737
+ */
7
1738
  constructor(options) {
8
1739
  this.apiKey = options.apiKey;
9
1740
  this.apiUrl = options.apiUrl ?? DEFAULT_SWIRLS_API_URL;
10
1741
  }
1742
+ /** Type-safe oRPC client with namespaced methods for all Swirls resources. */
11
1743
  get client() {
12
1744
  return createSwirlsClient({ apiUrl: this.apiUrl, apiKey: this.apiKey });
13
1745
  }
1746
+ /** TanStack Query utilities for use with `useQuery()` and `useMutation()`. */
14
1747
  get query() {
15
1748
  return createSwirlsQueryUtils(this.client);
16
1749
  }