@gitterm/opencode-cloud 0.0.0-stage → 0.1.3

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.js ADDED
@@ -0,0 +1,4192 @@
1
+ // @bun
2
+ // src/index.ts
3
+ import { Plugin } from "@opencode/plugin";
4
+ import { OpenCode as OpenCode2 } from "@opencode/client";
5
+ import { Service } from "@opencode/client/service";
6
+
7
+ // ../../node_modules/.bun/@trpc+client@11.8.1+56fb0e3277503e89/node_modules/@trpc/client/dist/objectSpread2-BvkFp-_Y.mjs
8
+ var __create = Object.create;
9
+ var __defProp = Object.defineProperty;
10
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
11
+ var __getOwnPropNames = Object.getOwnPropertyNames;
12
+ var __getProtoOf = Object.getPrototypeOf;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __commonJS = (cb, mod) => function() {
15
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
16
+ };
17
+ var __copyProps = (to, from, except, desc) => {
18
+ if (from && typeof from === "object" || typeof from === "function")
19
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key;i < n; i++) {
20
+ key = keys[i];
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, {
23
+ get: ((k) => from[k]).bind(null, key),
24
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
25
+ });
26
+ }
27
+ return to;
28
+ };
29
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
30
+ value: mod,
31
+ enumerable: true
32
+ }) : target, mod));
33
+ var require_typeof = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/typeof.js"(exports, module) {
34
+ function _typeof$2(o) {
35
+ "@babel/helpers - typeof";
36
+ return module.exports = _typeof$2 = typeof Symbol == "function" && typeof Symbol.iterator == "symbol" ? function(o$1) {
37
+ return typeof o$1;
38
+ } : function(o$1) {
39
+ return o$1 && typeof Symbol == "function" && o$1.constructor === Symbol && o$1 !== Symbol.prototype ? "symbol" : typeof o$1;
40
+ }, module.exports.__esModule = true, module.exports["default"] = module.exports, _typeof$2(o);
41
+ }
42
+ module.exports = _typeof$2, module.exports.__esModule = true, module.exports["default"] = module.exports;
43
+ } });
44
+ var require_toPrimitive = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/toPrimitive.js"(exports, module) {
45
+ var _typeof$1 = require_typeof()["default"];
46
+ function toPrimitive$1(t, r) {
47
+ if (_typeof$1(t) != "object" || !t)
48
+ return t;
49
+ var e = t[Symbol.toPrimitive];
50
+ if (e !== undefined) {
51
+ var i = e.call(t, r || "default");
52
+ if (_typeof$1(i) != "object")
53
+ return i;
54
+ throw new TypeError("@@toPrimitive must return a primitive value.");
55
+ }
56
+ return (r === "string" ? String : Number)(t);
57
+ }
58
+ module.exports = toPrimitive$1, module.exports.__esModule = true, module.exports["default"] = module.exports;
59
+ } });
60
+ var require_toPropertyKey = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/toPropertyKey.js"(exports, module) {
61
+ var _typeof = require_typeof()["default"];
62
+ var toPrimitive = require_toPrimitive();
63
+ function toPropertyKey$1(t) {
64
+ var i = toPrimitive(t, "string");
65
+ return _typeof(i) == "symbol" ? i : i + "";
66
+ }
67
+ module.exports = toPropertyKey$1, module.exports.__esModule = true, module.exports["default"] = module.exports;
68
+ } });
69
+ var require_defineProperty = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/defineProperty.js"(exports, module) {
70
+ var toPropertyKey = require_toPropertyKey();
71
+ function _defineProperty(e, r, t) {
72
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
73
+ value: t,
74
+ enumerable: true,
75
+ configurable: true,
76
+ writable: true
77
+ }) : e[r] = t, e;
78
+ }
79
+ module.exports = _defineProperty, module.exports.__esModule = true, module.exports["default"] = module.exports;
80
+ } });
81
+ var require_objectSpread2 = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/objectSpread2.js"(exports, module) {
82
+ var defineProperty = require_defineProperty();
83
+ function ownKeys(e, r) {
84
+ var t = Object.keys(e);
85
+ if (Object.getOwnPropertySymbols) {
86
+ var o = Object.getOwnPropertySymbols(e);
87
+ r && (o = o.filter(function(r$1) {
88
+ return Object.getOwnPropertyDescriptor(e, r$1).enumerable;
89
+ })), t.push.apply(t, o);
90
+ }
91
+ return t;
92
+ }
93
+ function _objectSpread2(e) {
94
+ for (var r = 1;r < arguments.length; r++) {
95
+ var t = arguments[r] != null ? arguments[r] : {};
96
+ r % 2 ? ownKeys(Object(t), true).forEach(function(r$1) {
97
+ defineProperty(e, r$1, t[r$1]);
98
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r$1) {
99
+ Object.defineProperty(e, r$1, Object.getOwnPropertyDescriptor(t, r$1));
100
+ });
101
+ }
102
+ return e;
103
+ }
104
+ module.exports = _objectSpread2, module.exports.__esModule = true, module.exports["default"] = module.exports;
105
+ } });
106
+
107
+ // ../../node_modules/.bun/@trpc+server@11.8.1+1fb4c65d43e298b9/node_modules/@trpc/server/dist/observable-UMO3vUa_.mjs
108
+ function observable(subscribe) {
109
+ const self = {
110
+ subscribe(observer) {
111
+ let teardownRef = null;
112
+ let isDone = false;
113
+ let unsubscribed = false;
114
+ let teardownImmediately = false;
115
+ function unsubscribe() {
116
+ if (teardownRef === null) {
117
+ teardownImmediately = true;
118
+ return;
119
+ }
120
+ if (unsubscribed)
121
+ return;
122
+ unsubscribed = true;
123
+ if (typeof teardownRef === "function")
124
+ teardownRef();
125
+ else if (teardownRef)
126
+ teardownRef.unsubscribe();
127
+ }
128
+ teardownRef = subscribe({
129
+ next(value) {
130
+ var _observer$next;
131
+ if (isDone)
132
+ return;
133
+ (_observer$next = observer.next) === null || _observer$next === undefined || _observer$next.call(observer, value);
134
+ },
135
+ error(err) {
136
+ var _observer$error;
137
+ if (isDone)
138
+ return;
139
+ isDone = true;
140
+ (_observer$error = observer.error) === null || _observer$error === undefined || _observer$error.call(observer, err);
141
+ unsubscribe();
142
+ },
143
+ complete() {
144
+ var _observer$complete;
145
+ if (isDone)
146
+ return;
147
+ isDone = true;
148
+ (_observer$complete = observer.complete) === null || _observer$complete === undefined || _observer$complete.call(observer);
149
+ unsubscribe();
150
+ }
151
+ });
152
+ if (teardownImmediately)
153
+ unsubscribe();
154
+ return { unsubscribe };
155
+ },
156
+ pipe(...operations) {
157
+ return operations.reduce(pipeReducer, self);
158
+ }
159
+ };
160
+ return self;
161
+ }
162
+ function pipeReducer(prev, fn) {
163
+ return fn(prev);
164
+ }
165
+ function observableToPromise(observable$1) {
166
+ const ac = new AbortController;
167
+ const promise = new Promise((resolve, reject) => {
168
+ let isDone = false;
169
+ function onDone() {
170
+ if (isDone)
171
+ return;
172
+ isDone = true;
173
+ obs$.unsubscribe();
174
+ }
175
+ ac.signal.addEventListener("abort", () => {
176
+ reject(ac.signal.reason);
177
+ });
178
+ const obs$ = observable$1.subscribe({
179
+ next(data) {
180
+ isDone = true;
181
+ resolve(data);
182
+ onDone();
183
+ },
184
+ error(data) {
185
+ reject(data);
186
+ },
187
+ complete() {
188
+ ac.abort();
189
+ onDone();
190
+ }
191
+ });
192
+ });
193
+ return promise;
194
+ }
195
+
196
+ // ../../node_modules/.bun/@trpc+server@11.8.1+1fb4c65d43e298b9/node_modules/@trpc/server/dist/observable-CUiPknO-.mjs
197
+ function share(_opts) {
198
+ return (source) => {
199
+ let refCount = 0;
200
+ let subscription = null;
201
+ const observers = [];
202
+ function startIfNeeded() {
203
+ if (subscription)
204
+ return;
205
+ subscription = source.subscribe({
206
+ next(value) {
207
+ for (const observer of observers) {
208
+ var _observer$next;
209
+ (_observer$next = observer.next) === null || _observer$next === undefined || _observer$next.call(observer, value);
210
+ }
211
+ },
212
+ error(error) {
213
+ for (const observer of observers) {
214
+ var _observer$error;
215
+ (_observer$error = observer.error) === null || _observer$error === undefined || _observer$error.call(observer, error);
216
+ }
217
+ },
218
+ complete() {
219
+ for (const observer of observers) {
220
+ var _observer$complete;
221
+ (_observer$complete = observer.complete) === null || _observer$complete === undefined || _observer$complete.call(observer);
222
+ }
223
+ }
224
+ });
225
+ }
226
+ function resetIfNeeded() {
227
+ if (refCount === 0 && subscription) {
228
+ const _sub = subscription;
229
+ subscription = null;
230
+ _sub.unsubscribe();
231
+ }
232
+ }
233
+ return observable((subscriber) => {
234
+ refCount++;
235
+ observers.push(subscriber);
236
+ startIfNeeded();
237
+ return { unsubscribe() {
238
+ refCount--;
239
+ resetIfNeeded();
240
+ const index = observers.findIndex((v) => v === subscriber);
241
+ if (index > -1)
242
+ observers.splice(index, 1);
243
+ } };
244
+ });
245
+ };
246
+ }
247
+ var distinctUnsetMarker = Symbol();
248
+ function behaviorSubject(initialValue) {
249
+ let value = initialValue;
250
+ const observerList = [];
251
+ const addObserver = (observer) => {
252
+ if (value !== undefined)
253
+ observer.next(value);
254
+ observerList.push(observer);
255
+ };
256
+ const removeObserver = (observer) => {
257
+ observerList.splice(observerList.indexOf(observer), 1);
258
+ };
259
+ const obs = observable((observer) => {
260
+ addObserver(observer);
261
+ return () => {
262
+ removeObserver(observer);
263
+ };
264
+ });
265
+ obs.next = (nextValue) => {
266
+ if (value === nextValue)
267
+ return;
268
+ value = nextValue;
269
+ for (const observer of observerList)
270
+ observer.next(nextValue);
271
+ };
272
+ obs.get = () => value;
273
+ return obs;
274
+ }
275
+
276
+ // ../../node_modules/.bun/@trpc+client@11.8.1+56fb0e3277503e89/node_modules/@trpc/client/dist/splitLink-B7Cuf2c_.mjs
277
+ function createChain(opts) {
278
+ return observable((observer) => {
279
+ function execute(index = 0, op = opts.op) {
280
+ const next = opts.links[index];
281
+ if (!next)
282
+ throw new Error("No more links to execute - did you forget to add an ending link?");
283
+ const subscription = next({
284
+ op,
285
+ next(nextOp) {
286
+ const nextObserver = execute(index + 1, nextOp);
287
+ return nextObserver;
288
+ }
289
+ });
290
+ return subscription;
291
+ }
292
+ const obs$ = execute();
293
+ return obs$.subscribe(observer);
294
+ });
295
+ }
296
+ function asArray(value) {
297
+ return Array.isArray(value) ? value : [value];
298
+ }
299
+ function splitLink(opts) {
300
+ return (runtime) => {
301
+ const yes = asArray(opts.true).map((link) => link(runtime));
302
+ const no = asArray(opts.false).map((link) => link(runtime));
303
+ return (props) => {
304
+ return observable((observer) => {
305
+ const links = opts.condition(props.op) ? yes : no;
306
+ return createChain({
307
+ op: props.op,
308
+ links
309
+ }).subscribe(observer);
310
+ });
311
+ };
312
+ };
313
+ }
314
+
315
+ // ../../node_modules/.bun/@trpc+server@11.8.1+1fb4c65d43e298b9/node_modules/@trpc/server/dist/codes-DagpWZLc.mjs
316
+ function isObject(value) {
317
+ return !!value && !Array.isArray(value) && typeof value === "object";
318
+ }
319
+ function emptyObject() {
320
+ return Object.create(null);
321
+ }
322
+ var run = (fn) => fn();
323
+ var TRPC_ERROR_CODES_BY_KEY = {
324
+ PARSE_ERROR: -32700,
325
+ BAD_REQUEST: -32600,
326
+ INTERNAL_SERVER_ERROR: -32603,
327
+ NOT_IMPLEMENTED: -32603,
328
+ BAD_GATEWAY: -32603,
329
+ SERVICE_UNAVAILABLE: -32603,
330
+ GATEWAY_TIMEOUT: -32603,
331
+ UNAUTHORIZED: -32001,
332
+ PAYMENT_REQUIRED: -32002,
333
+ FORBIDDEN: -32003,
334
+ NOT_FOUND: -32004,
335
+ METHOD_NOT_SUPPORTED: -32005,
336
+ TIMEOUT: -32008,
337
+ CONFLICT: -32009,
338
+ PRECONDITION_FAILED: -32012,
339
+ PAYLOAD_TOO_LARGE: -32013,
340
+ UNSUPPORTED_MEDIA_TYPE: -32015,
341
+ UNPROCESSABLE_CONTENT: -32022,
342
+ PRECONDITION_REQUIRED: -32028,
343
+ TOO_MANY_REQUESTS: -32029,
344
+ CLIENT_CLOSED_REQUEST: -32099
345
+ };
346
+ var retryableRpcCodes = [
347
+ TRPC_ERROR_CODES_BY_KEY.BAD_GATEWAY,
348
+ TRPC_ERROR_CODES_BY_KEY.SERVICE_UNAVAILABLE,
349
+ TRPC_ERROR_CODES_BY_KEY.GATEWAY_TIMEOUT,
350
+ TRPC_ERROR_CODES_BY_KEY.INTERNAL_SERVER_ERROR
351
+ ];
352
+
353
+ // ../../node_modules/.bun/@trpc+server@11.8.1+1fb4c65d43e298b9/node_modules/@trpc/server/dist/getErrorShape-vC8mUXJD.mjs
354
+ var __create2 = Object.create;
355
+ var __defProp2 = Object.defineProperty;
356
+ var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
357
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
358
+ var __getProtoOf2 = Object.getPrototypeOf;
359
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
360
+ var __commonJS2 = (cb, mod) => function() {
361
+ return mod || (0, cb[__getOwnPropNames2(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
362
+ };
363
+ var __copyProps2 = (to, from, except, desc) => {
364
+ if (from && typeof from === "object" || typeof from === "function")
365
+ for (var keys = __getOwnPropNames2(from), i = 0, n = keys.length, key;i < n; i++) {
366
+ key = keys[i];
367
+ if (!__hasOwnProp2.call(to, key) && key !== except)
368
+ __defProp2(to, key, {
369
+ get: ((k) => from[k]).bind(null, key),
370
+ enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable
371
+ });
372
+ }
373
+ return to;
374
+ };
375
+ var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2(isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", {
376
+ value: mod,
377
+ enumerable: true
378
+ }) : target, mod));
379
+ var noop = () => {};
380
+ var freezeIfAvailable = (obj) => {
381
+ if (Object.freeze)
382
+ Object.freeze(obj);
383
+ };
384
+ function createInnerProxy(callback, path, memo) {
385
+ var _memo$cacheKey;
386
+ const cacheKey = path.join(".");
387
+ (_memo$cacheKey = memo[cacheKey]) !== null && _memo$cacheKey !== undefined || (memo[cacheKey] = new Proxy(noop, {
388
+ get(_obj, key) {
389
+ if (typeof key !== "string" || key === "then")
390
+ return;
391
+ return createInnerProxy(callback, [...path, key], memo);
392
+ },
393
+ apply(_1, _2, args) {
394
+ const lastOfPath = path[path.length - 1];
395
+ let opts = {
396
+ args,
397
+ path
398
+ };
399
+ if (lastOfPath === "call")
400
+ opts = {
401
+ args: args.length >= 2 ? [args[1]] : [],
402
+ path: path.slice(0, -1)
403
+ };
404
+ else if (lastOfPath === "apply")
405
+ opts = {
406
+ args: args.length >= 2 ? args[1] : [],
407
+ path: path.slice(0, -1)
408
+ };
409
+ freezeIfAvailable(opts.args);
410
+ freezeIfAvailable(opts.path);
411
+ return callback(opts);
412
+ }
413
+ }));
414
+ return memo[cacheKey];
415
+ }
416
+ var createRecursiveProxy = (callback) => createInnerProxy(callback, [], emptyObject());
417
+ var createFlatProxy = (callback) => {
418
+ return new Proxy(noop, { get(_obj, name) {
419
+ if (name === "then")
420
+ return;
421
+ return callback(name);
422
+ } });
423
+ };
424
+ var require_typeof2 = __commonJS2({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/typeof.js"(exports, module) {
425
+ function _typeof$2(o) {
426
+ "@babel/helpers - typeof";
427
+ return module.exports = _typeof$2 = typeof Symbol == "function" && typeof Symbol.iterator == "symbol" ? function(o$1) {
428
+ return typeof o$1;
429
+ } : function(o$1) {
430
+ return o$1 && typeof Symbol == "function" && o$1.constructor === Symbol && o$1 !== Symbol.prototype ? "symbol" : typeof o$1;
431
+ }, module.exports.__esModule = true, module.exports["default"] = module.exports, _typeof$2(o);
432
+ }
433
+ module.exports = _typeof$2, module.exports.__esModule = true, module.exports["default"] = module.exports;
434
+ } });
435
+ var require_toPrimitive2 = __commonJS2({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/toPrimitive.js"(exports, module) {
436
+ var _typeof$1 = require_typeof2()["default"];
437
+ function toPrimitive$1(t, r) {
438
+ if (_typeof$1(t) != "object" || !t)
439
+ return t;
440
+ var e = t[Symbol.toPrimitive];
441
+ if (e !== undefined) {
442
+ var i = e.call(t, r || "default");
443
+ if (_typeof$1(i) != "object")
444
+ return i;
445
+ throw new TypeError("@@toPrimitive must return a primitive value.");
446
+ }
447
+ return (r === "string" ? String : Number)(t);
448
+ }
449
+ module.exports = toPrimitive$1, module.exports.__esModule = true, module.exports["default"] = module.exports;
450
+ } });
451
+ var require_toPropertyKey2 = __commonJS2({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/toPropertyKey.js"(exports, module) {
452
+ var _typeof = require_typeof2()["default"];
453
+ var toPrimitive = require_toPrimitive2();
454
+ function toPropertyKey$1(t) {
455
+ var i = toPrimitive(t, "string");
456
+ return _typeof(i) == "symbol" ? i : i + "";
457
+ }
458
+ module.exports = toPropertyKey$1, module.exports.__esModule = true, module.exports["default"] = module.exports;
459
+ } });
460
+ var require_defineProperty2 = __commonJS2({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/defineProperty.js"(exports, module) {
461
+ var toPropertyKey = require_toPropertyKey2();
462
+ function _defineProperty(e, r, t) {
463
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
464
+ value: t,
465
+ enumerable: true,
466
+ configurable: true,
467
+ writable: true
468
+ }) : e[r] = t, e;
469
+ }
470
+ module.exports = _defineProperty, module.exports.__esModule = true, module.exports["default"] = module.exports;
471
+ } });
472
+ var require_objectSpread22 = __commonJS2({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/objectSpread2.js"(exports, module) {
473
+ var defineProperty = require_defineProperty2();
474
+ function ownKeys(e, r) {
475
+ var t = Object.keys(e);
476
+ if (Object.getOwnPropertySymbols) {
477
+ var o = Object.getOwnPropertySymbols(e);
478
+ r && (o = o.filter(function(r$1) {
479
+ return Object.getOwnPropertyDescriptor(e, r$1).enumerable;
480
+ })), t.push.apply(t, o);
481
+ }
482
+ return t;
483
+ }
484
+ function _objectSpread2(e) {
485
+ for (var r = 1;r < arguments.length; r++) {
486
+ var t = arguments[r] != null ? arguments[r] : {};
487
+ r % 2 ? ownKeys(Object(t), true).forEach(function(r$1) {
488
+ defineProperty(e, r$1, t[r$1]);
489
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r$1) {
490
+ Object.defineProperty(e, r$1, Object.getOwnPropertyDescriptor(t, r$1));
491
+ });
492
+ }
493
+ return e;
494
+ }
495
+ module.exports = _objectSpread2, module.exports.__esModule = true, module.exports["default"] = module.exports;
496
+ } });
497
+ var import_objectSpread2 = __toESM2(require_objectSpread22(), 1);
498
+
499
+ // ../../node_modules/.bun/@trpc+server@11.8.1+1fb4c65d43e298b9/node_modules/@trpc/server/dist/tracked-D4V22yc5.mjs
500
+ var import_defineProperty = __toESM2(require_defineProperty2(), 1);
501
+ var import_objectSpread2$1 = __toESM2(require_objectSpread22(), 1);
502
+ function transformResultInner(response, transformer) {
503
+ if ("error" in response) {
504
+ const error = transformer.deserialize(response.error);
505
+ return {
506
+ ok: false,
507
+ error: (0, import_objectSpread2$1.default)((0, import_objectSpread2$1.default)({}, response), {}, { error })
508
+ };
509
+ }
510
+ const result = (0, import_objectSpread2$1.default)((0, import_objectSpread2$1.default)({}, response.result), (!response.result.type || response.result.type === "data") && {
511
+ type: "data",
512
+ data: transformer.deserialize(response.result.data)
513
+ });
514
+ return {
515
+ ok: true,
516
+ result
517
+ };
518
+ }
519
+ var TransformResultError = class extends Error {
520
+ constructor() {
521
+ super("Unable to transform response from server");
522
+ }
523
+ };
524
+ function transformResult(response, transformer) {
525
+ let result;
526
+ try {
527
+ result = transformResultInner(response, transformer);
528
+ } catch (_unused) {
529
+ throw new TransformResultError;
530
+ }
531
+ if (!result.ok && (!isObject(result.error.error) || typeof result.error.error["code"] !== "number"))
532
+ throw new TransformResultError;
533
+ if (result.ok && !isObject(result.result))
534
+ throw new TransformResultError;
535
+ return result;
536
+ }
537
+ var import_objectSpread22 = __toESM2(require_objectSpread22(), 1);
538
+ var trackedSymbol = Symbol();
539
+ // ../../node_modules/.bun/@trpc+server@11.8.1+1fb4c65d43e298b9/node_modules/@trpc/server/dist/resolveResponse-C7AcnFLN.mjs
540
+ var import_objectSpread2$12 = __toESM2(require_objectSpread22(), 1);
541
+ /*!
542
+ * is-plain-object <https://github.com/jonschlinkert/is-plain-object>
543
+ *
544
+ * Copyright (c) 2014-2017, Jon Schlinkert.
545
+ * Released under the MIT License.
546
+ */
547
+ var import_defineProperty2 = __toESM2(require_defineProperty2(), 1);
548
+ var _Symbol$toStringTag;
549
+ var subscribableCache = /* @__PURE__ */ new WeakMap;
550
+ var NOOP = () => {};
551
+ _Symbol$toStringTag = Symbol.toStringTag;
552
+ var Unpromise = class Unpromise {
553
+ constructor(arg) {
554
+ (0, import_defineProperty2.default)(this, "promise", undefined);
555
+ (0, import_defineProperty2.default)(this, "subscribers", []);
556
+ (0, import_defineProperty2.default)(this, "settlement", null);
557
+ (0, import_defineProperty2.default)(this, _Symbol$toStringTag, "Unpromise");
558
+ if (typeof arg === "function")
559
+ this.promise = new Promise(arg);
560
+ else
561
+ this.promise = arg;
562
+ const thenReturn = this.promise.then((value) => {
563
+ const { subscribers } = this;
564
+ this.subscribers = null;
565
+ this.settlement = {
566
+ status: "fulfilled",
567
+ value
568
+ };
569
+ subscribers === null || subscribers === undefined || subscribers.forEach(({ resolve }) => {
570
+ resolve(value);
571
+ });
572
+ });
573
+ if ("catch" in thenReturn)
574
+ thenReturn.catch((reason) => {
575
+ const { subscribers } = this;
576
+ this.subscribers = null;
577
+ this.settlement = {
578
+ status: "rejected",
579
+ reason
580
+ };
581
+ subscribers === null || subscribers === undefined || subscribers.forEach(({ reject }) => {
582
+ reject(reason);
583
+ });
584
+ });
585
+ }
586
+ subscribe() {
587
+ let promise;
588
+ let unsubscribe;
589
+ const { settlement } = this;
590
+ if (settlement === null) {
591
+ if (this.subscribers === null)
592
+ throw new Error("Unpromise settled but still has subscribers");
593
+ const subscriber = withResolvers();
594
+ this.subscribers = listWithMember(this.subscribers, subscriber);
595
+ promise = subscriber.promise;
596
+ unsubscribe = () => {
597
+ if (this.subscribers !== null)
598
+ this.subscribers = listWithoutMember(this.subscribers, subscriber);
599
+ };
600
+ } else {
601
+ const { status } = settlement;
602
+ if (status === "fulfilled")
603
+ promise = Promise.resolve(settlement.value);
604
+ else
605
+ promise = Promise.reject(settlement.reason);
606
+ unsubscribe = NOOP;
607
+ }
608
+ return Object.assign(promise, { unsubscribe });
609
+ }
610
+ then(onfulfilled, onrejected) {
611
+ const subscribed = this.subscribe();
612
+ const { unsubscribe } = subscribed;
613
+ return Object.assign(subscribed.then(onfulfilled, onrejected), { unsubscribe });
614
+ }
615
+ catch(onrejected) {
616
+ const subscribed = this.subscribe();
617
+ const { unsubscribe } = subscribed;
618
+ return Object.assign(subscribed.catch(onrejected), { unsubscribe });
619
+ }
620
+ finally(onfinally) {
621
+ const subscribed = this.subscribe();
622
+ const { unsubscribe } = subscribed;
623
+ return Object.assign(subscribed.finally(onfinally), { unsubscribe });
624
+ }
625
+ static proxy(promise) {
626
+ const cached = Unpromise.getSubscribablePromise(promise);
627
+ return typeof cached !== "undefined" ? cached : Unpromise.createSubscribablePromise(promise);
628
+ }
629
+ static createSubscribablePromise(promise) {
630
+ const created = new Unpromise(promise);
631
+ subscribableCache.set(promise, created);
632
+ subscribableCache.set(created, created);
633
+ return created;
634
+ }
635
+ static getSubscribablePromise(promise) {
636
+ return subscribableCache.get(promise);
637
+ }
638
+ static resolve(value) {
639
+ const promise = typeof value === "object" && value !== null && "then" in value && typeof value.then === "function" ? value : Promise.resolve(value);
640
+ return Unpromise.proxy(promise).subscribe();
641
+ }
642
+ static async any(values) {
643
+ const valuesArray = Array.isArray(values) ? values : [...values];
644
+ const subscribedPromises = valuesArray.map(Unpromise.resolve);
645
+ try {
646
+ return await Promise.any(subscribedPromises);
647
+ } finally {
648
+ subscribedPromises.forEach(({ unsubscribe }) => {
649
+ unsubscribe();
650
+ });
651
+ }
652
+ }
653
+ static async race(values) {
654
+ const valuesArray = Array.isArray(values) ? values : [...values];
655
+ const subscribedPromises = valuesArray.map(Unpromise.resolve);
656
+ try {
657
+ return await Promise.race(subscribedPromises);
658
+ } finally {
659
+ subscribedPromises.forEach(({ unsubscribe }) => {
660
+ unsubscribe();
661
+ });
662
+ }
663
+ }
664
+ static async raceReferences(promises) {
665
+ const selfPromises = promises.map(resolveSelfTuple);
666
+ try {
667
+ return await Promise.race(selfPromises);
668
+ } finally {
669
+ for (const promise of selfPromises)
670
+ promise.unsubscribe();
671
+ }
672
+ }
673
+ };
674
+ function resolveSelfTuple(promise) {
675
+ return Unpromise.proxy(promise).then(() => [promise]);
676
+ }
677
+ function withResolvers() {
678
+ let resolve;
679
+ let reject;
680
+ const promise = new Promise((_resolve, _reject) => {
681
+ resolve = _resolve;
682
+ reject = _reject;
683
+ });
684
+ return {
685
+ promise,
686
+ resolve,
687
+ reject
688
+ };
689
+ }
690
+ function listWithMember(arr, member) {
691
+ return [...arr, member];
692
+ }
693
+ function listWithoutIndex(arr, index) {
694
+ return [...arr.slice(0, index), ...arr.slice(index + 1)];
695
+ }
696
+ function listWithoutMember(arr, member) {
697
+ const index = arr.indexOf(member);
698
+ if (index !== -1)
699
+ return listWithoutIndex(arr, index);
700
+ return arr;
701
+ }
702
+ var _Symbol;
703
+ var _Symbol$dispose;
704
+ var _Symbol2;
705
+ var _Symbol2$asyncDispose;
706
+ (_Symbol$dispose = (_Symbol = Symbol).dispose) !== null && _Symbol$dispose !== undefined || (_Symbol.dispose = Symbol());
707
+ (_Symbol2$asyncDispose = (_Symbol2 = Symbol).asyncDispose) !== null && _Symbol2$asyncDispose !== undefined || (_Symbol2.asyncDispose = Symbol());
708
+ function makeResource(thing, dispose) {
709
+ const it = thing;
710
+ const existing = it[Symbol.dispose];
711
+ it[Symbol.dispose] = () => {
712
+ dispose();
713
+ existing === null || existing === undefined || existing();
714
+ };
715
+ return it;
716
+ }
717
+ function makeAsyncResource(thing, dispose) {
718
+ const it = thing;
719
+ const existing = it[Symbol.asyncDispose];
720
+ it[Symbol.asyncDispose] = async () => {
721
+ await dispose();
722
+ await (existing === null || existing === undefined ? undefined : existing());
723
+ };
724
+ return it;
725
+ }
726
+ var disposablePromiseTimerResult = Symbol();
727
+ function timerResource(ms) {
728
+ let timer = null;
729
+ return makeResource({ start() {
730
+ if (timer)
731
+ throw new Error("Timer already started");
732
+ const promise = new Promise((resolve) => {
733
+ timer = setTimeout(() => resolve(disposablePromiseTimerResult), ms);
734
+ });
735
+ return promise;
736
+ } }, () => {
737
+ if (timer)
738
+ clearTimeout(timer);
739
+ });
740
+ }
741
+ var require_usingCtx = __commonJS2({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/usingCtx.js"(exports, module) {
742
+ function _usingCtx() {
743
+ var r = typeof SuppressedError == "function" ? SuppressedError : function(r$1, e$1) {
744
+ var n$1 = Error();
745
+ return n$1.name = "SuppressedError", n$1.error = r$1, n$1.suppressed = e$1, n$1;
746
+ }, e = {}, n = [];
747
+ function using(r$1, e$1) {
748
+ if (e$1 != null) {
749
+ if (Object(e$1) !== e$1)
750
+ throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");
751
+ if (r$1)
752
+ var o = e$1[Symbol.asyncDispose || Symbol["for"]("Symbol.asyncDispose")];
753
+ if (o === undefined && (o = e$1[Symbol.dispose || Symbol["for"]("Symbol.dispose")], r$1))
754
+ var t = o;
755
+ if (typeof o != "function")
756
+ throw new TypeError("Object is not disposable.");
757
+ t && (o = function o$1() {
758
+ try {
759
+ t.call(e$1);
760
+ } catch (r$2) {
761
+ return Promise.reject(r$2);
762
+ }
763
+ }), n.push({
764
+ v: e$1,
765
+ d: o,
766
+ a: r$1
767
+ });
768
+ } else
769
+ r$1 && n.push({
770
+ d: e$1,
771
+ a: r$1
772
+ });
773
+ return e$1;
774
+ }
775
+ return {
776
+ e,
777
+ u: using.bind(null, false),
778
+ a: using.bind(null, true),
779
+ d: function d() {
780
+ var o, t = this.e, s = 0;
781
+ function next() {
782
+ for (;o = n.pop(); )
783
+ try {
784
+ if (!o.a && s === 1)
785
+ return s = 0, n.push(o), Promise.resolve().then(next);
786
+ if (o.d) {
787
+ var r$1 = o.d.call(o.v);
788
+ if (o.a)
789
+ return s |= 2, Promise.resolve(r$1).then(next, err);
790
+ } else
791
+ s |= 1;
792
+ } catch (r$2) {
793
+ return err(r$2);
794
+ }
795
+ if (s === 1)
796
+ return t !== e ? Promise.reject(t) : Promise.resolve();
797
+ if (t !== e)
798
+ throw t;
799
+ }
800
+ function err(n$1) {
801
+ return t = t !== e ? new r(n$1, t) : n$1, next();
802
+ }
803
+ return next();
804
+ }
805
+ };
806
+ }
807
+ module.exports = _usingCtx, module.exports.__esModule = true, module.exports["default"] = module.exports;
808
+ } });
809
+ var require_OverloadYield = __commonJS2({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/OverloadYield.js"(exports, module) {
810
+ function _OverloadYield(e, d) {
811
+ this.v = e, this.k = d;
812
+ }
813
+ module.exports = _OverloadYield, module.exports.__esModule = true, module.exports["default"] = module.exports;
814
+ } });
815
+ var require_awaitAsyncGenerator = __commonJS2({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/awaitAsyncGenerator.js"(exports, module) {
816
+ var OverloadYield$2 = require_OverloadYield();
817
+ function _awaitAsyncGenerator$5(e) {
818
+ return new OverloadYield$2(e, 0);
819
+ }
820
+ module.exports = _awaitAsyncGenerator$5, module.exports.__esModule = true, module.exports["default"] = module.exports;
821
+ } });
822
+ var require_wrapAsyncGenerator = __commonJS2({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/wrapAsyncGenerator.js"(exports, module) {
823
+ var OverloadYield$1 = require_OverloadYield();
824
+ function _wrapAsyncGenerator$6(e) {
825
+ return function() {
826
+ return new AsyncGenerator(e.apply(this, arguments));
827
+ };
828
+ }
829
+ function AsyncGenerator(e) {
830
+ var r, t;
831
+ function resume(r$1, t$1) {
832
+ try {
833
+ var n = e[r$1](t$1), o = n.value, u = o instanceof OverloadYield$1;
834
+ Promise.resolve(u ? o.v : o).then(function(t$2) {
835
+ if (u) {
836
+ var i = r$1 === "return" ? "return" : "next";
837
+ if (!o.k || t$2.done)
838
+ return resume(i, t$2);
839
+ t$2 = e[i](t$2).value;
840
+ }
841
+ settle(n.done ? "return" : "normal", t$2);
842
+ }, function(e$1) {
843
+ resume("throw", e$1);
844
+ });
845
+ } catch (e$1) {
846
+ settle("throw", e$1);
847
+ }
848
+ }
849
+ function settle(e$1, n) {
850
+ switch (e$1) {
851
+ case "return":
852
+ r.resolve({
853
+ value: n,
854
+ done: true
855
+ });
856
+ break;
857
+ case "throw":
858
+ r.reject(n);
859
+ break;
860
+ default:
861
+ r.resolve({
862
+ value: n,
863
+ done: false
864
+ });
865
+ }
866
+ (r = r.next) ? resume(r.key, r.arg) : t = null;
867
+ }
868
+ this._invoke = function(e$1, n) {
869
+ return new Promise(function(o, u) {
870
+ var i = {
871
+ key: e$1,
872
+ arg: n,
873
+ resolve: o,
874
+ reject: u,
875
+ next: null
876
+ };
877
+ t ? t = t.next = i : (r = t = i, resume(e$1, n));
878
+ });
879
+ }, typeof e["return"] != "function" && (this["return"] = undefined);
880
+ }
881
+ AsyncGenerator.prototype[typeof Symbol == "function" && Symbol.asyncIterator || "@@asyncIterator"] = function() {
882
+ return this;
883
+ }, AsyncGenerator.prototype.next = function(e) {
884
+ return this._invoke("next", e);
885
+ }, AsyncGenerator.prototype["throw"] = function(e) {
886
+ return this._invoke("throw", e);
887
+ }, AsyncGenerator.prototype["return"] = function(e) {
888
+ return this._invoke("return", e);
889
+ };
890
+ module.exports = _wrapAsyncGenerator$6, module.exports.__esModule = true, module.exports["default"] = module.exports;
891
+ } });
892
+ var import_usingCtx$4 = __toESM2(require_usingCtx(), 1);
893
+ var import_awaitAsyncGenerator$4 = __toESM2(require_awaitAsyncGenerator(), 1);
894
+ var import_wrapAsyncGenerator$5 = __toESM2(require_wrapAsyncGenerator(), 1);
895
+ var import_usingCtx$3 = __toESM2(require_usingCtx(), 1);
896
+ var import_awaitAsyncGenerator$3 = __toESM2(require_awaitAsyncGenerator(), 1);
897
+ var import_wrapAsyncGenerator$4 = __toESM2(require_wrapAsyncGenerator(), 1);
898
+ var import_usingCtx$2 = __toESM2(require_usingCtx(), 1);
899
+ var import_awaitAsyncGenerator$2 = __toESM2(require_awaitAsyncGenerator(), 1);
900
+ var import_wrapAsyncGenerator$3 = __toESM2(require_wrapAsyncGenerator(), 1);
901
+ var PING_SYM = Symbol("ping");
902
+ var require_asyncIterator = __commonJS2({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/asyncIterator.js"(exports, module) {
903
+ function _asyncIterator$2(r) {
904
+ var n, t, o, e = 2;
905
+ for (typeof Symbol != "undefined" && (t = Symbol.asyncIterator, o = Symbol.iterator);e--; ) {
906
+ if (t && (n = r[t]) != null)
907
+ return n.call(r);
908
+ if (o && (n = r[o]) != null)
909
+ return new AsyncFromSyncIterator(n.call(r));
910
+ t = "@@asyncIterator", o = "@@iterator";
911
+ }
912
+ throw new TypeError("Object is not async iterable");
913
+ }
914
+ function AsyncFromSyncIterator(r) {
915
+ function AsyncFromSyncIteratorContinuation(r$1) {
916
+ if (Object(r$1) !== r$1)
917
+ return Promise.reject(new TypeError(r$1 + " is not an object."));
918
+ var n = r$1.done;
919
+ return Promise.resolve(r$1.value).then(function(r$2) {
920
+ return {
921
+ value: r$2,
922
+ done: n
923
+ };
924
+ });
925
+ }
926
+ return AsyncFromSyncIterator = function AsyncFromSyncIterator$1(r$1) {
927
+ this.s = r$1, this.n = r$1.next;
928
+ }, AsyncFromSyncIterator.prototype = {
929
+ s: null,
930
+ n: null,
931
+ next: function next() {
932
+ return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments));
933
+ },
934
+ return: function _return(r$1) {
935
+ var n = this.s["return"];
936
+ return n === undefined ? Promise.resolve({
937
+ value: r$1,
938
+ done: true
939
+ }) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));
940
+ },
941
+ throw: function _throw(r$1) {
942
+ var n = this.s["return"];
943
+ return n === undefined ? Promise.reject(r$1) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));
944
+ }
945
+ }, new AsyncFromSyncIterator(r);
946
+ }
947
+ module.exports = _asyncIterator$2, module.exports.__esModule = true, module.exports["default"] = module.exports;
948
+ } });
949
+ var import_awaitAsyncGenerator$1 = __toESM2(require_awaitAsyncGenerator(), 1);
950
+ var import_wrapAsyncGenerator$2 = __toESM2(require_wrapAsyncGenerator(), 1);
951
+ var import_usingCtx$1 = __toESM2(require_usingCtx(), 1);
952
+ var import_asyncIterator$1 = __toESM2(require_asyncIterator(), 1);
953
+ var require_asyncGeneratorDelegate = __commonJS2({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/asyncGeneratorDelegate.js"(exports, module) {
954
+ var OverloadYield = require_OverloadYield();
955
+ function _asyncGeneratorDelegate$1(t) {
956
+ var e = {}, n = false;
957
+ function pump(e$1, r) {
958
+ return n = true, r = new Promise(function(n$1) {
959
+ n$1(t[e$1](r));
960
+ }), {
961
+ done: false,
962
+ value: new OverloadYield(r, 1)
963
+ };
964
+ }
965
+ return e[typeof Symbol != "undefined" && Symbol.iterator || "@@iterator"] = function() {
966
+ return this;
967
+ }, e.next = function(t$1) {
968
+ return n ? (n = false, t$1) : pump("next", t$1);
969
+ }, typeof t["throw"] == "function" && (e["throw"] = function(t$1) {
970
+ if (n)
971
+ throw n = false, t$1;
972
+ return pump("throw", t$1);
973
+ }), typeof t["return"] == "function" && (e["return"] = function(t$1) {
974
+ return n ? (n = false, t$1) : pump("return", t$1);
975
+ }), e;
976
+ }
977
+ module.exports = _asyncGeneratorDelegate$1, module.exports.__esModule = true, module.exports["default"] = module.exports;
978
+ } });
979
+ var import_asyncIterator = __toESM2(require_asyncIterator(), 1);
980
+ var import_awaitAsyncGenerator = __toESM2(require_awaitAsyncGenerator(), 1);
981
+ var import_wrapAsyncGenerator$1 = __toESM2(require_wrapAsyncGenerator(), 1);
982
+ var import_asyncGeneratorDelegate = __toESM2(require_asyncGeneratorDelegate(), 1);
983
+ var import_usingCtx = __toESM2(require_usingCtx(), 1);
984
+ var PING_EVENT = "ping";
985
+ var SERIALIZED_ERROR_EVENT = "serialized-error";
986
+ var CONNECTED_EVENT = "connected";
987
+ var RETURN_EVENT = "return";
988
+ async function withTimeout(opts) {
989
+ try {
990
+ var _usingCtx$1 = (0, import_usingCtx.default)();
991
+ const timeoutPromise = _usingCtx$1.u(timerResource(opts.timeoutMs));
992
+ const res = await Unpromise.race([opts.promise, timeoutPromise.start()]);
993
+ if (res === disposablePromiseTimerResult)
994
+ return await opts.onTimeout();
995
+ return res;
996
+ } catch (_) {
997
+ _usingCtx$1.e = _;
998
+ } finally {
999
+ _usingCtx$1.d();
1000
+ }
1001
+ }
1002
+ function sseStreamConsumer(opts) {
1003
+ const { deserialize = (v) => v } = opts;
1004
+ let clientOptions = emptyObject();
1005
+ const signal = opts.signal;
1006
+ let _es = null;
1007
+ const createStream = () => new ReadableStream({
1008
+ async start(controller) {
1009
+ const [url, init] = await Promise.all([opts.url(), opts.init()]);
1010
+ const eventSource = _es = new opts.EventSource(url, init);
1011
+ controller.enqueue({
1012
+ type: "connecting",
1013
+ eventSource: _es,
1014
+ event: null
1015
+ });
1016
+ eventSource.addEventListener(CONNECTED_EVENT, (_msg) => {
1017
+ const msg = _msg;
1018
+ const options = JSON.parse(msg.data);
1019
+ clientOptions = options;
1020
+ controller.enqueue({
1021
+ type: "connected",
1022
+ options,
1023
+ eventSource
1024
+ });
1025
+ });
1026
+ eventSource.addEventListener(SERIALIZED_ERROR_EVENT, (_msg) => {
1027
+ const msg = _msg;
1028
+ controller.enqueue({
1029
+ type: "serialized-error",
1030
+ error: deserialize(JSON.parse(msg.data)),
1031
+ eventSource
1032
+ });
1033
+ });
1034
+ eventSource.addEventListener(PING_EVENT, () => {
1035
+ controller.enqueue({
1036
+ type: "ping",
1037
+ eventSource
1038
+ });
1039
+ });
1040
+ eventSource.addEventListener(RETURN_EVENT, () => {
1041
+ eventSource.close();
1042
+ controller.close();
1043
+ _es = null;
1044
+ });
1045
+ eventSource.addEventListener("error", (event) => {
1046
+ if (eventSource.readyState === eventSource.CLOSED)
1047
+ controller.error(event);
1048
+ else
1049
+ controller.enqueue({
1050
+ type: "connecting",
1051
+ eventSource,
1052
+ event
1053
+ });
1054
+ });
1055
+ eventSource.addEventListener("message", (_msg) => {
1056
+ const msg = _msg;
1057
+ const chunk = deserialize(JSON.parse(msg.data));
1058
+ const def = { data: chunk };
1059
+ if (msg.lastEventId)
1060
+ def.id = msg.lastEventId;
1061
+ controller.enqueue({
1062
+ type: "data",
1063
+ data: def,
1064
+ eventSource
1065
+ });
1066
+ });
1067
+ const onAbort = () => {
1068
+ try {
1069
+ eventSource.close();
1070
+ controller.close();
1071
+ } catch (_unused) {}
1072
+ };
1073
+ if (signal.aborted)
1074
+ onAbort();
1075
+ else
1076
+ signal.addEventListener("abort", onAbort);
1077
+ },
1078
+ cancel() {
1079
+ _es === null || _es === undefined || _es.close();
1080
+ }
1081
+ });
1082
+ const getStreamResource = () => {
1083
+ let stream = createStream();
1084
+ let reader = stream.getReader();
1085
+ async function dispose() {
1086
+ await reader.cancel();
1087
+ _es = null;
1088
+ }
1089
+ return makeAsyncResource({
1090
+ read() {
1091
+ return reader.read();
1092
+ },
1093
+ async recreate() {
1094
+ await dispose();
1095
+ stream = createStream();
1096
+ reader = stream.getReader();
1097
+ }
1098
+ }, dispose);
1099
+ };
1100
+ return run((0, import_wrapAsyncGenerator$1.default)(function* () {
1101
+ try {
1102
+ var _usingCtx3 = (0, import_usingCtx.default)();
1103
+ const stream = _usingCtx3.a(getStreamResource());
1104
+ while (true) {
1105
+ let promise = stream.read();
1106
+ const timeoutMs = clientOptions.reconnectAfterInactivityMs;
1107
+ if (timeoutMs)
1108
+ promise = withTimeout({
1109
+ promise,
1110
+ timeoutMs,
1111
+ onTimeout: async () => {
1112
+ const res = {
1113
+ value: {
1114
+ type: "timeout",
1115
+ ms: timeoutMs,
1116
+ eventSource: _es
1117
+ },
1118
+ done: false
1119
+ };
1120
+ await stream.recreate();
1121
+ return res;
1122
+ }
1123
+ });
1124
+ const result = yield (0, import_awaitAsyncGenerator.default)(promise);
1125
+ if (result.done)
1126
+ return result.value;
1127
+ yield result.value;
1128
+ }
1129
+ } catch (_) {
1130
+ _usingCtx3.e = _;
1131
+ } finally {
1132
+ yield (0, import_awaitAsyncGenerator.default)(_usingCtx3.d());
1133
+ }
1134
+ }));
1135
+ }
1136
+ var import_wrapAsyncGenerator = __toESM2(require_wrapAsyncGenerator(), 1);
1137
+ var import_objectSpread23 = __toESM2(require_objectSpread22(), 1);
1138
+ // ../../node_modules/.bun/@trpc+client@11.8.1+56fb0e3277503e89/node_modules/@trpc/client/dist/TRPCClientError-CjKyS10w.mjs
1139
+ var import_defineProperty3 = __toESM(require_defineProperty(), 1);
1140
+ var import_objectSpread24 = __toESM(require_objectSpread2(), 1);
1141
+ function isTRPCClientError(cause) {
1142
+ return cause instanceof TRPCClientError;
1143
+ }
1144
+ function isTRPCErrorResponse(obj) {
1145
+ return isObject(obj) && isObject(obj["error"]) && typeof obj["error"]["code"] === "number" && typeof obj["error"]["message"] === "string";
1146
+ }
1147
+ function getMessageFromUnknownError(err, fallback) {
1148
+ if (typeof err === "string")
1149
+ return err;
1150
+ if (isObject(err) && typeof err["message"] === "string")
1151
+ return err["message"];
1152
+ return fallback;
1153
+ }
1154
+ var TRPCClientError = class TRPCClientError extends Error {
1155
+ constructor(message, opts) {
1156
+ var _opts$result, _opts$result2;
1157
+ const cause = opts === null || opts === undefined ? undefined : opts.cause;
1158
+ super(message, { cause });
1159
+ (0, import_defineProperty3.default)(this, "cause", undefined);
1160
+ (0, import_defineProperty3.default)(this, "shape", undefined);
1161
+ (0, import_defineProperty3.default)(this, "data", undefined);
1162
+ (0, import_defineProperty3.default)(this, "meta", undefined);
1163
+ this.meta = opts === null || opts === undefined ? undefined : opts.meta;
1164
+ this.cause = cause;
1165
+ this.shape = opts === null || opts === undefined || (_opts$result = opts.result) === null || _opts$result === undefined ? undefined : _opts$result.error;
1166
+ this.data = opts === null || opts === undefined || (_opts$result2 = opts.result) === null || _opts$result2 === undefined ? undefined : _opts$result2.error.data;
1167
+ this.name = "TRPCClientError";
1168
+ Object.setPrototypeOf(this, TRPCClientError.prototype);
1169
+ }
1170
+ static from(_cause, opts = {}) {
1171
+ const cause = _cause;
1172
+ if (isTRPCClientError(cause)) {
1173
+ if (opts.meta)
1174
+ cause.meta = (0, import_objectSpread24.default)((0, import_objectSpread24.default)({}, cause.meta), opts.meta);
1175
+ return cause;
1176
+ }
1177
+ if (isTRPCErrorResponse(cause))
1178
+ return new TRPCClientError(cause.error.message, (0, import_objectSpread24.default)((0, import_objectSpread24.default)({}, opts), {}, { result: cause }));
1179
+ return new TRPCClientError(getMessageFromUnknownError(cause, "Unknown error"), (0, import_objectSpread24.default)((0, import_objectSpread24.default)({}, opts), {}, { cause }));
1180
+ }
1181
+ };
1182
+
1183
+ // ../../node_modules/.bun/@trpc+client@11.8.1+56fb0e3277503e89/node_modules/@trpc/client/dist/unstable-internals-Bg7n9BBj.mjs
1184
+ function getTransformer(transformer) {
1185
+ const _transformer = transformer;
1186
+ if (!_transformer)
1187
+ return {
1188
+ input: {
1189
+ serialize: (data) => data,
1190
+ deserialize: (data) => data
1191
+ },
1192
+ output: {
1193
+ serialize: (data) => data,
1194
+ deserialize: (data) => data
1195
+ }
1196
+ };
1197
+ if ("input" in _transformer)
1198
+ return _transformer;
1199
+ return {
1200
+ input: _transformer,
1201
+ output: _transformer
1202
+ };
1203
+ }
1204
+
1205
+ // ../../node_modules/.bun/@trpc+client@11.8.1+56fb0e3277503e89/node_modules/@trpc/client/dist/httpUtils-Dv57hbOd.mjs
1206
+ var isFunction2 = (fn) => typeof fn === "function";
1207
+ function getFetch(customFetchImpl) {
1208
+ if (customFetchImpl)
1209
+ return customFetchImpl;
1210
+ if (typeof window !== "undefined" && isFunction2(window.fetch))
1211
+ return window.fetch;
1212
+ if (typeof globalThis !== "undefined" && isFunction2(globalThis.fetch))
1213
+ return globalThis.fetch;
1214
+ throw new Error("No fetch implementation found");
1215
+ }
1216
+ var import_objectSpread25 = __toESM(require_objectSpread2(), 1);
1217
+ function resolveHTTPLinkOptions(opts) {
1218
+ return {
1219
+ url: opts.url.toString(),
1220
+ fetch: opts.fetch,
1221
+ transformer: getTransformer(opts.transformer),
1222
+ methodOverride: opts.methodOverride
1223
+ };
1224
+ }
1225
+ function arrayToDict(array) {
1226
+ const dict = {};
1227
+ for (let index = 0;index < array.length; index++) {
1228
+ const element = array[index];
1229
+ dict[index] = element;
1230
+ }
1231
+ return dict;
1232
+ }
1233
+ var METHOD = {
1234
+ query: "GET",
1235
+ mutation: "POST",
1236
+ subscription: "PATCH"
1237
+ };
1238
+ function getInput(opts) {
1239
+ return "input" in opts ? opts.transformer.input.serialize(opts.input) : arrayToDict(opts.inputs.map((_input) => opts.transformer.input.serialize(_input)));
1240
+ }
1241
+ var getUrl = (opts) => {
1242
+ const parts = opts.url.split("?");
1243
+ const base = parts[0].replace(/\/$/, "");
1244
+ let url = base + "/" + opts.path;
1245
+ const queryParts = [];
1246
+ if (parts[1])
1247
+ queryParts.push(parts[1]);
1248
+ if ("inputs" in opts)
1249
+ queryParts.push("batch=1");
1250
+ if (opts.type === "query" || opts.type === "subscription") {
1251
+ const input = getInput(opts);
1252
+ if (input !== undefined && opts.methodOverride !== "POST")
1253
+ queryParts.push(`input=${encodeURIComponent(JSON.stringify(input))}`);
1254
+ }
1255
+ if (queryParts.length)
1256
+ url += "?" + queryParts.join("&");
1257
+ return url;
1258
+ };
1259
+ var getBody = (opts) => {
1260
+ if (opts.type === "query" && opts.methodOverride !== "POST")
1261
+ return;
1262
+ const input = getInput(opts);
1263
+ return input !== undefined ? JSON.stringify(input) : undefined;
1264
+ };
1265
+ var jsonHttpRequester = (opts) => {
1266
+ return httpRequest((0, import_objectSpread25.default)((0, import_objectSpread25.default)({}, opts), {}, {
1267
+ contentTypeHeader: "application/json",
1268
+ getUrl,
1269
+ getBody
1270
+ }));
1271
+ };
1272
+ var AbortError = class extends Error {
1273
+ constructor() {
1274
+ const name = "AbortError";
1275
+ super(name);
1276
+ this.name = name;
1277
+ this.message = name;
1278
+ }
1279
+ };
1280
+ var throwIfAborted = (signal) => {
1281
+ var _signal$throwIfAborte;
1282
+ if (!(signal === null || signal === undefined ? undefined : signal.aborted))
1283
+ return;
1284
+ (_signal$throwIfAborte = signal.throwIfAborted) === null || _signal$throwIfAborte === undefined || _signal$throwIfAborte.call(signal);
1285
+ if (typeof DOMException !== "undefined")
1286
+ throw new DOMException("AbortError", "AbortError");
1287
+ throw new AbortError;
1288
+ };
1289
+ async function fetchHTTPResponse(opts) {
1290
+ var _opts$methodOverride;
1291
+ throwIfAborted(opts.signal);
1292
+ const url = opts.getUrl(opts);
1293
+ const body = opts.getBody(opts);
1294
+ const method = (_opts$methodOverride = opts.methodOverride) !== null && _opts$methodOverride !== undefined ? _opts$methodOverride : METHOD[opts.type];
1295
+ const resolvedHeaders = await (async () => {
1296
+ const heads = await opts.headers();
1297
+ if (Symbol.iterator in heads)
1298
+ return Object.fromEntries(heads);
1299
+ return heads;
1300
+ })();
1301
+ const headers = (0, import_objectSpread25.default)((0, import_objectSpread25.default)((0, import_objectSpread25.default)({}, opts.contentTypeHeader && method !== "GET" ? { "content-type": opts.contentTypeHeader } : {}), opts.trpcAcceptHeader ? { "trpc-accept": opts.trpcAcceptHeader } : undefined), resolvedHeaders);
1302
+ return getFetch(opts.fetch)(url, {
1303
+ method,
1304
+ signal: opts.signal,
1305
+ body,
1306
+ headers
1307
+ });
1308
+ }
1309
+ async function httpRequest(opts) {
1310
+ const meta = {};
1311
+ const res = await fetchHTTPResponse(opts);
1312
+ meta.response = res;
1313
+ const json = await res.json();
1314
+ meta.responseJSON = json;
1315
+ return {
1316
+ json,
1317
+ meta
1318
+ };
1319
+ }
1320
+
1321
+ // ../../node_modules/.bun/@trpc+client@11.8.1+56fb0e3277503e89/node_modules/@trpc/client/dist/httpLink-DCFpUmZF.mjs
1322
+ var import_objectSpread26 = __toESM(require_objectSpread2(), 1);
1323
+
1324
+ // ../../node_modules/.bun/@trpc+client@11.8.1+56fb0e3277503e89/node_modules/@trpc/client/dist/httpBatchLink-BOe5aCcR.mjs
1325
+ var throwFatalError = () => {
1326
+ throw new Error("Something went wrong. Please submit an issue at https://github.com/trpc/trpc/issues/new");
1327
+ };
1328
+ function dataLoader(batchLoader) {
1329
+ let pendingItems = null;
1330
+ let dispatchTimer = null;
1331
+ const destroyTimerAndPendingItems = () => {
1332
+ clearTimeout(dispatchTimer);
1333
+ dispatchTimer = null;
1334
+ pendingItems = null;
1335
+ };
1336
+ function groupItems(items) {
1337
+ const groupedItems = [[]];
1338
+ let index = 0;
1339
+ while (true) {
1340
+ const item = items[index];
1341
+ if (!item)
1342
+ break;
1343
+ const lastGroup = groupedItems[groupedItems.length - 1];
1344
+ if (item.aborted) {
1345
+ var _item$reject;
1346
+ (_item$reject = item.reject) === null || _item$reject === undefined || _item$reject.call(item, new Error("Aborted"));
1347
+ index++;
1348
+ continue;
1349
+ }
1350
+ const isValid = batchLoader.validate(lastGroup.concat(item).map((it) => it.key));
1351
+ if (isValid) {
1352
+ lastGroup.push(item);
1353
+ index++;
1354
+ continue;
1355
+ }
1356
+ if (lastGroup.length === 0) {
1357
+ var _item$reject2;
1358
+ (_item$reject2 = item.reject) === null || _item$reject2 === undefined || _item$reject2.call(item, new Error("Input is too big for a single dispatch"));
1359
+ index++;
1360
+ continue;
1361
+ }
1362
+ groupedItems.push([]);
1363
+ }
1364
+ return groupedItems;
1365
+ }
1366
+ function dispatch() {
1367
+ const groupedItems = groupItems(pendingItems);
1368
+ destroyTimerAndPendingItems();
1369
+ for (const items of groupedItems) {
1370
+ if (!items.length)
1371
+ continue;
1372
+ const batch = { items };
1373
+ for (const item of items)
1374
+ item.batch = batch;
1375
+ const promise = batchLoader.fetch(batch.items.map((_item) => _item.key));
1376
+ promise.then(async (result) => {
1377
+ await Promise.all(result.map(async (valueOrPromise, index) => {
1378
+ const item = batch.items[index];
1379
+ try {
1380
+ var _item$resolve;
1381
+ const value = await Promise.resolve(valueOrPromise);
1382
+ (_item$resolve = item.resolve) === null || _item$resolve === undefined || _item$resolve.call(item, value);
1383
+ } catch (cause) {
1384
+ var _item$reject3;
1385
+ (_item$reject3 = item.reject) === null || _item$reject3 === undefined || _item$reject3.call(item, cause);
1386
+ }
1387
+ item.batch = null;
1388
+ item.reject = null;
1389
+ item.resolve = null;
1390
+ }));
1391
+ for (const item of batch.items) {
1392
+ var _item$reject4;
1393
+ (_item$reject4 = item.reject) === null || _item$reject4 === undefined || _item$reject4.call(item, new Error("Missing result"));
1394
+ item.batch = null;
1395
+ }
1396
+ }).catch((cause) => {
1397
+ for (const item of batch.items) {
1398
+ var _item$reject5;
1399
+ (_item$reject5 = item.reject) === null || _item$reject5 === undefined || _item$reject5.call(item, cause);
1400
+ item.batch = null;
1401
+ }
1402
+ });
1403
+ }
1404
+ }
1405
+ function load(key) {
1406
+ var _dispatchTimer;
1407
+ const item = {
1408
+ aborted: false,
1409
+ key,
1410
+ batch: null,
1411
+ resolve: throwFatalError,
1412
+ reject: throwFatalError
1413
+ };
1414
+ const promise = new Promise((resolve, reject) => {
1415
+ var _pendingItems;
1416
+ item.reject = reject;
1417
+ item.resolve = resolve;
1418
+ (_pendingItems = pendingItems) !== null && _pendingItems !== undefined || (pendingItems = []);
1419
+ pendingItems.push(item);
1420
+ });
1421
+ (_dispatchTimer = dispatchTimer) !== null && _dispatchTimer !== undefined || (dispatchTimer = setTimeout(dispatch));
1422
+ return promise;
1423
+ }
1424
+ return { load };
1425
+ }
1426
+ function allAbortSignals(...signals) {
1427
+ const ac = new AbortController;
1428
+ const count = signals.length;
1429
+ let abortedCount = 0;
1430
+ const onAbort = () => {
1431
+ if (++abortedCount === count)
1432
+ ac.abort();
1433
+ };
1434
+ for (const signal of signals)
1435
+ if (signal === null || signal === undefined ? undefined : signal.aborted)
1436
+ onAbort();
1437
+ else
1438
+ signal === null || signal === undefined || signal.addEventListener("abort", onAbort, { once: true });
1439
+ return ac.signal;
1440
+ }
1441
+ function raceAbortSignals(...signals) {
1442
+ const ac = new AbortController;
1443
+ for (const signal of signals)
1444
+ if (signal === null || signal === undefined ? undefined : signal.aborted)
1445
+ ac.abort();
1446
+ else
1447
+ signal === null || signal === undefined || signal.addEventListener("abort", () => ac.abort(), { once: true });
1448
+ return ac.signal;
1449
+ }
1450
+ var import_objectSpread27 = __toESM(require_objectSpread2(), 1);
1451
+ function httpBatchLink(opts) {
1452
+ var _opts$maxURLLength, _opts$maxItems;
1453
+ const resolvedOpts = resolveHTTPLinkOptions(opts);
1454
+ const maxURLLength = (_opts$maxURLLength = opts.maxURLLength) !== null && _opts$maxURLLength !== undefined ? _opts$maxURLLength : Infinity;
1455
+ const maxItems = (_opts$maxItems = opts.maxItems) !== null && _opts$maxItems !== undefined ? _opts$maxItems : Infinity;
1456
+ return () => {
1457
+ const batchLoader = (type) => {
1458
+ return {
1459
+ validate(batchOps) {
1460
+ if (maxURLLength === Infinity && maxItems === Infinity)
1461
+ return true;
1462
+ if (batchOps.length > maxItems)
1463
+ return false;
1464
+ const path = batchOps.map((op) => op.path).join(",");
1465
+ const inputs = batchOps.map((op) => op.input);
1466
+ const url = getUrl((0, import_objectSpread27.default)((0, import_objectSpread27.default)({}, resolvedOpts), {}, {
1467
+ type,
1468
+ path,
1469
+ inputs,
1470
+ signal: null
1471
+ }));
1472
+ return url.length <= maxURLLength;
1473
+ },
1474
+ async fetch(batchOps) {
1475
+ const path = batchOps.map((op) => op.path).join(",");
1476
+ const inputs = batchOps.map((op) => op.input);
1477
+ const signal = allAbortSignals(...batchOps.map((op) => op.signal));
1478
+ const res = await jsonHttpRequester((0, import_objectSpread27.default)((0, import_objectSpread27.default)({}, resolvedOpts), {}, {
1479
+ path,
1480
+ inputs,
1481
+ type,
1482
+ headers() {
1483
+ if (!opts.headers)
1484
+ return {};
1485
+ if (typeof opts.headers === "function")
1486
+ return opts.headers({ opList: batchOps });
1487
+ return opts.headers;
1488
+ },
1489
+ signal
1490
+ }));
1491
+ const resJSON = Array.isArray(res.json) ? res.json : batchOps.map(() => res.json);
1492
+ const result = resJSON.map((item) => ({
1493
+ meta: res.meta,
1494
+ json: item
1495
+ }));
1496
+ return result;
1497
+ }
1498
+ };
1499
+ };
1500
+ const query = dataLoader(batchLoader("query"));
1501
+ const mutation = dataLoader(batchLoader("mutation"));
1502
+ const loaders = {
1503
+ query,
1504
+ mutation
1505
+ };
1506
+ return ({ op }) => {
1507
+ return observable((observer) => {
1508
+ if (op.type === "subscription")
1509
+ throw new Error("Subscriptions are unsupported by `httpLink` - use `httpSubscriptionLink` or `wsLink`");
1510
+ const loader = loaders[op.type];
1511
+ const promise = loader.load(op);
1512
+ let _res = undefined;
1513
+ promise.then((res) => {
1514
+ _res = res;
1515
+ const transformed = transformResult(res.json, resolvedOpts.transformer.output);
1516
+ if (!transformed.ok) {
1517
+ observer.error(TRPCClientError.from(transformed.error, { meta: res.meta }));
1518
+ return;
1519
+ }
1520
+ observer.next({
1521
+ context: res.meta,
1522
+ result: transformed.result
1523
+ });
1524
+ observer.complete();
1525
+ }).catch((err) => {
1526
+ observer.error(TRPCClientError.from(err, { meta: _res === null || _res === undefined ? undefined : _res.meta }));
1527
+ });
1528
+ return () => {};
1529
+ });
1530
+ };
1531
+ };
1532
+ }
1533
+
1534
+ // ../../node_modules/.bun/@trpc+client@11.8.1+56fb0e3277503e89/node_modules/@trpc/client/dist/loggerLink-ineCN1PO.mjs
1535
+ var import_objectSpread28 = __toESM(require_objectSpread2(), 1);
1536
+
1537
+ // ../../node_modules/.bun/@trpc+client@11.8.1+56fb0e3277503e89/node_modules/@trpc/client/dist/wsLink-CatceK3c.mjs
1538
+ var resultOf = (value, ...args) => {
1539
+ return typeof value === "function" ? value(...args) : value;
1540
+ };
1541
+ var import_defineProperty$3 = __toESM(require_defineProperty(), 1);
1542
+ function withResolvers2() {
1543
+ let resolve;
1544
+ let reject;
1545
+ const promise = new Promise((res, rej) => {
1546
+ resolve = res;
1547
+ reject = rej;
1548
+ });
1549
+ return {
1550
+ promise,
1551
+ resolve,
1552
+ reject
1553
+ };
1554
+ }
1555
+ async function prepareUrl(urlOptions) {
1556
+ const url = await resultOf(urlOptions.url);
1557
+ if (!urlOptions.connectionParams)
1558
+ return url;
1559
+ const prefix = url.includes("?") ? "&" : "?";
1560
+ const connectionParams = `${prefix}connectionParams=1`;
1561
+ return url + connectionParams;
1562
+ }
1563
+ async function buildConnectionMessage(connectionParams) {
1564
+ const message = {
1565
+ method: "connectionParams",
1566
+ data: await resultOf(connectionParams)
1567
+ };
1568
+ return JSON.stringify(message);
1569
+ }
1570
+ var import_defineProperty$2 = __toESM(require_defineProperty(), 1);
1571
+ var import_defineProperty$1 = __toESM(require_defineProperty(), 1);
1572
+ function asyncWsOpen(ws) {
1573
+ const { promise, resolve, reject } = withResolvers2();
1574
+ ws.addEventListener("open", () => {
1575
+ ws.removeEventListener("error", reject);
1576
+ resolve();
1577
+ });
1578
+ ws.addEventListener("error", reject);
1579
+ return promise;
1580
+ }
1581
+ function setupPingInterval(ws, { intervalMs, pongTimeoutMs }) {
1582
+ let pingTimeout;
1583
+ let pongTimeout;
1584
+ function start() {
1585
+ pingTimeout = setTimeout(() => {
1586
+ ws.send("PING");
1587
+ pongTimeout = setTimeout(() => {
1588
+ ws.close();
1589
+ }, pongTimeoutMs);
1590
+ }, intervalMs);
1591
+ }
1592
+ function reset() {
1593
+ clearTimeout(pingTimeout);
1594
+ start();
1595
+ }
1596
+ function pong() {
1597
+ clearTimeout(pongTimeout);
1598
+ reset();
1599
+ }
1600
+ ws.addEventListener("open", start);
1601
+ ws.addEventListener("message", ({ data }) => {
1602
+ clearTimeout(pingTimeout);
1603
+ start();
1604
+ if (data === "PONG")
1605
+ pong();
1606
+ });
1607
+ ws.addEventListener("close", () => {
1608
+ clearTimeout(pingTimeout);
1609
+ clearTimeout(pongTimeout);
1610
+ });
1611
+ }
1612
+ var WsConnection = class WsConnection {
1613
+ constructor(opts) {
1614
+ var _opts$WebSocketPonyfi;
1615
+ (0, import_defineProperty$1.default)(this, "id", ++WsConnection.connectCount);
1616
+ (0, import_defineProperty$1.default)(this, "WebSocketPonyfill", undefined);
1617
+ (0, import_defineProperty$1.default)(this, "urlOptions", undefined);
1618
+ (0, import_defineProperty$1.default)(this, "keepAliveOpts", undefined);
1619
+ (0, import_defineProperty$1.default)(this, "wsObservable", behaviorSubject(null));
1620
+ (0, import_defineProperty$1.default)(this, "openPromise", null);
1621
+ this.WebSocketPonyfill = (_opts$WebSocketPonyfi = opts.WebSocketPonyfill) !== null && _opts$WebSocketPonyfi !== undefined ? _opts$WebSocketPonyfi : WebSocket;
1622
+ if (!this.WebSocketPonyfill)
1623
+ throw new Error("No WebSocket implementation found - you probably don't want to use this on the server, but if you do you need to pass a `WebSocket`-ponyfill");
1624
+ this.urlOptions = opts.urlOptions;
1625
+ this.keepAliveOpts = opts.keepAlive;
1626
+ }
1627
+ get ws() {
1628
+ return this.wsObservable.get();
1629
+ }
1630
+ set ws(ws) {
1631
+ this.wsObservable.next(ws);
1632
+ }
1633
+ isOpen() {
1634
+ return !!this.ws && this.ws.readyState === this.WebSocketPonyfill.OPEN && !this.openPromise;
1635
+ }
1636
+ isClosed() {
1637
+ return !!this.ws && (this.ws.readyState === this.WebSocketPonyfill.CLOSING || this.ws.readyState === this.WebSocketPonyfill.CLOSED);
1638
+ }
1639
+ async open() {
1640
+ var _this = this;
1641
+ if (_this.openPromise)
1642
+ return _this.openPromise;
1643
+ _this.id = ++WsConnection.connectCount;
1644
+ const wsPromise = prepareUrl(_this.urlOptions).then((url) => new _this.WebSocketPonyfill(url));
1645
+ _this.openPromise = wsPromise.then(async (ws) => {
1646
+ _this.ws = ws;
1647
+ ws.addEventListener("message", function({ data }) {
1648
+ if (data === "PING")
1649
+ this.send("PONG");
1650
+ });
1651
+ if (_this.keepAliveOpts.enabled)
1652
+ setupPingInterval(ws, _this.keepAliveOpts);
1653
+ ws.addEventListener("close", () => {
1654
+ if (_this.ws === ws)
1655
+ _this.ws = null;
1656
+ });
1657
+ await asyncWsOpen(ws);
1658
+ if (_this.urlOptions.connectionParams)
1659
+ ws.send(await buildConnectionMessage(_this.urlOptions.connectionParams));
1660
+ });
1661
+ try {
1662
+ await _this.openPromise;
1663
+ } finally {
1664
+ _this.openPromise = null;
1665
+ }
1666
+ }
1667
+ async close() {
1668
+ var _this2 = this;
1669
+ try {
1670
+ await _this2.openPromise;
1671
+ } finally {
1672
+ var _this$ws;
1673
+ (_this$ws = _this2.ws) === null || _this$ws === undefined || _this$ws.close();
1674
+ }
1675
+ }
1676
+ };
1677
+ (0, import_defineProperty$1.default)(WsConnection, "connectCount", 0);
1678
+ var import_defineProperty4 = __toESM(require_defineProperty(), 1);
1679
+ var import_objectSpread29 = __toESM(require_objectSpread2(), 1);
1680
+
1681
+ // ../../node_modules/.bun/@trpc+client@11.8.1+56fb0e3277503e89/node_modules/@trpc/client/dist/index.mjs
1682
+ var import_defineProperty5 = __toESM(require_defineProperty(), 1);
1683
+ var import_objectSpread2$4 = __toESM(require_objectSpread2(), 1);
1684
+ var TRPCUntypedClient = class {
1685
+ constructor(opts) {
1686
+ (0, import_defineProperty5.default)(this, "links", undefined);
1687
+ (0, import_defineProperty5.default)(this, "runtime", undefined);
1688
+ (0, import_defineProperty5.default)(this, "requestId", undefined);
1689
+ this.requestId = 0;
1690
+ this.runtime = {};
1691
+ this.links = opts.links.map((link) => link(this.runtime));
1692
+ }
1693
+ $request(opts) {
1694
+ var _opts$context;
1695
+ const chain$ = createChain({
1696
+ links: this.links,
1697
+ op: (0, import_objectSpread2$4.default)((0, import_objectSpread2$4.default)({}, opts), {}, {
1698
+ context: (_opts$context = opts.context) !== null && _opts$context !== undefined ? _opts$context : {},
1699
+ id: ++this.requestId
1700
+ })
1701
+ });
1702
+ return chain$.pipe(share());
1703
+ }
1704
+ async requestAsPromise(opts) {
1705
+ var _this = this;
1706
+ try {
1707
+ const req$ = _this.$request(opts);
1708
+ const envelope = await observableToPromise(req$);
1709
+ const data = envelope.result.data;
1710
+ return data;
1711
+ } catch (err) {
1712
+ throw TRPCClientError.from(err);
1713
+ }
1714
+ }
1715
+ query(path, input, opts) {
1716
+ return this.requestAsPromise({
1717
+ type: "query",
1718
+ path,
1719
+ input,
1720
+ context: opts === null || opts === undefined ? undefined : opts.context,
1721
+ signal: opts === null || opts === undefined ? undefined : opts.signal
1722
+ });
1723
+ }
1724
+ mutation(path, input, opts) {
1725
+ return this.requestAsPromise({
1726
+ type: "mutation",
1727
+ path,
1728
+ input,
1729
+ context: opts === null || opts === undefined ? undefined : opts.context,
1730
+ signal: opts === null || opts === undefined ? undefined : opts.signal
1731
+ });
1732
+ }
1733
+ subscription(path, input, opts) {
1734
+ const observable$ = this.$request({
1735
+ type: "subscription",
1736
+ path,
1737
+ input,
1738
+ context: opts.context,
1739
+ signal: opts.signal
1740
+ });
1741
+ return observable$.subscribe({
1742
+ next(envelope) {
1743
+ switch (envelope.result.type) {
1744
+ case "state": {
1745
+ var _opts$onConnectionSta;
1746
+ (_opts$onConnectionSta = opts.onConnectionStateChange) === null || _opts$onConnectionSta === undefined || _opts$onConnectionSta.call(opts, envelope.result);
1747
+ break;
1748
+ }
1749
+ case "started": {
1750
+ var _opts$onStarted;
1751
+ (_opts$onStarted = opts.onStarted) === null || _opts$onStarted === undefined || _opts$onStarted.call(opts, { context: envelope.context });
1752
+ break;
1753
+ }
1754
+ case "stopped": {
1755
+ var _opts$onStopped;
1756
+ (_opts$onStopped = opts.onStopped) === null || _opts$onStopped === undefined || _opts$onStopped.call(opts);
1757
+ break;
1758
+ }
1759
+ case "data":
1760
+ case undefined: {
1761
+ var _opts$onData;
1762
+ (_opts$onData = opts.onData) === null || _opts$onData === undefined || _opts$onData.call(opts, envelope.result.data);
1763
+ break;
1764
+ }
1765
+ }
1766
+ },
1767
+ error(err) {
1768
+ var _opts$onError;
1769
+ (_opts$onError = opts.onError) === null || _opts$onError === undefined || _opts$onError.call(opts, err);
1770
+ },
1771
+ complete() {
1772
+ var _opts$onComplete;
1773
+ (_opts$onComplete = opts.onComplete) === null || _opts$onComplete === undefined || _opts$onComplete.call(opts);
1774
+ }
1775
+ });
1776
+ }
1777
+ };
1778
+ var untypedClientSymbol = Symbol.for("trpc_untypedClient");
1779
+ var clientCallTypeMap = {
1780
+ query: "query",
1781
+ mutate: "mutation",
1782
+ subscribe: "subscription"
1783
+ };
1784
+ var clientCallTypeToProcedureType = (clientCallType) => {
1785
+ return clientCallTypeMap[clientCallType];
1786
+ };
1787
+ function createTRPCClientProxy(client) {
1788
+ const proxy = createRecursiveProxy(({ path, args }) => {
1789
+ const pathCopy = [...path];
1790
+ const procedureType = clientCallTypeToProcedureType(pathCopy.pop());
1791
+ const fullPath = pathCopy.join(".");
1792
+ return client[procedureType](fullPath, ...args);
1793
+ });
1794
+ return createFlatProxy((key) => {
1795
+ if (key === untypedClientSymbol)
1796
+ return client;
1797
+ return proxy[key];
1798
+ });
1799
+ }
1800
+ function createTRPCClient(opts) {
1801
+ const client = new TRPCUntypedClient(opts);
1802
+ const proxy = createTRPCClientProxy(client);
1803
+ return proxy;
1804
+ }
1805
+ var import_objectSpread2$3 = __toESM(require_objectSpread2(), 1);
1806
+ var import_objectSpread2$2 = __toESM(require_objectSpread2(), 1);
1807
+ function inputWithTrackedEventId(input, lastEventId) {
1808
+ if (!lastEventId)
1809
+ return input;
1810
+ if (input != null && typeof input !== "object")
1811
+ return input;
1812
+ return (0, import_objectSpread2$2.default)((0, import_objectSpread2$2.default)({}, input !== null && input !== undefined ? input : {}), {}, { lastEventId });
1813
+ }
1814
+ var require_asyncIterator2 = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/asyncIterator.js"(exports, module) {
1815
+ function _asyncIterator$1(r) {
1816
+ var n, t, o, e = 2;
1817
+ for (typeof Symbol != "undefined" && (t = Symbol.asyncIterator, o = Symbol.iterator);e--; ) {
1818
+ if (t && (n = r[t]) != null)
1819
+ return n.call(r);
1820
+ if (o && (n = r[o]) != null)
1821
+ return new AsyncFromSyncIterator(n.call(r));
1822
+ t = "@@asyncIterator", o = "@@iterator";
1823
+ }
1824
+ throw new TypeError("Object is not async iterable");
1825
+ }
1826
+ function AsyncFromSyncIterator(r) {
1827
+ function AsyncFromSyncIteratorContinuation(r$1) {
1828
+ if (Object(r$1) !== r$1)
1829
+ return Promise.reject(new TypeError(r$1 + " is not an object."));
1830
+ var n = r$1.done;
1831
+ return Promise.resolve(r$1.value).then(function(r$2) {
1832
+ return {
1833
+ value: r$2,
1834
+ done: n
1835
+ };
1836
+ });
1837
+ }
1838
+ return AsyncFromSyncIterator = function AsyncFromSyncIterator$1(r$1) {
1839
+ this.s = r$1, this.n = r$1.next;
1840
+ }, AsyncFromSyncIterator.prototype = {
1841
+ s: null,
1842
+ n: null,
1843
+ next: function next() {
1844
+ return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments));
1845
+ },
1846
+ return: function _return(r$1) {
1847
+ var n = this.s["return"];
1848
+ return n === undefined ? Promise.resolve({
1849
+ value: r$1,
1850
+ done: true
1851
+ }) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));
1852
+ },
1853
+ throw: function _throw(r$1) {
1854
+ var n = this.s["return"];
1855
+ return n === undefined ? Promise.reject(r$1) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));
1856
+ }
1857
+ }, new AsyncFromSyncIterator(r);
1858
+ }
1859
+ module.exports = _asyncIterator$1, module.exports.__esModule = true, module.exports["default"] = module.exports;
1860
+ } });
1861
+ var import_asyncIterator2 = __toESM(require_asyncIterator2(), 1);
1862
+ async function urlWithConnectionParams(opts) {
1863
+ let url = await resultOf(opts.url);
1864
+ if (opts.connectionParams) {
1865
+ const params = await resultOf(opts.connectionParams);
1866
+ const prefix = url.includes("?") ? "&" : "?";
1867
+ url += prefix + "connectionParams=" + encodeURIComponent(JSON.stringify(params));
1868
+ }
1869
+ return url;
1870
+ }
1871
+ function httpSubscriptionLink(opts) {
1872
+ const transformer = getTransformer(opts.transformer);
1873
+ return () => {
1874
+ return ({ op }) => {
1875
+ return observable((observer) => {
1876
+ var _opts$EventSource;
1877
+ const { type, path, input } = op;
1878
+ if (type !== "subscription")
1879
+ throw new Error("httpSubscriptionLink only supports subscriptions");
1880
+ let lastEventId = undefined;
1881
+ const ac = new AbortController;
1882
+ const signal = raceAbortSignals(op.signal, ac.signal);
1883
+ const eventSourceStream = sseStreamConsumer({
1884
+ url: async () => getUrl({
1885
+ transformer,
1886
+ url: await urlWithConnectionParams(opts),
1887
+ input: inputWithTrackedEventId(input, lastEventId),
1888
+ path,
1889
+ type,
1890
+ signal: null
1891
+ }),
1892
+ init: () => resultOf(opts.eventSourceOptions, { op }),
1893
+ signal,
1894
+ deserialize: (data) => transformer.output.deserialize(data),
1895
+ EventSource: (_opts$EventSource = opts.EventSource) !== null && _opts$EventSource !== undefined ? _opts$EventSource : globalThis.EventSource
1896
+ });
1897
+ const connectionState = behaviorSubject({
1898
+ type: "state",
1899
+ state: "connecting",
1900
+ error: null
1901
+ });
1902
+ const connectionSub = connectionState.subscribe({ next(state) {
1903
+ observer.next({ result: state });
1904
+ } });
1905
+ run(async () => {
1906
+ var _iteratorAbruptCompletion = false;
1907
+ var _didIteratorError = false;
1908
+ var _iteratorError;
1909
+ try {
1910
+ for (var _iterator = (0, import_asyncIterator2.default)(eventSourceStream), _step;_iteratorAbruptCompletion = !(_step = await _iterator.next()).done; _iteratorAbruptCompletion = false) {
1911
+ const chunk = _step.value;
1912
+ switch (chunk.type) {
1913
+ case "ping":
1914
+ break;
1915
+ case "data":
1916
+ const chunkData = chunk.data;
1917
+ let result;
1918
+ if (chunkData.id) {
1919
+ lastEventId = chunkData.id;
1920
+ result = {
1921
+ id: chunkData.id,
1922
+ data: chunkData
1923
+ };
1924
+ } else
1925
+ result = { data: chunkData.data };
1926
+ observer.next({
1927
+ result,
1928
+ context: { eventSource: chunk.eventSource }
1929
+ });
1930
+ break;
1931
+ case "connected": {
1932
+ observer.next({
1933
+ result: { type: "started" },
1934
+ context: { eventSource: chunk.eventSource }
1935
+ });
1936
+ connectionState.next({
1937
+ type: "state",
1938
+ state: "pending",
1939
+ error: null
1940
+ });
1941
+ break;
1942
+ }
1943
+ case "serialized-error": {
1944
+ const error = TRPCClientError.from({ error: chunk.error });
1945
+ if (retryableRpcCodes.includes(chunk.error.code)) {
1946
+ connectionState.next({
1947
+ type: "state",
1948
+ state: "connecting",
1949
+ error
1950
+ });
1951
+ break;
1952
+ }
1953
+ throw error;
1954
+ }
1955
+ case "connecting": {
1956
+ const lastState = connectionState.get();
1957
+ const error = chunk.event && TRPCClientError.from(chunk.event);
1958
+ if (!error && lastState.state === "connecting")
1959
+ break;
1960
+ connectionState.next({
1961
+ type: "state",
1962
+ state: "connecting",
1963
+ error
1964
+ });
1965
+ break;
1966
+ }
1967
+ case "timeout":
1968
+ connectionState.next({
1969
+ type: "state",
1970
+ state: "connecting",
1971
+ error: new TRPCClientError(`Timeout of ${chunk.ms}ms reached while waiting for a response`)
1972
+ });
1973
+ }
1974
+ }
1975
+ } catch (err) {
1976
+ _didIteratorError = true;
1977
+ _iteratorError = err;
1978
+ } finally {
1979
+ try {
1980
+ if (_iteratorAbruptCompletion && _iterator.return != null)
1981
+ await _iterator.return();
1982
+ } finally {
1983
+ if (_didIteratorError)
1984
+ throw _iteratorError;
1985
+ }
1986
+ }
1987
+ observer.next({ result: { type: "stopped" } });
1988
+ connectionState.next({
1989
+ type: "state",
1990
+ state: "idle",
1991
+ error: null
1992
+ });
1993
+ observer.complete();
1994
+ }).catch((error) => {
1995
+ observer.error(TRPCClientError.from(error));
1996
+ });
1997
+ return () => {
1998
+ observer.complete();
1999
+ ac.abort();
2000
+ connectionSub.unsubscribe();
2001
+ };
2002
+ });
2003
+ };
2004
+ };
2005
+ }
2006
+ var import_objectSpread2$13 = __toESM(require_objectSpread2(), 1);
2007
+ var require_usingCtx2 = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/usingCtx.js"(exports, module) {
2008
+ function _usingCtx() {
2009
+ var r = typeof SuppressedError == "function" ? SuppressedError : function(r$1, e$1) {
2010
+ var n$1 = Error();
2011
+ return n$1.name = "SuppressedError", n$1.error = r$1, n$1.suppressed = e$1, n$1;
2012
+ }, e = {}, n = [];
2013
+ function using(r$1, e$1) {
2014
+ if (e$1 != null) {
2015
+ if (Object(e$1) !== e$1)
2016
+ throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");
2017
+ if (r$1)
2018
+ var o = e$1[Symbol.asyncDispose || Symbol["for"]("Symbol.asyncDispose")];
2019
+ if (o === undefined && (o = e$1[Symbol.dispose || Symbol["for"]("Symbol.dispose")], r$1))
2020
+ var t = o;
2021
+ if (typeof o != "function")
2022
+ throw new TypeError("Object is not disposable.");
2023
+ t && (o = function o$1() {
2024
+ try {
2025
+ t.call(e$1);
2026
+ } catch (r$2) {
2027
+ return Promise.reject(r$2);
2028
+ }
2029
+ }), n.push({
2030
+ v: e$1,
2031
+ d: o,
2032
+ a: r$1
2033
+ });
2034
+ } else
2035
+ r$1 && n.push({
2036
+ d: e$1,
2037
+ a: r$1
2038
+ });
2039
+ return e$1;
2040
+ }
2041
+ return {
2042
+ e,
2043
+ u: using.bind(null, false),
2044
+ a: using.bind(null, true),
2045
+ d: function d() {
2046
+ var o, t = this.e, s = 0;
2047
+ function next() {
2048
+ for (;o = n.pop(); )
2049
+ try {
2050
+ if (!o.a && s === 1)
2051
+ return s = 0, n.push(o), Promise.resolve().then(next);
2052
+ if (o.d) {
2053
+ var r$1 = o.d.call(o.v);
2054
+ if (o.a)
2055
+ return s |= 2, Promise.resolve(r$1).then(next, err);
2056
+ } else
2057
+ s |= 1;
2058
+ } catch (r$2) {
2059
+ return err(r$2);
2060
+ }
2061
+ if (s === 1)
2062
+ return t !== e ? Promise.reject(t) : Promise.resolve();
2063
+ if (t !== e)
2064
+ throw t;
2065
+ }
2066
+ function err(n$1) {
2067
+ return t = t !== e ? new r(n$1, t) : n$1, next();
2068
+ }
2069
+ return next();
2070
+ }
2071
+ };
2072
+ }
2073
+ module.exports = _usingCtx, module.exports.__esModule = true, module.exports["default"] = module.exports;
2074
+ } });
2075
+ var require_OverloadYield2 = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/OverloadYield.js"(exports, module) {
2076
+ function _OverloadYield(e, d) {
2077
+ this.v = e, this.k = d;
2078
+ }
2079
+ module.exports = _OverloadYield, module.exports.__esModule = true, module.exports["default"] = module.exports;
2080
+ } });
2081
+ var require_awaitAsyncGenerator2 = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/awaitAsyncGenerator.js"(exports, module) {
2082
+ var OverloadYield$1 = require_OverloadYield2();
2083
+ function _awaitAsyncGenerator$1(e) {
2084
+ return new OverloadYield$1(e, 0);
2085
+ }
2086
+ module.exports = _awaitAsyncGenerator$1, module.exports.__esModule = true, module.exports["default"] = module.exports;
2087
+ } });
2088
+ var require_wrapAsyncGenerator2 = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/wrapAsyncGenerator.js"(exports, module) {
2089
+ var OverloadYield = require_OverloadYield2();
2090
+ function _wrapAsyncGenerator$1(e) {
2091
+ return function() {
2092
+ return new AsyncGenerator(e.apply(this, arguments));
2093
+ };
2094
+ }
2095
+ function AsyncGenerator(e) {
2096
+ var r, t;
2097
+ function resume(r$1, t$1) {
2098
+ try {
2099
+ var n = e[r$1](t$1), o = n.value, u = o instanceof OverloadYield;
2100
+ Promise.resolve(u ? o.v : o).then(function(t$2) {
2101
+ if (u) {
2102
+ var i = r$1 === "return" ? "return" : "next";
2103
+ if (!o.k || t$2.done)
2104
+ return resume(i, t$2);
2105
+ t$2 = e[i](t$2).value;
2106
+ }
2107
+ settle(n.done ? "return" : "normal", t$2);
2108
+ }, function(e$1) {
2109
+ resume("throw", e$1);
2110
+ });
2111
+ } catch (e$1) {
2112
+ settle("throw", e$1);
2113
+ }
2114
+ }
2115
+ function settle(e$1, n) {
2116
+ switch (e$1) {
2117
+ case "return":
2118
+ r.resolve({
2119
+ value: n,
2120
+ done: true
2121
+ });
2122
+ break;
2123
+ case "throw":
2124
+ r.reject(n);
2125
+ break;
2126
+ default:
2127
+ r.resolve({
2128
+ value: n,
2129
+ done: false
2130
+ });
2131
+ }
2132
+ (r = r.next) ? resume(r.key, r.arg) : t = null;
2133
+ }
2134
+ this._invoke = function(e$1, n) {
2135
+ return new Promise(function(o, u) {
2136
+ var i = {
2137
+ key: e$1,
2138
+ arg: n,
2139
+ resolve: o,
2140
+ reject: u,
2141
+ next: null
2142
+ };
2143
+ t ? t = t.next = i : (r = t = i, resume(e$1, n));
2144
+ });
2145
+ }, typeof e["return"] != "function" && (this["return"] = undefined);
2146
+ }
2147
+ AsyncGenerator.prototype[typeof Symbol == "function" && Symbol.asyncIterator || "@@asyncIterator"] = function() {
2148
+ return this;
2149
+ }, AsyncGenerator.prototype.next = function(e) {
2150
+ return this._invoke("next", e);
2151
+ }, AsyncGenerator.prototype["throw"] = function(e) {
2152
+ return this._invoke("throw", e);
2153
+ }, AsyncGenerator.prototype["return"] = function(e) {
2154
+ return this._invoke("return", e);
2155
+ };
2156
+ module.exports = _wrapAsyncGenerator$1, module.exports.__esModule = true, module.exports["default"] = module.exports;
2157
+ } });
2158
+ var import_usingCtx2 = __toESM(require_usingCtx2(), 1);
2159
+ var import_awaitAsyncGenerator2 = __toESM(require_awaitAsyncGenerator2(), 1);
2160
+ var import_wrapAsyncGenerator2 = __toESM(require_wrapAsyncGenerator2(), 1);
2161
+ var import_objectSpread210 = __toESM(require_objectSpread2(), 1);
2162
+ // ../../node_modules/.bun/eventsource-parser@4.1.0/node_modules/eventsource-parser/dist/errors.js
2163
+ class ParseError extends Error {
2164
+ constructor(message, options) {
2165
+ super(message);
2166
+ this.name = "ParseError";
2167
+ this.type = options.type;
2168
+ this.field = options.field;
2169
+ this.value = options.value;
2170
+ this.line = options.line;
2171
+ }
2172
+ }
2173
+
2174
+ // ../../node_modules/.bun/eventsource-parser@4.1.0/node_modules/eventsource-parser/dist/parse.js
2175
+ var LF = 10;
2176
+ var CR = 13;
2177
+ var SPACE = 32;
2178
+ var MAX_FIELD_PREFIX_LENGTH = 6;
2179
+ function createParser(config) {
2180
+ if (typeof config === "function") {
2181
+ throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");
2182
+ }
2183
+ const { maxBufferSize, onComment, onError, onEvent, onId, onRetry } = config;
2184
+ const pendingFragments = [];
2185
+ let pendingFragmentsLength = 0;
2186
+ let isFirstChunk = true;
2187
+ let id;
2188
+ let data = "";
2189
+ let dataLines = 0;
2190
+ let eventType;
2191
+ let terminated = false;
2192
+ let skippingLine = false;
2193
+ let skipNextLineFeed = false;
2194
+ function feed(chunk) {
2195
+ if (terminated) {
2196
+ throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");
2197
+ }
2198
+ if (isFirstChunk) {
2199
+ isFirstChunk = false;
2200
+ if (chunk.charCodeAt(0) === 65279) {
2201
+ chunk = chunk.slice(1);
2202
+ } else if (chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191) {
2203
+ chunk = chunk.slice(3);
2204
+ }
2205
+ }
2206
+ if (skippingLine || skipNextLineFeed) {
2207
+ chunk = resumeAfterSkip(chunk);
2208
+ if (!chunk) {
2209
+ return;
2210
+ }
2211
+ }
2212
+ if (!pendingFragments.length) {
2213
+ const trailing = processLines(chunk);
2214
+ if (trailing !== "") {
2215
+ storeTrailing(trailing);
2216
+ }
2217
+ checkBufferSize();
2218
+ return;
2219
+ }
2220
+ if (chunk.indexOf(`
2221
+ `) === -1 && chunk.indexOf("\r") === -1) {
2222
+ if (pendingFragmentsLength < MAX_FIELD_PREFIX_LENGTH) {
2223
+ const head = pendingFragments.join("") + chunk.slice(0, MAX_FIELD_PREFIX_LENGTH - pendingFragmentsLength);
2224
+ if (!shouldBufferTrailing(head)) {
2225
+ pendingFragments.length = 0;
2226
+ pendingFragmentsLength = 0;
2227
+ skippingLine = true;
2228
+ return;
2229
+ }
2230
+ }
2231
+ pendingFragments.push(chunk);
2232
+ pendingFragmentsLength += chunk.length;
2233
+ checkBufferSize();
2234
+ return;
2235
+ }
2236
+ pendingFragments.push(chunk);
2237
+ const input = pendingFragments.join("");
2238
+ pendingFragments.length = 0;
2239
+ pendingFragmentsLength = 0;
2240
+ storeTrailing(processLines(input));
2241
+ checkBufferSize();
2242
+ }
2243
+ function resumeAfterSkip(chunk) {
2244
+ if (chunk.length === 0) {
2245
+ return chunk;
2246
+ }
2247
+ if (skipNextLineFeed) {
2248
+ skipNextLineFeed = false;
2249
+ return chunk.charCodeAt(0) === LF ? chunk.slice(1) : chunk;
2250
+ }
2251
+ const crIndex = chunk.indexOf("\r");
2252
+ const lfIndex = chunk.indexOf(`
2253
+ `);
2254
+ const lineEnd = crIndex === -1 ? lfIndex : lfIndex === -1 ? crIndex : crIndex < lfIndex ? crIndex : lfIndex;
2255
+ if (lineEnd === -1) {
2256
+ return "";
2257
+ }
2258
+ if (lineEnd === chunk.length - 1 && chunk.charCodeAt(lineEnd) === CR) {
2259
+ skippingLine = false;
2260
+ skipNextLineFeed = true;
2261
+ return "";
2262
+ }
2263
+ skippingLine = false;
2264
+ return chunk.slice(lineEnd + (chunk.charCodeAt(lineEnd) === CR && chunk.charCodeAt(lineEnd + 1) === LF ? 2 : 1));
2265
+ }
2266
+ function storeTrailing(trailing) {
2267
+ if (!trailing)
2268
+ return;
2269
+ if (trailing.charCodeAt(trailing.length - 1) === CR) {
2270
+ parseLine(trailing, 0, trailing.length - 1);
2271
+ skipNextLineFeed = true;
2272
+ return;
2273
+ }
2274
+ if (shouldBufferTrailing(trailing)) {
2275
+ pendingFragments.push(trailing);
2276
+ pendingFragmentsLength = trailing.length;
2277
+ return;
2278
+ }
2279
+ skippingLine = true;
2280
+ }
2281
+ function shouldBufferTrailing(trailing) {
2282
+ const firstCharCode = trailing.charCodeAt(0);
2283
+ return firstCharCode === 58 && !!onComment || firstCharCode === 100 && isPotentialField(trailing, "data") || firstCharCode === 101 && isPotentialField(trailing, "event") || firstCharCode === 105 && isPotentialField(trailing, "id") || firstCharCode === 114 && isPotentialField(trailing, "retry");
2284
+ }
2285
+ function checkBufferSize() {
2286
+ if (maxBufferSize === undefined)
2287
+ return;
2288
+ if (pendingFragmentsLength + data.length <= maxBufferSize)
2289
+ return;
2290
+ terminated = true;
2291
+ pendingFragments.length = 0;
2292
+ pendingFragmentsLength = 0;
2293
+ id = undefined;
2294
+ data = "";
2295
+ dataLines = 0;
2296
+ eventType = undefined;
2297
+ skippingLine = false;
2298
+ skipNextLineFeed = false;
2299
+ onError === null || onError === undefined || onError(new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, {
2300
+ type: "max-buffer-size-exceeded"
2301
+ }));
2302
+ }
2303
+ function processLines(chunk) {
2304
+ let searchIndex = 0;
2305
+ if (chunk.indexOf("\r") === -1) {
2306
+ let lfIndex = chunk.indexOf(`
2307
+ `, searchIndex);
2308
+ while (lfIndex !== -1) {
2309
+ if (searchIndex === lfIndex) {
2310
+ if (id !== undefined) {
2311
+ onId === null || onId === undefined || onId(id);
2312
+ }
2313
+ if (dataLines > 0) {
2314
+ onEvent === null || onEvent === undefined || onEvent({ id, event: eventType, data });
2315
+ }
2316
+ id = undefined;
2317
+ data = "";
2318
+ dataLines = 0;
2319
+ eventType = undefined;
2320
+ searchIndex = lfIndex + 1;
2321
+ lfIndex = chunk.indexOf(`
2322
+ `, searchIndex);
2323
+ continue;
2324
+ }
2325
+ const firstCharCode = chunk.charCodeAt(searchIndex);
2326
+ if (isDataPrefix(chunk, searchIndex, firstCharCode)) {
2327
+ const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5;
2328
+ const value = chunk.slice(valueStart, lfIndex);
2329
+ if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {
2330
+ if (id !== undefined) {
2331
+ onId === null || onId === undefined || onId(id);
2332
+ }
2333
+ onEvent === null || onEvent === undefined || onEvent({ id, event: eventType, data: value });
2334
+ id = undefined;
2335
+ data = "";
2336
+ eventType = undefined;
2337
+ searchIndex = lfIndex + 2;
2338
+ lfIndex = chunk.indexOf(`
2339
+ `, searchIndex);
2340
+ continue;
2341
+ }
2342
+ data = dataLines === 0 ? value : `${data}
2343
+ ${value}`;
2344
+ dataLines++;
2345
+ } else if (isEventPrefix(chunk, searchIndex, firstCharCode)) {
2346
+ eventType = chunk.slice(chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6, lfIndex) || undefined;
2347
+ } else {
2348
+ parseLine(chunk, searchIndex, lfIndex);
2349
+ }
2350
+ searchIndex = lfIndex + 1;
2351
+ lfIndex = chunk.indexOf(`
2352
+ `, searchIndex);
2353
+ }
2354
+ return chunk.slice(searchIndex);
2355
+ }
2356
+ while (searchIndex < chunk.length) {
2357
+ const crIndex = chunk.indexOf("\r", searchIndex);
2358
+ const lfIndex = chunk.indexOf(`
2359
+ `, searchIndex);
2360
+ let lineEnd = -1;
2361
+ if (crIndex !== -1 && lfIndex !== -1) {
2362
+ lineEnd = crIndex < lfIndex ? crIndex : lfIndex;
2363
+ } else if (crIndex !== -1) {
2364
+ if (crIndex === chunk.length - 1) {
2365
+ lineEnd = -1;
2366
+ } else {
2367
+ lineEnd = crIndex;
2368
+ }
2369
+ } else if (lfIndex !== -1) {
2370
+ lineEnd = lfIndex;
2371
+ }
2372
+ if (lineEnd === -1) {
2373
+ break;
2374
+ }
2375
+ parseLine(chunk, searchIndex, lineEnd);
2376
+ searchIndex = lineEnd + 1;
2377
+ if (chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF) {
2378
+ searchIndex++;
2379
+ }
2380
+ }
2381
+ return chunk.slice(searchIndex);
2382
+ }
2383
+ function parseLine(chunk, start, end) {
2384
+ if (start === end) {
2385
+ dispatchEvent();
2386
+ return;
2387
+ }
2388
+ const firstCharCode = chunk.charCodeAt(start);
2389
+ if (isDataPrefix(chunk, start, firstCharCode)) {
2390
+ const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5;
2391
+ const value = chunk.slice(valueStart, end);
2392
+ data = dataLines === 0 ? value : `${data}
2393
+ ${value}`;
2394
+ dataLines++;
2395
+ return;
2396
+ }
2397
+ if (isEventPrefix(chunk, start, firstCharCode)) {
2398
+ eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || undefined;
2399
+ return;
2400
+ }
2401
+ if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {
2402
+ const value = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);
2403
+ if (!value.includes("\x00"))
2404
+ id = value;
2405
+ return;
2406
+ }
2407
+ if (firstCharCode === 58) {
2408
+ if (onComment) {
2409
+ const line = chunk.slice(start, end);
2410
+ onComment(line.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));
2411
+ }
2412
+ return;
2413
+ }
2414
+ const line = chunk.slice(start, end);
2415
+ const fieldSeparatorIndex = line.indexOf(":");
2416
+ if (fieldSeparatorIndex === -1) {
2417
+ processField(line, "", line);
2418
+ return;
2419
+ }
2420
+ const field = line.slice(0, fieldSeparatorIndex);
2421
+ const offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1;
2422
+ const value = line.slice(fieldSeparatorIndex + offset);
2423
+ processField(field, value, line);
2424
+ }
2425
+ function processField(field, value, line) {
2426
+ switch (field) {
2427
+ case "event":
2428
+ eventType = value || undefined;
2429
+ break;
2430
+ case "data":
2431
+ data = dataLines === 0 ? value : `${data}
2432
+ ${value}`;
2433
+ dataLines++;
2434
+ break;
2435
+ case "id":
2436
+ if (!value.includes("\x00"))
2437
+ id = value;
2438
+ break;
2439
+ case "retry":
2440
+ if (/^\d+$/.test(value)) {
2441
+ onRetry === null || onRetry === undefined || onRetry(parseInt(value, 10));
2442
+ } else {
2443
+ onError === null || onError === undefined || onError(new ParseError(`Invalid \`retry\` value: "${value}"`, {
2444
+ type: "invalid-retry",
2445
+ value,
2446
+ line
2447
+ }));
2448
+ }
2449
+ break;
2450
+ default:
2451
+ onError === null || onError === undefined || onError(new ParseError(`Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`, { type: "unknown-field", field, value, line }));
2452
+ break;
2453
+ }
2454
+ }
2455
+ function dispatchEvent() {
2456
+ if (id !== undefined) {
2457
+ onId === null || onId === undefined || onId(id);
2458
+ }
2459
+ if (dataLines > 0) {
2460
+ onEvent === null || onEvent === undefined || onEvent({
2461
+ id,
2462
+ event: eventType,
2463
+ data
2464
+ });
2465
+ }
2466
+ id = undefined;
2467
+ data = "";
2468
+ dataLines = 0;
2469
+ eventType = undefined;
2470
+ }
2471
+ function reset(options = {}) {
2472
+ if (options.consume && pendingFragments.length > 0) {
2473
+ const incompleteLine = pendingFragments.join("");
2474
+ parseLine(incompleteLine, 0, incompleteLine.length);
2475
+ }
2476
+ isFirstChunk = true;
2477
+ id = undefined;
2478
+ data = "";
2479
+ dataLines = 0;
2480
+ eventType = undefined;
2481
+ pendingFragments.length = 0;
2482
+ pendingFragmentsLength = 0;
2483
+ terminated = false;
2484
+ skippingLine = false;
2485
+ skipNextLineFeed = false;
2486
+ }
2487
+ return { feed, reset };
2488
+ }
2489
+ function isDataPrefix(chunk, i, firstCharCode) {
2490
+ return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58;
2491
+ }
2492
+ function isEventPrefix(chunk, i, firstCharCode) {
2493
+ return firstCharCode === 101 && chunk.charCodeAt(i + 1) === 118 && chunk.charCodeAt(i + 2) === 101 && chunk.charCodeAt(i + 3) === 110 && chunk.charCodeAt(i + 4) === 116 && chunk.charCodeAt(i + 5) === 58;
2494
+ }
2495
+ function isPotentialField(line, field) {
2496
+ let i = 1;
2497
+ while (i < line.length && i < field.length) {
2498
+ if (line.charCodeAt(i) !== field.charCodeAt(i)) {
2499
+ return false;
2500
+ }
2501
+ i++;
2502
+ }
2503
+ return line.length <= field.length || line.charCodeAt(field.length) === 58;
2504
+ }
2505
+ // ../../node_modules/.bun/eventsource@5.1.1/node_modules/eventsource/dist/errors.js
2506
+ class ErrorEvent extends Event {
2507
+ code;
2508
+ message;
2509
+ constructor(type, errorEventInitDict) {
2510
+ super(type);
2511
+ this.code = errorEventInitDict?.code ?? undefined;
2512
+ this.message = errorEventInitDict?.message ?? undefined;
2513
+ }
2514
+ [Symbol.for("nodejs.util.inspect.custom")](_depth, options, inspect) {
2515
+ return inspect(inspectableError(this), options);
2516
+ }
2517
+ [Symbol.for("Deno.customInspect")](inspect, options) {
2518
+ return inspect(inspectableError(this), options);
2519
+ }
2520
+ }
2521
+ function syntaxError(message) {
2522
+ const DomException = globalThis.DOMException;
2523
+ if (typeof DomException === "function") {
2524
+ return new DomException(message, "SyntaxError");
2525
+ }
2526
+ return new SyntaxError(message);
2527
+ }
2528
+ function flattenError(err) {
2529
+ if (!(err instanceof Error)) {
2530
+ return `${err}`;
2531
+ }
2532
+ if ("errors" in err && Array.isArray(err.errors)) {
2533
+ return err.errors.map(flattenError).join(", ");
2534
+ }
2535
+ if ("cause" in err && err.cause instanceof Error) {
2536
+ return `${err}: ${flattenError(err.cause)}`;
2537
+ }
2538
+ return err.message;
2539
+ }
2540
+ function inspectableError(err) {
2541
+ return {
2542
+ type: err.type,
2543
+ message: err.message,
2544
+ code: err.code,
2545
+ defaultPrevented: err.defaultPrevented,
2546
+ cancelable: err.cancelable,
2547
+ timeStamp: err.timeStamp
2548
+ };
2549
+ }
2550
+
2551
+ // ../../node_modules/.bun/eventsource@5.1.1/node_modules/eventsource/dist/EventSource.js
2552
+ var DEFAULT_MAX_BUFFER_SIZE = 100 * 1024 * 1024;
2553
+
2554
+ class EventSourceImpl extends EventTarget {
2555
+ static CONNECTING = 0;
2556
+ static OPEN = 1;
2557
+ static CLOSED = 2;
2558
+ CONNECTING = 0;
2559
+ OPEN = 1;
2560
+ CLOSED = 2;
2561
+ get readyState() {
2562
+ return this.#readyState;
2563
+ }
2564
+ get url() {
2565
+ return this.#url.href;
2566
+ }
2567
+ get withCredentials() {
2568
+ return this.#withCredentials;
2569
+ }
2570
+ get onerror() {
2571
+ return this.#onError;
2572
+ }
2573
+ set onerror(value) {
2574
+ if (this.#onError) {
2575
+ this.removeEventListener("error", this.#onError);
2576
+ }
2577
+ this.#onError = value;
2578
+ if (value) {
2579
+ this.addEventListener("error", value);
2580
+ }
2581
+ }
2582
+ get onmessage() {
2583
+ return this.#onMessage;
2584
+ }
2585
+ set onmessage(value) {
2586
+ if (this.#onMessage) {
2587
+ this.removeEventListener("message", this.#onMessage);
2588
+ }
2589
+ this.#onMessage = value;
2590
+ if (value) {
2591
+ this.addEventListener("message", value);
2592
+ }
2593
+ }
2594
+ get onopen() {
2595
+ return this.#onOpen;
2596
+ }
2597
+ set onopen(value) {
2598
+ if (this.#onOpen) {
2599
+ this.removeEventListener("open", this.#onOpen);
2600
+ }
2601
+ this.#onOpen = value;
2602
+ if (value) {
2603
+ this.addEventListener("open", value);
2604
+ }
2605
+ }
2606
+ addEventListener(type, listener, options) {
2607
+ const listen = listener;
2608
+ super.addEventListener(type, listen, options);
2609
+ }
2610
+ removeEventListener(type, listener, options) {
2611
+ const listen = listener;
2612
+ super.removeEventListener(type, listen, options);
2613
+ }
2614
+ constructor(url, eventSourceInitDict) {
2615
+ super();
2616
+ try {
2617
+ if (url instanceof URL) {
2618
+ this.#url = url;
2619
+ } else if (typeof url === "string") {
2620
+ this.#url = new URL(url, getBaseURL());
2621
+ } else {
2622
+ throw new Error("Invalid URL");
2623
+ }
2624
+ } catch {
2625
+ throw syntaxError("An invalid or illegal string was specified");
2626
+ }
2627
+ this.#parser = createParser({
2628
+ maxBufferSize: eventSourceInitDict?.maxBufferSize ?? DEFAULT_MAX_BUFFER_SIZE,
2629
+ onEvent: this.#onEvent,
2630
+ onError: this.#onParseError,
2631
+ onId: this.#onIdChange,
2632
+ onRetry: this.#onRetryChange
2633
+ });
2634
+ this.#readyState = this.CONNECTING;
2635
+ this.#reconnectInterval = 3000;
2636
+ this.#fetch = eventSourceInitDict?.fetch ?? globalThis.fetch;
2637
+ this.#withCredentials = eventSourceInitDict?.withCredentials ?? false;
2638
+ this.#connect();
2639
+ }
2640
+ close() {
2641
+ if (this.#reconnectTimer)
2642
+ clearTimeout(this.#reconnectTimer);
2643
+ if (this.#readyState === this.CLOSED)
2644
+ return;
2645
+ if (this.#controller)
2646
+ this.#controller.abort();
2647
+ this.#readyState = this.CLOSED;
2648
+ this.#controller = undefined;
2649
+ }
2650
+ #readyState;
2651
+ #url;
2652
+ #redirectUrl;
2653
+ #withCredentials;
2654
+ #fetch;
2655
+ #reconnectInterval;
2656
+ #reconnectTimer;
2657
+ #lastEventId = null;
2658
+ #controller;
2659
+ #parser;
2660
+ #onError = null;
2661
+ #onMessage = null;
2662
+ #onOpen = null;
2663
+ #connect() {
2664
+ this.#readyState = this.CONNECTING;
2665
+ this.#controller = new AbortController;
2666
+ const fetch2 = this.#fetch;
2667
+ fetch2(this.#url, this.#getRequestOptions()).then(this.#onFetchResponse).catch(this.#onFetchError);
2668
+ }
2669
+ #onFetchResponse = async (response) => {
2670
+ this.#parser.reset();
2671
+ const { body, redirected, status, headers } = response;
2672
+ if (status === 204) {
2673
+ this.#failConnection("Server sent HTTP 204, not reconnecting", 204);
2674
+ this.close();
2675
+ return;
2676
+ }
2677
+ if (redirected) {
2678
+ this.#redirectUrl = new URL(response.url);
2679
+ } else {
2680
+ this.#redirectUrl = undefined;
2681
+ }
2682
+ if (status !== 200) {
2683
+ this.#failConnection(`Non-200 status code (${status})`, status);
2684
+ return;
2685
+ }
2686
+ const contentType = headers.get("content-type") || "";
2687
+ if (!contentType.startsWith("text/event-stream")) {
2688
+ this.#failConnection('Invalid content type, expected "text/event-stream"', status);
2689
+ return;
2690
+ }
2691
+ if (this.#readyState === this.CLOSED) {
2692
+ return;
2693
+ }
2694
+ this.#readyState = this.OPEN;
2695
+ const openEvent = new Event("open");
2696
+ this.dispatchEvent(openEvent);
2697
+ if (typeof body !== "object" || !body || !("getReader" in body)) {
2698
+ this.#failConnection("Invalid response body, expected a web ReadableStream", status);
2699
+ this.close();
2700
+ return;
2701
+ }
2702
+ const decoder = new TextDecoder;
2703
+ const reader = body.getReader();
2704
+ let open = true;
2705
+ do {
2706
+ const { done, value } = await reader.read();
2707
+ if (this.#readyState === this.CLOSED) {
2708
+ open = false;
2709
+ break;
2710
+ }
2711
+ if (value) {
2712
+ this.#parser.feed(decoder.decode(value, { stream: !done }));
2713
+ }
2714
+ if (!done) {
2715
+ continue;
2716
+ }
2717
+ open = false;
2718
+ this.#parser.reset();
2719
+ this.#scheduleReconnect();
2720
+ } while (open);
2721
+ };
2722
+ #onFetchError = (err) => {
2723
+ this.#controller = undefined;
2724
+ if (err.name === "AbortError" || err.type === "aborted") {
2725
+ return;
2726
+ }
2727
+ this.#scheduleReconnect(flattenError(err));
2728
+ };
2729
+ #getRequestOptions() {
2730
+ const lastEvent = this.#lastEventId ? { "Last-Event-ID": this.#lastEventId } : undefined;
2731
+ const init = {
2732
+ mode: "cors",
2733
+ redirect: "follow",
2734
+ headers: { Accept: "text/event-stream", ...lastEvent },
2735
+ cache: "no-store",
2736
+ signal: this.#controller?.signal
2737
+ };
2738
+ if ("window" in globalThis) {
2739
+ init.credentials = this.withCredentials ? "include" : "same-origin";
2740
+ }
2741
+ return init;
2742
+ }
2743
+ #onIdChange = (value) => {
2744
+ this.#lastEventId = value;
2745
+ };
2746
+ #onEvent = (event) => {
2747
+ const origin = this.#redirectUrl ? this.#redirectUrl.origin : this.#url.origin;
2748
+ const lastEventId = this.#lastEventId ?? "";
2749
+ const messageEvent = new MessageEvent(event.event || "message", {
2750
+ data: event.data,
2751
+ origin,
2752
+ lastEventId
2753
+ });
2754
+ if (messageEvent.origin !== origin) {
2755
+ defineEventProperty(messageEvent, "origin", origin);
2756
+ }
2757
+ if (messageEvent.lastEventId !== lastEventId) {
2758
+ defineEventProperty(messageEvent, "lastEventId", lastEventId);
2759
+ }
2760
+ this.dispatchEvent(messageEvent);
2761
+ };
2762
+ #onRetryChange = (value) => {
2763
+ this.#reconnectInterval = value;
2764
+ };
2765
+ #onParseError = (error) => {
2766
+ if (error.type !== "max-buffer-size-exceeded") {
2767
+ return;
2768
+ }
2769
+ this.close();
2770
+ this.#failConnection(error.message);
2771
+ };
2772
+ #failConnection(message, code) {
2773
+ if (this.#readyState !== this.CLOSED) {
2774
+ this.#readyState = this.CLOSED;
2775
+ }
2776
+ const errorEvent = new ErrorEvent("error", { code, message });
2777
+ this.dispatchEvent(errorEvent);
2778
+ }
2779
+ #scheduleReconnect(message, code) {
2780
+ if (this.#readyState === this.CLOSED) {
2781
+ return;
2782
+ }
2783
+ this.#readyState = this.CONNECTING;
2784
+ const errorEvent = new ErrorEvent("error", { code, message });
2785
+ this.dispatchEvent(errorEvent);
2786
+ const timer = setTimeout(this.#reconnect, this.#reconnectInterval);
2787
+ if (typeof timer === "object" && timer !== null && "unref" in timer) {
2788
+ timer.unref();
2789
+ }
2790
+ this.#reconnectTimer = timer;
2791
+ }
2792
+ #reconnect = () => {
2793
+ this.#reconnectTimer = undefined;
2794
+ if (this.#readyState !== this.CONNECTING) {
2795
+ return;
2796
+ }
2797
+ this.#connect();
2798
+ };
2799
+ }
2800
+ Object.defineProperty(EventSourceImpl, "name", { value: "EventSource" });
2801
+ Object.defineProperty(EventSourceImpl, Symbol.for("eventsource.supports-fetch-override"), {
2802
+ value: true,
2803
+ writable: false,
2804
+ configurable: false,
2805
+ enumerable: false
2806
+ });
2807
+ var EventSource = EventSourceImpl;
2808
+ function getBaseURL() {
2809
+ const doc = "document" in globalThis ? globalThis.document : undefined;
2810
+ return doc && typeof doc === "object" && "baseURI" in doc && typeof doc.baseURI === "string" ? doc.baseURI : undefined;
2811
+ }
2812
+ function defineEventProperty(event, property, value) {
2813
+ Object.defineProperty(event, property, {
2814
+ value,
2815
+ enumerable: true,
2816
+ configurable: true
2817
+ });
2818
+ }
2819
+ // ../sdk/dist/index.js
2820
+ import { readFileSync } from "fs";
2821
+ import { homedir } from "os";
2822
+ import { dirname, join } from "path";
2823
+ var DEFAULT_GITTERM_SERVER_URL = "https://api.gitterm.dev";
2824
+ function getConfigPath(configPath) {
2825
+ return configPath ?? join(homedir(), ".config", "gitterm", "cli.json");
2826
+ }
2827
+ function parseConfig(text) {
2828
+ const parsed = JSON.parse(text);
2829
+ if (!parsed.token || !parsed.serverUrl)
2830
+ return null;
2831
+ return {
2832
+ serverUrl: parsed.serverUrl,
2833
+ token: parsed.token,
2834
+ createdAt: parsed.createdAt ?? Date.now()
2835
+ };
2836
+ }
2837
+ function loadConfigSync(configPath) {
2838
+ try {
2839
+ const text = readFileSync(getConfigPath(configPath), "utf-8");
2840
+ return parseConfig(text);
2841
+ } catch {
2842
+ return null;
2843
+ }
2844
+ }
2845
+ var WORKSPACE_LIFECYCLE_ERROR_CODES = [
2846
+ "WORKSPACE_NOT_RUNNING",
2847
+ "WORKSPACE_TERMINATED",
2848
+ "WORKSPACE_NON_RECOVERABLE",
2849
+ "WORKSPACE_START_TIMEOUT",
2850
+ "WORKSPACE_RESTART_FAILED"
2851
+ ];
2852
+
2853
+ class GittermError extends Error {
2854
+ code;
2855
+ status;
2856
+ constructor(code, message, options = {}) {
2857
+ super(message, "cause" in options ? { cause: options.cause } : undefined);
2858
+ this.name = "GittermError";
2859
+ this.code = code;
2860
+ this.status = options.status;
2861
+ }
2862
+ }
2863
+
2864
+ class WorkspaceLifecycleError extends GittermError {
2865
+ constructor(code, message, options = {}) {
2866
+ super(code, message, options);
2867
+ this.name = "WorkspaceLifecycleError";
2868
+ }
2869
+ }
2870
+
2871
+ class AgentRunError extends GittermError {
2872
+ run;
2873
+ constructor(run, code) {
2874
+ super(code, run.error ?? (code === "INPUT_REQUIRED" ? "The agent needs input; supply a handler or use runs.respond()" : `Agent run ${run.status}`));
2875
+ this.run = run;
2876
+ this.name = "AgentRunError";
2877
+ }
2878
+ }
2879
+ var LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
2880
+ function normalizeServerUrl(value) {
2881
+ let url;
2882
+ try {
2883
+ url = new URL(value);
2884
+ } catch {
2885
+ throw new Error(`Invalid GitTerm server URL: ${value}`);
2886
+ }
2887
+ if (url.username || url.password) {
2888
+ throw new Error("GitTerm server URL must not contain credentials");
2889
+ }
2890
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && LOOPBACK_HOSTS.has(url.hostname))) {
2891
+ throw new Error("GitTerm server URL must use HTTPS (HTTP is allowed only for loopback)");
2892
+ }
2893
+ url.hash = "";
2894
+ url.search = "";
2895
+ return url.toString().replace(/\/$/, "");
2896
+ }
2897
+ function withPath(serverUrl, pathname) {
2898
+ const url = new URL(serverUrl);
2899
+ url.pathname = pathname;
2900
+ return url.toString();
2901
+ }
2902
+ function basePath(serverUrl) {
2903
+ return new URL(serverUrl).pathname.replace(/\/+$/, "");
2904
+ }
2905
+ function trpcEndpoint(serverUrl) {
2906
+ const base = basePath(serverUrl);
2907
+ return withPath(serverUrl, base.endsWith("/trpc") ? base : `${base}/trpc`);
2908
+ }
2909
+ function createNoRedirectFetch(fetchImpl = fetch) {
2910
+ return async (input, init) => {
2911
+ const response = await fetchImpl(input, { ...init, redirect: "manual" });
2912
+ if (response.status >= 300 && response.status < 400) {
2913
+ const location = response.headers.get("location");
2914
+ throw new Error(location ? `GitTerm server redirects are not allowed: ${location}` : "GitTerm server redirects are not allowed");
2915
+ }
2916
+ return response;
2917
+ };
2918
+ }
2919
+ function terminal(status) {
2920
+ return status === "completed" || status === "failed" || status === "cancelled";
2921
+ }
2922
+ function aborted(signal) {
2923
+ if (signal?.aborted)
2924
+ throw new GittermError("ABORTED", "Run observation was aborted; the agent was not cancelled");
2925
+ }
2926
+ async function abortable(operation, signal) {
2927
+ if (signal.aborted)
2928
+ operation.catch(() => {});
2929
+ aborted(signal);
2930
+ let onAbort;
2931
+ try {
2932
+ return await Promise.race([
2933
+ operation,
2934
+ new Promise((_, reject) => {
2935
+ onAbort = () => reject(new GittermError("ABORTED", "Run observation was aborted; the agent was not cancelled"));
2936
+ signal.addEventListener("abort", onAbort, { once: true });
2937
+ })
2938
+ ]);
2939
+ } finally {
2940
+ if (onAbort)
2941
+ signal.removeEventListener("abort", onAbort);
2942
+ }
2943
+ }
2944
+ async function deadline(options, operation) {
2945
+ aborted(options?.signal);
2946
+ const timeoutMs = options?.timeoutMs ?? 30 * 60000;
2947
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 0)
2948
+ throw new GittermError("BAD_REQUEST", "timeoutMs must be finite and non-negative");
2949
+ const controller = new AbortController;
2950
+ const onAbort = () => controller.abort();
2951
+ options?.signal?.addEventListener("abort", onAbort, { once: true });
2952
+ let timedOut = false;
2953
+ const timer = setTimeout(() => {
2954
+ timedOut = true;
2955
+ controller.abort();
2956
+ }, timeoutMs);
2957
+ try {
2958
+ return await operation(controller.signal);
2959
+ } catch (error) {
2960
+ if (timedOut)
2961
+ throw new GittermError("TIMEOUT", "Run observation timed out; the agent was not cancelled", {
2962
+ cause: error
2963
+ });
2964
+ aborted(options?.signal);
2965
+ throw error;
2966
+ } finally {
2967
+ clearTimeout(timer);
2968
+ options?.signal?.removeEventListener("abort", onAbort);
2969
+ controller.abort();
2970
+ }
2971
+ }
2972
+ async function* runEvents(states) {
2973
+ const seen = new Set;
2974
+ let pending = new Set;
2975
+ let status;
2976
+ for await (const run of states) {
2977
+ if (run.status !== status) {
2978
+ status = run.status;
2979
+ yield { type: "run.status", run };
2980
+ }
2981
+ const current = new Set(run.pendingInputs.map((request) => request.id));
2982
+ for (const requestId of pending) {
2983
+ if (!current.has(requestId))
2984
+ yield { type: "input.resolved", run, requestId };
2985
+ }
2986
+ pending = current;
2987
+ for (const request of run.pendingInputs) {
2988
+ if (seen.has(request.id))
2989
+ continue;
2990
+ seen.add(request.id);
2991
+ yield { type: "input.required", run, request };
2992
+ }
2993
+ if (run.status === "completed" || run.status === "failed" || run.status === "cancelled") {
2994
+ yield { type: `run.${run.status}`, run };
2995
+ return;
2996
+ }
2997
+ }
2998
+ }
2999
+ function runHelpers(operations) {
3000
+ return {
3001
+ events: (ref, options) => runEvents(operations.watch(ref, options)),
3002
+ wait: (ref, options) => deadline(options, async (signal) => {
3003
+ for await (const run of operations.watch(ref, { signal })) {
3004
+ if (terminal(run.status) || run.status === "awaiting_input" && options?.until !== "terminal")
3005
+ return run;
3006
+ }
3007
+ throw new GittermError("NETWORK", "Run stream ended before a terminal state");
3008
+ }),
3009
+ result: (ref, options) => deadline(options, async (signal) => {
3010
+ for await (const event of runEvents(operations.watch(ref, { signal }))) {
3011
+ aborted(signal);
3012
+ if (event.type === "run.completed")
3013
+ return event.run;
3014
+ if (event.type === "run.failed")
3015
+ throw new AgentRunError(event.run, "RUN_FAILED");
3016
+ if (event.type === "run.cancelled")
3017
+ throw new AgentRunError(event.run, "RUN_CANCELLED");
3018
+ if (event.type !== "input.required")
3019
+ continue;
3020
+ const { request } = event;
3021
+ let reply;
3022
+ if (request.kind === "permission") {
3023
+ if (!options?.onPermission)
3024
+ throw new AgentRunError(event.run, "INPUT_REQUIRED");
3025
+ reply = {
3026
+ type: "permission",
3027
+ response: await abortable(Promise.resolve(options.onPermission(request, { signal })), signal)
3028
+ };
3029
+ } else {
3030
+ if (!options?.onQuestion)
3031
+ throw new AgentRunError(event.run, "INPUT_REQUIRED");
3032
+ reply = {
3033
+ type: "question",
3034
+ ...await abortable(Promise.resolve(options.onQuestion(request, { signal })), signal)
3035
+ };
3036
+ }
3037
+ aborted(signal);
3038
+ try {
3039
+ await abortable(operations.respond(ref, { requestId: request.id, reply }), signal);
3040
+ } catch (error) {
3041
+ if (!(error instanceof GittermError) || error.code !== "INPUT_NOT_PENDING")
3042
+ throw error;
3043
+ }
3044
+ }
3045
+ throw new GittermError("NETWORK", "Run stream ended before a terminal state");
3046
+ })
3047
+ };
3048
+ }
3049
+ function toConnection(connection) {
3050
+ const details = connection.details;
3051
+ return {
3052
+ ...connection,
3053
+ connectedAt: toIso(connection.connectedAt),
3054
+ details: "lastCheckedAt" in details ? { ...details, lastCheckedAt: toIso(details.lastCheckedAt) } : details
3055
+ };
3056
+ }
3057
+ function envValue(name) {
3058
+ const value = typeof process !== "undefined" ? process.env[name] : undefined;
3059
+ return value && value.trim() ? value : undefined;
3060
+ }
3061
+ function resolveCredentials(options) {
3062
+ const config = !options.serverUrl || !options.token ? loadConfigSync(options.configPath) : null;
3063
+ const serverUrl = options.serverUrl ?? envValue("GITTERM_SERVER_URL") ?? config?.serverUrl ?? DEFAULT_GITTERM_SERVER_URL;
3064
+ const token = options.token ?? envValue("GITTERM_API_TOKEN") ?? config?.token;
3065
+ if (!serverUrl || !token) {
3066
+ throw new GittermError("NOT_LOGGED_IN", "Not logged in. Run: gitterm login");
3067
+ }
3068
+ return { serverUrl: normalizeServerUrl(serverUrl), token };
3069
+ }
3070
+ function toIso(value) {
3071
+ if (!value)
3072
+ return null;
3073
+ return value instanceof Date ? value.toISOString() : value;
3074
+ }
3075
+ function normalizeBaseCommit(value) {
3076
+ if (value == null)
3077
+ return null;
3078
+ const trimmed = value.trim();
3079
+ if (!trimmed)
3080
+ return null;
3081
+ return /^[0-9a-f]{40}([0-9a-f]{24})?$/i.test(trimmed) ? trimmed.toLowerCase() : trimmed;
3082
+ }
3083
+ function workspaceIdOf(ref) {
3084
+ return typeof ref === "string" ? ref : ref.id;
3085
+ }
3086
+ function runTargetOf(ref) {
3087
+ return { workspaceId: ref.workspaceId, runId: ref.id };
3088
+ }
3089
+ function throwIfAborted2(signal, what) {
3090
+ if (signal?.aborted)
3091
+ throw new GittermError("ABORTED", `Aborted while ${what}`);
3092
+ }
3093
+ function sleep2(ms, signal, what) {
3094
+ return new Promise((resolve, reject) => {
3095
+ const timer = setTimeout(() => {
3096
+ signal?.removeEventListener("abort", onAbort);
3097
+ resolve();
3098
+ }, ms);
3099
+ const onAbort = () => {
3100
+ clearTimeout(timer);
3101
+ reject(new GittermError("ABORTED", `Aborted while ${what}`));
3102
+ };
3103
+ signal?.addEventListener("abort", onAbort, { once: true });
3104
+ });
3105
+ }
3106
+ function normalizeWorkspace(workspace) {
3107
+ if (!workspace)
3108
+ return null;
3109
+ return {
3110
+ id: workspace.id,
3111
+ name: workspace.name,
3112
+ status: workspace.status,
3113
+ repositoryUrl: workspace.repositoryUrl,
3114
+ repositoryBranch: workspace.repositoryBranch,
3115
+ baseCommit: normalizeBaseCommit(workspace.baseCommit ?? workspace.repositoryBaseCommit ?? null),
3116
+ checkoutRef: workspace.checkoutRef ?? workspace.repositoryCheckoutRef ?? null,
3117
+ domain: workspace.domain,
3118
+ subdomain: workspace.subdomain,
3119
+ persistent: workspace.persistent,
3120
+ hostingType: workspace.hostingType,
3121
+ serverOnly: workspace.serverOnly,
3122
+ workspaceProfile: workspace.workspaceProfile,
3123
+ cloudProviderId: workspace.cloudProviderId,
3124
+ agentType: workspace.image?.agentType ? {
3125
+ id: workspace.image.agentType.id,
3126
+ name: workspace.image.agentType.name,
3127
+ description: workspace.image.agentType.description
3128
+ } : null,
3129
+ image: workspace.image ? {
3130
+ id: workspace.image.id,
3131
+ name: workspace.image.name,
3132
+ imageId: workspace.image.imageId
3133
+ } : null,
3134
+ metadata: workspace.metadata ?? {},
3135
+ autoTerminateAt: toIso(workspace.autoTerminateAt),
3136
+ customImage: workspace.customImage ?? null,
3137
+ startedAt: toIso(workspace.startedAt),
3138
+ pausedAt: toIso(workspace.pausedAt),
3139
+ terminatedAt: toIso(workspace.terminatedAt),
3140
+ lastActiveAt: toIso(workspace.lastActiveAt),
3141
+ updatedAt: toIso(workspace.updatedAt)
3142
+ };
3143
+ }
3144
+ function normalizeRuntime(runtime) {
3145
+ return {
3146
+ workspaceId: runtime.workspaceId,
3147
+ status: runtime.status,
3148
+ url: runtime.url,
3149
+ headers: runtime.headers,
3150
+ password: runtime.password,
3151
+ directory: runtime.directory,
3152
+ repo: runtime.repo,
3153
+ branch: runtime.branch,
3154
+ baseCommit: normalizeBaseCommit(runtime.baseCommit),
3155
+ checkoutRef: runtime.checkoutRef,
3156
+ persistent: runtime.persistent,
3157
+ recoverable: runtime.recoverable,
3158
+ providerKey: runtime.providerKey
3159
+ };
3160
+ }
3161
+ function mapTrpcCode(code) {
3162
+ switch (code) {
3163
+ case "UNAUTHORIZED":
3164
+ return "UNAUTHORIZED";
3165
+ case "NOT_FOUND":
3166
+ return "NOT_FOUND";
3167
+ case "FORBIDDEN":
3168
+ return "FORBIDDEN";
3169
+ case "BAD_REQUEST":
3170
+ return "BAD_REQUEST";
3171
+ case "CONFLICT":
3172
+ return "CONFLICT";
3173
+ case "TIMEOUT":
3174
+ return "TIMEOUT";
3175
+ default:
3176
+ return "SERVER_ERROR";
3177
+ }
3178
+ }
3179
+ function credentialErrorCode(message) {
3180
+ const match = /^(MODEL_CREDENTIAL_(?:UNAVAILABLE|DUPLICATE_PROVIDER|INVALID|REQUIRED)):\s*/.exec(message);
3181
+ return match?.[1];
3182
+ }
3183
+ function toGittermError(serverUrl, error) {
3184
+ if (error instanceof GittermError)
3185
+ return error;
3186
+ if (error instanceof TRPCClientError) {
3187
+ const data = error.data;
3188
+ if (!data) {
3189
+ return new GittermError("NETWORK", `Could not reach the GitTerm server at ${serverUrl}`, {
3190
+ cause: error.cause ?? error
3191
+ });
3192
+ }
3193
+ const status = { status: data.httpStatus };
3194
+ const structuredLifecycleCode = WORKSPACE_LIFECYCLE_ERROR_CODES.find((candidate) => candidate === data.workspaceLifecycleCode);
3195
+ if (structuredLifecycleCode) {
3196
+ return new WorkspaceLifecycleError(structuredLifecycleCode, error.message, status);
3197
+ }
3198
+ if (error.message.startsWith("INPUT_NOT_PENDING:"))
3199
+ return new GittermError("INPUT_NOT_PENDING", error.message, status);
3200
+ const credentialCode = credentialErrorCode(error.message);
3201
+ if (credentialCode)
3202
+ return new GittermError(credentialCode, error.message, status);
3203
+ const lifecycleCode = WORKSPACE_LIFECYCLE_ERROR_CODES.find((candidate) => error.message.startsWith(`${candidate}:`));
3204
+ if (lifecycleCode)
3205
+ return new WorkspaceLifecycleError(lifecycleCode, error.message, status);
3206
+ const code = mapTrpcCode(data.code);
3207
+ return new GittermError(code, code === "UNAUTHORIZED" ? `${error.message}. Check your GitTerm API token, or create a new one in the dashboard.` : error.message, status);
3208
+ }
3209
+ return new GittermError("NETWORK", error instanceof Error ? error.message : "Network request failed", { cause: error });
3210
+ }
3211
+ async function runWithServer(serverUrl, operation) {
3212
+ try {
3213
+ return await operation();
3214
+ } catch (error) {
3215
+ throw toGittermError(serverUrl, error);
3216
+ }
3217
+ }
3218
+ function isTerminalRun(status) {
3219
+ return status === "completed" || status === "failed" || status === "cancelled";
3220
+ }
3221
+ async function* watchRun(trpc, serverUrl, target, options) {
3222
+ const what = `watching run ${target.runId}`;
3223
+ throwIfAborted2(options?.signal, what);
3224
+ const queue = [];
3225
+ let wake;
3226
+ const push = (item) => {
3227
+ queue.push(item);
3228
+ wake?.();
3229
+ wake = undefined;
3230
+ };
3231
+ const onAbort = () => push({ error: new GittermError("ABORTED", `Aborted while ${what}`) });
3232
+ options?.signal?.addEventListener("abort", onAbort, { once: true });
3233
+ let last;
3234
+ const subscription = trpc.run.lifecycle.subscribe(target, {
3235
+ onData: (event) => {
3236
+ last = event.run;
3237
+ push({ run: last });
3238
+ },
3239
+ onError: (error) => push({ error }),
3240
+ onComplete: () => push(last && isTerminalRun(last.status) ? { done: true } : {
3241
+ error: new GittermError("NETWORK", `Run ${target.runId} event stream ended unexpectedly`)
3242
+ })
3243
+ });
3244
+ try {
3245
+ while (true) {
3246
+ throwIfAborted2(options?.signal, what);
3247
+ if (queue.length === 0)
3248
+ await new Promise((resolve) => wake = resolve);
3249
+ const item = queue.shift();
3250
+ if ("done" in item)
3251
+ return;
3252
+ if ("error" in item)
3253
+ throw toGittermError(serverUrl, item.error);
3254
+ yield item.run;
3255
+ if (isTerminalRun(item.run.status))
3256
+ return;
3257
+ }
3258
+ } finally {
3259
+ options?.signal?.removeEventListener("abort", onAbort);
3260
+ subscription.unsubscribe();
3261
+ }
3262
+ }
3263
+ function createGittermClient(options = {}) {
3264
+ const credentials = resolveCredentials(options);
3265
+ const fetchImpl = createNoRedirectFetch(options.fetch);
3266
+ const authorization = `Bearer ${credentials.token}`;
3267
+ const trpc = createTRPCClient({
3268
+ links: [
3269
+ splitLink({
3270
+ condition: (operation) => operation.type === "subscription",
3271
+ true: httpSubscriptionLink({
3272
+ url: trpcEndpoint(credentials.serverUrl),
3273
+ EventSource,
3274
+ eventSourceOptions: {
3275
+ fetch: (url, init) => fetchImpl(url, { ...init, headers: { ...init.headers, authorization } })
3276
+ }
3277
+ }),
3278
+ false: httpBatchLink({
3279
+ url: trpcEndpoint(credentials.serverUrl),
3280
+ fetch: fetchImpl,
3281
+ headers: () => ({ authorization })
3282
+ })
3283
+ })
3284
+ ]
3285
+ });
3286
+ const run = (operation) => runWithServer(credentials.serverUrl, operation);
3287
+ const watch = (ref, watchOptions) => watchRun(trpc, credentials.serverUrl, runTargetOf(ref), watchOptions);
3288
+ const respond = (ref, input) => run(async () => trpc.run.respond.mutate({ ...runTargetOf(ref), ...input }));
3289
+ const normalizeCreateResult = (result) => {
3290
+ const workspace = normalizeWorkspace(result.workspace);
3291
+ if (!workspace)
3292
+ throw new GittermError("SERVER_ERROR", "Workspace creation failed");
3293
+ const runtime = result.runtime ? normalizeRuntime(result.runtime) : {
3294
+ workspaceId: workspace.id,
3295
+ status: workspace.status,
3296
+ url: null,
3297
+ directory: "/workspace",
3298
+ repo: workspace.repositoryUrl,
3299
+ branch: workspace.repositoryBranch,
3300
+ baseCommit: workspace.baseCommit,
3301
+ checkoutRef: workspace.checkoutRef,
3302
+ persistent: workspace.persistent,
3303
+ recoverable: workspace.status !== "terminated",
3304
+ providerKey: null
3305
+ };
3306
+ return { workspace, runtime };
3307
+ };
3308
+ const createWorkspace = (input) => run(async () => {
3309
+ const result = await trpc.workspace.createWorkspace.mutate(input);
3310
+ return normalizeCreateResult(result);
3311
+ });
3312
+ const waitForWorkspaceSetup = async (workspaceId, waitOptions) => {
3313
+ const timeoutMs = waitOptions?.timeoutMs ?? 10 * 60000;
3314
+ const pollIntervalMs = waitOptions?.pollIntervalMs ?? 2000;
3315
+ const signal = waitOptions?.signal;
3316
+ const deadline = Date.now() + timeoutMs;
3317
+ while (true) {
3318
+ throwIfAborted2(signal, "waiting for workspace setup");
3319
+ const result = await trpc.workspace.getSetupStatus.query({ workspaceId }, { signal });
3320
+ if (result.status === "not_requested" || result.status === "succeeded")
3321
+ return result;
3322
+ if (result.status === "failed") {
3323
+ const log = result.log?.trim();
3324
+ throw new GittermError("BAD_REQUEST", `Workspace setup failed${result.exitCode === null ? "" : ` with exit code ${result.exitCode}`}${log ? `
3325
+ ${log}` : ""}`);
3326
+ }
3327
+ if (Date.now() >= deadline) {
3328
+ const log = result.log?.trim();
3329
+ throw new GittermError("TIMEOUT", `Timed out waiting for workspace ${workspaceId} setup (last status: ${result.status})${log ? `
3330
+ ${log}` : ""}`);
3331
+ }
3332
+ await sleep2(pollIntervalMs, signal, "waiting for workspace setup");
3333
+ }
3334
+ };
3335
+ return {
3336
+ serverUrl: credentials.serverUrl,
3337
+ auth: {
3338
+ status: () => run(async () => {
3339
+ const me = await trpc.agent.me.query();
3340
+ return {
3341
+ loggedIn: true,
3342
+ userId: me.userId,
3343
+ email: me.email,
3344
+ name: me.name,
3345
+ plan: me.plan ?? "free",
3346
+ authMethod: me.authMethod
3347
+ };
3348
+ })
3349
+ },
3350
+ workspaces: {
3351
+ list: (input) => run(async () => {
3352
+ const result = await trpc.workspace.listWorkspaces.query(input);
3353
+ return {
3354
+ workspaces: result.workspaces.map(normalizeWorkspace).filter((workspace) => workspace !== null),
3355
+ pagination: result.pagination
3356
+ };
3357
+ }),
3358
+ get: (ref) => run(async () => {
3359
+ const result = await trpc.workspace.getWorkspace.query({
3360
+ workspaceId: workspaceIdOf(ref)
3361
+ });
3362
+ const workspace = normalizeWorkspace(result.workspace);
3363
+ if (!workspace)
3364
+ throw new GittermError("NOT_FOUND", "Workspace not found");
3365
+ return workspace;
3366
+ }),
3367
+ getRuntimeAccess: (ref) => run(async () => {
3368
+ const result = await trpc.workspace.getRuntimeAccess.query({
3369
+ workspaceId: workspaceIdOf(ref)
3370
+ });
3371
+ return normalizeRuntime(result);
3372
+ }),
3373
+ ensureRunning: (ref, waitOptions) => run(async () => {
3374
+ throwIfAborted2(waitOptions?.signal, "ensuring the workspace is running");
3375
+ const result = await trpc.workspace.ensureRunning.mutate({
3376
+ workspaceId: workspaceIdOf(ref),
3377
+ timeoutMs: waitOptions?.timeoutMs,
3378
+ pollIntervalMs: waitOptions?.pollIntervalMs
3379
+ }, { signal: waitOptions?.signal });
3380
+ const workspace = normalizeWorkspace(result.workspace);
3381
+ if (!workspace)
3382
+ throw new GittermError("SERVER_ERROR", "ensureRunning failed");
3383
+ return {
3384
+ workspace,
3385
+ runtime: normalizeRuntime(result.runtime)
3386
+ };
3387
+ }),
3388
+ pause: (ref) => run(async () => {
3389
+ const result = await trpc.workspace.pauseWorkspace.mutate({
3390
+ workspaceId: workspaceIdOf(ref)
3391
+ });
3392
+ return { durationMinutes: result.durationMinutes };
3393
+ }),
3394
+ restart: (ref) => run(async () => {
3395
+ const result = await trpc.workspace.restartWorkspace.mutate({
3396
+ workspaceId: workspaceIdOf(ref)
3397
+ });
3398
+ return { status: result.status };
3399
+ }),
3400
+ terminate: (ref) => run(async () => {
3401
+ const result = await trpc.workspace.deleteWorkspace.mutate({
3402
+ workspaceId: workspaceIdOf(ref)
3403
+ });
3404
+ return {
3405
+ workspace: normalizeWorkspace(result.workspace),
3406
+ cleanupInBackground: result.cleanupInBackground
3407
+ };
3408
+ }),
3409
+ create: createWorkspace,
3410
+ models: (ref) => run(() => trpc.workspace.getModelAccess.query({ workspaceId: workspaceIdOf(ref) })),
3411
+ setupStatus: (ref) => run(async () => trpc.workspace.getSetupStatus.query({ workspaceId: workspaceIdOf(ref) })),
3412
+ waitForSetup: (ref, waitOptions) => run(() => waitForWorkspaceSetup(workspaceIdOf(ref), waitOptions))
3413
+ },
3414
+ sandboxes: {
3415
+ create: (input) => run(() => trpc.sandbox.create.mutate(input)),
3416
+ list: (input) => run(() => trpc.sandbox.list.query(input)),
3417
+ get: (sandboxId) => run(() => trpc.sandbox.get.query({ sandboxId })),
3418
+ run: (sandboxId, command, options) => run(async () => {
3419
+ const result = await trpc.sandbox.run.mutate({ sandboxId, command, ...options });
3420
+ if (!result)
3421
+ throw new GittermError("SERVER_ERROR", "Sandbox command returned no result");
3422
+ return result;
3423
+ }),
3424
+ writeFile: (sandboxId, path, data) => run(async () => {
3425
+ await trpc.sandbox.writeFile.mutate({
3426
+ sandboxId,
3427
+ path,
3428
+ contentBase64: Buffer.from(data).toString("base64")
3429
+ });
3430
+ }),
3431
+ readFile: (sandboxId, path) => run(async () => {
3432
+ const result = await trpc.sandbox.readFile.mutate({ sandboxId, path });
3433
+ return new Uint8Array(Buffer.from(result?.contentBase64 ?? "", "base64"));
3434
+ }),
3435
+ preview: (sandboxId, port, options) => run(async () => {
3436
+ const result = await trpc.sandbox.preview.mutate({
3437
+ sandboxId,
3438
+ port,
3439
+ public: options?.public
3440
+ });
3441
+ if (!result)
3442
+ throw new GittermError("SERVER_ERROR", "Sandbox preview returned no result");
3443
+ return result;
3444
+ }),
3445
+ resume: (sandboxId) => run(async () => {
3446
+ await trpc.workspace.restartWorkspace.mutate({ workspaceId: sandboxId });
3447
+ }),
3448
+ terminate: (sandboxId) => run(async () => {
3449
+ await trpc.sandbox.terminate.mutate({ sandboxId });
3450
+ }),
3451
+ saveSnapshot: (sandboxId, label) => run(() => trpc.sandbox.saveSnapshot.mutate({ sandboxId, label: label.slice(0, 120) })),
3452
+ listSnapshots: () => run(() => trpc.sandbox.snapshots.query()),
3453
+ deleteSnapshot: (snapshotId) => run(async () => {
3454
+ await trpc.sandbox.deleteSnapshot.mutate({ snapshotId });
3455
+ }),
3456
+ onJobFinished: (listener) => {
3457
+ const subscription = trpc.sandbox.jobEvents.subscribe(undefined, {
3458
+ onData: (event) => listener(event),
3459
+ onError: () => {}
3460
+ });
3461
+ return () => subscription.unsubscribe();
3462
+ }
3463
+ },
3464
+ runs: {
3465
+ create: (input) => run(async () => {
3466
+ const { signal, workspace, ...rest } = input;
3467
+ const request = {
3468
+ ...rest,
3469
+ workspaceId: workspaceIdOf(workspace),
3470
+ context: rest.context?.type === "continue" ? { type: "continue", runId: rest.context.run.id } : rest.context
3471
+ };
3472
+ if (request.waitForSetup) {
3473
+ await waitForWorkspaceSetup(request.workspaceId, {
3474
+ timeoutMs: request.setupTimeoutMs,
3475
+ signal
3476
+ });
3477
+ }
3478
+ throwIfAborted2(signal, "creating the run");
3479
+ return trpc.run.create.mutate({ ...request, idempotencyKey: request.idempotencyKey ?? crypto.randomUUID() }, { signal });
3480
+ }),
3481
+ list: (ref, listOptions) => run(async () => trpc.run.list.query({
3482
+ workspaceId: workspaceIdOf(ref),
3483
+ ...listOptions
3484
+ })),
3485
+ get: (ref) => run(async () => trpc.run.get.query(runTargetOf(ref))),
3486
+ messages: (ref) => run(async () => {
3487
+ const messages = await trpc.run.messages.query(runTargetOf(ref));
3488
+ return messages.map((message) => ({ ...message, parts: message.parts ?? [] }));
3489
+ }),
3490
+ cancel: (ref) => run(async () => trpc.run.cancel.mutate(runTargetOf(ref))),
3491
+ respond,
3492
+ watch,
3493
+ ...runHelpers({ watch, respond })
3494
+ },
3495
+ catalog: {
3496
+ agentTypes: (input) => run(async () => {
3497
+ const result = await trpc.workspace.listAgentTypes.query(input);
3498
+ return result.agentTypes;
3499
+ }),
3500
+ cloudProviders: (input) => run(async () => {
3501
+ const result = await trpc.workspace.listCloudProviders.query(input);
3502
+ return result.cloudProviders;
3503
+ }),
3504
+ workspaceOptions: () => run(async () => trpc.workspace.getWorkspaceCatalog.query())
3505
+ },
3506
+ integrations: {
3507
+ catalog: () => run(async () => trpc.integrations.catalog.query()),
3508
+ connections: {
3509
+ list: (filter) => run(async () => {
3510
+ const result = await trpc.integrations.connections.list.query(filter);
3511
+ return result.map(toConnection);
3512
+ }),
3513
+ get: (id) => run(async () => toConnection(await trpc.integrations.connections.get.query({ id }))),
3514
+ resolve: (references, options) => run(async () => {
3515
+ const result = await trpc.integrations.connections.resolve.query({
3516
+ references,
3517
+ ...options?.repo ? { repo: options.repo } : {}
3518
+ });
3519
+ return result.map(toConnection);
3520
+ }),
3521
+ create: (input) => run(async () => {
3522
+ const result = await trpc.integrations.connections.create.mutate(input);
3523
+ return result.status !== "pending" ? { ...result, connection: toConnection(result.connection) } : result;
3524
+ }),
3525
+ remove: (id) => run(async () => {
3526
+ await trpc.integrations.connections.remove.mutate({ id });
3527
+ }),
3528
+ waitFor: ({
3529
+ integration,
3530
+ since,
3531
+ connectionId,
3532
+ timeoutMs = 5 * 60000,
3533
+ intervalMs = 3000
3534
+ }) => run(async () => {
3535
+ const sinceMs = since ? new Date(since).getTime() : 0;
3536
+ const deadline = Date.now() + timeoutMs;
3537
+ while (Date.now() < deadline) {
3538
+ const result = await trpc.integrations.connections.list.query({
3539
+ integration,
3540
+ kind: "personal"
3541
+ });
3542
+ const match = result.map(toConnection).filter((c) => c.status === "connected" && (connectionId ? c.id === connectionId : new Date(c.connectedAt).getTime() >= sinceMs)).sort((a, b) => b.connectedAt.localeCompare(a.connectedAt))[0];
3543
+ if (match)
3544
+ return match;
3545
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
3546
+ }
3547
+ throw new Error(`Timed out waiting for a ${integration} connection`);
3548
+ })
3549
+ },
3550
+ github: {
3551
+ repositories: (connectionId) => run(async () => trpc.integrations.github.repositories.query({ connectionId })),
3552
+ branches: (connectionId, owner, repo) => run(async () => trpc.integrations.github.branches.query({ connectionId, owner, repo }))
3553
+ },
3554
+ google: {
3555
+ setup: () => run(async () => trpc.integrations.google.setup.query())
3556
+ },
3557
+ mcp: {
3558
+ test: (id) => run(async () => {
3559
+ const result = await trpc.integrations.mcp.test.mutate({ id });
3560
+ return { ...result, connection: toConnection(result.connection) };
3561
+ }),
3562
+ update: (input) => run(async () => toConnection(await trpc.integrations.mcp.update.mutate(input)))
3563
+ }
3564
+ },
3565
+ bots: {
3566
+ acquireLease: (leaseId) => run(() => trpc.bots.acquireLease.mutate({ leaseId })),
3567
+ releaseLease: (leaseId) => run(() => trpc.bots.releaseLease.mutate({ leaseId })),
3568
+ self: () => run(async () => trpc.bots.self.query())
3569
+ },
3570
+ credentials: {
3571
+ list: () => run(async () => {
3572
+ const result = await trpc.modelCredentials.listMyCredentials.query();
3573
+ return result.credentials.map((credential) => ({
3574
+ ...credential,
3575
+ lastUsedAt: toIso(credential.lastUsedAt),
3576
+ oauthExpiresAt: toIso(credential.oauthExpiresAt),
3577
+ createdAt: toIso(credential.createdAt),
3578
+ updatedAt: toIso(credential.updatedAt)
3579
+ }));
3580
+ }),
3581
+ listProviders: () => run(async () => {
3582
+ const result = await trpc.modelCredentials.listProviders.query();
3583
+ return result.providers.map((provider) => ({
3584
+ id: provider.id,
3585
+ name: provider.name,
3586
+ logicalProviderKey: provider.logicalProviderKey,
3587
+ displayName: provider.displayName,
3588
+ authType: provider.authType,
3589
+ isRecommended: provider.isRecommended
3590
+ }));
3591
+ })
3592
+ }
3593
+ };
3594
+ }
3595
+
3596
+ // src/handoff.ts
3597
+ import { randomUUID } from "crypto";
3598
+ import { realpath as realpath2 } from "fs/promises";
3599
+ import path2 from "path";
3600
+ import { setTimeout as delay } from "timers/promises";
3601
+ import { OpenCode } from "@opencode/client";
3602
+
3603
+ // src/snapshot.ts
3604
+ import { createHash } from "crypto";
3605
+ import { execFile } from "child_process";
3606
+ import { lstat, mkdtemp, readFile, realpath, rm, stat } from "fs/promises";
3607
+ import { tmpdir } from "os";
3608
+ import path from "path";
3609
+ var MAX_SNAPSHOT_BYTES = 25 * 1024 * 1024;
3610
+ var DIFF_ARGS = [
3611
+ "--binary",
3612
+ "--full-index",
3613
+ "--no-ext-diff",
3614
+ "--no-textconv",
3615
+ "--no-renames",
3616
+ "--no-color",
3617
+ "--unified=3",
3618
+ "--inter-hunk-context=0",
3619
+ "--diff-algorithm=myers",
3620
+ "--no-indent-heuristic",
3621
+ "--src-prefix=a/",
3622
+ "--dst-prefix=b/"
3623
+ ];
3624
+ async function git(directory, args, maxBytes = MAX_SNAPSHOT_BYTES) {
3625
+ return new Promise((resolve, reject) => {
3626
+ execFile("git", ["-c", "core.quotePath=true", ...args], {
3627
+ cwd: directory,
3628
+ encoding: "buffer",
3629
+ maxBuffer: maxBytes,
3630
+ timeout: 60000,
3631
+ env: { ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_TERMINAL_PROMPT: "0" }
3632
+ }, (error, stdout) => {
3633
+ if (error)
3634
+ reject(new Error("Git snapshot operation failed. Check repository access, unresolved conflicts, and snapshot size."));
3635
+ else
3636
+ resolve(stdout);
3637
+ });
3638
+ });
3639
+ }
3640
+ async function checkoutRoot(directory) {
3641
+ return realpath((await git(directory, ["rev-parse", "--show-toplevel"])).toString().trim());
3642
+ }
3643
+ var PRIVATE_KEY = /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----(?:\r?\n[+\- ]?|(?:\\r)?\\n)(?:[A-Za-z-]+: [^\r\n]*(?:\r?\n[+\- ]?|(?:\\r)?\\n))*(?:\r?\n[+\- ]?|(?:\\r)?\\n)?[A-Za-z0-9+/]{16}/;
3644
+ function safeRelativePath(file) {
3645
+ return Boolean(file) && !file.includes("\\") && !file.includes("\x00") && !path.posix.isAbsolute(file) && file.split("/").every((part) => part !== "" && part !== "." && part !== ".." && part.toLowerCase() !== ".git");
3646
+ }
3647
+ function sensitivePath(file) {
3648
+ return /(^|\/)(\.env($|\.(?!(?:[^/]*\.)?(?:example|sample|template)$))|id_(rsa|ed25519|ecdsa)($|\.)|credentials(?:\.json)?$)|\.(pem|p12|pfx|key)$/i.test(file);
3649
+ }
3650
+ var nulList = (buffer) => {
3651
+ if (!Buffer.from(buffer.toString()).equals(buffer))
3652
+ throw new Error("Non-UTF-8 filenames are not supported by cloud handoff.");
3653
+ return buffer.toString().split("\x00").filter(Boolean);
3654
+ };
3655
+ var stateDigest = (state) => createHash("sha256").update(JSON.stringify(state)).digest("hex");
3656
+ async function readWorkingState(root, includeChanges) {
3657
+ const head = (await git(root, ["rev-parse", "HEAD"])).toString().trim();
3658
+ if ((await git(root, ["ls-files", "--unmerged", "-z"])).length) {
3659
+ throw new Error("Resolve merge conflicts before continuing in the cloud.");
3660
+ }
3661
+ if ((await git(root, ["ls-files", "--stage"])).toString().split(`
3662
+ `).some((line) => line.startsWith("160000 "))) {
3663
+ throw new Error("Cloud handoff does not support submodules yet.");
3664
+ }
3665
+ if (!includeChanges)
3666
+ return { head, staged: "", unstaged: "", files: [], changedPaths: [] };
3667
+ if ((await git(root, ["diff", "--name-only", "--diff-filter=A", "--"])).length) {
3668
+ throw new Error("Stage or unstage intent-to-add files before cloud handoff.");
3669
+ }
3670
+ const stagedBytes = await git(root, ["diff", ...DIFF_ARGS, "--cached", "HEAD", "--"]);
3671
+ const unstagedBytes = await git(root, ["diff", ...DIFF_ARGS, "--"]);
3672
+ if (PRIVATE_KEY.test(stagedBytes.toString() + unstagedBytes.toString())) {
3673
+ throw new Error("Private key material detected in changed files. Remove it before uploading.");
3674
+ }
3675
+ const staged = stagedBytes.toString("base64");
3676
+ const unstaged = unstagedBytes.toString("base64");
3677
+ const untracked = nulList(await git(root, ["ls-files", "--others", "--exclude-standard", "-z"])).toSorted();
3678
+ const changedPaths = [
3679
+ ...new Set([
3680
+ ...nulList(await git(root, ["diff", "--name-only", "-z", "--no-renames", "HEAD", "--"])),
3681
+ ...nulList(await git(root, ["diff", "--name-only", "-z", "--cached", "HEAD", "--"])),
3682
+ ...untracked
3683
+ ])
3684
+ ].toSorted();
3685
+ for (const file of changedPaths) {
3686
+ if (!safeRelativePath(file))
3687
+ throw new Error("The checkout contains a path that cannot be transferred safely.");
3688
+ if (sensitivePath(file))
3689
+ throw new Error(`Potential secret file ${JSON.stringify(file)} is changed. Exclude it or continue without uncommitted changes.`);
3690
+ }
3691
+ let bytes = stagedBytes.length + unstagedBytes.length;
3692
+ const files = [];
3693
+ for (const file of untracked) {
3694
+ const full = path.join(root, file);
3695
+ const info = await lstat(full);
3696
+ if (!info.isFile() || await realpath(full) !== full) {
3697
+ throw new Error("Untracked symlinks, nested repositories, and special files are not supported.");
3698
+ }
3699
+ bytes += info.size;
3700
+ if (bytes > MAX_SNAPSHOT_BYTES)
3701
+ throw new Error("Uncommitted changes exceed the 25 MiB handoff limit.");
3702
+ const content = await readFile(full);
3703
+ if (PRIVATE_KEY.test(content.toString("latin1"))) {
3704
+ throw new Error(`Private key material detected in ${JSON.stringify(file)}. Remove it before uploading.`);
3705
+ }
3706
+ files.push({
3707
+ path: file,
3708
+ data: content.toString("base64"),
3709
+ executable: Boolean(info.mode & 73)
3710
+ });
3711
+ }
3712
+ return { head, staged, unstaged, files, changedPaths };
3713
+ }
3714
+ async function captureSnapshot(directory, includeChanges) {
3715
+ const root = await checkoutRoot(directory);
3716
+ const temporary = await mkdtemp(path.join(tmpdir(), "gitterm-handoff-"));
3717
+ try {
3718
+ const before = await readWorkingState(root, includeChanges);
3719
+ const bundlePath = path.join(temporary, "checkout.bundle");
3720
+ await git(root, ["bundle", "create", bundlePath, "HEAD"]);
3721
+ const bundleSize = (await stat(bundlePath)).size;
3722
+ if (bundleSize > MAX_SNAPSHOT_BYTES)
3723
+ throw new Error("Repository history exceeds the 25 MiB handoff limit.");
3724
+ const bundle = (await readFile(bundlePath)).toString("base64");
3725
+ const after = await readWorkingState(root, includeChanges);
3726
+ const digest = stateDigest(before);
3727
+ if (digest !== stateDigest(after))
3728
+ throw new Error("The checkout changed during capture. Pause writers and retry.");
3729
+ const bytes = bundleSize + Buffer.from(before.staged, "base64").length + Buffer.from(before.unstaged, "base64").length + before.files.reduce((sum, file) => sum + Buffer.from(file.data, "base64").length, 0);
3730
+ if (bytes > MAX_SNAPSHOT_BYTES)
3731
+ throw new Error("Checkout snapshot exceeds the 25 MiB handoff limit.");
3732
+ return { version: 1, ...before, bundle, digest, bytes };
3733
+ } finally {
3734
+ await rm(temporary, { recursive: true, force: true });
3735
+ }
3736
+ }
3737
+ async function repositoryUrl(root) {
3738
+ const url = (await git(root, ["remote", "get-url", "origin"])).toString().trim();
3739
+ if (/^https:\/\//i.test(url)) {
3740
+ const parsed = new URL(url);
3741
+ if (parsed.username || parsed.password || parsed.search || parsed.hash)
3742
+ throw new Error("Use a credential-free origin URL and a GitTerm repository connection.");
3743
+ return parsed.href;
3744
+ }
3745
+ const ssh = /^(?:git@github\.com:|ssh:\/\/git@github\.com\/)([^\s]+)$/.exec(url);
3746
+ if (ssh?.[1])
3747
+ return `https://github.com/${ssh[1]}`;
3748
+ throw new Error("Cloud handoff needs an HTTPS origin (or a GitHub SSH origin). Configure repository access in GitTerm.");
3749
+ }
3750
+ async function sharedCheckoutSessions(root, sessionID, sessions) {
3751
+ const matches = [];
3752
+ for (const session of sessions) {
3753
+ if (session.id === sessionID)
3754
+ continue;
3755
+ try {
3756
+ if (await checkoutRoot(session.location.directory) === root)
3757
+ matches.push(session.id);
3758
+ } catch {}
3759
+ }
3760
+ return matches;
3761
+ }
3762
+
3763
+ // src/restore.ts
3764
+ var RESTORE_SCRIPT = String.raw`
3765
+ const fs = require("node:fs");
3766
+ const path = require("node:path");
3767
+ const cp = require("node:child_process");
3768
+ const crypto = require("node:crypto");
3769
+ const stage = process.argv[1];
3770
+ if (!/^\.gitterm-handoff-[a-f0-9-]+$/.test(stage)) throw new Error("Invalid staging directory");
3771
+ const diffArgs = ${JSON.stringify(DIFF_ARGS)};
3772
+ const git = (...args) => cp.execFileSync("git", ["-c", "core.hooksPath=/dev/null", "-c", "core.quotePath=true", ...args], { maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
3773
+ const safePath = file => typeof file === "string" && file.length > 0 && !file.includes("\\") && !file.includes("\0") && !path.posix.isAbsolute(file) && file.split("/").every(part => part && part !== "." && part !== ".." && part.toLowerCase() !== ".git");
3774
+ try {
3775
+ const snapshot = JSON.parse(fs.readFileSync(path.join(stage, "snapshot.json"), "utf8"));
3776
+ if (snapshot.version !== 1 || !/^[a-f0-9]{40}([a-f0-9]{24})?$/.test(snapshot.head)) throw new Error("Invalid snapshot");
3777
+ const untracked = git("ls-files", "--others", "--exclude-standard", "-z").toString().split("\0").filter(Boolean);
3778
+ if (git("diff", "HEAD", "--").length || git("diff", "--cached", "HEAD", "--").length || untracked.some(file => !file.startsWith(stage + "/"))) throw new Error("Cloud checkout has existing changes");
3779
+ const bundle = path.join(stage, "checkout.bundle");
3780
+ fs.writeFileSync(bundle, Buffer.from(snapshot.bundle, "base64"), { mode: 0o600 });
3781
+ git("bundle", "verify", bundle);
3782
+ git("fetch", "--no-tags", "./" + bundle, "HEAD");
3783
+ if (git("rev-parse", "FETCH_HEAD").toString().trim() !== snapshot.head) throw new Error("Bundle revision mismatch");
3784
+ git("checkout", "--no-overwrite-ignore", "-b", "gitterm/" + stage.slice(".gitterm-handoff-".length), "FETCH_HEAD");
3785
+ if (snapshot.staged) {
3786
+ const patch = path.join(stage, "staged.patch");
3787
+ fs.writeFileSync(patch, Buffer.from(snapshot.staged, "base64"));
3788
+ git("apply", "--index", "--binary", "--whitespace=nowarn", patch);
3789
+ }
3790
+ if (snapshot.unstaged) {
3791
+ const patch = path.join(stage, "unstaged.patch");
3792
+ fs.writeFileSync(patch, Buffer.from(snapshot.unstaged, "base64"));
3793
+ git("apply", "--binary", "--whitespace=nowarn", patch);
3794
+ }
3795
+ for (const file of snapshot.files) {
3796
+ if (!safePath(file.path)) throw new Error("Unsafe file path");
3797
+ const pieces = file.path.split("/");
3798
+ let directory = process.cwd();
3799
+ for (const piece of pieces.slice(0, -1)) {
3800
+ directory = path.join(directory, piece);
3801
+ if (!fs.existsSync(directory)) fs.mkdirSync(directory);
3802
+ if (!fs.lstatSync(directory).isDirectory() || fs.lstatSync(directory).isSymbolicLink()) throw new Error("Unsafe parent directory");
3803
+ }
3804
+ fs.writeFileSync(file.path, Buffer.from(file.data, "base64"), { flag: "wx", mode: file.executable ? 0o755 : 0o644 });
3805
+ }
3806
+ fs.rmSync(stage, { recursive: true });
3807
+ const restoredUntracked = git("ls-files", "--others", "--exclude-standard", "-z").toString().split("\0").filter(Boolean).sort();
3808
+ const expectedUntracked = snapshot.files.map(file => file.path).sort();
3809
+ if (JSON.stringify(restoredUntracked) !== JSON.stringify(expectedUntracked)) throw new Error("Untracked file inventory mismatch");
3810
+ const files = snapshot.files.map(file => ({ path: file.path, data: fs.readFileSync(file.path).toString("base64"), executable: Boolean(fs.statSync(file.path).mode & 0o111) }));
3811
+ const state = { head: git("rev-parse", "HEAD").toString().trim(), staged: git("diff", ...diffArgs, "--cached", "HEAD", "--").toString("base64"), unstaged: git("diff", ...diffArgs, "--").toString("base64"), files, changedPaths: snapshot.changedPaths };
3812
+ const digest = crypto.createHash("sha256").update(JSON.stringify(state)).digest("hex");
3813
+ if (digest !== snapshot.digest) throw new Error("Restored checkout verification failed");
3814
+ process.stdout.write("GITTERM_HANDOFF_VERIFIED");
3815
+ } catch {
3816
+ // Never print patches, files, credentials, or upstream command output.
3817
+ process.stderr.write("GitTerm checkout restoration failed. Local files are unchanged.\n");
3818
+ process.exitCode = 1;
3819
+ } finally {
3820
+ fs.rmSync(stage, { recursive: true, force: true });
3821
+ }
3822
+ `;
3823
+ var shellQuote = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
3824
+
3825
+ // src/handoff.ts
3826
+ var STEPS = {
3827
+ creating: "creating the cloud workspace",
3828
+ restoring: "restoring your checkout in the cloud",
3829
+ importing: "importing this session into the cloud",
3830
+ ready: "finishing",
3831
+ failed: "finishing"
3832
+ };
3833
+
3834
+ class HandoffCancelled extends Error {
3835
+ constructor() {
3836
+ super("Cloud handoff cancelled. Local files and sessions are unchanged.");
3837
+ }
3838
+ }
3839
+ function changePrompt(sharedCount) {
3840
+ return [
3841
+ "Copies this checkout's tracked edits and non-ignored untracked files. Local files remain unchanged.",
3842
+ sharedCount > 0 ? `${sharedCount} other active session(s) use this checkout. Their changes may be included too.` : "",
3843
+ "Other OpenCode servers, editors, and background writers cannot all be detected. Pause writers for a consistent snapshot."
3844
+ ].filter(Boolean).join(`
3845
+ `);
3846
+ }
3847
+ async function askForm(client, sessionID, title, fields, signal) {
3848
+ const form = await client.session.form.create({ sessionID, title, fields }, { signal });
3849
+ const deadline = Date.now() + 10 * 60000;
3850
+ try {
3851
+ while (Date.now() < deadline) {
3852
+ const detail = await client.session.form.get({ sessionID, formID: form.id }, { signal });
3853
+ if (detail.state.status === "cancelled")
3854
+ throw new HandoffCancelled;
3855
+ if (detail.state.status === "answered")
3856
+ return detail.state.answer;
3857
+ await delay(400, undefined, { signal });
3858
+ }
3859
+ throw new HandoffCancelled;
3860
+ } finally {
3861
+ await client.session.form.cancel({ sessionID, formID: form.id }, { signal: AbortSignal.timeout(5000) }).catch(() => {});
3862
+ }
3863
+ }
3864
+ async function assertIdle(client, sessionID, signal) {
3865
+ if ((await client.session.active({ signal }))[sessionID]) {
3866
+ throw new Error("Stop this session's running agent before continuing in the cloud. Other sessions will not be interrupted.");
3867
+ }
3868
+ if ((await client.session.inbox.list({ sessionID }, { signal })).length > 0) {
3869
+ throw new Error("This session has pending input. Finish or cancel it before continuing in the cloud.");
3870
+ }
3871
+ }
3872
+ function runtimeClient(runtime) {
3873
+ if (!runtime.url)
3874
+ throw new Error("The workspace does not have an OpenCode server URL.");
3875
+ const url = new URL(runtime.url);
3876
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))) {
3877
+ throw new Error("Cloud handoff requires HTTPS (or a loopback development server).");
3878
+ }
3879
+ const headers = new Headers(runtime.headers);
3880
+ if (runtime.password)
3881
+ headers.set("Authorization", `Basic ${Buffer.from(`opencode:${runtime.password}`).toString("base64")}`);
3882
+ if (!headers.has("Authorization"))
3883
+ throw new Error("The workspace did not return an OpenCode access credential.");
3884
+ return OpenCode.make({
3885
+ baseUrl: runtime.url,
3886
+ headers,
3887
+ fetch: (input, init) => fetch(input, { ...init, redirect: "error" })
3888
+ });
3889
+ }
3890
+ async function runRemoteShell(remote, directory, command, signal) {
3891
+ const location = { directory };
3892
+ let shell = (await remote.shell.create({ location, cwd: directory, command, timeout: 120000 }, { signal })).data;
3893
+ try {
3894
+ while (shell.status === "running") {
3895
+ await delay(300, undefined, { signal });
3896
+ shell = (await remote.shell.get({ id: shell.id, location }, { signal })).data;
3897
+ }
3898
+ if (shell.status !== "exited" || shell.exit !== 0) {
3899
+ throw new Error("Cloud checkout restoration failed. The workspace is retained for inspection; local files are unchanged.");
3900
+ }
3901
+ } finally {
3902
+ if (shell.status === "running")
3903
+ await remote.shell.remove({ id: shell.id, location }, { signal: AbortSignal.timeout(5000) }).catch(() => {});
3904
+ }
3905
+ }
3906
+ function importPayload(data, directory) {
3907
+ const {
3908
+ parentID: _parent,
3909
+ fork: _fork,
3910
+ revert: _revert,
3911
+ permissions: _permissions,
3912
+ ...info
3913
+ } = data.info;
3914
+ return {
3915
+ info: { ...info, location: { directory } },
3916
+ messages: data.messages,
3917
+ location: { directory }
3918
+ };
3919
+ }
3920
+ async function handoffSession(sessionID, deps) {
3921
+ const { local, gitterm, options, signal } = deps;
3922
+ await assertIdle(local, sessionID, signal);
3923
+ const session = await local.session.get({ sessionID }, { signal });
3924
+ const sourceDirectory = await realpath2(session.location.directory);
3925
+ const root = await checkoutRoot(sourceDirectory);
3926
+ const repo = await repositoryUrl(root);
3927
+ const active = await local.session.active({ signal });
3928
+ const activeSessions = await Promise.all(Object.keys(active).filter((id) => id !== sessionID).map((id) => local.session.get({ sessionID: id }, { signal }).catch(() => {
3929
+ return;
3930
+ })));
3931
+ const shared = await sharedCheckoutSessions(root, sessionID, activeSessions.filter((item) => item !== undefined));
3932
+ const choice = await askForm(local, sessionID, "Continue in GitTerm", [
3933
+ {
3934
+ key: "changes",
3935
+ type: "boolean",
3936
+ title: "Include uncommitted changes?",
3937
+ description: changePrompt(shared.length),
3938
+ default: false,
3939
+ required: true
3940
+ }
3941
+ ], signal);
3942
+ const includeChanges = choice.changes === true;
3943
+ await assertIdle(local, sessionID, signal);
3944
+ const snapshot = await captureSnapshot(root, includeChanges);
3945
+ const manifest = snapshot.changedPaths.slice(0, 100).map((file) => JSON.stringify(file)).join(`
3946
+ `);
3947
+ const confirmation = await askForm(local, sessionID, "Create cloud workspace?", [
3948
+ {
3949
+ key: "create",
3950
+ type: "boolean",
3951
+ title: "Upload this snapshot and start billable cloud compute?",
3952
+ required: true,
3953
+ default: false,
3954
+ description: [
3955
+ `Repository: ${repo}
3956
+ Commit: ${snapshot.head}
3957
+ Snapshot: ${(snapshot.bytes / 1024 / 1024).toFixed(2)} MiB`,
3958
+ includeChanges ? `${snapshot.changedPaths.length} changed paths${manifest ? `:
3959
+ ${manifest}` : ""}${snapshot.changedPaths.length > 100 ? `
3960
+ (additional paths omitted)` : ""}` : "Uncommitted changes are excluded.",
3961
+ "Uploads this conversation (which may contain secrets) and Git history, including unpublished commits. Ignored files are not separately uploaded; tracked history can contain secrets. Review before approving.",
3962
+ "Uses your GitTerm model/repository connections, not separately copied local credential stores. Cloud compute may incur charges until paused or terminated in GitTerm. Local work remains untouched; later local edits will not sync."
3963
+ ].join(`
3964
+
3965
+ `)
3966
+ }
3967
+ ], signal);
3968
+ if (confirmation.create !== true)
3969
+ throw new HandoffCancelled;
3970
+ await assertIdle(local, sessionID, signal);
3971
+ const exported = await local.session.export({ sessionID }, { signal });
3972
+ await assertIdle(local, sessionID, signal);
3973
+ if (exported.info.location.directory !== session.location.directory || exported.info.time.updated !== session.time.updated) {
3974
+ throw new Error("The session changed during handoff preparation. Retry after it is idle.");
3975
+ }
3976
+ if (Buffer.byteLength(JSON.stringify(exported)) > 25 * 1024 * 1024)
3977
+ throw new Error("Session history exceeds the 25 MiB handoff limit.");
3978
+ const record = {
3979
+ attemptID: randomUUID(),
3980
+ sessionID,
3981
+ phase: "creating",
3982
+ sourceDirectory: root,
3983
+ head: snapshot.head,
3984
+ includeChanges,
3985
+ sharedSessions: shared.length,
3986
+ createdAt: new Date().toISOString()
3987
+ };
3988
+ await deps.save(record);
3989
+ try {
3990
+ await deps.progress("Creating a GitTerm workspace. Your local checkout and sessions remain unchanged.");
3991
+ const created = await gitterm.workspaces.create({
3992
+ idempotencyKey: `opencode-handoff:${record.attemptID}`,
3993
+ name: options.name ?? session.title ?? "OpenCode cloud handoff",
3994
+ repo,
3995
+ agent: "opencode",
3996
+ provider: options.provider,
3997
+ persistent: options.persistent,
3998
+ connections: options.connections,
3999
+ metadata: { "opencode.handoff": record.attemptID, "opencode.session": sessionID }
4000
+ });
4001
+ record.workspaceID = created.workspace.id;
4002
+ record.phase = "restoring";
4003
+ await deps.save(record);
4004
+ await gitterm.workspaces.ensureRunning(record.workspaceID, { signal });
4005
+ const runtime = await gitterm.workspaces.getRuntimeAccess(record.workspaceID);
4006
+ const remote = runtimeClient(runtime);
4007
+ await remote.server.info({ signal });
4008
+ const stage = `.gitterm-handoff-${record.attemptID}`;
4009
+ await deps.progress("Restoring and verifying the captured checkout in the cloud.");
4010
+ await runRemoteShell(remote, runtime.directory, `node -e ${shellQuote('require("node:fs").mkdirSync(process.argv[1], { mode: 0o700 })')} ${shellQuote(stage)}`, signal);
4011
+ try {
4012
+ await remote.file.write({
4013
+ location: { directory: runtime.directory },
4014
+ path: `${stage}/snapshot.json`,
4015
+ payload: Buffer.from(JSON.stringify(snapshot))
4016
+ }, { signal });
4017
+ await runRemoteShell(remote, runtime.directory, `node -e ${shellQuote(RESTORE_SCRIPT)} ${shellQuote(stage)}`, signal);
4018
+ } finally {
4019
+ await runRemoteShell(remote, runtime.directory, `node -e ${shellQuote('require("node:fs").rmSync(process.argv[1], { recursive: true, force: true })')} ${shellQuote(stage)}`, AbortSignal.timeout(1e4)).catch(() => {});
4020
+ }
4021
+ const subpath = path2.relative(root, sourceDirectory).split(path2.sep).join("/");
4022
+ if (subpath.startsWith("../") || path2.isAbsolute(subpath))
4023
+ throw new Error("The session moved outside its source checkout.");
4024
+ const directory = path2.posix.join(runtime.directory, subpath);
4025
+ await runRemoteShell(remote, runtime.directory, `node -e ${shellQuote('require("node:fs").mkdirSync(process.argv[1], { recursive: true })')} ${shellQuote(directory)}`, signal);
4026
+ record.phase = "importing";
4027
+ await deps.save(record);
4028
+ const imported = await remote.session.import(importPayload(exported, directory), { signal });
4029
+ if (imported.id !== sessionID || imported.location.directory !== directory)
4030
+ throw new Error("Cloud session verification failed.");
4031
+ await remote.session.synthetic({
4032
+ sessionID,
4033
+ resume: false,
4034
+ text: [
4035
+ `Continued from local checkout ${root}. The current cloud working directory is ${directory}.`,
4036
+ includeChanges ? "The captured checkout includes uncommitted changes, potentially from other sessions." : "Uncommitted local changes were excluded; do not assume edits described in history exist here.",
4037
+ "Historical absolute paths refer to the old machine. Use the cloud checkout. Local processes, separately ignored files, credential stores, and global plugins/configuration were not migrated. Repository-owned configuration travels with the checkout. Select an available cloud model/agent if needed."
4038
+ ].join(`
4039
+ `)
4040
+ }, { signal });
4041
+ record.phase = "ready";
4042
+ await deps.save(record);
4043
+ return record;
4044
+ } catch (error) {
4045
+ const step = STEPS[record.phase];
4046
+ record.phase = "failed";
4047
+ await deps.save(record);
4048
+ console.error("GitTerm cloud handoff failed while", step, error);
4049
+ const reason = error instanceof GittermError ? ` ${error.message}` : "";
4050
+ throw new Error(`Cloud handoff failed while ${step}${record.workspaceID ? ` for workspace ${record.workspaceID}` : ` (attempt ${record.attemptID})`}.${reason} Check GitTerm before retrying; a workspace may still be running and incurring charges. Local files and sessions are unchanged.`);
4051
+ }
4052
+ }
4053
+ async function showConnection(local, gitterm, record, signal) {
4054
+ if (record.phase !== "ready" || !record.workspaceID) {
4055
+ throw new Error(`The last cloud handoff is ${record.phase}. ${record.workspaceID ? `Inspect workspace ${record.workspaceID} in GitTerm.` : `Look for attempt ${record.attemptID} in GitTerm.`} Local work is unchanged.`);
4056
+ }
4057
+ await gitterm.workspaces.ensureRunning(record.workspaceID, { signal });
4058
+ const runtime = await gitterm.workspaces.getRuntimeAccess(record.workspaceID);
4059
+ const remote = runtimeClient(runtime);
4060
+ let connection = runtime.url;
4061
+ let paired = false;
4062
+ if (new URL(connection).pathname === "/") {
4063
+ try {
4064
+ const pairing = await remote.server.pair({ signal });
4065
+ connection = `${connection.replace(/\/$/, "")}/auth/connect/${encodeURIComponent(pairing.code)}`;
4066
+ paired = true;
4067
+ } catch {}
4068
+ }
4069
+ await askForm(local, record.sessionID, "Your cloud session is ready", [
4070
+ {
4071
+ key: "open",
4072
+ type: "external",
4073
+ url: connection,
4074
+ title: "Open cloud OpenCode",
4075
+ description: paired ? "One-time link; expires in five minutes. Alternatively paste into desktop Connect server." : "Sign in using the workspace credential from your GitTerm dashboard."
4076
+ },
4077
+ {
4078
+ key: "done",
4079
+ type: "boolean",
4080
+ title: "Done",
4081
+ default: true,
4082
+ description: `Open session ${record.sessionID}. Workspace: ${record.workspaceID}. Run /cloud for a fresh connection to this same workspace. Later local changes are not synced. Local work is unchanged.`,
4083
+ required: true
4084
+ }
4085
+ ], signal);
4086
+ }
4087
+
4088
+ // src/index.ts
4089
+ var sessionKey = (sessionID) => `handoff/session/${sessionID}`;
4090
+ async function localClient(options) {
4091
+ const explicit = options.localServerUrl ?? process.env.GITTERM_OPENCODE_LOCAL_SERVER_URL;
4092
+ if (explicit) {
4093
+ const url = new URL(explicit);
4094
+ if (!["http:", "https:"].includes(url.protocol) || !["localhost", "127.0.0.1", "[::1]"].includes(url.hostname) || url.username || url.password) {
4095
+ throw new Error("localServerUrl must be a loopback OpenCode server URL without embedded credentials.");
4096
+ }
4097
+ const password = options.localServerPassword ?? process.env.GITTERM_OPENCODE_LOCAL_SERVER_PASSWORD;
4098
+ return OpenCode2.make({
4099
+ baseUrl: explicit,
4100
+ headers: password ? { Authorization: `Basic ${Buffer.from(`opencode:${password}`).toString("base64")}` } : {},
4101
+ fetch: (input, init) => fetch(input, { ...init, redirect: "error" })
4102
+ });
4103
+ }
4104
+ const endpoint = await Service.discover();
4105
+ if (!endpoint)
4106
+ throw new Error("Cannot discover this OpenCode service. For standalone/custom servers, set localServerUrl and the optional localServerPassword plugin options.");
4107
+ return OpenCode2.make({
4108
+ baseUrl: endpoint.url,
4109
+ headers: Service.headers(endpoint),
4110
+ fetch: (input, init) => fetch(input, { ...init, redirect: "error" })
4111
+ });
4112
+ }
4113
+ var GittermCloudPlugin = Plugin.define({
4114
+ id: "gitterm.cloud",
4115
+ async setup(ctx) {
4116
+ const options = ctx.options;
4117
+ const controller = new AbortController;
4118
+ const busy = new Set;
4119
+ const load = async (sessionID) => await ctx.storage.get(sessionKey(sessionID));
4120
+ const save = async (record) => {
4121
+ await ctx.storage.set(`handoff/attempt/${record.attemptID}`, { ...record });
4122
+ await ctx.storage.set(sessionKey(record.sessionID), { ...record });
4123
+ };
4124
+ const gitterm = () => createGittermClient({ serverUrl: options.serverUrl, token: options.token });
4125
+ await ctx.command.transform((editor) => {
4126
+ editor.add({
4127
+ name: "cloud",
4128
+ description: "Continue in GitTerm, or reconnect to this session's existing cloud workspace",
4129
+ async execute({ sessionID }) {
4130
+ if (busy.has(sessionID))
4131
+ throw new Error("A cloud handoff is already in progress for this session.");
4132
+ busy.add(sessionID);
4133
+ try {
4134
+ if (process.env.WORKSPACE_ID)
4135
+ throw new Error("This session is already running in a GitTerm workspace.");
4136
+ const local = await localClient(options);
4137
+ const source = await ctx.session.get({ sessionID });
4138
+ const connected = await local.session.get({ sessionID }, { signal: controller.signal });
4139
+ if (connected.location.directory !== source.location.directory || connected.time.created !== source.time.created) {
4140
+ throw new Error("/cloud can't reach the OpenCode server holding this session (opencode --standalone uses a private one). Run `opencode serve --port 4096`, open it with `opencode --server http://127.0.0.1:4096`, and set the plugin's localServerUrl to that address.");
4141
+ }
4142
+ const client = gitterm();
4143
+ const previous = await load(sessionID);
4144
+ if (previous?.phase === "ready") {
4145
+ await showConnection(local, client, previous, controller.signal);
4146
+ return;
4147
+ }
4148
+ if (previous) {
4149
+ const answer = await askForm(local, sessionID, "Previous cloud handoff is incomplete", [
4150
+ {
4151
+ key: "retry",
4152
+ type: "boolean",
4153
+ title: "Start a new cloud handoff?",
4154
+ default: false,
4155
+ required: true,
4156
+ description: `Previous attempt: ${previous.attemptID}${previous.workspaceID ? `; workspace: ${previous.workspaceID}` : ""}. Check GitTerm first: that workspace may still be running. It will NOT be deleted by retrying, and another workspace may incur additional charges.`
4157
+ }
4158
+ ], controller.signal);
4159
+ if (answer.retry !== true)
4160
+ throw new HandoffCancelled;
4161
+ }
4162
+ await client.auth.status();
4163
+ const record = await handoffSession(sessionID, {
4164
+ local,
4165
+ gitterm: client,
4166
+ options,
4167
+ signal: controller.signal,
4168
+ save,
4169
+ progress: async (text) => {
4170
+ console.info(`GitTerm: ${text}`);
4171
+ }
4172
+ });
4173
+ await showConnection(local, client, record, controller.signal);
4174
+ } catch (error) {
4175
+ if (!(error instanceof HandoffCancelled))
4176
+ throw error;
4177
+ } finally {
4178
+ busy.delete(sessionID);
4179
+ }
4180
+ }
4181
+ });
4182
+ });
4183
+ return async () => {
4184
+ controller.abort();
4185
+ };
4186
+ }
4187
+ });
4188
+ var src_default = GittermCloudPlugin;
4189
+ export {
4190
+ GittermCloudPlugin,
4191
+ src_default as default
4192
+ };