@willh/subtitle-correction-agent 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +184 -0
  3. package/dist/index.js +4783 -0
  4. package/package.json +44 -0
package/dist/index.js ADDED
@@ -0,0 +1,4783 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from "node:module";
3
+ var __create = Object.create;
4
+ var __getProtoOf = Object.getPrototypeOf;
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __toESM = (mod, isNodeMode, target) => {
9
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
10
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
11
+ for (let key of __getOwnPropNames(mod))
12
+ if (!__hasOwnProp.call(to, key))
13
+ __defProp(to, key, {
14
+ get: () => mod[key],
15
+ enumerable: true
16
+ });
17
+ return to;
18
+ };
19
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
20
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
21
+
22
+ // node_modules/vscode-jsonrpc/lib/common/is.js
23
+ var require_is = __commonJS((exports) => {
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.stringArray = exports.array = exports.func = exports.error = exports.number = exports.string = exports.boolean = undefined;
26
+ function boolean(value) {
27
+ return value === true || value === false;
28
+ }
29
+ exports.boolean = boolean;
30
+ function string(value) {
31
+ return typeof value === "string" || value instanceof String;
32
+ }
33
+ exports.string = string;
34
+ function number(value) {
35
+ return typeof value === "number" || value instanceof Number;
36
+ }
37
+ exports.number = number;
38
+ function error(value) {
39
+ return value instanceof Error;
40
+ }
41
+ exports.error = error;
42
+ function func(value) {
43
+ return typeof value === "function";
44
+ }
45
+ exports.func = func;
46
+ function array(value) {
47
+ return Array.isArray(value);
48
+ }
49
+ exports.array = array;
50
+ function stringArray(value) {
51
+ return array(value) && value.every((elem) => string(elem));
52
+ }
53
+ exports.stringArray = stringArray;
54
+ });
55
+
56
+ // node_modules/vscode-jsonrpc/lib/common/messages.js
57
+ var require_messages = __commonJS((exports) => {
58
+ Object.defineProperty(exports, "__esModule", { value: true });
59
+ exports.Message = exports.NotificationType9 = exports.NotificationType8 = exports.NotificationType7 = exports.NotificationType6 = exports.NotificationType5 = exports.NotificationType4 = exports.NotificationType3 = exports.NotificationType2 = exports.NotificationType1 = exports.NotificationType0 = exports.NotificationType = exports.RequestType9 = exports.RequestType8 = exports.RequestType7 = exports.RequestType6 = exports.RequestType5 = exports.RequestType4 = exports.RequestType3 = exports.RequestType2 = exports.RequestType1 = exports.RequestType = exports.RequestType0 = exports.AbstractMessageSignature = exports.ParameterStructures = exports.ResponseError = exports.ErrorCodes = undefined;
60
+ var is = require_is();
61
+ var ErrorCodes;
62
+ (function(ErrorCodes2) {
63
+ ErrorCodes2.ParseError = -32700;
64
+ ErrorCodes2.InvalidRequest = -32600;
65
+ ErrorCodes2.MethodNotFound = -32601;
66
+ ErrorCodes2.InvalidParams = -32602;
67
+ ErrorCodes2.InternalError = -32603;
68
+ ErrorCodes2.jsonrpcReservedErrorRangeStart = -32099;
69
+ ErrorCodes2.serverErrorStart = -32099;
70
+ ErrorCodes2.MessageWriteError = -32099;
71
+ ErrorCodes2.MessageReadError = -32098;
72
+ ErrorCodes2.PendingResponseRejected = -32097;
73
+ ErrorCodes2.ConnectionInactive = -32096;
74
+ ErrorCodes2.ServerNotInitialized = -32002;
75
+ ErrorCodes2.UnknownErrorCode = -32001;
76
+ ErrorCodes2.jsonrpcReservedErrorRangeEnd = -32000;
77
+ ErrorCodes2.serverErrorEnd = -32000;
78
+ })(ErrorCodes || (exports.ErrorCodes = ErrorCodes = {}));
79
+
80
+ class ResponseError extends Error {
81
+ constructor(code, message, data) {
82
+ super(message);
83
+ this.code = is.number(code) ? code : ErrorCodes.UnknownErrorCode;
84
+ this.data = data;
85
+ Object.setPrototypeOf(this, ResponseError.prototype);
86
+ }
87
+ toJson() {
88
+ const result = {
89
+ code: this.code,
90
+ message: this.message
91
+ };
92
+ if (this.data !== undefined) {
93
+ result.data = this.data;
94
+ }
95
+ return result;
96
+ }
97
+ }
98
+ exports.ResponseError = ResponseError;
99
+
100
+ class ParameterStructures {
101
+ constructor(kind) {
102
+ this.kind = kind;
103
+ }
104
+ static is(value) {
105
+ return value === ParameterStructures.auto || value === ParameterStructures.byName || value === ParameterStructures.byPosition;
106
+ }
107
+ toString() {
108
+ return this.kind;
109
+ }
110
+ }
111
+ exports.ParameterStructures = ParameterStructures;
112
+ ParameterStructures.auto = new ParameterStructures("auto");
113
+ ParameterStructures.byPosition = new ParameterStructures("byPosition");
114
+ ParameterStructures.byName = new ParameterStructures("byName");
115
+
116
+ class AbstractMessageSignature {
117
+ constructor(method, numberOfParams) {
118
+ this.method = method;
119
+ this.numberOfParams = numberOfParams;
120
+ }
121
+ get parameterStructures() {
122
+ return ParameterStructures.auto;
123
+ }
124
+ }
125
+ exports.AbstractMessageSignature = AbstractMessageSignature;
126
+
127
+ class RequestType0 extends AbstractMessageSignature {
128
+ constructor(method) {
129
+ super(method, 0);
130
+ }
131
+ }
132
+ exports.RequestType0 = RequestType0;
133
+
134
+ class RequestType extends AbstractMessageSignature {
135
+ constructor(method, _parameterStructures = ParameterStructures.auto) {
136
+ super(method, 1);
137
+ this._parameterStructures = _parameterStructures;
138
+ }
139
+ get parameterStructures() {
140
+ return this._parameterStructures;
141
+ }
142
+ }
143
+ exports.RequestType = RequestType;
144
+
145
+ class RequestType1 extends AbstractMessageSignature {
146
+ constructor(method, _parameterStructures = ParameterStructures.auto) {
147
+ super(method, 1);
148
+ this._parameterStructures = _parameterStructures;
149
+ }
150
+ get parameterStructures() {
151
+ return this._parameterStructures;
152
+ }
153
+ }
154
+ exports.RequestType1 = RequestType1;
155
+
156
+ class RequestType2 extends AbstractMessageSignature {
157
+ constructor(method) {
158
+ super(method, 2);
159
+ }
160
+ }
161
+ exports.RequestType2 = RequestType2;
162
+
163
+ class RequestType3 extends AbstractMessageSignature {
164
+ constructor(method) {
165
+ super(method, 3);
166
+ }
167
+ }
168
+ exports.RequestType3 = RequestType3;
169
+
170
+ class RequestType4 extends AbstractMessageSignature {
171
+ constructor(method) {
172
+ super(method, 4);
173
+ }
174
+ }
175
+ exports.RequestType4 = RequestType4;
176
+
177
+ class RequestType5 extends AbstractMessageSignature {
178
+ constructor(method) {
179
+ super(method, 5);
180
+ }
181
+ }
182
+ exports.RequestType5 = RequestType5;
183
+
184
+ class RequestType6 extends AbstractMessageSignature {
185
+ constructor(method) {
186
+ super(method, 6);
187
+ }
188
+ }
189
+ exports.RequestType6 = RequestType6;
190
+
191
+ class RequestType7 extends AbstractMessageSignature {
192
+ constructor(method) {
193
+ super(method, 7);
194
+ }
195
+ }
196
+ exports.RequestType7 = RequestType7;
197
+
198
+ class RequestType8 extends AbstractMessageSignature {
199
+ constructor(method) {
200
+ super(method, 8);
201
+ }
202
+ }
203
+ exports.RequestType8 = RequestType8;
204
+
205
+ class RequestType9 extends AbstractMessageSignature {
206
+ constructor(method) {
207
+ super(method, 9);
208
+ }
209
+ }
210
+ exports.RequestType9 = RequestType9;
211
+
212
+ class NotificationType extends AbstractMessageSignature {
213
+ constructor(method, _parameterStructures = ParameterStructures.auto) {
214
+ super(method, 1);
215
+ this._parameterStructures = _parameterStructures;
216
+ }
217
+ get parameterStructures() {
218
+ return this._parameterStructures;
219
+ }
220
+ }
221
+ exports.NotificationType = NotificationType;
222
+
223
+ class NotificationType0 extends AbstractMessageSignature {
224
+ constructor(method) {
225
+ super(method, 0);
226
+ }
227
+ }
228
+ exports.NotificationType0 = NotificationType0;
229
+
230
+ class NotificationType1 extends AbstractMessageSignature {
231
+ constructor(method, _parameterStructures = ParameterStructures.auto) {
232
+ super(method, 1);
233
+ this._parameterStructures = _parameterStructures;
234
+ }
235
+ get parameterStructures() {
236
+ return this._parameterStructures;
237
+ }
238
+ }
239
+ exports.NotificationType1 = NotificationType1;
240
+
241
+ class NotificationType2 extends AbstractMessageSignature {
242
+ constructor(method) {
243
+ super(method, 2);
244
+ }
245
+ }
246
+ exports.NotificationType2 = NotificationType2;
247
+
248
+ class NotificationType3 extends AbstractMessageSignature {
249
+ constructor(method) {
250
+ super(method, 3);
251
+ }
252
+ }
253
+ exports.NotificationType3 = NotificationType3;
254
+
255
+ class NotificationType4 extends AbstractMessageSignature {
256
+ constructor(method) {
257
+ super(method, 4);
258
+ }
259
+ }
260
+ exports.NotificationType4 = NotificationType4;
261
+
262
+ class NotificationType5 extends AbstractMessageSignature {
263
+ constructor(method) {
264
+ super(method, 5);
265
+ }
266
+ }
267
+ exports.NotificationType5 = NotificationType5;
268
+
269
+ class NotificationType6 extends AbstractMessageSignature {
270
+ constructor(method) {
271
+ super(method, 6);
272
+ }
273
+ }
274
+ exports.NotificationType6 = NotificationType6;
275
+
276
+ class NotificationType7 extends AbstractMessageSignature {
277
+ constructor(method) {
278
+ super(method, 7);
279
+ }
280
+ }
281
+ exports.NotificationType7 = NotificationType7;
282
+
283
+ class NotificationType8 extends AbstractMessageSignature {
284
+ constructor(method) {
285
+ super(method, 8);
286
+ }
287
+ }
288
+ exports.NotificationType8 = NotificationType8;
289
+
290
+ class NotificationType9 extends AbstractMessageSignature {
291
+ constructor(method) {
292
+ super(method, 9);
293
+ }
294
+ }
295
+ exports.NotificationType9 = NotificationType9;
296
+ var Message;
297
+ (function(Message2) {
298
+ function isRequest(message) {
299
+ const candidate = message;
300
+ return candidate && is.string(candidate.method) && (is.string(candidate.id) || is.number(candidate.id));
301
+ }
302
+ Message2.isRequest = isRequest;
303
+ function isNotification(message) {
304
+ const candidate = message;
305
+ return candidate && is.string(candidate.method) && message.id === undefined;
306
+ }
307
+ Message2.isNotification = isNotification;
308
+ function isResponse(message) {
309
+ const candidate = message;
310
+ return candidate && (candidate.result !== undefined || !!candidate.error) && (is.string(candidate.id) || is.number(candidate.id) || candidate.id === null);
311
+ }
312
+ Message2.isResponse = isResponse;
313
+ })(Message || (exports.Message = Message = {}));
314
+ });
315
+
316
+ // node_modules/vscode-jsonrpc/lib/common/linkedMap.js
317
+ var require_linkedMap = __commonJS((exports) => {
318
+ var _a;
319
+ Object.defineProperty(exports, "__esModule", { value: true });
320
+ exports.LRUCache = exports.LinkedMap = exports.Touch = undefined;
321
+ var Touch;
322
+ (function(Touch2) {
323
+ Touch2.None = 0;
324
+ Touch2.First = 1;
325
+ Touch2.AsOld = Touch2.First;
326
+ Touch2.Last = 2;
327
+ Touch2.AsNew = Touch2.Last;
328
+ })(Touch || (exports.Touch = Touch = {}));
329
+
330
+ class LinkedMap {
331
+ constructor() {
332
+ this[_a] = "LinkedMap";
333
+ this._map = new Map;
334
+ this._head = undefined;
335
+ this._tail = undefined;
336
+ this._size = 0;
337
+ this._state = 0;
338
+ }
339
+ clear() {
340
+ this._map.clear();
341
+ this._head = undefined;
342
+ this._tail = undefined;
343
+ this._size = 0;
344
+ this._state++;
345
+ }
346
+ isEmpty() {
347
+ return !this._head && !this._tail;
348
+ }
349
+ get size() {
350
+ return this._size;
351
+ }
352
+ get first() {
353
+ return this._head?.value;
354
+ }
355
+ get last() {
356
+ return this._tail?.value;
357
+ }
358
+ has(key) {
359
+ return this._map.has(key);
360
+ }
361
+ get(key, touch = Touch.None) {
362
+ const item = this._map.get(key);
363
+ if (!item) {
364
+ return;
365
+ }
366
+ if (touch !== Touch.None) {
367
+ this.touch(item, touch);
368
+ }
369
+ return item.value;
370
+ }
371
+ set(key, value, touch = Touch.None) {
372
+ let item = this._map.get(key);
373
+ if (item) {
374
+ item.value = value;
375
+ if (touch !== Touch.None) {
376
+ this.touch(item, touch);
377
+ }
378
+ } else {
379
+ item = { key, value, next: undefined, previous: undefined };
380
+ switch (touch) {
381
+ case Touch.None:
382
+ this.addItemLast(item);
383
+ break;
384
+ case Touch.First:
385
+ this.addItemFirst(item);
386
+ break;
387
+ case Touch.Last:
388
+ this.addItemLast(item);
389
+ break;
390
+ default:
391
+ this.addItemLast(item);
392
+ break;
393
+ }
394
+ this._map.set(key, item);
395
+ this._size++;
396
+ }
397
+ return this;
398
+ }
399
+ delete(key) {
400
+ return !!this.remove(key);
401
+ }
402
+ remove(key) {
403
+ const item = this._map.get(key);
404
+ if (!item) {
405
+ return;
406
+ }
407
+ this._map.delete(key);
408
+ this.removeItem(item);
409
+ this._size--;
410
+ return item.value;
411
+ }
412
+ shift() {
413
+ if (!this._head && !this._tail) {
414
+ return;
415
+ }
416
+ if (!this._head || !this._tail) {
417
+ throw new Error("Invalid list");
418
+ }
419
+ const item = this._head;
420
+ this._map.delete(item.key);
421
+ this.removeItem(item);
422
+ this._size--;
423
+ return item.value;
424
+ }
425
+ forEach(callbackfn, thisArg) {
426
+ const state = this._state;
427
+ let current = this._head;
428
+ while (current) {
429
+ if (thisArg) {
430
+ callbackfn.bind(thisArg)(current.value, current.key, this);
431
+ } else {
432
+ callbackfn(current.value, current.key, this);
433
+ }
434
+ if (this._state !== state) {
435
+ throw new Error(`LinkedMap got modified during iteration.`);
436
+ }
437
+ current = current.next;
438
+ }
439
+ }
440
+ keys() {
441
+ const state = this._state;
442
+ let current = this._head;
443
+ const iterator = {
444
+ [Symbol.iterator]: () => {
445
+ return iterator;
446
+ },
447
+ next: () => {
448
+ if (this._state !== state) {
449
+ throw new Error(`LinkedMap got modified during iteration.`);
450
+ }
451
+ if (current) {
452
+ const result = { value: current.key, done: false };
453
+ current = current.next;
454
+ return result;
455
+ } else {
456
+ return { value: undefined, done: true };
457
+ }
458
+ }
459
+ };
460
+ return iterator;
461
+ }
462
+ values() {
463
+ const state = this._state;
464
+ let current = this._head;
465
+ const iterator = {
466
+ [Symbol.iterator]: () => {
467
+ return iterator;
468
+ },
469
+ next: () => {
470
+ if (this._state !== state) {
471
+ throw new Error(`LinkedMap got modified during iteration.`);
472
+ }
473
+ if (current) {
474
+ const result = { value: current.value, done: false };
475
+ current = current.next;
476
+ return result;
477
+ } else {
478
+ return { value: undefined, done: true };
479
+ }
480
+ }
481
+ };
482
+ return iterator;
483
+ }
484
+ entries() {
485
+ const state = this._state;
486
+ let current = this._head;
487
+ const iterator = {
488
+ [Symbol.iterator]: () => {
489
+ return iterator;
490
+ },
491
+ next: () => {
492
+ if (this._state !== state) {
493
+ throw new Error(`LinkedMap got modified during iteration.`);
494
+ }
495
+ if (current) {
496
+ const result = { value: [current.key, current.value], done: false };
497
+ current = current.next;
498
+ return result;
499
+ } else {
500
+ return { value: undefined, done: true };
501
+ }
502
+ }
503
+ };
504
+ return iterator;
505
+ }
506
+ [(_a = Symbol.toStringTag, Symbol.iterator)]() {
507
+ return this.entries();
508
+ }
509
+ trimOld(newSize) {
510
+ if (newSize >= this.size) {
511
+ return;
512
+ }
513
+ if (newSize === 0) {
514
+ this.clear();
515
+ return;
516
+ }
517
+ let current = this._head;
518
+ let currentSize = this.size;
519
+ while (current && currentSize > newSize) {
520
+ this._map.delete(current.key);
521
+ current = current.next;
522
+ currentSize--;
523
+ }
524
+ this._head = current;
525
+ this._size = currentSize;
526
+ if (current) {
527
+ current.previous = undefined;
528
+ }
529
+ this._state++;
530
+ }
531
+ addItemFirst(item) {
532
+ if (!this._head && !this._tail) {
533
+ this._tail = item;
534
+ } else if (!this._head) {
535
+ throw new Error("Invalid list");
536
+ } else {
537
+ item.next = this._head;
538
+ this._head.previous = item;
539
+ }
540
+ this._head = item;
541
+ this._state++;
542
+ }
543
+ addItemLast(item) {
544
+ if (!this._head && !this._tail) {
545
+ this._head = item;
546
+ } else if (!this._tail) {
547
+ throw new Error("Invalid list");
548
+ } else {
549
+ item.previous = this._tail;
550
+ this._tail.next = item;
551
+ }
552
+ this._tail = item;
553
+ this._state++;
554
+ }
555
+ removeItem(item) {
556
+ if (item === this._head && item === this._tail) {
557
+ this._head = undefined;
558
+ this._tail = undefined;
559
+ } else if (item === this._head) {
560
+ if (!item.next) {
561
+ throw new Error("Invalid list");
562
+ }
563
+ item.next.previous = undefined;
564
+ this._head = item.next;
565
+ } else if (item === this._tail) {
566
+ if (!item.previous) {
567
+ throw new Error("Invalid list");
568
+ }
569
+ item.previous.next = undefined;
570
+ this._tail = item.previous;
571
+ } else {
572
+ const next = item.next;
573
+ const previous = item.previous;
574
+ if (!next || !previous) {
575
+ throw new Error("Invalid list");
576
+ }
577
+ next.previous = previous;
578
+ previous.next = next;
579
+ }
580
+ item.next = undefined;
581
+ item.previous = undefined;
582
+ this._state++;
583
+ }
584
+ touch(item, touch) {
585
+ if (!this._head || !this._tail) {
586
+ throw new Error("Invalid list");
587
+ }
588
+ if (touch !== Touch.First && touch !== Touch.Last) {
589
+ return;
590
+ }
591
+ if (touch === Touch.First) {
592
+ if (item === this._head) {
593
+ return;
594
+ }
595
+ const next = item.next;
596
+ const previous = item.previous;
597
+ if (item === this._tail) {
598
+ previous.next = undefined;
599
+ this._tail = previous;
600
+ } else {
601
+ next.previous = previous;
602
+ previous.next = next;
603
+ }
604
+ item.previous = undefined;
605
+ item.next = this._head;
606
+ this._head.previous = item;
607
+ this._head = item;
608
+ this._state++;
609
+ } else if (touch === Touch.Last) {
610
+ if (item === this._tail) {
611
+ return;
612
+ }
613
+ const next = item.next;
614
+ const previous = item.previous;
615
+ if (item === this._head) {
616
+ next.previous = undefined;
617
+ this._head = next;
618
+ } else {
619
+ next.previous = previous;
620
+ previous.next = next;
621
+ }
622
+ item.next = undefined;
623
+ item.previous = this._tail;
624
+ this._tail.next = item;
625
+ this._tail = item;
626
+ this._state++;
627
+ }
628
+ }
629
+ toJSON() {
630
+ const data = [];
631
+ this.forEach((value, key) => {
632
+ data.push([key, value]);
633
+ });
634
+ return data;
635
+ }
636
+ fromJSON(data) {
637
+ this.clear();
638
+ for (const [key, value] of data) {
639
+ this.set(key, value);
640
+ }
641
+ }
642
+ }
643
+ exports.LinkedMap = LinkedMap;
644
+
645
+ class LRUCache extends LinkedMap {
646
+ constructor(limit, ratio = 1) {
647
+ super();
648
+ this._limit = limit;
649
+ this._ratio = Math.min(Math.max(0, ratio), 1);
650
+ }
651
+ get limit() {
652
+ return this._limit;
653
+ }
654
+ set limit(limit) {
655
+ this._limit = limit;
656
+ this.checkTrim();
657
+ }
658
+ get ratio() {
659
+ return this._ratio;
660
+ }
661
+ set ratio(ratio) {
662
+ this._ratio = Math.min(Math.max(0, ratio), 1);
663
+ this.checkTrim();
664
+ }
665
+ get(key, touch = Touch.AsNew) {
666
+ return super.get(key, touch);
667
+ }
668
+ peek(key) {
669
+ return super.get(key, Touch.None);
670
+ }
671
+ set(key, value) {
672
+ super.set(key, value, Touch.Last);
673
+ this.checkTrim();
674
+ return this;
675
+ }
676
+ checkTrim() {
677
+ if (this.size > this._limit) {
678
+ this.trimOld(Math.round(this._limit * this._ratio));
679
+ }
680
+ }
681
+ }
682
+ exports.LRUCache = LRUCache;
683
+ });
684
+
685
+ // node_modules/vscode-jsonrpc/lib/common/disposable.js
686
+ var require_disposable = __commonJS((exports) => {
687
+ Object.defineProperty(exports, "__esModule", { value: true });
688
+ exports.Disposable = undefined;
689
+ var Disposable;
690
+ (function(Disposable2) {
691
+ function create(func) {
692
+ return {
693
+ dispose: func
694
+ };
695
+ }
696
+ Disposable2.create = create;
697
+ })(Disposable || (exports.Disposable = Disposable = {}));
698
+ });
699
+
700
+ // node_modules/vscode-jsonrpc/lib/common/ral.js
701
+ var require_ral = __commonJS((exports) => {
702
+ Object.defineProperty(exports, "__esModule", { value: true });
703
+ var _ral;
704
+ function RAL() {
705
+ if (_ral === undefined) {
706
+ throw new Error(`No runtime abstraction layer installed`);
707
+ }
708
+ return _ral;
709
+ }
710
+ (function(RAL2) {
711
+ function install(ral) {
712
+ if (ral === undefined) {
713
+ throw new Error(`No runtime abstraction layer provided`);
714
+ }
715
+ _ral = ral;
716
+ }
717
+ RAL2.install = install;
718
+ })(RAL || (RAL = {}));
719
+ exports.default = RAL;
720
+ });
721
+
722
+ // node_modules/vscode-jsonrpc/lib/common/events.js
723
+ var require_events = __commonJS((exports) => {
724
+ Object.defineProperty(exports, "__esModule", { value: true });
725
+ exports.Emitter = exports.Event = undefined;
726
+ var ral_1 = require_ral();
727
+ var Event;
728
+ (function(Event2) {
729
+ const _disposable = { dispose() {} };
730
+ Event2.None = function() {
731
+ return _disposable;
732
+ };
733
+ })(Event || (exports.Event = Event = {}));
734
+
735
+ class CallbackList {
736
+ add(callback, context = null, bucket) {
737
+ if (!this._callbacks) {
738
+ this._callbacks = [];
739
+ this._contexts = [];
740
+ }
741
+ this._callbacks.push(callback);
742
+ this._contexts.push(context);
743
+ if (Array.isArray(bucket)) {
744
+ bucket.push({ dispose: () => this.remove(callback, context) });
745
+ }
746
+ }
747
+ remove(callback, context = null) {
748
+ if (!this._callbacks) {
749
+ return;
750
+ }
751
+ let foundCallbackWithDifferentContext = false;
752
+ for (let i = 0, len = this._callbacks.length;i < len; i++) {
753
+ if (this._callbacks[i] === callback) {
754
+ if (this._contexts[i] === context) {
755
+ this._callbacks.splice(i, 1);
756
+ this._contexts.splice(i, 1);
757
+ return;
758
+ } else {
759
+ foundCallbackWithDifferentContext = true;
760
+ }
761
+ }
762
+ }
763
+ if (foundCallbackWithDifferentContext) {
764
+ throw new Error("When adding a listener with a context, you should remove it with the same context");
765
+ }
766
+ }
767
+ invoke(...args) {
768
+ if (!this._callbacks) {
769
+ return [];
770
+ }
771
+ const ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);
772
+ for (let i = 0, len = callbacks.length;i < len; i++) {
773
+ try {
774
+ ret.push(callbacks[i].apply(contexts[i], args));
775
+ } catch (e) {
776
+ (0, ral_1.default)().console.error(e);
777
+ }
778
+ }
779
+ return ret;
780
+ }
781
+ isEmpty() {
782
+ return !this._callbacks || this._callbacks.length === 0;
783
+ }
784
+ dispose() {
785
+ this._callbacks = undefined;
786
+ this._contexts = undefined;
787
+ }
788
+ }
789
+
790
+ class Emitter {
791
+ constructor(_options) {
792
+ this._options = _options;
793
+ }
794
+ get event() {
795
+ if (!this._event) {
796
+ this._event = (listener, thisArgs, disposables) => {
797
+ if (!this._callbacks) {
798
+ this._callbacks = new CallbackList;
799
+ }
800
+ if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) {
801
+ this._options.onFirstListenerAdd(this);
802
+ }
803
+ this._callbacks.add(listener, thisArgs);
804
+ const result = {
805
+ dispose: () => {
806
+ if (!this._callbacks) {
807
+ return;
808
+ }
809
+ this._callbacks.remove(listener, thisArgs);
810
+ result.dispose = Emitter._noop;
811
+ if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) {
812
+ this._options.onLastListenerRemove(this);
813
+ }
814
+ }
815
+ };
816
+ if (Array.isArray(disposables)) {
817
+ disposables.push(result);
818
+ }
819
+ return result;
820
+ };
821
+ }
822
+ return this._event;
823
+ }
824
+ fire(event) {
825
+ if (this._callbacks) {
826
+ this._callbacks.invoke.call(this._callbacks, event);
827
+ }
828
+ }
829
+ dispose() {
830
+ if (this._callbacks) {
831
+ this._callbacks.dispose();
832
+ this._callbacks = undefined;
833
+ }
834
+ }
835
+ }
836
+ exports.Emitter = Emitter;
837
+ Emitter._noop = function() {};
838
+ });
839
+
840
+ // node_modules/vscode-jsonrpc/lib/common/cancellation.js
841
+ var require_cancellation = __commonJS((exports) => {
842
+ Object.defineProperty(exports, "__esModule", { value: true });
843
+ exports.CancellationTokenSource = exports.CancellationToken = undefined;
844
+ var ral_1 = require_ral();
845
+ var Is = require_is();
846
+ var events_1 = require_events();
847
+ var CancellationToken;
848
+ (function(CancellationToken2) {
849
+ CancellationToken2.None = Object.freeze({
850
+ isCancellationRequested: false,
851
+ onCancellationRequested: events_1.Event.None
852
+ });
853
+ CancellationToken2.Cancelled = Object.freeze({
854
+ isCancellationRequested: true,
855
+ onCancellationRequested: events_1.Event.None
856
+ });
857
+ function is(value) {
858
+ const candidate = value;
859
+ return candidate && (candidate === CancellationToken2.None || candidate === CancellationToken2.Cancelled || Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested);
860
+ }
861
+ CancellationToken2.is = is;
862
+ })(CancellationToken || (exports.CancellationToken = CancellationToken = {}));
863
+ var shortcutEvent = Object.freeze(function(callback, context) {
864
+ const handle = (0, ral_1.default)().timer.setTimeout(callback.bind(context), 0);
865
+ return { dispose() {
866
+ handle.dispose();
867
+ } };
868
+ });
869
+
870
+ class MutableToken {
871
+ constructor() {
872
+ this._isCancelled = false;
873
+ }
874
+ cancel() {
875
+ if (!this._isCancelled) {
876
+ this._isCancelled = true;
877
+ if (this._emitter) {
878
+ this._emitter.fire(undefined);
879
+ this.dispose();
880
+ }
881
+ }
882
+ }
883
+ get isCancellationRequested() {
884
+ return this._isCancelled;
885
+ }
886
+ get onCancellationRequested() {
887
+ if (this._isCancelled) {
888
+ return shortcutEvent;
889
+ }
890
+ if (!this._emitter) {
891
+ this._emitter = new events_1.Emitter;
892
+ }
893
+ return this._emitter.event;
894
+ }
895
+ dispose() {
896
+ if (this._emitter) {
897
+ this._emitter.dispose();
898
+ this._emitter = undefined;
899
+ }
900
+ }
901
+ }
902
+
903
+ class CancellationTokenSource {
904
+ get token() {
905
+ if (!this._token) {
906
+ this._token = new MutableToken;
907
+ }
908
+ return this._token;
909
+ }
910
+ cancel() {
911
+ if (!this._token) {
912
+ this._token = CancellationToken.Cancelled;
913
+ } else {
914
+ this._token.cancel();
915
+ }
916
+ }
917
+ dispose() {
918
+ if (!this._token) {
919
+ this._token = CancellationToken.None;
920
+ } else if (this._token instanceof MutableToken) {
921
+ this._token.dispose();
922
+ }
923
+ }
924
+ }
925
+ exports.CancellationTokenSource = CancellationTokenSource;
926
+ });
927
+
928
+ // node_modules/vscode-jsonrpc/lib/common/sharedArrayCancellation.js
929
+ var require_sharedArrayCancellation = __commonJS((exports) => {
930
+ Object.defineProperty(exports, "__esModule", { value: true });
931
+ exports.SharedArrayReceiverStrategy = exports.SharedArraySenderStrategy = undefined;
932
+ var cancellation_1 = require_cancellation();
933
+ var CancellationState;
934
+ (function(CancellationState2) {
935
+ CancellationState2.Continue = 0;
936
+ CancellationState2.Cancelled = 1;
937
+ })(CancellationState || (CancellationState = {}));
938
+
939
+ class SharedArraySenderStrategy {
940
+ constructor() {
941
+ this.buffers = new Map;
942
+ }
943
+ enableCancellation(request) {
944
+ if (request.id === null) {
945
+ return;
946
+ }
947
+ const buffer = new SharedArrayBuffer(4);
948
+ const data = new Int32Array(buffer, 0, 1);
949
+ data[0] = CancellationState.Continue;
950
+ this.buffers.set(request.id, buffer);
951
+ request.$cancellationData = buffer;
952
+ }
953
+ async sendCancellation(_conn, id) {
954
+ const buffer = this.buffers.get(id);
955
+ if (buffer === undefined) {
956
+ return;
957
+ }
958
+ const data = new Int32Array(buffer, 0, 1);
959
+ Atomics.store(data, 0, CancellationState.Cancelled);
960
+ }
961
+ cleanup(id) {
962
+ this.buffers.delete(id);
963
+ }
964
+ dispose() {
965
+ this.buffers.clear();
966
+ }
967
+ }
968
+ exports.SharedArraySenderStrategy = SharedArraySenderStrategy;
969
+
970
+ class SharedArrayBufferCancellationToken {
971
+ constructor(buffer) {
972
+ this.data = new Int32Array(buffer, 0, 1);
973
+ }
974
+ get isCancellationRequested() {
975
+ return Atomics.load(this.data, 0) === CancellationState.Cancelled;
976
+ }
977
+ get onCancellationRequested() {
978
+ throw new Error(`Cancellation over SharedArrayBuffer doesn't support cancellation events`);
979
+ }
980
+ }
981
+
982
+ class SharedArrayBufferCancellationTokenSource {
983
+ constructor(buffer) {
984
+ this.token = new SharedArrayBufferCancellationToken(buffer);
985
+ }
986
+ cancel() {}
987
+ dispose() {}
988
+ }
989
+
990
+ class SharedArrayReceiverStrategy {
991
+ constructor() {
992
+ this.kind = "request";
993
+ }
994
+ createCancellationTokenSource(request) {
995
+ const buffer = request.$cancellationData;
996
+ if (buffer === undefined) {
997
+ return new cancellation_1.CancellationTokenSource;
998
+ }
999
+ return new SharedArrayBufferCancellationTokenSource(buffer);
1000
+ }
1001
+ }
1002
+ exports.SharedArrayReceiverStrategy = SharedArrayReceiverStrategy;
1003
+ });
1004
+
1005
+ // node_modules/vscode-jsonrpc/lib/common/semaphore.js
1006
+ var require_semaphore = __commonJS((exports) => {
1007
+ Object.defineProperty(exports, "__esModule", { value: true });
1008
+ exports.Semaphore = undefined;
1009
+ var ral_1 = require_ral();
1010
+
1011
+ class Semaphore {
1012
+ constructor(capacity = 1) {
1013
+ if (capacity <= 0) {
1014
+ throw new Error("Capacity must be greater than 0");
1015
+ }
1016
+ this._capacity = capacity;
1017
+ this._active = 0;
1018
+ this._waiting = [];
1019
+ }
1020
+ lock(thunk) {
1021
+ return new Promise((resolve, reject) => {
1022
+ this._waiting.push({ thunk, resolve, reject });
1023
+ this.runNext();
1024
+ });
1025
+ }
1026
+ get active() {
1027
+ return this._active;
1028
+ }
1029
+ runNext() {
1030
+ if (this._waiting.length === 0 || this._active === this._capacity) {
1031
+ return;
1032
+ }
1033
+ (0, ral_1.default)().timer.setImmediate(() => this.doRunNext());
1034
+ }
1035
+ doRunNext() {
1036
+ if (this._waiting.length === 0 || this._active === this._capacity) {
1037
+ return;
1038
+ }
1039
+ const next = this._waiting.shift();
1040
+ this._active++;
1041
+ if (this._active > this._capacity) {
1042
+ throw new Error(`To many thunks active`);
1043
+ }
1044
+ try {
1045
+ const result = next.thunk();
1046
+ if (result instanceof Promise) {
1047
+ result.then((value) => {
1048
+ this._active--;
1049
+ next.resolve(value);
1050
+ this.runNext();
1051
+ }, (err) => {
1052
+ this._active--;
1053
+ next.reject(err);
1054
+ this.runNext();
1055
+ });
1056
+ } else {
1057
+ this._active--;
1058
+ next.resolve(result);
1059
+ this.runNext();
1060
+ }
1061
+ } catch (err) {
1062
+ this._active--;
1063
+ next.reject(err);
1064
+ this.runNext();
1065
+ }
1066
+ }
1067
+ }
1068
+ exports.Semaphore = Semaphore;
1069
+ });
1070
+
1071
+ // node_modules/vscode-jsonrpc/lib/common/messageReader.js
1072
+ var require_messageReader = __commonJS((exports) => {
1073
+ Object.defineProperty(exports, "__esModule", { value: true });
1074
+ exports.ReadableStreamMessageReader = exports.AbstractMessageReader = exports.MessageReader = undefined;
1075
+ var ral_1 = require_ral();
1076
+ var Is = require_is();
1077
+ var events_1 = require_events();
1078
+ var semaphore_1 = require_semaphore();
1079
+ var MessageReader;
1080
+ (function(MessageReader2) {
1081
+ function is(value) {
1082
+ let candidate = value;
1083
+ return candidate && Is.func(candidate.listen) && Is.func(candidate.dispose) && Is.func(candidate.onError) && Is.func(candidate.onClose) && Is.func(candidate.onPartialMessage);
1084
+ }
1085
+ MessageReader2.is = is;
1086
+ })(MessageReader || (exports.MessageReader = MessageReader = {}));
1087
+
1088
+ class AbstractMessageReader {
1089
+ constructor() {
1090
+ this.errorEmitter = new events_1.Emitter;
1091
+ this.closeEmitter = new events_1.Emitter;
1092
+ this.partialMessageEmitter = new events_1.Emitter;
1093
+ }
1094
+ dispose() {
1095
+ this.errorEmitter.dispose();
1096
+ this.closeEmitter.dispose();
1097
+ }
1098
+ get onError() {
1099
+ return this.errorEmitter.event;
1100
+ }
1101
+ fireError(error) {
1102
+ this.errorEmitter.fire(this.asError(error));
1103
+ }
1104
+ get onClose() {
1105
+ return this.closeEmitter.event;
1106
+ }
1107
+ fireClose() {
1108
+ this.closeEmitter.fire(undefined);
1109
+ }
1110
+ get onPartialMessage() {
1111
+ return this.partialMessageEmitter.event;
1112
+ }
1113
+ firePartialMessage(info) {
1114
+ this.partialMessageEmitter.fire(info);
1115
+ }
1116
+ asError(error) {
1117
+ if (error instanceof Error) {
1118
+ return error;
1119
+ } else {
1120
+ return new Error(`Reader received error. Reason: ${Is.string(error.message) ? error.message : "unknown"}`);
1121
+ }
1122
+ }
1123
+ }
1124
+ exports.AbstractMessageReader = AbstractMessageReader;
1125
+ var ResolvedMessageReaderOptions;
1126
+ (function(ResolvedMessageReaderOptions2) {
1127
+ function fromOptions(options) {
1128
+ let charset;
1129
+ let result;
1130
+ let contentDecoder;
1131
+ const contentDecoders = new Map;
1132
+ let contentTypeDecoder;
1133
+ const contentTypeDecoders = new Map;
1134
+ if (options === undefined || typeof options === "string") {
1135
+ charset = options ?? "utf-8";
1136
+ } else {
1137
+ charset = options.charset ?? "utf-8";
1138
+ if (options.contentDecoder !== undefined) {
1139
+ contentDecoder = options.contentDecoder;
1140
+ contentDecoders.set(contentDecoder.name, contentDecoder);
1141
+ }
1142
+ if (options.contentDecoders !== undefined) {
1143
+ for (const decoder of options.contentDecoders) {
1144
+ contentDecoders.set(decoder.name, decoder);
1145
+ }
1146
+ }
1147
+ if (options.contentTypeDecoder !== undefined) {
1148
+ contentTypeDecoder = options.contentTypeDecoder;
1149
+ contentTypeDecoders.set(contentTypeDecoder.name, contentTypeDecoder);
1150
+ }
1151
+ if (options.contentTypeDecoders !== undefined) {
1152
+ for (const decoder of options.contentTypeDecoders) {
1153
+ contentTypeDecoders.set(decoder.name, decoder);
1154
+ }
1155
+ }
1156
+ }
1157
+ if (contentTypeDecoder === undefined) {
1158
+ contentTypeDecoder = (0, ral_1.default)().applicationJson.decoder;
1159
+ contentTypeDecoders.set(contentTypeDecoder.name, contentTypeDecoder);
1160
+ }
1161
+ return { charset, contentDecoder, contentDecoders, contentTypeDecoder, contentTypeDecoders };
1162
+ }
1163
+ ResolvedMessageReaderOptions2.fromOptions = fromOptions;
1164
+ })(ResolvedMessageReaderOptions || (ResolvedMessageReaderOptions = {}));
1165
+
1166
+ class ReadableStreamMessageReader extends AbstractMessageReader {
1167
+ constructor(readable, options) {
1168
+ super();
1169
+ this.readable = readable;
1170
+ this.options = ResolvedMessageReaderOptions.fromOptions(options);
1171
+ this.buffer = (0, ral_1.default)().messageBuffer.create(this.options.charset);
1172
+ this._partialMessageTimeout = 1e4;
1173
+ this.nextMessageLength = -1;
1174
+ this.messageToken = 0;
1175
+ this.readSemaphore = new semaphore_1.Semaphore(1);
1176
+ }
1177
+ set partialMessageTimeout(timeout) {
1178
+ this._partialMessageTimeout = timeout;
1179
+ }
1180
+ get partialMessageTimeout() {
1181
+ return this._partialMessageTimeout;
1182
+ }
1183
+ listen(callback) {
1184
+ this.nextMessageLength = -1;
1185
+ this.messageToken = 0;
1186
+ this.partialMessageTimer = undefined;
1187
+ this.callback = callback;
1188
+ const result = this.readable.onData((data) => {
1189
+ this.onData(data);
1190
+ });
1191
+ this.readable.onError((error) => this.fireError(error));
1192
+ this.readable.onClose(() => this.fireClose());
1193
+ return result;
1194
+ }
1195
+ onData(data) {
1196
+ try {
1197
+ this.buffer.append(data);
1198
+ while (true) {
1199
+ if (this.nextMessageLength === -1) {
1200
+ const headers = this.buffer.tryReadHeaders(true);
1201
+ if (!headers) {
1202
+ return;
1203
+ }
1204
+ const contentLength = headers.get("content-length");
1205
+ if (!contentLength) {
1206
+ this.fireError(new Error(`Header must provide a Content-Length property.
1207
+ ${JSON.stringify(Object.fromEntries(headers))}`));
1208
+ return;
1209
+ }
1210
+ const length = parseInt(contentLength);
1211
+ if (isNaN(length)) {
1212
+ this.fireError(new Error(`Content-Length value must be a number. Got ${contentLength}`));
1213
+ return;
1214
+ }
1215
+ this.nextMessageLength = length;
1216
+ }
1217
+ const body = this.buffer.tryReadBody(this.nextMessageLength);
1218
+ if (body === undefined) {
1219
+ this.setPartialMessageTimer();
1220
+ return;
1221
+ }
1222
+ this.clearPartialMessageTimer();
1223
+ this.nextMessageLength = -1;
1224
+ this.readSemaphore.lock(async () => {
1225
+ const bytes = this.options.contentDecoder !== undefined ? await this.options.contentDecoder.decode(body) : body;
1226
+ const message = await this.options.contentTypeDecoder.decode(bytes, this.options);
1227
+ this.callback(message);
1228
+ }).catch((error) => {
1229
+ this.fireError(error);
1230
+ });
1231
+ }
1232
+ } catch (error) {
1233
+ this.fireError(error);
1234
+ }
1235
+ }
1236
+ clearPartialMessageTimer() {
1237
+ if (this.partialMessageTimer) {
1238
+ this.partialMessageTimer.dispose();
1239
+ this.partialMessageTimer = undefined;
1240
+ }
1241
+ }
1242
+ setPartialMessageTimer() {
1243
+ this.clearPartialMessageTimer();
1244
+ if (this._partialMessageTimeout <= 0) {
1245
+ return;
1246
+ }
1247
+ this.partialMessageTimer = (0, ral_1.default)().timer.setTimeout((token, timeout) => {
1248
+ this.partialMessageTimer = undefined;
1249
+ if (token === this.messageToken) {
1250
+ this.firePartialMessage({ messageToken: token, waitingTime: timeout });
1251
+ this.setPartialMessageTimer();
1252
+ }
1253
+ }, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout);
1254
+ }
1255
+ }
1256
+ exports.ReadableStreamMessageReader = ReadableStreamMessageReader;
1257
+ });
1258
+
1259
+ // node_modules/vscode-jsonrpc/lib/common/messageWriter.js
1260
+ var require_messageWriter = __commonJS((exports) => {
1261
+ Object.defineProperty(exports, "__esModule", { value: true });
1262
+ exports.WriteableStreamMessageWriter = exports.AbstractMessageWriter = exports.MessageWriter = undefined;
1263
+ var ral_1 = require_ral();
1264
+ var Is = require_is();
1265
+ var semaphore_1 = require_semaphore();
1266
+ var events_1 = require_events();
1267
+ var ContentLength = "Content-Length: ";
1268
+ var CRLF = `\r
1269
+ `;
1270
+ var MessageWriter;
1271
+ (function(MessageWriter2) {
1272
+ function is(value) {
1273
+ let candidate = value;
1274
+ return candidate && Is.func(candidate.dispose) && Is.func(candidate.onClose) && Is.func(candidate.onError) && Is.func(candidate.write);
1275
+ }
1276
+ MessageWriter2.is = is;
1277
+ })(MessageWriter || (exports.MessageWriter = MessageWriter = {}));
1278
+
1279
+ class AbstractMessageWriter {
1280
+ constructor() {
1281
+ this.errorEmitter = new events_1.Emitter;
1282
+ this.closeEmitter = new events_1.Emitter;
1283
+ }
1284
+ dispose() {
1285
+ this.errorEmitter.dispose();
1286
+ this.closeEmitter.dispose();
1287
+ }
1288
+ get onError() {
1289
+ return this.errorEmitter.event;
1290
+ }
1291
+ fireError(error, message, count) {
1292
+ this.errorEmitter.fire([this.asError(error), message, count]);
1293
+ }
1294
+ get onClose() {
1295
+ return this.closeEmitter.event;
1296
+ }
1297
+ fireClose() {
1298
+ this.closeEmitter.fire(undefined);
1299
+ }
1300
+ asError(error) {
1301
+ if (error instanceof Error) {
1302
+ return error;
1303
+ } else {
1304
+ return new Error(`Writer received error. Reason: ${Is.string(error.message) ? error.message : "unknown"}`);
1305
+ }
1306
+ }
1307
+ }
1308
+ exports.AbstractMessageWriter = AbstractMessageWriter;
1309
+ var ResolvedMessageWriterOptions;
1310
+ (function(ResolvedMessageWriterOptions2) {
1311
+ function fromOptions(options) {
1312
+ if (options === undefined || typeof options === "string") {
1313
+ return { charset: options ?? "utf-8", contentTypeEncoder: (0, ral_1.default)().applicationJson.encoder };
1314
+ } else {
1315
+ return { charset: options.charset ?? "utf-8", contentEncoder: options.contentEncoder, contentTypeEncoder: options.contentTypeEncoder ?? (0, ral_1.default)().applicationJson.encoder };
1316
+ }
1317
+ }
1318
+ ResolvedMessageWriterOptions2.fromOptions = fromOptions;
1319
+ })(ResolvedMessageWriterOptions || (ResolvedMessageWriterOptions = {}));
1320
+
1321
+ class WriteableStreamMessageWriter extends AbstractMessageWriter {
1322
+ constructor(writable, options) {
1323
+ super();
1324
+ this.writable = writable;
1325
+ this.options = ResolvedMessageWriterOptions.fromOptions(options);
1326
+ this.errorCount = 0;
1327
+ this.writeSemaphore = new semaphore_1.Semaphore(1);
1328
+ this.writable.onError((error) => this.fireError(error));
1329
+ this.writable.onClose(() => this.fireClose());
1330
+ }
1331
+ async write(msg) {
1332
+ return this.writeSemaphore.lock(async () => {
1333
+ const payload = this.options.contentTypeEncoder.encode(msg, this.options).then((buffer) => {
1334
+ if (this.options.contentEncoder !== undefined) {
1335
+ return this.options.contentEncoder.encode(buffer);
1336
+ } else {
1337
+ return buffer;
1338
+ }
1339
+ });
1340
+ return payload.then((buffer) => {
1341
+ const headers = [];
1342
+ headers.push(ContentLength, buffer.byteLength.toString(), CRLF);
1343
+ headers.push(CRLF);
1344
+ return this.doWrite(msg, headers, buffer);
1345
+ }, (error) => {
1346
+ this.fireError(error);
1347
+ throw error;
1348
+ });
1349
+ });
1350
+ }
1351
+ async doWrite(msg, headers, data) {
1352
+ try {
1353
+ await this.writable.write(headers.join(""), "ascii");
1354
+ return this.writable.write(data);
1355
+ } catch (error) {
1356
+ this.handleError(error, msg);
1357
+ return Promise.reject(error);
1358
+ }
1359
+ }
1360
+ handleError(error, msg) {
1361
+ this.errorCount++;
1362
+ this.fireError(error, msg, this.errorCount);
1363
+ }
1364
+ end() {
1365
+ this.writable.end();
1366
+ }
1367
+ }
1368
+ exports.WriteableStreamMessageWriter = WriteableStreamMessageWriter;
1369
+ });
1370
+
1371
+ // node_modules/vscode-jsonrpc/lib/common/messageBuffer.js
1372
+ var require_messageBuffer = __commonJS((exports) => {
1373
+ Object.defineProperty(exports, "__esModule", { value: true });
1374
+ exports.AbstractMessageBuffer = undefined;
1375
+ var CR = 13;
1376
+ var LF = 10;
1377
+ var CRLF = `\r
1378
+ `;
1379
+
1380
+ class AbstractMessageBuffer {
1381
+ constructor(encoding = "utf-8") {
1382
+ this._encoding = encoding;
1383
+ this._chunks = [];
1384
+ this._totalLength = 0;
1385
+ }
1386
+ get encoding() {
1387
+ return this._encoding;
1388
+ }
1389
+ append(chunk) {
1390
+ const toAppend = typeof chunk === "string" ? this.fromString(chunk, this._encoding) : chunk;
1391
+ this._chunks.push(toAppend);
1392
+ this._totalLength += toAppend.byteLength;
1393
+ }
1394
+ tryReadHeaders(lowerCaseKeys = false) {
1395
+ if (this._chunks.length === 0) {
1396
+ return;
1397
+ }
1398
+ let state = 0;
1399
+ let chunkIndex = 0;
1400
+ let offset = 0;
1401
+ let chunkBytesRead = 0;
1402
+ row:
1403
+ while (chunkIndex < this._chunks.length) {
1404
+ const chunk = this._chunks[chunkIndex];
1405
+ offset = 0;
1406
+ column:
1407
+ while (offset < chunk.length) {
1408
+ const value = chunk[offset];
1409
+ switch (value) {
1410
+ case CR:
1411
+ switch (state) {
1412
+ case 0:
1413
+ state = 1;
1414
+ break;
1415
+ case 2:
1416
+ state = 3;
1417
+ break;
1418
+ default:
1419
+ state = 0;
1420
+ }
1421
+ break;
1422
+ case LF:
1423
+ switch (state) {
1424
+ case 1:
1425
+ state = 2;
1426
+ break;
1427
+ case 3:
1428
+ state = 4;
1429
+ offset++;
1430
+ break row;
1431
+ default:
1432
+ state = 0;
1433
+ }
1434
+ break;
1435
+ default:
1436
+ state = 0;
1437
+ }
1438
+ offset++;
1439
+ }
1440
+ chunkBytesRead += chunk.byteLength;
1441
+ chunkIndex++;
1442
+ }
1443
+ if (state !== 4) {
1444
+ return;
1445
+ }
1446
+ const buffer = this._read(chunkBytesRead + offset);
1447
+ const result = new Map;
1448
+ const headers = this.toString(buffer, "ascii").split(CRLF);
1449
+ if (headers.length < 2) {
1450
+ return result;
1451
+ }
1452
+ for (let i = 0;i < headers.length - 2; i++) {
1453
+ const header = headers[i];
1454
+ const index = header.indexOf(":");
1455
+ if (index === -1) {
1456
+ throw new Error(`Message header must separate key and value using ':'
1457
+ ${header}`);
1458
+ }
1459
+ const key = header.substr(0, index);
1460
+ const value = header.substr(index + 1).trim();
1461
+ result.set(lowerCaseKeys ? key.toLowerCase() : key, value);
1462
+ }
1463
+ return result;
1464
+ }
1465
+ tryReadBody(length) {
1466
+ if (this._totalLength < length) {
1467
+ return;
1468
+ }
1469
+ return this._read(length);
1470
+ }
1471
+ get numberOfBytes() {
1472
+ return this._totalLength;
1473
+ }
1474
+ _read(byteCount) {
1475
+ if (byteCount === 0) {
1476
+ return this.emptyBuffer();
1477
+ }
1478
+ if (byteCount > this._totalLength) {
1479
+ throw new Error(`Cannot read so many bytes!`);
1480
+ }
1481
+ if (this._chunks[0].byteLength === byteCount) {
1482
+ const chunk = this._chunks[0];
1483
+ this._chunks.shift();
1484
+ this._totalLength -= byteCount;
1485
+ return this.asNative(chunk);
1486
+ }
1487
+ if (this._chunks[0].byteLength > byteCount) {
1488
+ const chunk = this._chunks[0];
1489
+ const result2 = this.asNative(chunk, byteCount);
1490
+ this._chunks[0] = chunk.slice(byteCount);
1491
+ this._totalLength -= byteCount;
1492
+ return result2;
1493
+ }
1494
+ const result = this.allocNative(byteCount);
1495
+ let resultOffset = 0;
1496
+ let chunkIndex = 0;
1497
+ while (byteCount > 0) {
1498
+ const chunk = this._chunks[chunkIndex];
1499
+ if (chunk.byteLength > byteCount) {
1500
+ const chunkPart = chunk.slice(0, byteCount);
1501
+ result.set(chunkPart, resultOffset);
1502
+ resultOffset += byteCount;
1503
+ this._chunks[chunkIndex] = chunk.slice(byteCount);
1504
+ this._totalLength -= byteCount;
1505
+ byteCount -= byteCount;
1506
+ } else {
1507
+ result.set(chunk, resultOffset);
1508
+ resultOffset += chunk.byteLength;
1509
+ this._chunks.shift();
1510
+ this._totalLength -= chunk.byteLength;
1511
+ byteCount -= chunk.byteLength;
1512
+ }
1513
+ }
1514
+ return result;
1515
+ }
1516
+ }
1517
+ exports.AbstractMessageBuffer = AbstractMessageBuffer;
1518
+ });
1519
+
1520
+ // node_modules/vscode-jsonrpc/lib/common/connection.js
1521
+ var require_connection = __commonJS((exports) => {
1522
+ Object.defineProperty(exports, "__esModule", { value: true });
1523
+ exports.createMessageConnection = exports.ConnectionOptions = exports.MessageStrategy = exports.CancellationStrategy = exports.CancellationSenderStrategy = exports.CancellationReceiverStrategy = exports.RequestCancellationReceiverStrategy = exports.IdCancellationReceiverStrategy = exports.ConnectionStrategy = exports.ConnectionError = exports.ConnectionErrors = exports.LogTraceNotification = exports.SetTraceNotification = exports.TraceFormat = exports.TraceValues = exports.Trace = exports.NullLogger = exports.ProgressType = exports.ProgressToken = undefined;
1524
+ var ral_1 = require_ral();
1525
+ var Is = require_is();
1526
+ var messages_1 = require_messages();
1527
+ var linkedMap_1 = require_linkedMap();
1528
+ var events_1 = require_events();
1529
+ var cancellation_1 = require_cancellation();
1530
+ var CancelNotification;
1531
+ (function(CancelNotification2) {
1532
+ CancelNotification2.type = new messages_1.NotificationType("$/cancelRequest");
1533
+ })(CancelNotification || (CancelNotification = {}));
1534
+ var ProgressToken;
1535
+ (function(ProgressToken2) {
1536
+ function is(value) {
1537
+ return typeof value === "string" || typeof value === "number";
1538
+ }
1539
+ ProgressToken2.is = is;
1540
+ })(ProgressToken || (exports.ProgressToken = ProgressToken = {}));
1541
+ var ProgressNotification;
1542
+ (function(ProgressNotification2) {
1543
+ ProgressNotification2.type = new messages_1.NotificationType("$/progress");
1544
+ })(ProgressNotification || (ProgressNotification = {}));
1545
+
1546
+ class ProgressType {
1547
+ constructor() {}
1548
+ }
1549
+ exports.ProgressType = ProgressType;
1550
+ var StarRequestHandler;
1551
+ (function(StarRequestHandler2) {
1552
+ function is(value) {
1553
+ return Is.func(value);
1554
+ }
1555
+ StarRequestHandler2.is = is;
1556
+ })(StarRequestHandler || (StarRequestHandler = {}));
1557
+ exports.NullLogger = Object.freeze({
1558
+ error: () => {},
1559
+ warn: () => {},
1560
+ info: () => {},
1561
+ log: () => {}
1562
+ });
1563
+ var Trace;
1564
+ (function(Trace2) {
1565
+ Trace2[Trace2["Off"] = 0] = "Off";
1566
+ Trace2[Trace2["Messages"] = 1] = "Messages";
1567
+ Trace2[Trace2["Compact"] = 2] = "Compact";
1568
+ Trace2[Trace2["Verbose"] = 3] = "Verbose";
1569
+ })(Trace || (exports.Trace = Trace = {}));
1570
+ var TraceValues;
1571
+ (function(TraceValues2) {
1572
+ TraceValues2.Off = "off";
1573
+ TraceValues2.Messages = "messages";
1574
+ TraceValues2.Compact = "compact";
1575
+ TraceValues2.Verbose = "verbose";
1576
+ })(TraceValues || (exports.TraceValues = TraceValues = {}));
1577
+ (function(Trace2) {
1578
+ function fromString(value) {
1579
+ if (!Is.string(value)) {
1580
+ return Trace2.Off;
1581
+ }
1582
+ value = value.toLowerCase();
1583
+ switch (value) {
1584
+ case "off":
1585
+ return Trace2.Off;
1586
+ case "messages":
1587
+ return Trace2.Messages;
1588
+ case "compact":
1589
+ return Trace2.Compact;
1590
+ case "verbose":
1591
+ return Trace2.Verbose;
1592
+ default:
1593
+ return Trace2.Off;
1594
+ }
1595
+ }
1596
+ Trace2.fromString = fromString;
1597
+ function toString(value) {
1598
+ switch (value) {
1599
+ case Trace2.Off:
1600
+ return "off";
1601
+ case Trace2.Messages:
1602
+ return "messages";
1603
+ case Trace2.Compact:
1604
+ return "compact";
1605
+ case Trace2.Verbose:
1606
+ return "verbose";
1607
+ default:
1608
+ return "off";
1609
+ }
1610
+ }
1611
+ Trace2.toString = toString;
1612
+ })(Trace || (exports.Trace = Trace = {}));
1613
+ var TraceFormat;
1614
+ (function(TraceFormat2) {
1615
+ TraceFormat2["Text"] = "text";
1616
+ TraceFormat2["JSON"] = "json";
1617
+ })(TraceFormat || (exports.TraceFormat = TraceFormat = {}));
1618
+ (function(TraceFormat2) {
1619
+ function fromString(value) {
1620
+ if (!Is.string(value)) {
1621
+ return TraceFormat2.Text;
1622
+ }
1623
+ value = value.toLowerCase();
1624
+ if (value === "json") {
1625
+ return TraceFormat2.JSON;
1626
+ } else {
1627
+ return TraceFormat2.Text;
1628
+ }
1629
+ }
1630
+ TraceFormat2.fromString = fromString;
1631
+ })(TraceFormat || (exports.TraceFormat = TraceFormat = {}));
1632
+ var SetTraceNotification;
1633
+ (function(SetTraceNotification2) {
1634
+ SetTraceNotification2.type = new messages_1.NotificationType("$/setTrace");
1635
+ })(SetTraceNotification || (exports.SetTraceNotification = SetTraceNotification = {}));
1636
+ var LogTraceNotification;
1637
+ (function(LogTraceNotification2) {
1638
+ LogTraceNotification2.type = new messages_1.NotificationType("$/logTrace");
1639
+ })(LogTraceNotification || (exports.LogTraceNotification = LogTraceNotification = {}));
1640
+ var ConnectionErrors;
1641
+ (function(ConnectionErrors2) {
1642
+ ConnectionErrors2[ConnectionErrors2["Closed"] = 1] = "Closed";
1643
+ ConnectionErrors2[ConnectionErrors2["Disposed"] = 2] = "Disposed";
1644
+ ConnectionErrors2[ConnectionErrors2["AlreadyListening"] = 3] = "AlreadyListening";
1645
+ })(ConnectionErrors || (exports.ConnectionErrors = ConnectionErrors = {}));
1646
+
1647
+ class ConnectionError extends Error {
1648
+ constructor(code, message) {
1649
+ super(message);
1650
+ this.code = code;
1651
+ Object.setPrototypeOf(this, ConnectionError.prototype);
1652
+ }
1653
+ }
1654
+ exports.ConnectionError = ConnectionError;
1655
+ var ConnectionStrategy;
1656
+ (function(ConnectionStrategy2) {
1657
+ function is(value) {
1658
+ const candidate = value;
1659
+ return candidate && Is.func(candidate.cancelUndispatched);
1660
+ }
1661
+ ConnectionStrategy2.is = is;
1662
+ })(ConnectionStrategy || (exports.ConnectionStrategy = ConnectionStrategy = {}));
1663
+ var IdCancellationReceiverStrategy;
1664
+ (function(IdCancellationReceiverStrategy2) {
1665
+ function is(value) {
1666
+ const candidate = value;
1667
+ return candidate && (candidate.kind === undefined || candidate.kind === "id") && Is.func(candidate.createCancellationTokenSource) && (candidate.dispose === undefined || Is.func(candidate.dispose));
1668
+ }
1669
+ IdCancellationReceiverStrategy2.is = is;
1670
+ })(IdCancellationReceiverStrategy || (exports.IdCancellationReceiverStrategy = IdCancellationReceiverStrategy = {}));
1671
+ var RequestCancellationReceiverStrategy;
1672
+ (function(RequestCancellationReceiverStrategy2) {
1673
+ function is(value) {
1674
+ const candidate = value;
1675
+ return candidate && candidate.kind === "request" && Is.func(candidate.createCancellationTokenSource) && (candidate.dispose === undefined || Is.func(candidate.dispose));
1676
+ }
1677
+ RequestCancellationReceiverStrategy2.is = is;
1678
+ })(RequestCancellationReceiverStrategy || (exports.RequestCancellationReceiverStrategy = RequestCancellationReceiverStrategy = {}));
1679
+ var CancellationReceiverStrategy;
1680
+ (function(CancellationReceiverStrategy2) {
1681
+ CancellationReceiverStrategy2.Message = Object.freeze({
1682
+ createCancellationTokenSource(_) {
1683
+ return new cancellation_1.CancellationTokenSource;
1684
+ }
1685
+ });
1686
+ function is(value) {
1687
+ return IdCancellationReceiverStrategy.is(value) || RequestCancellationReceiverStrategy.is(value);
1688
+ }
1689
+ CancellationReceiverStrategy2.is = is;
1690
+ })(CancellationReceiverStrategy || (exports.CancellationReceiverStrategy = CancellationReceiverStrategy = {}));
1691
+ var CancellationSenderStrategy;
1692
+ (function(CancellationSenderStrategy2) {
1693
+ CancellationSenderStrategy2.Message = Object.freeze({
1694
+ sendCancellation(conn, id) {
1695
+ return conn.sendNotification(CancelNotification.type, { id });
1696
+ },
1697
+ cleanup(_) {}
1698
+ });
1699
+ function is(value) {
1700
+ const candidate = value;
1701
+ return candidate && Is.func(candidate.sendCancellation) && Is.func(candidate.cleanup);
1702
+ }
1703
+ CancellationSenderStrategy2.is = is;
1704
+ })(CancellationSenderStrategy || (exports.CancellationSenderStrategy = CancellationSenderStrategy = {}));
1705
+ var CancellationStrategy;
1706
+ (function(CancellationStrategy2) {
1707
+ CancellationStrategy2.Message = Object.freeze({
1708
+ receiver: CancellationReceiverStrategy.Message,
1709
+ sender: CancellationSenderStrategy.Message
1710
+ });
1711
+ function is(value) {
1712
+ const candidate = value;
1713
+ return candidate && CancellationReceiverStrategy.is(candidate.receiver) && CancellationSenderStrategy.is(candidate.sender);
1714
+ }
1715
+ CancellationStrategy2.is = is;
1716
+ })(CancellationStrategy || (exports.CancellationStrategy = CancellationStrategy = {}));
1717
+ var MessageStrategy;
1718
+ (function(MessageStrategy2) {
1719
+ function is(value) {
1720
+ const candidate = value;
1721
+ return candidate && Is.func(candidate.handleMessage);
1722
+ }
1723
+ MessageStrategy2.is = is;
1724
+ })(MessageStrategy || (exports.MessageStrategy = MessageStrategy = {}));
1725
+ var ConnectionOptions;
1726
+ (function(ConnectionOptions2) {
1727
+ function is(value) {
1728
+ const candidate = value;
1729
+ return candidate && (CancellationStrategy.is(candidate.cancellationStrategy) || ConnectionStrategy.is(candidate.connectionStrategy) || MessageStrategy.is(candidate.messageStrategy));
1730
+ }
1731
+ ConnectionOptions2.is = is;
1732
+ })(ConnectionOptions || (exports.ConnectionOptions = ConnectionOptions = {}));
1733
+ var ConnectionState;
1734
+ (function(ConnectionState2) {
1735
+ ConnectionState2[ConnectionState2["New"] = 1] = "New";
1736
+ ConnectionState2[ConnectionState2["Listening"] = 2] = "Listening";
1737
+ ConnectionState2[ConnectionState2["Closed"] = 3] = "Closed";
1738
+ ConnectionState2[ConnectionState2["Disposed"] = 4] = "Disposed";
1739
+ })(ConnectionState || (ConnectionState = {}));
1740
+ function createMessageConnection(messageReader, messageWriter, _logger, options) {
1741
+ const logger = _logger !== undefined ? _logger : exports.NullLogger;
1742
+ let sequenceNumber = 0;
1743
+ let notificationSequenceNumber = 0;
1744
+ let unknownResponseSequenceNumber = 0;
1745
+ const version = "2.0";
1746
+ let starRequestHandler = undefined;
1747
+ const requestHandlers = new Map;
1748
+ let starNotificationHandler = undefined;
1749
+ const notificationHandlers = new Map;
1750
+ const progressHandlers = new Map;
1751
+ let timer;
1752
+ let messageQueue = new linkedMap_1.LinkedMap;
1753
+ let responsePromises = new Map;
1754
+ let knownCanceledRequests = new Set;
1755
+ let requestTokens = new Map;
1756
+ let trace = Trace.Off;
1757
+ let traceFormat = TraceFormat.Text;
1758
+ let tracer;
1759
+ let state = ConnectionState.New;
1760
+ const errorEmitter = new events_1.Emitter;
1761
+ const closeEmitter = new events_1.Emitter;
1762
+ const unhandledNotificationEmitter = new events_1.Emitter;
1763
+ const unhandledProgressEmitter = new events_1.Emitter;
1764
+ const disposeEmitter = new events_1.Emitter;
1765
+ const cancellationStrategy = options && options.cancellationStrategy ? options.cancellationStrategy : CancellationStrategy.Message;
1766
+ function createRequestQueueKey(id) {
1767
+ if (id === null) {
1768
+ throw new Error(`Can't send requests with id null since the response can't be correlated.`);
1769
+ }
1770
+ return "req-" + id.toString();
1771
+ }
1772
+ function createResponseQueueKey(id) {
1773
+ if (id === null) {
1774
+ return "res-unknown-" + (++unknownResponseSequenceNumber).toString();
1775
+ } else {
1776
+ return "res-" + id.toString();
1777
+ }
1778
+ }
1779
+ function createNotificationQueueKey() {
1780
+ return "not-" + (++notificationSequenceNumber).toString();
1781
+ }
1782
+ function addMessageToQueue(queue, message) {
1783
+ if (messages_1.Message.isRequest(message)) {
1784
+ queue.set(createRequestQueueKey(message.id), message);
1785
+ } else if (messages_1.Message.isResponse(message)) {
1786
+ queue.set(createResponseQueueKey(message.id), message);
1787
+ } else {
1788
+ queue.set(createNotificationQueueKey(), message);
1789
+ }
1790
+ }
1791
+ function cancelUndispatched(_message) {
1792
+ return;
1793
+ }
1794
+ function isListening() {
1795
+ return state === ConnectionState.Listening;
1796
+ }
1797
+ function isClosed() {
1798
+ return state === ConnectionState.Closed;
1799
+ }
1800
+ function isDisposed() {
1801
+ return state === ConnectionState.Disposed;
1802
+ }
1803
+ function closeHandler() {
1804
+ if (state === ConnectionState.New || state === ConnectionState.Listening) {
1805
+ state = ConnectionState.Closed;
1806
+ closeEmitter.fire(undefined);
1807
+ }
1808
+ }
1809
+ function readErrorHandler(error) {
1810
+ errorEmitter.fire([error, undefined, undefined]);
1811
+ }
1812
+ function writeErrorHandler(data) {
1813
+ errorEmitter.fire(data);
1814
+ }
1815
+ messageReader.onClose(closeHandler);
1816
+ messageReader.onError(readErrorHandler);
1817
+ messageWriter.onClose(closeHandler);
1818
+ messageWriter.onError(writeErrorHandler);
1819
+ function triggerMessageQueue() {
1820
+ if (timer || messageQueue.size === 0) {
1821
+ return;
1822
+ }
1823
+ timer = (0, ral_1.default)().timer.setImmediate(() => {
1824
+ timer = undefined;
1825
+ processMessageQueue();
1826
+ });
1827
+ }
1828
+ function handleMessage(message) {
1829
+ if (messages_1.Message.isRequest(message)) {
1830
+ handleRequest(message);
1831
+ } else if (messages_1.Message.isNotification(message)) {
1832
+ handleNotification(message);
1833
+ } else if (messages_1.Message.isResponse(message)) {
1834
+ handleResponse(message);
1835
+ } else {
1836
+ handleInvalidMessage(message);
1837
+ }
1838
+ }
1839
+ function processMessageQueue() {
1840
+ if (messageQueue.size === 0) {
1841
+ return;
1842
+ }
1843
+ const message = messageQueue.shift();
1844
+ try {
1845
+ const messageStrategy = options?.messageStrategy;
1846
+ if (MessageStrategy.is(messageStrategy)) {
1847
+ messageStrategy.handleMessage(message, handleMessage);
1848
+ } else {
1849
+ handleMessage(message);
1850
+ }
1851
+ } finally {
1852
+ triggerMessageQueue();
1853
+ }
1854
+ }
1855
+ const callback = (message) => {
1856
+ try {
1857
+ if (messages_1.Message.isNotification(message) && message.method === CancelNotification.type.method) {
1858
+ const cancelId = message.params.id;
1859
+ const key = createRequestQueueKey(cancelId);
1860
+ const toCancel = messageQueue.get(key);
1861
+ if (messages_1.Message.isRequest(toCancel)) {
1862
+ const strategy = options?.connectionStrategy;
1863
+ const response = strategy && strategy.cancelUndispatched ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel);
1864
+ if (response && (response.error !== undefined || response.result !== undefined)) {
1865
+ messageQueue.delete(key);
1866
+ requestTokens.delete(cancelId);
1867
+ response.id = toCancel.id;
1868
+ traceSendingResponse(response, message.method, Date.now());
1869
+ messageWriter.write(response).catch(() => logger.error(`Sending response for canceled message failed.`));
1870
+ return;
1871
+ }
1872
+ }
1873
+ const cancellationToken = requestTokens.get(cancelId);
1874
+ if (cancellationToken !== undefined) {
1875
+ cancellationToken.cancel();
1876
+ traceReceivedNotification(message);
1877
+ return;
1878
+ } else {
1879
+ knownCanceledRequests.add(cancelId);
1880
+ }
1881
+ }
1882
+ addMessageToQueue(messageQueue, message);
1883
+ } finally {
1884
+ triggerMessageQueue();
1885
+ }
1886
+ };
1887
+ function handleRequest(requestMessage) {
1888
+ if (isDisposed()) {
1889
+ return;
1890
+ }
1891
+ function reply(resultOrError, method, startTime2) {
1892
+ const message = {
1893
+ jsonrpc: version,
1894
+ id: requestMessage.id
1895
+ };
1896
+ if (resultOrError instanceof messages_1.ResponseError) {
1897
+ message.error = resultOrError.toJson();
1898
+ } else {
1899
+ message.result = resultOrError === undefined ? null : resultOrError;
1900
+ }
1901
+ traceSendingResponse(message, method, startTime2);
1902
+ messageWriter.write(message).catch(() => logger.error(`Sending response failed.`));
1903
+ }
1904
+ function replyError(error, method, startTime2) {
1905
+ const message = {
1906
+ jsonrpc: version,
1907
+ id: requestMessage.id,
1908
+ error: error.toJson()
1909
+ };
1910
+ traceSendingResponse(message, method, startTime2);
1911
+ messageWriter.write(message).catch(() => logger.error(`Sending response failed.`));
1912
+ }
1913
+ function replySuccess(result, method, startTime2) {
1914
+ if (result === undefined) {
1915
+ result = null;
1916
+ }
1917
+ const message = {
1918
+ jsonrpc: version,
1919
+ id: requestMessage.id,
1920
+ result
1921
+ };
1922
+ traceSendingResponse(message, method, startTime2);
1923
+ messageWriter.write(message).catch(() => logger.error(`Sending response failed.`));
1924
+ }
1925
+ traceReceivedRequest(requestMessage);
1926
+ const element = requestHandlers.get(requestMessage.method);
1927
+ let type;
1928
+ let requestHandler;
1929
+ if (element) {
1930
+ type = element.type;
1931
+ requestHandler = element.handler;
1932
+ }
1933
+ const startTime = Date.now();
1934
+ if (requestHandler || starRequestHandler) {
1935
+ const tokenKey = requestMessage.id ?? String(Date.now());
1936
+ const cancellationSource = IdCancellationReceiverStrategy.is(cancellationStrategy.receiver) ? cancellationStrategy.receiver.createCancellationTokenSource(tokenKey) : cancellationStrategy.receiver.createCancellationTokenSource(requestMessage);
1937
+ if (requestMessage.id !== null && knownCanceledRequests.has(requestMessage.id)) {
1938
+ cancellationSource.cancel();
1939
+ }
1940
+ if (requestMessage.id !== null) {
1941
+ requestTokens.set(tokenKey, cancellationSource);
1942
+ }
1943
+ try {
1944
+ let handlerResult;
1945
+ if (requestHandler) {
1946
+ if (requestMessage.params === undefined) {
1947
+ if (type !== undefined && type.numberOfParams !== 0) {
1948
+ replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines ${type.numberOfParams} params but received none.`), requestMessage.method, startTime);
1949
+ return;
1950
+ }
1951
+ handlerResult = requestHandler(cancellationSource.token);
1952
+ } else if (Array.isArray(requestMessage.params)) {
1953
+ if (type !== undefined && type.parameterStructures === messages_1.ParameterStructures.byName) {
1954
+ replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines parameters by name but received parameters by position`), requestMessage.method, startTime);
1955
+ return;
1956
+ }
1957
+ handlerResult = requestHandler(...requestMessage.params, cancellationSource.token);
1958
+ } else {
1959
+ if (type !== undefined && type.parameterStructures === messages_1.ParameterStructures.byPosition) {
1960
+ replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines parameters by position but received parameters by name`), requestMessage.method, startTime);
1961
+ return;
1962
+ }
1963
+ handlerResult = requestHandler(requestMessage.params, cancellationSource.token);
1964
+ }
1965
+ } else if (starRequestHandler) {
1966
+ handlerResult = starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token);
1967
+ }
1968
+ const promise = handlerResult;
1969
+ if (!handlerResult) {
1970
+ requestTokens.delete(tokenKey);
1971
+ replySuccess(handlerResult, requestMessage.method, startTime);
1972
+ } else if (promise.then) {
1973
+ promise.then((resultOrError) => {
1974
+ requestTokens.delete(tokenKey);
1975
+ reply(resultOrError, requestMessage.method, startTime);
1976
+ }, (error) => {
1977
+ requestTokens.delete(tokenKey);
1978
+ if (error instanceof messages_1.ResponseError) {
1979
+ replyError(error, requestMessage.method, startTime);
1980
+ } else if (error && Is.string(error.message)) {
1981
+ replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
1982
+ } else {
1983
+ replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
1984
+ }
1985
+ });
1986
+ } else {
1987
+ requestTokens.delete(tokenKey);
1988
+ reply(handlerResult, requestMessage.method, startTime);
1989
+ }
1990
+ } catch (error) {
1991
+ requestTokens.delete(tokenKey);
1992
+ if (error instanceof messages_1.ResponseError) {
1993
+ reply(error, requestMessage.method, startTime);
1994
+ } else if (error && Is.string(error.message)) {
1995
+ replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
1996
+ } else {
1997
+ replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
1998
+ }
1999
+ }
2000
+ } else {
2001
+ replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime);
2002
+ }
2003
+ }
2004
+ function handleResponse(responseMessage) {
2005
+ if (isDisposed()) {
2006
+ return;
2007
+ }
2008
+ if (responseMessage.id === null) {
2009
+ if (responseMessage.error) {
2010
+ logger.error(`Received response message without id: Error is:
2011
+ ${JSON.stringify(responseMessage.error, undefined, 4)}`);
2012
+ } else {
2013
+ logger.error(`Received response message without id. No further error information provided.`);
2014
+ }
2015
+ } else {
2016
+ const key = responseMessage.id;
2017
+ const responsePromise = responsePromises.get(key);
2018
+ traceReceivedResponse(responseMessage, responsePromise);
2019
+ if (responsePromise !== undefined) {
2020
+ responsePromises.delete(key);
2021
+ try {
2022
+ if (responseMessage.error) {
2023
+ const error = responseMessage.error;
2024
+ responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data));
2025
+ } else if (responseMessage.result !== undefined) {
2026
+ responsePromise.resolve(responseMessage.result);
2027
+ } else {
2028
+ throw new Error("Should never happen.");
2029
+ }
2030
+ } catch (error) {
2031
+ if (error.message) {
2032
+ logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`);
2033
+ } else {
2034
+ logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`);
2035
+ }
2036
+ }
2037
+ }
2038
+ }
2039
+ }
2040
+ function handleNotification(message) {
2041
+ if (isDisposed()) {
2042
+ return;
2043
+ }
2044
+ let type = undefined;
2045
+ let notificationHandler;
2046
+ if (message.method === CancelNotification.type.method) {
2047
+ const cancelId = message.params.id;
2048
+ knownCanceledRequests.delete(cancelId);
2049
+ traceReceivedNotification(message);
2050
+ return;
2051
+ } else {
2052
+ const element = notificationHandlers.get(message.method);
2053
+ if (element) {
2054
+ notificationHandler = element.handler;
2055
+ type = element.type;
2056
+ }
2057
+ }
2058
+ if (notificationHandler || starNotificationHandler) {
2059
+ try {
2060
+ traceReceivedNotification(message);
2061
+ if (notificationHandler) {
2062
+ if (message.params === undefined) {
2063
+ if (type !== undefined) {
2064
+ if (type.numberOfParams !== 0 && type.parameterStructures !== messages_1.ParameterStructures.byName) {
2065
+ logger.error(`Notification ${message.method} defines ${type.numberOfParams} params but received none.`);
2066
+ }
2067
+ }
2068
+ notificationHandler();
2069
+ } else if (Array.isArray(message.params)) {
2070
+ const params = message.params;
2071
+ if (message.method === ProgressNotification.type.method && params.length === 2 && ProgressToken.is(params[0])) {
2072
+ notificationHandler({ token: params[0], value: params[1] });
2073
+ } else {
2074
+ if (type !== undefined) {
2075
+ if (type.parameterStructures === messages_1.ParameterStructures.byName) {
2076
+ logger.error(`Notification ${message.method} defines parameters by name but received parameters by position`);
2077
+ }
2078
+ if (type.numberOfParams !== message.params.length) {
2079
+ logger.error(`Notification ${message.method} defines ${type.numberOfParams} params but received ${params.length} arguments`);
2080
+ }
2081
+ }
2082
+ notificationHandler(...params);
2083
+ }
2084
+ } else {
2085
+ if (type !== undefined && type.parameterStructures === messages_1.ParameterStructures.byPosition) {
2086
+ logger.error(`Notification ${message.method} defines parameters by position but received parameters by name`);
2087
+ }
2088
+ notificationHandler(message.params);
2089
+ }
2090
+ } else if (starNotificationHandler) {
2091
+ starNotificationHandler(message.method, message.params);
2092
+ }
2093
+ } catch (error) {
2094
+ if (error.message) {
2095
+ logger.error(`Notification handler '${message.method}' failed with message: ${error.message}`);
2096
+ } else {
2097
+ logger.error(`Notification handler '${message.method}' failed unexpectedly.`);
2098
+ }
2099
+ }
2100
+ } else {
2101
+ unhandledNotificationEmitter.fire(message);
2102
+ }
2103
+ }
2104
+ function handleInvalidMessage(message) {
2105
+ if (!message) {
2106
+ logger.error("Received empty message.");
2107
+ return;
2108
+ }
2109
+ logger.error(`Received message which is neither a response nor a notification message:
2110
+ ${JSON.stringify(message, null, 4)}`);
2111
+ const responseMessage = message;
2112
+ if (Is.string(responseMessage.id) || Is.number(responseMessage.id)) {
2113
+ const key = responseMessage.id;
2114
+ const responseHandler = responsePromises.get(key);
2115
+ if (responseHandler) {
2116
+ responseHandler.reject(new Error("The received response has neither a result nor an error property."));
2117
+ }
2118
+ }
2119
+ }
2120
+ function stringifyTrace(params) {
2121
+ if (params === undefined || params === null) {
2122
+ return;
2123
+ }
2124
+ switch (trace) {
2125
+ case Trace.Verbose:
2126
+ return JSON.stringify(params, null, 4);
2127
+ case Trace.Compact:
2128
+ return JSON.stringify(params);
2129
+ default:
2130
+ return;
2131
+ }
2132
+ }
2133
+ function traceSendingRequest(message) {
2134
+ if (trace === Trace.Off || !tracer) {
2135
+ return;
2136
+ }
2137
+ if (traceFormat === TraceFormat.Text) {
2138
+ let data = undefined;
2139
+ if ((trace === Trace.Verbose || trace === Trace.Compact) && message.params) {
2140
+ data = `Params: ${stringifyTrace(message.params)}
2141
+
2142
+ `;
2143
+ }
2144
+ tracer.log(`Sending request '${message.method} - (${message.id})'.`, data);
2145
+ } else {
2146
+ logLSPMessage("send-request", message);
2147
+ }
2148
+ }
2149
+ function traceSendingNotification(message) {
2150
+ if (trace === Trace.Off || !tracer) {
2151
+ return;
2152
+ }
2153
+ if (traceFormat === TraceFormat.Text) {
2154
+ let data = undefined;
2155
+ if (trace === Trace.Verbose || trace === Trace.Compact) {
2156
+ if (message.params) {
2157
+ data = `Params: ${stringifyTrace(message.params)}
2158
+
2159
+ `;
2160
+ } else {
2161
+ data = `No parameters provided.
2162
+
2163
+ `;
2164
+ }
2165
+ }
2166
+ tracer.log(`Sending notification '${message.method}'.`, data);
2167
+ } else {
2168
+ logLSPMessage("send-notification", message);
2169
+ }
2170
+ }
2171
+ function traceSendingResponse(message, method, startTime) {
2172
+ if (trace === Trace.Off || !tracer) {
2173
+ return;
2174
+ }
2175
+ if (traceFormat === TraceFormat.Text) {
2176
+ let data = undefined;
2177
+ if (trace === Trace.Verbose || trace === Trace.Compact) {
2178
+ if (message.error && message.error.data) {
2179
+ data = `Error data: ${stringifyTrace(message.error.data)}
2180
+
2181
+ `;
2182
+ } else {
2183
+ if (message.result) {
2184
+ data = `Result: ${stringifyTrace(message.result)}
2185
+
2186
+ `;
2187
+ } else if (message.error === undefined) {
2188
+ data = `No result returned.
2189
+
2190
+ `;
2191
+ }
2192
+ }
2193
+ }
2194
+ tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data);
2195
+ } else {
2196
+ logLSPMessage("send-response", message);
2197
+ }
2198
+ }
2199
+ function traceReceivedRequest(message) {
2200
+ if (trace === Trace.Off || !tracer) {
2201
+ return;
2202
+ }
2203
+ if (traceFormat === TraceFormat.Text) {
2204
+ let data = undefined;
2205
+ if ((trace === Trace.Verbose || trace === Trace.Compact) && message.params) {
2206
+ data = `Params: ${stringifyTrace(message.params)}
2207
+
2208
+ `;
2209
+ }
2210
+ tracer.log(`Received request '${message.method} - (${message.id})'.`, data);
2211
+ } else {
2212
+ logLSPMessage("receive-request", message);
2213
+ }
2214
+ }
2215
+ function traceReceivedNotification(message) {
2216
+ if (trace === Trace.Off || !tracer || message.method === LogTraceNotification.type.method) {
2217
+ return;
2218
+ }
2219
+ if (traceFormat === TraceFormat.Text) {
2220
+ let data = undefined;
2221
+ if (trace === Trace.Verbose || trace === Trace.Compact) {
2222
+ if (message.params) {
2223
+ data = `Params: ${stringifyTrace(message.params)}
2224
+
2225
+ `;
2226
+ } else {
2227
+ data = `No parameters provided.
2228
+
2229
+ `;
2230
+ }
2231
+ }
2232
+ tracer.log(`Received notification '${message.method}'.`, data);
2233
+ } else {
2234
+ logLSPMessage("receive-notification", message);
2235
+ }
2236
+ }
2237
+ function traceReceivedResponse(message, responsePromise) {
2238
+ if (trace === Trace.Off || !tracer) {
2239
+ return;
2240
+ }
2241
+ if (traceFormat === TraceFormat.Text) {
2242
+ let data = undefined;
2243
+ if (trace === Trace.Verbose || trace === Trace.Compact) {
2244
+ if (message.error && message.error.data) {
2245
+ data = `Error data: ${stringifyTrace(message.error.data)}
2246
+
2247
+ `;
2248
+ } else {
2249
+ if (message.result) {
2250
+ data = `Result: ${stringifyTrace(message.result)}
2251
+
2252
+ `;
2253
+ } else if (message.error === undefined) {
2254
+ data = `No result returned.
2255
+
2256
+ `;
2257
+ }
2258
+ }
2259
+ }
2260
+ if (responsePromise) {
2261
+ const error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : "";
2262
+ tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data);
2263
+ } else {
2264
+ tracer.log(`Received response ${message.id} without active response promise.`, data);
2265
+ }
2266
+ } else {
2267
+ logLSPMessage("receive-response", message);
2268
+ }
2269
+ }
2270
+ function logLSPMessage(type, message) {
2271
+ if (!tracer || trace === Trace.Off) {
2272
+ return;
2273
+ }
2274
+ const lspMessage = {
2275
+ isLSPMessage: true,
2276
+ type,
2277
+ message,
2278
+ timestamp: Date.now()
2279
+ };
2280
+ tracer.log(lspMessage);
2281
+ }
2282
+ function throwIfClosedOrDisposed() {
2283
+ if (isClosed()) {
2284
+ throw new ConnectionError(ConnectionErrors.Closed, "Connection is closed.");
2285
+ }
2286
+ if (isDisposed()) {
2287
+ throw new ConnectionError(ConnectionErrors.Disposed, "Connection is disposed.");
2288
+ }
2289
+ }
2290
+ function throwIfListening() {
2291
+ if (isListening()) {
2292
+ throw new ConnectionError(ConnectionErrors.AlreadyListening, "Connection is already listening");
2293
+ }
2294
+ }
2295
+ function throwIfNotListening() {
2296
+ if (!isListening()) {
2297
+ throw new Error("Call listen() first.");
2298
+ }
2299
+ }
2300
+ function undefinedToNull(param) {
2301
+ if (param === undefined) {
2302
+ return null;
2303
+ } else {
2304
+ return param;
2305
+ }
2306
+ }
2307
+ function nullToUndefined(param) {
2308
+ if (param === null) {
2309
+ return;
2310
+ } else {
2311
+ return param;
2312
+ }
2313
+ }
2314
+ function isNamedParam(param) {
2315
+ return param !== undefined && param !== null && !Array.isArray(param) && typeof param === "object";
2316
+ }
2317
+ function computeSingleParam(parameterStructures, param) {
2318
+ switch (parameterStructures) {
2319
+ case messages_1.ParameterStructures.auto:
2320
+ if (isNamedParam(param)) {
2321
+ return nullToUndefined(param);
2322
+ } else {
2323
+ return [undefinedToNull(param)];
2324
+ }
2325
+ case messages_1.ParameterStructures.byName:
2326
+ if (!isNamedParam(param)) {
2327
+ throw new Error(`Received parameters by name but param is not an object literal.`);
2328
+ }
2329
+ return nullToUndefined(param);
2330
+ case messages_1.ParameterStructures.byPosition:
2331
+ return [undefinedToNull(param)];
2332
+ default:
2333
+ throw new Error(`Unknown parameter structure ${parameterStructures.toString()}`);
2334
+ }
2335
+ }
2336
+ function computeMessageParams(type, params) {
2337
+ let result;
2338
+ const numberOfParams = type.numberOfParams;
2339
+ switch (numberOfParams) {
2340
+ case 0:
2341
+ result = undefined;
2342
+ break;
2343
+ case 1:
2344
+ result = computeSingleParam(type.parameterStructures, params[0]);
2345
+ break;
2346
+ default:
2347
+ result = [];
2348
+ for (let i = 0;i < params.length && i < numberOfParams; i++) {
2349
+ result.push(undefinedToNull(params[i]));
2350
+ }
2351
+ if (params.length < numberOfParams) {
2352
+ for (let i = params.length;i < numberOfParams; i++) {
2353
+ result.push(null);
2354
+ }
2355
+ }
2356
+ break;
2357
+ }
2358
+ return result;
2359
+ }
2360
+ const connection = {
2361
+ sendNotification: (type, ...args) => {
2362
+ throwIfClosedOrDisposed();
2363
+ let method;
2364
+ let messageParams;
2365
+ if (Is.string(type)) {
2366
+ method = type;
2367
+ const first = args[0];
2368
+ let paramStart = 0;
2369
+ let parameterStructures = messages_1.ParameterStructures.auto;
2370
+ if (messages_1.ParameterStructures.is(first)) {
2371
+ paramStart = 1;
2372
+ parameterStructures = first;
2373
+ }
2374
+ let paramEnd = args.length;
2375
+ const numberOfParams = paramEnd - paramStart;
2376
+ switch (numberOfParams) {
2377
+ case 0:
2378
+ messageParams = undefined;
2379
+ break;
2380
+ case 1:
2381
+ messageParams = computeSingleParam(parameterStructures, args[paramStart]);
2382
+ break;
2383
+ default:
2384
+ if (parameterStructures === messages_1.ParameterStructures.byName) {
2385
+ throw new Error(`Received ${numberOfParams} parameters for 'by Name' notification parameter structure.`);
2386
+ }
2387
+ messageParams = args.slice(paramStart, paramEnd).map((value) => undefinedToNull(value));
2388
+ break;
2389
+ }
2390
+ } else {
2391
+ const params = args;
2392
+ method = type.method;
2393
+ messageParams = computeMessageParams(type, params);
2394
+ }
2395
+ const notificationMessage = {
2396
+ jsonrpc: version,
2397
+ method,
2398
+ params: messageParams
2399
+ };
2400
+ traceSendingNotification(notificationMessage);
2401
+ return messageWriter.write(notificationMessage).catch((error) => {
2402
+ logger.error(`Sending notification failed.`);
2403
+ throw error;
2404
+ });
2405
+ },
2406
+ onNotification: (type, handler) => {
2407
+ throwIfClosedOrDisposed();
2408
+ let method;
2409
+ if (Is.func(type)) {
2410
+ starNotificationHandler = type;
2411
+ } else if (handler) {
2412
+ if (Is.string(type)) {
2413
+ method = type;
2414
+ notificationHandlers.set(type, { type: undefined, handler });
2415
+ } else {
2416
+ method = type.method;
2417
+ notificationHandlers.set(type.method, { type, handler });
2418
+ }
2419
+ }
2420
+ return {
2421
+ dispose: () => {
2422
+ if (method !== undefined) {
2423
+ notificationHandlers.delete(method);
2424
+ } else {
2425
+ starNotificationHandler = undefined;
2426
+ }
2427
+ }
2428
+ };
2429
+ },
2430
+ onProgress: (_type, token, handler) => {
2431
+ if (progressHandlers.has(token)) {
2432
+ throw new Error(`Progress handler for token ${token} already registered`);
2433
+ }
2434
+ progressHandlers.set(token, handler);
2435
+ return {
2436
+ dispose: () => {
2437
+ progressHandlers.delete(token);
2438
+ }
2439
+ };
2440
+ },
2441
+ sendProgress: (_type, token, value) => {
2442
+ return connection.sendNotification(ProgressNotification.type, { token, value });
2443
+ },
2444
+ onUnhandledProgress: unhandledProgressEmitter.event,
2445
+ sendRequest: (type, ...args) => {
2446
+ throwIfClosedOrDisposed();
2447
+ throwIfNotListening();
2448
+ let method;
2449
+ let messageParams;
2450
+ let token = undefined;
2451
+ if (Is.string(type)) {
2452
+ method = type;
2453
+ const first = args[0];
2454
+ const last = args[args.length - 1];
2455
+ let paramStart = 0;
2456
+ let parameterStructures = messages_1.ParameterStructures.auto;
2457
+ if (messages_1.ParameterStructures.is(first)) {
2458
+ paramStart = 1;
2459
+ parameterStructures = first;
2460
+ }
2461
+ let paramEnd = args.length;
2462
+ if (cancellation_1.CancellationToken.is(last)) {
2463
+ paramEnd = paramEnd - 1;
2464
+ token = last;
2465
+ }
2466
+ const numberOfParams = paramEnd - paramStart;
2467
+ switch (numberOfParams) {
2468
+ case 0:
2469
+ messageParams = undefined;
2470
+ break;
2471
+ case 1:
2472
+ messageParams = computeSingleParam(parameterStructures, args[paramStart]);
2473
+ break;
2474
+ default:
2475
+ if (parameterStructures === messages_1.ParameterStructures.byName) {
2476
+ throw new Error(`Received ${numberOfParams} parameters for 'by Name' request parameter structure.`);
2477
+ }
2478
+ messageParams = args.slice(paramStart, paramEnd).map((value) => undefinedToNull(value));
2479
+ break;
2480
+ }
2481
+ } else {
2482
+ const params = args;
2483
+ method = type.method;
2484
+ messageParams = computeMessageParams(type, params);
2485
+ const numberOfParams = type.numberOfParams;
2486
+ token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : undefined;
2487
+ }
2488
+ const id = sequenceNumber++;
2489
+ let disposable;
2490
+ if (token) {
2491
+ disposable = token.onCancellationRequested(() => {
2492
+ const p = cancellationStrategy.sender.sendCancellation(connection, id);
2493
+ if (p === undefined) {
2494
+ logger.log(`Received no promise from cancellation strategy when cancelling id ${id}`);
2495
+ return Promise.resolve();
2496
+ } else {
2497
+ return p.catch(() => {
2498
+ logger.log(`Sending cancellation messages for id ${id} failed`);
2499
+ });
2500
+ }
2501
+ });
2502
+ }
2503
+ const requestMessage = {
2504
+ jsonrpc: version,
2505
+ id,
2506
+ method,
2507
+ params: messageParams
2508
+ };
2509
+ traceSendingRequest(requestMessage);
2510
+ if (typeof cancellationStrategy.sender.enableCancellation === "function") {
2511
+ cancellationStrategy.sender.enableCancellation(requestMessage);
2512
+ }
2513
+ return new Promise(async (resolve, reject) => {
2514
+ const resolveWithCleanup = (r) => {
2515
+ resolve(r);
2516
+ cancellationStrategy.sender.cleanup(id);
2517
+ disposable?.dispose();
2518
+ };
2519
+ const rejectWithCleanup = (r) => {
2520
+ reject(r);
2521
+ cancellationStrategy.sender.cleanup(id);
2522
+ disposable?.dispose();
2523
+ };
2524
+ const responsePromise = { method, timerStart: Date.now(), resolve: resolveWithCleanup, reject: rejectWithCleanup };
2525
+ try {
2526
+ responsePromises.set(id, responsePromise);
2527
+ await messageWriter.write(requestMessage);
2528
+ } catch (error) {
2529
+ responsePromises.delete(id);
2530
+ responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, error.message ? error.message : "Unknown reason"));
2531
+ logger.error(`Sending request failed.`);
2532
+ throw error;
2533
+ }
2534
+ });
2535
+ },
2536
+ onRequest: (type, handler) => {
2537
+ throwIfClosedOrDisposed();
2538
+ let method = null;
2539
+ if (StarRequestHandler.is(type)) {
2540
+ method = undefined;
2541
+ starRequestHandler = type;
2542
+ } else if (Is.string(type)) {
2543
+ method = null;
2544
+ if (handler !== undefined) {
2545
+ method = type;
2546
+ requestHandlers.set(type, { handler, type: undefined });
2547
+ }
2548
+ } else {
2549
+ if (handler !== undefined) {
2550
+ method = type.method;
2551
+ requestHandlers.set(type.method, { type, handler });
2552
+ }
2553
+ }
2554
+ return {
2555
+ dispose: () => {
2556
+ if (method === null) {
2557
+ return;
2558
+ }
2559
+ if (method !== undefined) {
2560
+ requestHandlers.delete(method);
2561
+ } else {
2562
+ starRequestHandler = undefined;
2563
+ }
2564
+ }
2565
+ };
2566
+ },
2567
+ hasPendingResponse: () => {
2568
+ return responsePromises.size > 0;
2569
+ },
2570
+ trace: async (_value, _tracer, sendNotificationOrTraceOptions) => {
2571
+ let _sendNotification = false;
2572
+ let _traceFormat = TraceFormat.Text;
2573
+ if (sendNotificationOrTraceOptions !== undefined) {
2574
+ if (Is.boolean(sendNotificationOrTraceOptions)) {
2575
+ _sendNotification = sendNotificationOrTraceOptions;
2576
+ } else {
2577
+ _sendNotification = sendNotificationOrTraceOptions.sendNotification || false;
2578
+ _traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text;
2579
+ }
2580
+ }
2581
+ trace = _value;
2582
+ traceFormat = _traceFormat;
2583
+ if (trace === Trace.Off) {
2584
+ tracer = undefined;
2585
+ } else {
2586
+ tracer = _tracer;
2587
+ }
2588
+ if (_sendNotification && !isClosed() && !isDisposed()) {
2589
+ await connection.sendNotification(SetTraceNotification.type, { value: Trace.toString(_value) });
2590
+ }
2591
+ },
2592
+ onError: errorEmitter.event,
2593
+ onClose: closeEmitter.event,
2594
+ onUnhandledNotification: unhandledNotificationEmitter.event,
2595
+ onDispose: disposeEmitter.event,
2596
+ end: () => {
2597
+ messageWriter.end();
2598
+ },
2599
+ dispose: () => {
2600
+ if (isDisposed()) {
2601
+ return;
2602
+ }
2603
+ state = ConnectionState.Disposed;
2604
+ disposeEmitter.fire(undefined);
2605
+ const error = new messages_1.ResponseError(messages_1.ErrorCodes.PendingResponseRejected, "Pending response rejected since connection got disposed");
2606
+ for (const promise of responsePromises.values()) {
2607
+ promise.reject(error);
2608
+ }
2609
+ responsePromises = new Map;
2610
+ requestTokens = new Map;
2611
+ knownCanceledRequests = new Set;
2612
+ messageQueue = new linkedMap_1.LinkedMap;
2613
+ if (Is.func(messageWriter.dispose)) {
2614
+ messageWriter.dispose();
2615
+ }
2616
+ if (Is.func(messageReader.dispose)) {
2617
+ messageReader.dispose();
2618
+ }
2619
+ },
2620
+ listen: () => {
2621
+ throwIfClosedOrDisposed();
2622
+ throwIfListening();
2623
+ state = ConnectionState.Listening;
2624
+ messageReader.listen(callback);
2625
+ },
2626
+ inspect: () => {
2627
+ (0, ral_1.default)().console.log("inspect");
2628
+ }
2629
+ };
2630
+ connection.onNotification(LogTraceNotification.type, (params) => {
2631
+ if (trace === Trace.Off || !tracer) {
2632
+ return;
2633
+ }
2634
+ const verbose = trace === Trace.Verbose || trace === Trace.Compact;
2635
+ tracer.log(params.message, verbose ? params.verbose : undefined);
2636
+ });
2637
+ connection.onNotification(ProgressNotification.type, (params) => {
2638
+ const handler = progressHandlers.get(params.token);
2639
+ if (handler) {
2640
+ handler(params.value);
2641
+ } else {
2642
+ unhandledProgressEmitter.fire(params);
2643
+ }
2644
+ });
2645
+ return connection;
2646
+ }
2647
+ exports.createMessageConnection = createMessageConnection;
2648
+ });
2649
+
2650
+ // node_modules/vscode-jsonrpc/lib/common/api.js
2651
+ var require_api = __commonJS((exports) => {
2652
+ Object.defineProperty(exports, "__esModule", { value: true });
2653
+ exports.ProgressType = exports.ProgressToken = exports.createMessageConnection = exports.NullLogger = exports.ConnectionOptions = exports.ConnectionStrategy = exports.AbstractMessageBuffer = exports.WriteableStreamMessageWriter = exports.AbstractMessageWriter = exports.MessageWriter = exports.ReadableStreamMessageReader = exports.AbstractMessageReader = exports.MessageReader = exports.SharedArrayReceiverStrategy = exports.SharedArraySenderStrategy = exports.CancellationToken = exports.CancellationTokenSource = exports.Emitter = exports.Event = exports.Disposable = exports.LRUCache = exports.Touch = exports.LinkedMap = exports.ParameterStructures = exports.NotificationType9 = exports.NotificationType8 = exports.NotificationType7 = exports.NotificationType6 = exports.NotificationType5 = exports.NotificationType4 = exports.NotificationType3 = exports.NotificationType2 = exports.NotificationType1 = exports.NotificationType0 = exports.NotificationType = exports.ErrorCodes = exports.ResponseError = exports.RequestType9 = exports.RequestType8 = exports.RequestType7 = exports.RequestType6 = exports.RequestType5 = exports.RequestType4 = exports.RequestType3 = exports.RequestType2 = exports.RequestType1 = exports.RequestType0 = exports.RequestType = exports.Message = exports.RAL = undefined;
2654
+ exports.MessageStrategy = exports.CancellationStrategy = exports.CancellationSenderStrategy = exports.CancellationReceiverStrategy = exports.ConnectionError = exports.ConnectionErrors = exports.LogTraceNotification = exports.SetTraceNotification = exports.TraceFormat = exports.TraceValues = exports.Trace = undefined;
2655
+ var messages_1 = require_messages();
2656
+ Object.defineProperty(exports, "Message", { enumerable: true, get: function() {
2657
+ return messages_1.Message;
2658
+ } });
2659
+ Object.defineProperty(exports, "RequestType", { enumerable: true, get: function() {
2660
+ return messages_1.RequestType;
2661
+ } });
2662
+ Object.defineProperty(exports, "RequestType0", { enumerable: true, get: function() {
2663
+ return messages_1.RequestType0;
2664
+ } });
2665
+ Object.defineProperty(exports, "RequestType1", { enumerable: true, get: function() {
2666
+ return messages_1.RequestType1;
2667
+ } });
2668
+ Object.defineProperty(exports, "RequestType2", { enumerable: true, get: function() {
2669
+ return messages_1.RequestType2;
2670
+ } });
2671
+ Object.defineProperty(exports, "RequestType3", { enumerable: true, get: function() {
2672
+ return messages_1.RequestType3;
2673
+ } });
2674
+ Object.defineProperty(exports, "RequestType4", { enumerable: true, get: function() {
2675
+ return messages_1.RequestType4;
2676
+ } });
2677
+ Object.defineProperty(exports, "RequestType5", { enumerable: true, get: function() {
2678
+ return messages_1.RequestType5;
2679
+ } });
2680
+ Object.defineProperty(exports, "RequestType6", { enumerable: true, get: function() {
2681
+ return messages_1.RequestType6;
2682
+ } });
2683
+ Object.defineProperty(exports, "RequestType7", { enumerable: true, get: function() {
2684
+ return messages_1.RequestType7;
2685
+ } });
2686
+ Object.defineProperty(exports, "RequestType8", { enumerable: true, get: function() {
2687
+ return messages_1.RequestType8;
2688
+ } });
2689
+ Object.defineProperty(exports, "RequestType9", { enumerable: true, get: function() {
2690
+ return messages_1.RequestType9;
2691
+ } });
2692
+ Object.defineProperty(exports, "ResponseError", { enumerable: true, get: function() {
2693
+ return messages_1.ResponseError;
2694
+ } });
2695
+ Object.defineProperty(exports, "ErrorCodes", { enumerable: true, get: function() {
2696
+ return messages_1.ErrorCodes;
2697
+ } });
2698
+ Object.defineProperty(exports, "NotificationType", { enumerable: true, get: function() {
2699
+ return messages_1.NotificationType;
2700
+ } });
2701
+ Object.defineProperty(exports, "NotificationType0", { enumerable: true, get: function() {
2702
+ return messages_1.NotificationType0;
2703
+ } });
2704
+ Object.defineProperty(exports, "NotificationType1", { enumerable: true, get: function() {
2705
+ return messages_1.NotificationType1;
2706
+ } });
2707
+ Object.defineProperty(exports, "NotificationType2", { enumerable: true, get: function() {
2708
+ return messages_1.NotificationType2;
2709
+ } });
2710
+ Object.defineProperty(exports, "NotificationType3", { enumerable: true, get: function() {
2711
+ return messages_1.NotificationType3;
2712
+ } });
2713
+ Object.defineProperty(exports, "NotificationType4", { enumerable: true, get: function() {
2714
+ return messages_1.NotificationType4;
2715
+ } });
2716
+ Object.defineProperty(exports, "NotificationType5", { enumerable: true, get: function() {
2717
+ return messages_1.NotificationType5;
2718
+ } });
2719
+ Object.defineProperty(exports, "NotificationType6", { enumerable: true, get: function() {
2720
+ return messages_1.NotificationType6;
2721
+ } });
2722
+ Object.defineProperty(exports, "NotificationType7", { enumerable: true, get: function() {
2723
+ return messages_1.NotificationType7;
2724
+ } });
2725
+ Object.defineProperty(exports, "NotificationType8", { enumerable: true, get: function() {
2726
+ return messages_1.NotificationType8;
2727
+ } });
2728
+ Object.defineProperty(exports, "NotificationType9", { enumerable: true, get: function() {
2729
+ return messages_1.NotificationType9;
2730
+ } });
2731
+ Object.defineProperty(exports, "ParameterStructures", { enumerable: true, get: function() {
2732
+ return messages_1.ParameterStructures;
2733
+ } });
2734
+ var linkedMap_1 = require_linkedMap();
2735
+ Object.defineProperty(exports, "LinkedMap", { enumerable: true, get: function() {
2736
+ return linkedMap_1.LinkedMap;
2737
+ } });
2738
+ Object.defineProperty(exports, "LRUCache", { enumerable: true, get: function() {
2739
+ return linkedMap_1.LRUCache;
2740
+ } });
2741
+ Object.defineProperty(exports, "Touch", { enumerable: true, get: function() {
2742
+ return linkedMap_1.Touch;
2743
+ } });
2744
+ var disposable_1 = require_disposable();
2745
+ Object.defineProperty(exports, "Disposable", { enumerable: true, get: function() {
2746
+ return disposable_1.Disposable;
2747
+ } });
2748
+ var events_1 = require_events();
2749
+ Object.defineProperty(exports, "Event", { enumerable: true, get: function() {
2750
+ return events_1.Event;
2751
+ } });
2752
+ Object.defineProperty(exports, "Emitter", { enumerable: true, get: function() {
2753
+ return events_1.Emitter;
2754
+ } });
2755
+ var cancellation_1 = require_cancellation();
2756
+ Object.defineProperty(exports, "CancellationTokenSource", { enumerable: true, get: function() {
2757
+ return cancellation_1.CancellationTokenSource;
2758
+ } });
2759
+ Object.defineProperty(exports, "CancellationToken", { enumerable: true, get: function() {
2760
+ return cancellation_1.CancellationToken;
2761
+ } });
2762
+ var sharedArrayCancellation_1 = require_sharedArrayCancellation();
2763
+ Object.defineProperty(exports, "SharedArraySenderStrategy", { enumerable: true, get: function() {
2764
+ return sharedArrayCancellation_1.SharedArraySenderStrategy;
2765
+ } });
2766
+ Object.defineProperty(exports, "SharedArrayReceiverStrategy", { enumerable: true, get: function() {
2767
+ return sharedArrayCancellation_1.SharedArrayReceiverStrategy;
2768
+ } });
2769
+ var messageReader_1 = require_messageReader();
2770
+ Object.defineProperty(exports, "MessageReader", { enumerable: true, get: function() {
2771
+ return messageReader_1.MessageReader;
2772
+ } });
2773
+ Object.defineProperty(exports, "AbstractMessageReader", { enumerable: true, get: function() {
2774
+ return messageReader_1.AbstractMessageReader;
2775
+ } });
2776
+ Object.defineProperty(exports, "ReadableStreamMessageReader", { enumerable: true, get: function() {
2777
+ return messageReader_1.ReadableStreamMessageReader;
2778
+ } });
2779
+ var messageWriter_1 = require_messageWriter();
2780
+ Object.defineProperty(exports, "MessageWriter", { enumerable: true, get: function() {
2781
+ return messageWriter_1.MessageWriter;
2782
+ } });
2783
+ Object.defineProperty(exports, "AbstractMessageWriter", { enumerable: true, get: function() {
2784
+ return messageWriter_1.AbstractMessageWriter;
2785
+ } });
2786
+ Object.defineProperty(exports, "WriteableStreamMessageWriter", { enumerable: true, get: function() {
2787
+ return messageWriter_1.WriteableStreamMessageWriter;
2788
+ } });
2789
+ var messageBuffer_1 = require_messageBuffer();
2790
+ Object.defineProperty(exports, "AbstractMessageBuffer", { enumerable: true, get: function() {
2791
+ return messageBuffer_1.AbstractMessageBuffer;
2792
+ } });
2793
+ var connection_1 = require_connection();
2794
+ Object.defineProperty(exports, "ConnectionStrategy", { enumerable: true, get: function() {
2795
+ return connection_1.ConnectionStrategy;
2796
+ } });
2797
+ Object.defineProperty(exports, "ConnectionOptions", { enumerable: true, get: function() {
2798
+ return connection_1.ConnectionOptions;
2799
+ } });
2800
+ Object.defineProperty(exports, "NullLogger", { enumerable: true, get: function() {
2801
+ return connection_1.NullLogger;
2802
+ } });
2803
+ Object.defineProperty(exports, "createMessageConnection", { enumerable: true, get: function() {
2804
+ return connection_1.createMessageConnection;
2805
+ } });
2806
+ Object.defineProperty(exports, "ProgressToken", { enumerable: true, get: function() {
2807
+ return connection_1.ProgressToken;
2808
+ } });
2809
+ Object.defineProperty(exports, "ProgressType", { enumerable: true, get: function() {
2810
+ return connection_1.ProgressType;
2811
+ } });
2812
+ Object.defineProperty(exports, "Trace", { enumerable: true, get: function() {
2813
+ return connection_1.Trace;
2814
+ } });
2815
+ Object.defineProperty(exports, "TraceValues", { enumerable: true, get: function() {
2816
+ return connection_1.TraceValues;
2817
+ } });
2818
+ Object.defineProperty(exports, "TraceFormat", { enumerable: true, get: function() {
2819
+ return connection_1.TraceFormat;
2820
+ } });
2821
+ Object.defineProperty(exports, "SetTraceNotification", { enumerable: true, get: function() {
2822
+ return connection_1.SetTraceNotification;
2823
+ } });
2824
+ Object.defineProperty(exports, "LogTraceNotification", { enumerable: true, get: function() {
2825
+ return connection_1.LogTraceNotification;
2826
+ } });
2827
+ Object.defineProperty(exports, "ConnectionErrors", { enumerable: true, get: function() {
2828
+ return connection_1.ConnectionErrors;
2829
+ } });
2830
+ Object.defineProperty(exports, "ConnectionError", { enumerable: true, get: function() {
2831
+ return connection_1.ConnectionError;
2832
+ } });
2833
+ Object.defineProperty(exports, "CancellationReceiverStrategy", { enumerable: true, get: function() {
2834
+ return connection_1.CancellationReceiverStrategy;
2835
+ } });
2836
+ Object.defineProperty(exports, "CancellationSenderStrategy", { enumerable: true, get: function() {
2837
+ return connection_1.CancellationSenderStrategy;
2838
+ } });
2839
+ Object.defineProperty(exports, "CancellationStrategy", { enumerable: true, get: function() {
2840
+ return connection_1.CancellationStrategy;
2841
+ } });
2842
+ Object.defineProperty(exports, "MessageStrategy", { enumerable: true, get: function() {
2843
+ return connection_1.MessageStrategy;
2844
+ } });
2845
+ var ral_1 = require_ral();
2846
+ exports.RAL = ral_1.default;
2847
+ });
2848
+
2849
+ // node_modules/vscode-jsonrpc/lib/node/ril.js
2850
+ var require_ril = __commonJS((exports) => {
2851
+ Object.defineProperty(exports, "__esModule", { value: true });
2852
+ var util_1 = __require("util");
2853
+ var api_1 = require_api();
2854
+
2855
+ class MessageBuffer extends api_1.AbstractMessageBuffer {
2856
+ constructor(encoding = "utf-8") {
2857
+ super(encoding);
2858
+ }
2859
+ emptyBuffer() {
2860
+ return MessageBuffer.emptyBuffer;
2861
+ }
2862
+ fromString(value, encoding) {
2863
+ return Buffer.from(value, encoding);
2864
+ }
2865
+ toString(value, encoding) {
2866
+ if (value instanceof Buffer) {
2867
+ return value.toString(encoding);
2868
+ } else {
2869
+ return new util_1.TextDecoder(encoding).decode(value);
2870
+ }
2871
+ }
2872
+ asNative(buffer, length) {
2873
+ if (length === undefined) {
2874
+ return buffer instanceof Buffer ? buffer : Buffer.from(buffer);
2875
+ } else {
2876
+ return buffer instanceof Buffer ? buffer.slice(0, length) : Buffer.from(buffer, 0, length);
2877
+ }
2878
+ }
2879
+ allocNative(length) {
2880
+ return Buffer.allocUnsafe(length);
2881
+ }
2882
+ }
2883
+ MessageBuffer.emptyBuffer = Buffer.allocUnsafe(0);
2884
+
2885
+ class ReadableStreamWrapper {
2886
+ constructor(stream) {
2887
+ this.stream = stream;
2888
+ }
2889
+ onClose(listener) {
2890
+ this.stream.on("close", listener);
2891
+ return api_1.Disposable.create(() => this.stream.off("close", listener));
2892
+ }
2893
+ onError(listener) {
2894
+ this.stream.on("error", listener);
2895
+ return api_1.Disposable.create(() => this.stream.off("error", listener));
2896
+ }
2897
+ onEnd(listener) {
2898
+ this.stream.on("end", listener);
2899
+ return api_1.Disposable.create(() => this.stream.off("end", listener));
2900
+ }
2901
+ onData(listener) {
2902
+ this.stream.on("data", listener);
2903
+ return api_1.Disposable.create(() => this.stream.off("data", listener));
2904
+ }
2905
+ }
2906
+
2907
+ class WritableStreamWrapper {
2908
+ constructor(stream) {
2909
+ this.stream = stream;
2910
+ }
2911
+ onClose(listener) {
2912
+ this.stream.on("close", listener);
2913
+ return api_1.Disposable.create(() => this.stream.off("close", listener));
2914
+ }
2915
+ onError(listener) {
2916
+ this.stream.on("error", listener);
2917
+ return api_1.Disposable.create(() => this.stream.off("error", listener));
2918
+ }
2919
+ onEnd(listener) {
2920
+ this.stream.on("end", listener);
2921
+ return api_1.Disposable.create(() => this.stream.off("end", listener));
2922
+ }
2923
+ write(data, encoding) {
2924
+ return new Promise((resolve, reject) => {
2925
+ const callback = (error) => {
2926
+ if (error === undefined || error === null) {
2927
+ resolve();
2928
+ } else {
2929
+ reject(error);
2930
+ }
2931
+ };
2932
+ if (typeof data === "string") {
2933
+ this.stream.write(data, encoding, callback);
2934
+ } else {
2935
+ this.stream.write(data, callback);
2936
+ }
2937
+ });
2938
+ }
2939
+ end() {
2940
+ this.stream.end();
2941
+ }
2942
+ }
2943
+ var _ril = Object.freeze({
2944
+ messageBuffer: Object.freeze({
2945
+ create: (encoding) => new MessageBuffer(encoding)
2946
+ }),
2947
+ applicationJson: Object.freeze({
2948
+ encoder: Object.freeze({
2949
+ name: "application/json",
2950
+ encode: (msg, options) => {
2951
+ try {
2952
+ return Promise.resolve(Buffer.from(JSON.stringify(msg, undefined, 0), options.charset));
2953
+ } catch (err) {
2954
+ return Promise.reject(err);
2955
+ }
2956
+ }
2957
+ }),
2958
+ decoder: Object.freeze({
2959
+ name: "application/json",
2960
+ decode: (buffer, options) => {
2961
+ try {
2962
+ if (buffer instanceof Buffer) {
2963
+ return Promise.resolve(JSON.parse(buffer.toString(options.charset)));
2964
+ } else {
2965
+ return Promise.resolve(JSON.parse(new util_1.TextDecoder(options.charset).decode(buffer)));
2966
+ }
2967
+ } catch (err) {
2968
+ return Promise.reject(err);
2969
+ }
2970
+ }
2971
+ })
2972
+ }),
2973
+ stream: Object.freeze({
2974
+ asReadableStream: (stream) => new ReadableStreamWrapper(stream),
2975
+ asWritableStream: (stream) => new WritableStreamWrapper(stream)
2976
+ }),
2977
+ console,
2978
+ timer: Object.freeze({
2979
+ setTimeout(callback, ms, ...args) {
2980
+ const handle = setTimeout(callback, ms, ...args);
2981
+ return { dispose: () => clearTimeout(handle) };
2982
+ },
2983
+ setImmediate(callback, ...args) {
2984
+ const handle = setImmediate(callback, ...args);
2985
+ return { dispose: () => clearImmediate(handle) };
2986
+ },
2987
+ setInterval(callback, ms, ...args) {
2988
+ const handle = setInterval(callback, ms, ...args);
2989
+ return { dispose: () => clearInterval(handle) };
2990
+ }
2991
+ })
2992
+ });
2993
+ function RIL() {
2994
+ return _ril;
2995
+ }
2996
+ (function(RIL2) {
2997
+ function install() {
2998
+ api_1.RAL.install(_ril);
2999
+ }
3000
+ RIL2.install = install;
3001
+ })(RIL || (RIL = {}));
3002
+ exports.default = RIL;
3003
+ });
3004
+
3005
+ // node_modules/vscode-jsonrpc/lib/node/main.js
3006
+ var require_main = __commonJS((exports) => {
3007
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
3008
+ if (k2 === undefined)
3009
+ k2 = k;
3010
+ var desc = Object.getOwnPropertyDescriptor(m, k);
3011
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
3012
+ desc = { enumerable: true, get: function() {
3013
+ return m[k];
3014
+ } };
3015
+ }
3016
+ Object.defineProperty(o, k2, desc);
3017
+ } : function(o, m, k, k2) {
3018
+ if (k2 === undefined)
3019
+ k2 = k;
3020
+ o[k2] = m[k];
3021
+ });
3022
+ var __exportStar = exports && exports.__exportStar || function(m, exports2) {
3023
+ for (var p in m)
3024
+ if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p))
3025
+ __createBinding(exports2, m, p);
3026
+ };
3027
+ Object.defineProperty(exports, "__esModule", { value: true });
3028
+ exports.createMessageConnection = exports.createServerSocketTransport = exports.createClientSocketTransport = exports.createServerPipeTransport = exports.createClientPipeTransport = exports.generateRandomPipeName = exports.StreamMessageWriter = exports.StreamMessageReader = exports.SocketMessageWriter = exports.SocketMessageReader = exports.PortMessageWriter = exports.PortMessageReader = exports.IPCMessageWriter = exports.IPCMessageReader = undefined;
3029
+ var ril_1 = require_ril();
3030
+ ril_1.default.install();
3031
+ var path = __require("path");
3032
+ var os = __require("os");
3033
+ var crypto_1 = __require("crypto");
3034
+ var net_1 = __require("net");
3035
+ var api_1 = require_api();
3036
+ __exportStar(require_api(), exports);
3037
+
3038
+ class IPCMessageReader extends api_1.AbstractMessageReader {
3039
+ constructor(process2) {
3040
+ super();
3041
+ this.process = process2;
3042
+ let eventEmitter = this.process;
3043
+ eventEmitter.on("error", (error) => this.fireError(error));
3044
+ eventEmitter.on("close", () => this.fireClose());
3045
+ }
3046
+ listen(callback) {
3047
+ this.process.on("message", callback);
3048
+ return api_1.Disposable.create(() => this.process.off("message", callback));
3049
+ }
3050
+ }
3051
+ exports.IPCMessageReader = IPCMessageReader;
3052
+
3053
+ class IPCMessageWriter extends api_1.AbstractMessageWriter {
3054
+ constructor(process2) {
3055
+ super();
3056
+ this.process = process2;
3057
+ this.errorCount = 0;
3058
+ const eventEmitter = this.process;
3059
+ eventEmitter.on("error", (error) => this.fireError(error));
3060
+ eventEmitter.on("close", () => this.fireClose);
3061
+ }
3062
+ write(msg) {
3063
+ try {
3064
+ if (typeof this.process.send === "function") {
3065
+ this.process.send(msg, undefined, undefined, (error) => {
3066
+ if (error) {
3067
+ this.errorCount++;
3068
+ this.handleError(error, msg);
3069
+ } else {
3070
+ this.errorCount = 0;
3071
+ }
3072
+ });
3073
+ }
3074
+ return Promise.resolve();
3075
+ } catch (error) {
3076
+ this.handleError(error, msg);
3077
+ return Promise.reject(error);
3078
+ }
3079
+ }
3080
+ handleError(error, msg) {
3081
+ this.errorCount++;
3082
+ this.fireError(error, msg, this.errorCount);
3083
+ }
3084
+ end() {}
3085
+ }
3086
+ exports.IPCMessageWriter = IPCMessageWriter;
3087
+
3088
+ class PortMessageReader extends api_1.AbstractMessageReader {
3089
+ constructor(port) {
3090
+ super();
3091
+ this.onData = new api_1.Emitter;
3092
+ port.on("close", () => this.fireClose);
3093
+ port.on("error", (error) => this.fireError(error));
3094
+ port.on("message", (message) => {
3095
+ this.onData.fire(message);
3096
+ });
3097
+ }
3098
+ listen(callback) {
3099
+ return this.onData.event(callback);
3100
+ }
3101
+ }
3102
+ exports.PortMessageReader = PortMessageReader;
3103
+
3104
+ class PortMessageWriter extends api_1.AbstractMessageWriter {
3105
+ constructor(port) {
3106
+ super();
3107
+ this.port = port;
3108
+ this.errorCount = 0;
3109
+ port.on("close", () => this.fireClose());
3110
+ port.on("error", (error) => this.fireError(error));
3111
+ }
3112
+ write(msg) {
3113
+ try {
3114
+ this.port.postMessage(msg);
3115
+ return Promise.resolve();
3116
+ } catch (error) {
3117
+ this.handleError(error, msg);
3118
+ return Promise.reject(error);
3119
+ }
3120
+ }
3121
+ handleError(error, msg) {
3122
+ this.errorCount++;
3123
+ this.fireError(error, msg, this.errorCount);
3124
+ }
3125
+ end() {}
3126
+ }
3127
+ exports.PortMessageWriter = PortMessageWriter;
3128
+
3129
+ class SocketMessageReader extends api_1.ReadableStreamMessageReader {
3130
+ constructor(socket, encoding = "utf-8") {
3131
+ super((0, ril_1.default)().stream.asReadableStream(socket), encoding);
3132
+ }
3133
+ }
3134
+ exports.SocketMessageReader = SocketMessageReader;
3135
+
3136
+ class SocketMessageWriter extends api_1.WriteableStreamMessageWriter {
3137
+ constructor(socket, options) {
3138
+ super((0, ril_1.default)().stream.asWritableStream(socket), options);
3139
+ this.socket = socket;
3140
+ }
3141
+ dispose() {
3142
+ super.dispose();
3143
+ this.socket.destroy();
3144
+ }
3145
+ }
3146
+ exports.SocketMessageWriter = SocketMessageWriter;
3147
+
3148
+ class StreamMessageReader extends api_1.ReadableStreamMessageReader {
3149
+ constructor(readable, encoding) {
3150
+ super((0, ril_1.default)().stream.asReadableStream(readable), encoding);
3151
+ }
3152
+ }
3153
+ exports.StreamMessageReader = StreamMessageReader;
3154
+
3155
+ class StreamMessageWriter extends api_1.WriteableStreamMessageWriter {
3156
+ constructor(writable, options) {
3157
+ super((0, ril_1.default)().stream.asWritableStream(writable), options);
3158
+ }
3159
+ }
3160
+ exports.StreamMessageWriter = StreamMessageWriter;
3161
+ var XDG_RUNTIME_DIR = process.env["XDG_RUNTIME_DIR"];
3162
+ var safeIpcPathLengths = new Map([
3163
+ ["linux", 107],
3164
+ ["darwin", 103]
3165
+ ]);
3166
+ function generateRandomPipeName() {
3167
+ const randomSuffix = (0, crypto_1.randomBytes)(21).toString("hex");
3168
+ if (process.platform === "win32") {
3169
+ return `\\\\.\\pipe\\vscode-jsonrpc-${randomSuffix}-sock`;
3170
+ }
3171
+ let result;
3172
+ if (XDG_RUNTIME_DIR) {
3173
+ result = path.join(XDG_RUNTIME_DIR, `vscode-ipc-${randomSuffix}.sock`);
3174
+ } else {
3175
+ result = path.join(os.tmpdir(), `vscode-${randomSuffix}.sock`);
3176
+ }
3177
+ const limit = safeIpcPathLengths.get(process.platform);
3178
+ if (limit !== undefined && result.length > limit) {
3179
+ (0, ril_1.default)().console.warn(`WARNING: IPC handle "${result}" is longer than ${limit} characters.`);
3180
+ }
3181
+ return result;
3182
+ }
3183
+ exports.generateRandomPipeName = generateRandomPipeName;
3184
+ function createClientPipeTransport(pipeName, encoding = "utf-8") {
3185
+ let connectResolve;
3186
+ const connected = new Promise((resolve, _reject) => {
3187
+ connectResolve = resolve;
3188
+ });
3189
+ return new Promise((resolve, reject) => {
3190
+ let server = (0, net_1.createServer)((socket) => {
3191
+ server.close();
3192
+ connectResolve([
3193
+ new SocketMessageReader(socket, encoding),
3194
+ new SocketMessageWriter(socket, encoding)
3195
+ ]);
3196
+ });
3197
+ server.on("error", reject);
3198
+ server.listen(pipeName, () => {
3199
+ server.removeListener("error", reject);
3200
+ resolve({
3201
+ onConnected: () => {
3202
+ return connected;
3203
+ }
3204
+ });
3205
+ });
3206
+ });
3207
+ }
3208
+ exports.createClientPipeTransport = createClientPipeTransport;
3209
+ function createServerPipeTransport(pipeName, encoding = "utf-8") {
3210
+ const socket = (0, net_1.createConnection)(pipeName);
3211
+ return [
3212
+ new SocketMessageReader(socket, encoding),
3213
+ new SocketMessageWriter(socket, encoding)
3214
+ ];
3215
+ }
3216
+ exports.createServerPipeTransport = createServerPipeTransport;
3217
+ function createClientSocketTransport(port, encoding = "utf-8") {
3218
+ let connectResolve;
3219
+ const connected = new Promise((resolve, _reject) => {
3220
+ connectResolve = resolve;
3221
+ });
3222
+ return new Promise((resolve, reject) => {
3223
+ const server = (0, net_1.createServer)((socket) => {
3224
+ server.close();
3225
+ connectResolve([
3226
+ new SocketMessageReader(socket, encoding),
3227
+ new SocketMessageWriter(socket, encoding)
3228
+ ]);
3229
+ });
3230
+ server.on("error", reject);
3231
+ server.listen(port, "127.0.0.1", () => {
3232
+ server.removeListener("error", reject);
3233
+ resolve({
3234
+ onConnected: () => {
3235
+ return connected;
3236
+ }
3237
+ });
3238
+ });
3239
+ });
3240
+ }
3241
+ exports.createClientSocketTransport = createClientSocketTransport;
3242
+ function createServerSocketTransport(port, encoding = "utf-8") {
3243
+ const socket = (0, net_1.createConnection)(port, "127.0.0.1");
3244
+ return [
3245
+ new SocketMessageReader(socket, encoding),
3246
+ new SocketMessageWriter(socket, encoding)
3247
+ ];
3248
+ }
3249
+ exports.createServerSocketTransport = createServerSocketTransport;
3250
+ function isReadableStream(value) {
3251
+ const candidate = value;
3252
+ return candidate.read !== undefined && candidate.addListener !== undefined;
3253
+ }
3254
+ function isWritableStream(value) {
3255
+ const candidate = value;
3256
+ return candidate.write !== undefined && candidate.addListener !== undefined;
3257
+ }
3258
+ function createMessageConnection(input, output, logger, options) {
3259
+ if (!logger) {
3260
+ logger = api_1.NullLogger;
3261
+ }
3262
+ const reader = isReadableStream(input) ? new StreamMessageReader(input) : input;
3263
+ const writer = isWritableStream(output) ? new StreamMessageWriter(output) : output;
3264
+ if (api_1.ConnectionStrategy.is(options)) {
3265
+ options = { connectionStrategy: options };
3266
+ }
3267
+ return (0, api_1.createMessageConnection)(reader, writer, logger, options);
3268
+ }
3269
+ exports.createMessageConnection = createMessageConnection;
3270
+ });
3271
+
3272
+ // src/index.ts
3273
+ import * as path5 from "path";
3274
+ import * as fs5 from "fs";
3275
+ import { fileURLToPath } from "url";
3276
+
3277
+ // node_modules/@github/copilot-sdk/dist/client.js
3278
+ var import_node = __toESM(require_main(), 1);
3279
+ import { spawn } from "node:child_process";
3280
+ import { Socket } from "node:net";
3281
+
3282
+ // node_modules/@github/copilot-sdk/dist/sdkProtocolVersion.js
3283
+ var SDK_PROTOCOL_VERSION = 2;
3284
+ function getSdkProtocolVersion() {
3285
+ return SDK_PROTOCOL_VERSION;
3286
+ }
3287
+
3288
+ // node_modules/@github/copilot-sdk/dist/session.js
3289
+ class CopilotSession {
3290
+ constructor(sessionId, connection, _workspacePath) {
3291
+ this.sessionId = sessionId;
3292
+ this.connection = connection;
3293
+ this._workspacePath = _workspacePath;
3294
+ }
3295
+ eventHandlers = /* @__PURE__ */ new Set;
3296
+ toolHandlers = /* @__PURE__ */ new Map;
3297
+ permissionHandler;
3298
+ get workspacePath() {
3299
+ return this._workspacePath;
3300
+ }
3301
+ async send(options) {
3302
+ const response = await this.connection.sendRequest("session.send", {
3303
+ sessionId: this.sessionId,
3304
+ prompt: options.prompt,
3305
+ attachments: options.attachments,
3306
+ mode: options.mode
3307
+ });
3308
+ return response.messageId;
3309
+ }
3310
+ async sendAndWait(options, timeout) {
3311
+ const effectiveTimeout = timeout ?? 60000;
3312
+ let resolveIdle;
3313
+ let rejectWithError;
3314
+ const idlePromise = new Promise((resolve, reject) => {
3315
+ resolveIdle = resolve;
3316
+ rejectWithError = reject;
3317
+ });
3318
+ let lastAssistantMessage;
3319
+ const unsubscribe = this.on((event) => {
3320
+ if (event.type === "assistant.message") {
3321
+ lastAssistantMessage = event;
3322
+ } else if (event.type === "session.idle") {
3323
+ resolveIdle();
3324
+ } else if (event.type === "session.error") {
3325
+ const error = new Error(event.data.message);
3326
+ error.stack = event.data.stack;
3327
+ rejectWithError(error);
3328
+ }
3329
+ });
3330
+ try {
3331
+ await this.send(options);
3332
+ const timeoutPromise = new Promise((_, reject) => {
3333
+ setTimeout(() => reject(new Error(`Timeout after ${effectiveTimeout}ms waiting for session.idle`)), effectiveTimeout);
3334
+ });
3335
+ await Promise.race([idlePromise, timeoutPromise]);
3336
+ return lastAssistantMessage;
3337
+ } finally {
3338
+ unsubscribe();
3339
+ }
3340
+ }
3341
+ on(handler) {
3342
+ this.eventHandlers.add(handler);
3343
+ return () => {
3344
+ this.eventHandlers.delete(handler);
3345
+ };
3346
+ }
3347
+ _dispatchEvent(event) {
3348
+ for (const handler of this.eventHandlers) {
3349
+ try {
3350
+ handler(event);
3351
+ } catch (_error) {}
3352
+ }
3353
+ }
3354
+ registerTools(tools) {
3355
+ this.toolHandlers.clear();
3356
+ if (!tools) {
3357
+ return;
3358
+ }
3359
+ for (const tool of tools) {
3360
+ this.toolHandlers.set(tool.name, tool.handler);
3361
+ }
3362
+ }
3363
+ getToolHandler(name) {
3364
+ return this.toolHandlers.get(name);
3365
+ }
3366
+ registerPermissionHandler(handler) {
3367
+ this.permissionHandler = handler;
3368
+ }
3369
+ async _handlePermissionRequest(request) {
3370
+ if (!this.permissionHandler) {
3371
+ return { kind: "denied-no-approval-rule-and-could-not-request-from-user" };
3372
+ }
3373
+ try {
3374
+ const result = await this.permissionHandler(request, {
3375
+ sessionId: this.sessionId
3376
+ });
3377
+ return result;
3378
+ } catch (_error) {
3379
+ return { kind: "denied-no-approval-rule-and-could-not-request-from-user" };
3380
+ }
3381
+ }
3382
+ async getMessages() {
3383
+ const response = await this.connection.sendRequest("session.getMessages", {
3384
+ sessionId: this.sessionId
3385
+ });
3386
+ return response.events;
3387
+ }
3388
+ async destroy() {
3389
+ await this.connection.sendRequest("session.destroy", {
3390
+ sessionId: this.sessionId
3391
+ });
3392
+ this.eventHandlers.clear();
3393
+ this.toolHandlers.clear();
3394
+ this.permissionHandler = undefined;
3395
+ }
3396
+ async abort() {
3397
+ await this.connection.sendRequest("session.abort", {
3398
+ sessionId: this.sessionId
3399
+ });
3400
+ }
3401
+ }
3402
+
3403
+ // node_modules/@github/copilot-sdk/dist/client.js
3404
+ function isZodSchema(value) {
3405
+ return value != null && typeof value === "object" && "toJSONSchema" in value && typeof value.toJSONSchema === "function";
3406
+ }
3407
+ function toJsonSchema(parameters) {
3408
+ if (!parameters)
3409
+ return;
3410
+ if (isZodSchema(parameters)) {
3411
+ return parameters.toJSONSchema();
3412
+ }
3413
+ return parameters;
3414
+ }
3415
+
3416
+ class CopilotClient {
3417
+ cliProcess = null;
3418
+ connection = null;
3419
+ socket = null;
3420
+ actualPort = null;
3421
+ actualHost = "localhost";
3422
+ state = "disconnected";
3423
+ sessions = /* @__PURE__ */ new Map;
3424
+ options;
3425
+ isExternalServer = false;
3426
+ forceStopping = false;
3427
+ constructor(options = {}) {
3428
+ if (options.cliUrl && (options.useStdio === true || options.cliPath)) {
3429
+ throw new Error("cliUrl is mutually exclusive with useStdio and cliPath");
3430
+ }
3431
+ if (options.cliUrl) {
3432
+ const { host, port } = this.parseCliUrl(options.cliUrl);
3433
+ this.actualHost = host;
3434
+ this.actualPort = port;
3435
+ this.isExternalServer = true;
3436
+ }
3437
+ this.options = {
3438
+ cliPath: options.cliPath || "copilot",
3439
+ cliArgs: options.cliArgs ?? [],
3440
+ cwd: options.cwd ?? process.cwd(),
3441
+ port: options.port || 0,
3442
+ useStdio: options.cliUrl ? false : options.useStdio ?? true,
3443
+ cliUrl: options.cliUrl,
3444
+ logLevel: options.logLevel || "debug",
3445
+ autoStart: options.autoStart ?? true,
3446
+ autoRestart: options.autoRestart ?? true,
3447
+ env: options.env ?? process.env
3448
+ };
3449
+ }
3450
+ parseCliUrl(url) {
3451
+ let cleanUrl = url.replace(/^https?:\/\//, "");
3452
+ if (/^\d+$/.test(cleanUrl)) {
3453
+ return { host: "localhost", port: parseInt(cleanUrl, 10) };
3454
+ }
3455
+ const parts = cleanUrl.split(":");
3456
+ if (parts.length !== 2) {
3457
+ throw new Error(`Invalid cliUrl format: ${url}. Expected "host:port", "http://host:port", or "port"`);
3458
+ }
3459
+ const host = parts[0] || "localhost";
3460
+ const port = parseInt(parts[1], 10);
3461
+ if (isNaN(port) || port <= 0 || port > 65535) {
3462
+ throw new Error(`Invalid port in cliUrl: ${url}`);
3463
+ }
3464
+ return { host, port };
3465
+ }
3466
+ async start() {
3467
+ if (this.state === "connected") {
3468
+ return;
3469
+ }
3470
+ this.state = "connecting";
3471
+ try {
3472
+ if (!this.isExternalServer) {
3473
+ await this.startCLIServer();
3474
+ }
3475
+ await this.connectToServer();
3476
+ await this.verifyProtocolVersion();
3477
+ this.state = "connected";
3478
+ } catch (error) {
3479
+ this.state = "error";
3480
+ throw error;
3481
+ }
3482
+ }
3483
+ async stop() {
3484
+ const errors = [];
3485
+ for (const session of this.sessions.values()) {
3486
+ const sessionId = session.sessionId;
3487
+ let lastError = null;
3488
+ for (let attempt = 1;attempt <= 3; attempt++) {
3489
+ try {
3490
+ await session.destroy();
3491
+ lastError = null;
3492
+ break;
3493
+ } catch (error) {
3494
+ lastError = error instanceof Error ? error : new Error(String(error));
3495
+ if (attempt < 3) {
3496
+ const delay = 100 * Math.pow(2, attempt - 1);
3497
+ await new Promise((resolve) => setTimeout(resolve, delay));
3498
+ }
3499
+ }
3500
+ }
3501
+ if (lastError) {
3502
+ errors.push(new Error(`Failed to destroy session ${sessionId} after 3 attempts: ${lastError.message}`));
3503
+ }
3504
+ }
3505
+ this.sessions.clear();
3506
+ if (this.connection) {
3507
+ try {
3508
+ this.connection.dispose();
3509
+ } catch (error) {
3510
+ errors.push(new Error(`Failed to dispose connection: ${error instanceof Error ? error.message : String(error)}`));
3511
+ }
3512
+ this.connection = null;
3513
+ }
3514
+ if (this.socket) {
3515
+ try {
3516
+ this.socket.end();
3517
+ } catch (error) {
3518
+ errors.push(new Error(`Failed to close socket: ${error instanceof Error ? error.message : String(error)}`));
3519
+ }
3520
+ this.socket = null;
3521
+ }
3522
+ if (this.cliProcess && !this.isExternalServer) {
3523
+ try {
3524
+ this.cliProcess.kill();
3525
+ } catch (error) {
3526
+ errors.push(new Error(`Failed to kill CLI process: ${error instanceof Error ? error.message : String(error)}`));
3527
+ }
3528
+ this.cliProcess = null;
3529
+ }
3530
+ this.state = "disconnected";
3531
+ this.actualPort = null;
3532
+ return errors;
3533
+ }
3534
+ async forceStop() {
3535
+ this.forceStopping = true;
3536
+ this.sessions.clear();
3537
+ if (this.connection) {
3538
+ try {
3539
+ this.connection.dispose();
3540
+ } catch {}
3541
+ this.connection = null;
3542
+ }
3543
+ if (this.socket) {
3544
+ try {
3545
+ this.socket.destroy();
3546
+ } catch {}
3547
+ this.socket = null;
3548
+ }
3549
+ if (this.cliProcess && !this.isExternalServer) {
3550
+ try {
3551
+ this.cliProcess.kill("SIGKILL");
3552
+ } catch {}
3553
+ this.cliProcess = null;
3554
+ }
3555
+ this.state = "disconnected";
3556
+ this.actualPort = null;
3557
+ }
3558
+ async createSession(config = {}) {
3559
+ if (!this.connection) {
3560
+ if (this.options.autoStart) {
3561
+ await this.start();
3562
+ } else {
3563
+ throw new Error("Client not connected. Call start() first.");
3564
+ }
3565
+ }
3566
+ const response = await this.connection.sendRequest("session.create", {
3567
+ model: config.model,
3568
+ sessionId: config.sessionId,
3569
+ tools: config.tools?.map((tool) => ({
3570
+ name: tool.name,
3571
+ description: tool.description,
3572
+ parameters: toJsonSchema(tool.parameters)
3573
+ })),
3574
+ systemMessage: config.systemMessage,
3575
+ availableTools: config.availableTools,
3576
+ excludedTools: config.excludedTools,
3577
+ provider: config.provider,
3578
+ requestPermission: !!config.onPermissionRequest,
3579
+ streaming: config.streaming,
3580
+ mcpServers: config.mcpServers,
3581
+ customAgents: config.customAgents,
3582
+ configDir: config.configDir,
3583
+ skillDirectories: config.skillDirectories,
3584
+ disabledSkills: config.disabledSkills,
3585
+ infiniteSessions: config.infiniteSessions
3586
+ });
3587
+ const { sessionId, workspacePath } = response;
3588
+ const session = new CopilotSession(sessionId, this.connection, workspacePath);
3589
+ session.registerTools(config.tools);
3590
+ if (config.onPermissionRequest) {
3591
+ session.registerPermissionHandler(config.onPermissionRequest);
3592
+ }
3593
+ this.sessions.set(sessionId, session);
3594
+ return session;
3595
+ }
3596
+ async resumeSession(sessionId, config = {}) {
3597
+ if (!this.connection) {
3598
+ if (this.options.autoStart) {
3599
+ await this.start();
3600
+ } else {
3601
+ throw new Error("Client not connected. Call start() first.");
3602
+ }
3603
+ }
3604
+ const response = await this.connection.sendRequest("session.resume", {
3605
+ sessionId,
3606
+ tools: config.tools?.map((tool) => ({
3607
+ name: tool.name,
3608
+ description: tool.description,
3609
+ parameters: toJsonSchema(tool.parameters)
3610
+ })),
3611
+ provider: config.provider,
3612
+ requestPermission: !!config.onPermissionRequest,
3613
+ streaming: config.streaming,
3614
+ mcpServers: config.mcpServers,
3615
+ customAgents: config.customAgents,
3616
+ skillDirectories: config.skillDirectories,
3617
+ disabledSkills: config.disabledSkills
3618
+ });
3619
+ const { sessionId: resumedSessionId, workspacePath } = response;
3620
+ const session = new CopilotSession(resumedSessionId, this.connection, workspacePath);
3621
+ session.registerTools(config.tools);
3622
+ if (config.onPermissionRequest) {
3623
+ session.registerPermissionHandler(config.onPermissionRequest);
3624
+ }
3625
+ this.sessions.set(resumedSessionId, session);
3626
+ return session;
3627
+ }
3628
+ getState() {
3629
+ return this.state;
3630
+ }
3631
+ async ping(message) {
3632
+ if (!this.connection) {
3633
+ throw new Error("Client not connected");
3634
+ }
3635
+ const result = await this.connection.sendRequest("ping", { message });
3636
+ return result;
3637
+ }
3638
+ async getStatus() {
3639
+ if (!this.connection) {
3640
+ throw new Error("Client not connected");
3641
+ }
3642
+ const result = await this.connection.sendRequest("status.get", {});
3643
+ return result;
3644
+ }
3645
+ async getAuthStatus() {
3646
+ if (!this.connection) {
3647
+ throw new Error("Client not connected");
3648
+ }
3649
+ const result = await this.connection.sendRequest("auth.getStatus", {});
3650
+ return result;
3651
+ }
3652
+ async listModels() {
3653
+ if (!this.connection) {
3654
+ throw new Error("Client not connected");
3655
+ }
3656
+ const result = await this.connection.sendRequest("models.list", {});
3657
+ const response = result;
3658
+ return response.models;
3659
+ }
3660
+ async verifyProtocolVersion() {
3661
+ const expectedVersion = getSdkProtocolVersion();
3662
+ const pingResult = await this.ping();
3663
+ const serverVersion = pingResult.protocolVersion;
3664
+ if (serverVersion === undefined) {
3665
+ throw new Error(`SDK protocol version mismatch: SDK expects version ${expectedVersion}, but server does not report a protocol version. Please update your server to ensure compatibility.`);
3666
+ }
3667
+ if (serverVersion !== expectedVersion) {
3668
+ throw new Error(`SDK protocol version mismatch: SDK expects version ${expectedVersion}, but server reports version ${serverVersion}. Please update your SDK or server to ensure compatibility.`);
3669
+ }
3670
+ }
3671
+ async getLastSessionId() {
3672
+ if (!this.connection) {
3673
+ throw new Error("Client not connected");
3674
+ }
3675
+ const response = await this.connection.sendRequest("session.getLastId", {});
3676
+ return response.sessionId;
3677
+ }
3678
+ async deleteSession(sessionId) {
3679
+ if (!this.connection) {
3680
+ throw new Error("Client not connected");
3681
+ }
3682
+ const response = await this.connection.sendRequest("session.delete", {
3683
+ sessionId
3684
+ });
3685
+ const { success, error } = response;
3686
+ if (!success) {
3687
+ throw new Error(`Failed to delete session ${sessionId}: ${error || "Unknown error"}`);
3688
+ }
3689
+ this.sessions.delete(sessionId);
3690
+ }
3691
+ async listSessions() {
3692
+ if (!this.connection) {
3693
+ throw new Error("Client not connected");
3694
+ }
3695
+ const response = await this.connection.sendRequest("session.list", {});
3696
+ const { sessions } = response;
3697
+ return sessions.map((s) => ({
3698
+ sessionId: s.sessionId,
3699
+ startTime: new Date(s.startTime),
3700
+ modifiedTime: new Date(s.modifiedTime),
3701
+ summary: s.summary,
3702
+ isRemote: s.isRemote
3703
+ }));
3704
+ }
3705
+ async startCLIServer() {
3706
+ return new Promise((resolve, reject) => {
3707
+ const args = [
3708
+ ...this.options.cliArgs,
3709
+ "--server",
3710
+ "--log-level",
3711
+ this.options.logLevel
3712
+ ];
3713
+ if (this.options.useStdio) {
3714
+ args.push("--stdio");
3715
+ } else if (this.options.port > 0) {
3716
+ args.push("--port", this.options.port.toString());
3717
+ }
3718
+ const envWithoutNodeDebug = { ...this.options.env };
3719
+ delete envWithoutNodeDebug.NODE_DEBUG;
3720
+ const isJsFile = this.options.cliPath.endsWith(".js");
3721
+ const isAbsolutePath = this.options.cliPath.startsWith("/") || /^[a-zA-Z]:/.test(this.options.cliPath);
3722
+ let command;
3723
+ let spawnArgs;
3724
+ if (isJsFile) {
3725
+ command = "node";
3726
+ spawnArgs = [this.options.cliPath, ...args];
3727
+ } else if (process.platform === "win32" && !isAbsolutePath) {
3728
+ command = "cmd";
3729
+ spawnArgs = ["/c", `${this.options.cliPath}`, ...args];
3730
+ } else {
3731
+ command = this.options.cliPath;
3732
+ spawnArgs = args;
3733
+ }
3734
+ this.cliProcess = spawn(command, spawnArgs, {
3735
+ stdio: this.options.useStdio ? ["pipe", "pipe", "pipe"] : ["ignore", "pipe", "pipe"],
3736
+ cwd: this.options.cwd,
3737
+ env: envWithoutNodeDebug
3738
+ });
3739
+ let stdout = "";
3740
+ let resolved = false;
3741
+ if (this.options.useStdio) {
3742
+ resolved = true;
3743
+ resolve();
3744
+ } else {
3745
+ this.cliProcess.stdout?.on("data", (data) => {
3746
+ stdout += data.toString();
3747
+ const match = stdout.match(/listening on port (\d+)/i);
3748
+ if (match && !resolved) {
3749
+ this.actualPort = parseInt(match[1], 10);
3750
+ resolved = true;
3751
+ resolve();
3752
+ }
3753
+ });
3754
+ }
3755
+ this.cliProcess.stderr?.on("data", (data) => {
3756
+ const lines = data.toString().split(`
3757
+ `);
3758
+ for (const line of lines) {
3759
+ if (line.trim()) {
3760
+ process.stderr.write(`[CLI subprocess] ${line}
3761
+ `);
3762
+ }
3763
+ }
3764
+ });
3765
+ this.cliProcess.on("error", (error) => {
3766
+ if (!resolved) {
3767
+ resolved = true;
3768
+ reject(new Error(`Failed to start CLI server: ${error.message}`));
3769
+ }
3770
+ });
3771
+ this.cliProcess.on("exit", (code) => {
3772
+ if (!resolved) {
3773
+ resolved = true;
3774
+ reject(new Error(`CLI server exited with code ${code}`));
3775
+ } else if (this.options.autoRestart && this.state === "connected") {
3776
+ this.reconnect();
3777
+ }
3778
+ });
3779
+ setTimeout(() => {
3780
+ if (!resolved) {
3781
+ resolved = true;
3782
+ reject(new Error("Timeout waiting for CLI server to start"));
3783
+ }
3784
+ }, 1e4);
3785
+ });
3786
+ }
3787
+ async connectToServer() {
3788
+ if (this.options.useStdio) {
3789
+ return this.connectViaStdio();
3790
+ } else {
3791
+ return this.connectViaTcp();
3792
+ }
3793
+ }
3794
+ async connectViaStdio() {
3795
+ if (!this.cliProcess) {
3796
+ throw new Error("CLI process not started");
3797
+ }
3798
+ this.cliProcess.stdin?.on("error", (err) => {
3799
+ if (!this.forceStopping) {
3800
+ throw err;
3801
+ }
3802
+ });
3803
+ this.connection = import_node.createMessageConnection(new import_node.StreamMessageReader(this.cliProcess.stdout), new import_node.StreamMessageWriter(this.cliProcess.stdin));
3804
+ this.attachConnectionHandlers();
3805
+ this.connection.listen();
3806
+ }
3807
+ async connectViaTcp() {
3808
+ if (!this.actualPort) {
3809
+ throw new Error("Server port not available");
3810
+ }
3811
+ return new Promise((resolve, reject) => {
3812
+ this.socket = new Socket;
3813
+ this.socket.connect(this.actualPort, this.actualHost, () => {
3814
+ this.connection = import_node.createMessageConnection(new import_node.StreamMessageReader(this.socket), new import_node.StreamMessageWriter(this.socket));
3815
+ this.attachConnectionHandlers();
3816
+ this.connection.listen();
3817
+ resolve();
3818
+ });
3819
+ this.socket.on("error", (error) => {
3820
+ reject(new Error(`Failed to connect to CLI server: ${error.message}`));
3821
+ });
3822
+ });
3823
+ }
3824
+ attachConnectionHandlers() {
3825
+ if (!this.connection) {
3826
+ return;
3827
+ }
3828
+ this.connection.onNotification("session.event", (notification) => {
3829
+ this.handleSessionEventNotification(notification);
3830
+ });
3831
+ this.connection.onRequest("tool.call", async (params) => await this.handleToolCallRequest(params));
3832
+ this.connection.onRequest("permission.request", async (params) => await this.handlePermissionRequest(params));
3833
+ this.connection.onClose(() => {
3834
+ if (this.state === "connected" && this.options.autoRestart) {
3835
+ this.reconnect();
3836
+ }
3837
+ });
3838
+ this.connection.onError((_error) => {});
3839
+ }
3840
+ handleSessionEventNotification(notification) {
3841
+ if (typeof notification !== "object" || !notification || !("sessionId" in notification) || typeof notification.sessionId !== "string" || !("event" in notification)) {
3842
+ return;
3843
+ }
3844
+ const session = this.sessions.get(notification.sessionId);
3845
+ if (session) {
3846
+ session._dispatchEvent(notification.event);
3847
+ }
3848
+ }
3849
+ async handleToolCallRequest(params) {
3850
+ if (!params || typeof params.sessionId !== "string" || typeof params.toolCallId !== "string" || typeof params.toolName !== "string") {
3851
+ throw new Error("Invalid tool call payload");
3852
+ }
3853
+ const session = this.sessions.get(params.sessionId);
3854
+ if (!session) {
3855
+ throw new Error(`Unknown session ${params.sessionId}`);
3856
+ }
3857
+ const handler = session.getToolHandler(params.toolName);
3858
+ if (!handler) {
3859
+ return { result: this.buildUnsupportedToolResult(params.toolName) };
3860
+ }
3861
+ return await this.executeToolCall(handler, params);
3862
+ }
3863
+ async executeToolCall(handler, request) {
3864
+ try {
3865
+ const invocation = {
3866
+ sessionId: request.sessionId,
3867
+ toolCallId: request.toolCallId,
3868
+ toolName: request.toolName,
3869
+ arguments: request.arguments
3870
+ };
3871
+ const result = await handler(request.arguments, invocation);
3872
+ return { result: this.normalizeToolResult(result) };
3873
+ } catch (error) {
3874
+ const message = error instanceof Error ? error.message : String(error);
3875
+ return {
3876
+ result: {
3877
+ textResultForLlm: "Invoking this tool produced an error. Detailed information is not available.",
3878
+ resultType: "failure",
3879
+ error: message,
3880
+ toolTelemetry: {}
3881
+ }
3882
+ };
3883
+ }
3884
+ }
3885
+ async handlePermissionRequest(params) {
3886
+ if (!params || typeof params.sessionId !== "string" || !params.permissionRequest) {
3887
+ throw new Error("Invalid permission request payload");
3888
+ }
3889
+ const session = this.sessions.get(params.sessionId);
3890
+ if (!session) {
3891
+ throw new Error(`Session not found: ${params.sessionId}`);
3892
+ }
3893
+ try {
3894
+ const result = await session._handlePermissionRequest(params.permissionRequest);
3895
+ return { result };
3896
+ } catch (_error) {
3897
+ return {
3898
+ result: {
3899
+ kind: "denied-no-approval-rule-and-could-not-request-from-user"
3900
+ }
3901
+ };
3902
+ }
3903
+ }
3904
+ normalizeToolResult(result) {
3905
+ if (result === undefined || result === null) {
3906
+ return {
3907
+ textResultForLlm: "Tool returned no result",
3908
+ resultType: "failure",
3909
+ error: "tool returned no result",
3910
+ toolTelemetry: {}
3911
+ };
3912
+ }
3913
+ if (this.isToolResultObject(result)) {
3914
+ return result;
3915
+ }
3916
+ const textResult = typeof result === "string" ? result : JSON.stringify(result);
3917
+ return {
3918
+ textResultForLlm: textResult,
3919
+ resultType: "success",
3920
+ toolTelemetry: {}
3921
+ };
3922
+ }
3923
+ isToolResultObject(value) {
3924
+ return typeof value === "object" && value !== null && "textResultForLlm" in value && typeof value.textResultForLlm === "string" && "resultType" in value;
3925
+ }
3926
+ buildUnsupportedToolResult(toolName) {
3927
+ return {
3928
+ textResultForLlm: `Tool '${toolName}' is not supported by this client instance.`,
3929
+ resultType: "failure",
3930
+ error: `tool '${toolName}' not supported`,
3931
+ toolTelemetry: {}
3932
+ };
3933
+ }
3934
+ async reconnect() {
3935
+ this.state = "disconnected";
3936
+ try {
3937
+ await this.stop();
3938
+ await this.start();
3939
+ } catch (_error) {}
3940
+ }
3941
+ }
3942
+
3943
+ // src/agent.ts
3944
+ import * as fs4 from "fs";
3945
+ import * as path4 from "path";
3946
+
3947
+ // src/tools/read-vtt.ts
3948
+ import * as fs from "fs";
3949
+ import * as path from "path";
3950
+
3951
+ // src/utils/vtt-parser.ts
3952
+ function parseTimeToSeconds(timeStr) {
3953
+ const parts = timeStr.trim().split(":");
3954
+ if (parts.length === 3) {
3955
+ const [hours, minutes, seconds] = parts;
3956
+ return parseInt(hours, 10) * 3600 + parseInt(minutes, 10) * 60 + parseFloat(seconds);
3957
+ } else if (parts.length === 2) {
3958
+ const [minutes, seconds] = parts;
3959
+ return parseInt(minutes, 10) * 60 + parseFloat(seconds);
3960
+ }
3961
+ return parseFloat(timeStr);
3962
+ }
3963
+ function parseVtt(content, filePath) {
3964
+ const lines = content.replace(/\r\n/g, `
3965
+ `).split(`
3966
+ `);
3967
+ const cues = [];
3968
+ let index = 0;
3969
+ let i = 0;
3970
+ while (i < lines.length && !lines[i].includes("-->")) {
3971
+ i++;
3972
+ }
3973
+ while (i < lines.length) {
3974
+ const line = lines[i].trim();
3975
+ if (line.includes("-->")) {
3976
+ const timeParts = line.split("-->");
3977
+ if (timeParts.length >= 2) {
3978
+ const startTime = timeParts[0].trim().split(" ")[0];
3979
+ const endTime = timeParts[1].trim().split(" ")[0];
3980
+ const textLines = [];
3981
+ i++;
3982
+ while (i < lines.length && lines[i].trim() !== "" && !lines[i].includes("-->")) {
3983
+ textLines.push(lines[i].trim());
3984
+ i++;
3985
+ }
3986
+ if (textLines.length > 0) {
3987
+ cues.push({
3988
+ index: index++,
3989
+ startTime,
3990
+ endTime,
3991
+ startSeconds: parseTimeToSeconds(startTime),
3992
+ endSeconds: parseTimeToSeconds(endTime),
3993
+ text: textLines.join(`
3994
+ `)
3995
+ });
3996
+ }
3997
+ } else {
3998
+ i++;
3999
+ }
4000
+ } else {
4001
+ i++;
4002
+ }
4003
+ }
4004
+ return {
4005
+ filePath,
4006
+ cues,
4007
+ rawContent: content
4008
+ };
4009
+ }
4010
+ function formatVtt(vttFile) {
4011
+ const lines = ["WEBVTT", ""];
4012
+ for (const cue of vttFile.cues) {
4013
+ lines.push(`${cue.startTime} --> ${cue.endTime}`);
4014
+ lines.push(cue.text);
4015
+ lines.push("");
4016
+ }
4017
+ return lines.join(`
4018
+ `);
4019
+ }
4020
+ function formatCuesForDisplay(vttFile) {
4021
+ return vttFile.cues.map((cue) => `[${cue.index}] ${cue.startTime} --> ${cue.endTime}
4022
+ ${cue.text}`).join(`
4023
+
4024
+ `);
4025
+ }
4026
+
4027
+ // src/tools/read-vtt.ts
4028
+ var cachedVttFile = null;
4029
+ function getCachedVttFile() {
4030
+ return cachedVttFile;
4031
+ }
4032
+ var readVttTool = {
4033
+ name: "read_vtt_file",
4034
+ description: "讀取並解析 VTT 字幕檔案,回傳所有字幕的時間戳和內容。",
4035
+ parameters: {
4036
+ type: "object",
4037
+ properties: {
4038
+ filePath: { type: "string", description: "VTT 檔案的完整路徑" }
4039
+ },
4040
+ required: ["filePath"]
4041
+ },
4042
+ handler: async ({ filePath }) => {
4043
+ try {
4044
+ console.log(`[DEBUG] readVttTool: Starting to read ${filePath}`);
4045
+ const absolutePath = path.resolve(filePath);
4046
+ if (!fs.existsSync(absolutePath)) {
4047
+ console.log(`[DEBUG] readVttTool: File not found ${absolutePath}`);
4048
+ return { success: false, error: `檔案不存在: ${absolutePath}` };
4049
+ }
4050
+ const content = fs.readFileSync(absolutePath, "utf-8");
4051
+ console.log(`[DEBUG] readVttTool: File read, size ${content.length} bytes`);
4052
+ const vttFile = parseVtt(content, absolutePath);
4053
+ cachedVttFile = vttFile;
4054
+ const displayCues = formatCuesForDisplay(vttFile);
4055
+ console.log(`[DEBUG] readVttTool: Parsed ${vttFile.cues.length} cues, formatted length ${displayCues.length}`);
4056
+ return {
4057
+ success: true,
4058
+ filePath: absolutePath,
4059
+ totalCues: vttFile.cues.length,
4060
+ cues: displayCues
4061
+ };
4062
+ } catch (error) {
4063
+ console.error(`[DEBUG] readVttTool Error:`, error);
4064
+ return { success: false, error: String(error) };
4065
+ }
4066
+ }
4067
+ };
4068
+ var getVttCuesTool = {
4069
+ name: "get_vtt_cues",
4070
+ description: "取得已載入 VTT 檔案的特定範圍字幕 (用於分批處理大檔案)",
4071
+ parameters: {
4072
+ type: "object",
4073
+ properties: {
4074
+ startIndex: { type: "number", description: "起始 Cue 索引 (從 0 開始)" },
4075
+ endIndex: { type: "number", description: "結束 Cue 索引 (不含)" }
4076
+ },
4077
+ required: ["startIndex", "endIndex"]
4078
+ },
4079
+ handler: async ({ startIndex, endIndex }) => {
4080
+ if (!cachedVttFile) {
4081
+ return { success: false, error: "請先使用 read_vtt_file 載入 VTT 檔案" };
4082
+ }
4083
+ const cues = cachedVttFile.cues.slice(startIndex, endIndex);
4084
+ return {
4085
+ success: true,
4086
+ totalCues: cachedVttFile.cues.length,
4087
+ requestedRange: `${startIndex}-${endIndex}`,
4088
+ returnedCues: cues.length,
4089
+ cues: cues.map((cue) => ({
4090
+ index: cue.index,
4091
+ time: `${cue.startTime} --> ${cue.endTime}`,
4092
+ text: cue.text
4093
+ }))
4094
+ };
4095
+ }
4096
+ };
4097
+ // src/tools/write-file.ts
4098
+ import * as fs2 from "fs";
4099
+ import * as path2 from "path";
4100
+ var writeFileTool = {
4101
+ name: "write_file",
4102
+ description: "將內容寫入到指定的檔案中。用於產生修正清單、章節資訊、總結等輸出檔案。",
4103
+ parameters: {
4104
+ type: "object",
4105
+ properties: {
4106
+ filePath: { type: "string", description: "要寫入的檔案路徑" },
4107
+ content: { type: "string", description: "要寫入的內容" },
4108
+ encoding: { type: "string", description: "檔案編碼,預設為 utf-8" }
4109
+ },
4110
+ required: ["filePath", "content"]
4111
+ },
4112
+ handler: async ({ filePath, content, encoding = "utf-8" }) => {
4113
+ try {
4114
+ const absolutePath = path2.resolve(filePath);
4115
+ const dir = path2.dirname(absolutePath);
4116
+ if (!fs2.existsSync(dir)) {
4117
+ fs2.mkdirSync(dir, { recursive: true });
4118
+ }
4119
+ fs2.writeFileSync(absolutePath, content, { encoding });
4120
+ return {
4121
+ success: true,
4122
+ filePath: absolutePath,
4123
+ bytesWritten: Buffer.byteLength(content, encoding)
4124
+ };
4125
+ } catch (error) {
4126
+ return { success: false, error: String(error) };
4127
+ }
4128
+ }
4129
+ };
4130
+ var appendFileTool = {
4131
+ name: "append_file",
4132
+ description: "將內容附加到指定的檔案末尾。",
4133
+ parameters: {
4134
+ type: "object",
4135
+ properties: {
4136
+ filePath: { type: "string", description: "要附加內容的檔案路徑" },
4137
+ content: { type: "string", description: "要附加的內容" }
4138
+ },
4139
+ required: ["filePath", "content"]
4140
+ },
4141
+ handler: async ({ filePath, content }) => {
4142
+ try {
4143
+ const absolutePath = path2.resolve(filePath);
4144
+ fs2.appendFileSync(absolutePath, content, "utf-8");
4145
+ return {
4146
+ success: true,
4147
+ filePath: absolutePath,
4148
+ bytesAppended: Buffer.byteLength(content, "utf-8")
4149
+ };
4150
+ } catch (error) {
4151
+ return { success: false, error: String(error) };
4152
+ }
4153
+ }
4154
+ };
4155
+ // src/tools/update-vtt.ts
4156
+ import * as fs3 from "fs";
4157
+ import * as path3 from "path";
4158
+ var updateCueTool = {
4159
+ name: "update_cue",
4160
+ description: "更新指定索引的字幕內容。用於校正字幕中的錯字。",
4161
+ parameters: {
4162
+ type: "object",
4163
+ properties: {
4164
+ cueIndex: { type: "number", description: "要更新的 Cue 索引 (從 0 開始)" },
4165
+ newText: { type: "string", description: "校正後的字幕文字" }
4166
+ },
4167
+ required: ["cueIndex", "newText"]
4168
+ },
4169
+ handler: async ({ cueIndex, newText }) => {
4170
+ const vttFile = getCachedVttFile();
4171
+ if (!vttFile) {
4172
+ return { success: false, error: "請先使用 read_vtt_file 載入 VTT 檔案" };
4173
+ }
4174
+ if (cueIndex < 0 || cueIndex >= vttFile.cues.length) {
4175
+ return { success: false, error: `無效的 Cue 索引: ${cueIndex},有效範圍: 0-${vttFile.cues.length - 1}` };
4176
+ }
4177
+ const oldText = vttFile.cues[cueIndex].text;
4178
+ vttFile.cues[cueIndex].text = newText;
4179
+ return {
4180
+ success: true,
4181
+ cueIndex,
4182
+ oldText,
4183
+ newText,
4184
+ time: `${vttFile.cues[cueIndex].startTime} --> ${vttFile.cues[cueIndex].endTime}`
4185
+ };
4186
+ }
4187
+ };
4188
+ var batchUpdateCuesTool = {
4189
+ name: "batch_update_cues",
4190
+ description: "批次更新多個字幕內容。用於一次校正多個字幕中的錯字。",
4191
+ parameters: {
4192
+ type: "object",
4193
+ properties: {
4194
+ updates: {
4195
+ type: "array",
4196
+ description: "要更新的字幕清單",
4197
+ items: {
4198
+ type: "object",
4199
+ properties: {
4200
+ cueIndex: { type: "number", description: "要更新的 Cue 索引" },
4201
+ newText: { type: "string", description: "校正後的字幕文字" }
4202
+ },
4203
+ required: ["cueIndex", "newText"]
4204
+ }
4205
+ }
4206
+ },
4207
+ required: ["updates"]
4208
+ },
4209
+ handler: async ({ updates }) => {
4210
+ const vttFile = getCachedVttFile();
4211
+ if (!vttFile) {
4212
+ return { success: false, error: "請先使用 read_vtt_file 載入 VTT 檔案" };
4213
+ }
4214
+ const results = [];
4215
+ for (const update of updates) {
4216
+ if (update.cueIndex >= 0 && update.cueIndex < vttFile.cues.length) {
4217
+ const oldText = vttFile.cues[update.cueIndex].text;
4218
+ vttFile.cues[update.cueIndex].text = update.newText;
4219
+ results.push({
4220
+ cueIndex: update.cueIndex,
4221
+ oldText,
4222
+ newText: update.newText,
4223
+ time: `${vttFile.cues[update.cueIndex].startTime} --> ${vttFile.cues[update.cueIndex].endTime}`
4224
+ });
4225
+ }
4226
+ }
4227
+ return {
4228
+ success: true,
4229
+ updatedCount: results.length,
4230
+ updates: results
4231
+ };
4232
+ }
4233
+ };
4234
+ var saveVttTool = {
4235
+ name: "save_vtt",
4236
+ description: "將修改後的 VTT 字幕儲存到檔案。",
4237
+ parameters: {
4238
+ type: "object",
4239
+ properties: {
4240
+ outputPath: { type: "string", description: "輸出檔案路徑,若未指定則覆蓋原檔案" }
4241
+ },
4242
+ required: []
4243
+ },
4244
+ handler: async ({ outputPath }) => {
4245
+ const vttFile = getCachedVttFile();
4246
+ if (!vttFile) {
4247
+ return { success: false, error: "請先使用 read_vtt_file 載入 VTT 檔案" };
4248
+ }
4249
+ try {
4250
+ const targetPath = outputPath ? path3.resolve(outputPath) : vttFile.filePath;
4251
+ const content = formatVtt(vttFile);
4252
+ fs3.writeFileSync(targetPath, content, "utf-8");
4253
+ return {
4254
+ success: true,
4255
+ filePath: targetPath,
4256
+ totalCues: vttFile.cues.length
4257
+ };
4258
+ } catch (error) {
4259
+ return { success: false, error: String(error) };
4260
+ }
4261
+ }
4262
+ };
4263
+ // src/agent.ts
4264
+ class EventLogger {
4265
+ filePath;
4266
+ stream;
4267
+ isFirst = true;
4268
+ constructor(filePath) {
4269
+ this.filePath = filePath;
4270
+ this.stream = fs4.createWriteStream(filePath, { encoding: "utf-8" });
4271
+ this.stream.write(`[
4272
+ `);
4273
+ }
4274
+ append(event) {
4275
+ const payload = JSON.stringify(event, (_key, value) => typeof value === "bigint" ? value.toString() : value, 2);
4276
+ const prefix = this.isFirst ? "" : `,
4277
+ `;
4278
+ this.isFirst = false;
4279
+ this.stream.write(`${prefix}${payload}`);
4280
+ }
4281
+ close() {
4282
+ this.stream.write(`
4283
+ ]
4284
+ `);
4285
+ this.stream.end();
4286
+ }
4287
+ }
4288
+ function isDebugEnabled() {
4289
+ const raw = process.env.BOT_DEBUG;
4290
+ if (!raw) {
4291
+ return false;
4292
+ }
4293
+ return raw === "1" || raw.toLowerCase() === "true";
4294
+ }
4295
+ async function sendAndWait(session, prompt, eventLogger) {
4296
+ return new Promise((resolve5, reject) => {
4297
+ let content = "";
4298
+ let isResolved = false;
4299
+ let timeoutId;
4300
+ let unsubscribe;
4301
+ const cleanup = () => {
4302
+ if (timeoutId)
4303
+ clearTimeout(timeoutId);
4304
+ if (unsubscribe)
4305
+ unsubscribe();
4306
+ };
4307
+ const handleEvent = (event) => {
4308
+ eventLogger?.append(event);
4309
+ if (isDebugEnabled()) {
4310
+ console.log(`[DEBUG] Event received: ${event.type}`);
4311
+ }
4312
+ if (event.type === "assistant.message_delta") {
4313
+ const delta = event.data.deltaContent ?? "";
4314
+ process.stdout.write(delta);
4315
+ }
4316
+ if (event.type === "assistant.message") {
4317
+ content = event.data.content ?? "";
4318
+ }
4319
+ if (event.type === "session.idle" && !isResolved) {
4320
+ isResolved = true;
4321
+ console.log(`
4322
+ `);
4323
+ cleanup();
4324
+ resolve5(content);
4325
+ }
4326
+ if (event.type === "session.error") {
4327
+ if (!isResolved) {
4328
+ isResolved = true;
4329
+ cleanup();
4330
+ reject(new Error(event.data?.message ?? "Unknown error"));
4331
+ }
4332
+ }
4333
+ };
4334
+ unsubscribe = session.on(handleEvent);
4335
+ timeoutId = setTimeout(() => {
4336
+ if (!isResolved) {
4337
+ isResolved = true;
4338
+ cleanup();
4339
+ reject(new Error("Timeout: 等待 Copilot 回應超過 120 秒"));
4340
+ }
4341
+ }, 120000);
4342
+ session.send({ prompt }).catch((err) => {
4343
+ if (!isResolved) {
4344
+ isResolved = true;
4345
+ cleanup();
4346
+ reject(err);
4347
+ }
4348
+ });
4349
+ });
4350
+ }
4351
+ async function runSubtitleCorrectionAgent(config) {
4352
+ const { vttFilePath } = config;
4353
+ const absolutePath = path4.resolve(vttFilePath);
4354
+ const dir = config.outputDir || path4.dirname(absolutePath);
4355
+ const baseName = path4.basename(absolutePath, path4.extname(absolutePath));
4356
+ const debugEvents = isDebugEnabled();
4357
+ const eventLogPath = debugEvents ? path4.join(dir, `${baseName}-copilot-events.json`) : undefined;
4358
+ const eventLogger = eventLogPath ? new EventLogger(eventLogPath) : undefined;
4359
+ const correctedVttPath = path4.join(dir, `${baseName}-corrected.vtt`);
4360
+ const correctionsPath = path4.join(dir, `${baseName}-corrections.txt`);
4361
+ const chaptersPath = path4.join(dir, `${baseName}-chapters.txt`);
4362
+ const summaryPath = path4.join(dir, `${baseName}-summary.txt`);
4363
+ console.log("=".repeat(60));
4364
+ console.log("字幕校正代理人 - 啟動");
4365
+ console.log("=".repeat(60));
4366
+ console.log(`輸入檔案: ${absolutePath}`);
4367
+ console.log(`輸出目錄: ${dir}`);
4368
+ console.log("=".repeat(60));
4369
+ if (eventLogPath) {
4370
+ console.log(`偵錯: Copilot events 記錄到 ${eventLogPath}`);
4371
+ }
4372
+ const client = new CopilotClient;
4373
+ try {
4374
+ await client.start();
4375
+ const azureEndpoint = process.env.AZURE_OPENAI_ENDPOINT;
4376
+ const azureApiKey = process.env.AZURE_OPENAI_API_KEY;
4377
+ const azureDeployment = process.env.AZURE_OPENAI_DEPLOYMENT;
4378
+ const tools = [
4379
+ readVttTool,
4380
+ getVttCuesTool,
4381
+ writeFileTool,
4382
+ appendFileTool,
4383
+ updateCueTool,
4384
+ batchUpdateCuesTool,
4385
+ saveVttTool
4386
+ ];
4387
+ let session;
4388
+ if (azureEndpoint && azureApiKey && azureDeployment) {
4389
+ console.log("使用 Azure OpenAI 作為模型提供者");
4390
+ session = await client.createSession({
4391
+ model: azureDeployment,
4392
+ streaming: true,
4393
+ provider: {
4394
+ type: "azure",
4395
+ baseUrl: azureEndpoint,
4396
+ apiKey: azureApiKey,
4397
+ azure: {
4398
+ apiVersion: process.env.AZURE_OPENAI_API_VERSION || "2024-10-21"
4399
+ }
4400
+ },
4401
+ tools
4402
+ });
4403
+ } else {
4404
+ console.log("未找到完整的 Azure 配置,將使用預設的 GitHub Copilot 認證");
4405
+ session = await client.createSession({
4406
+ tools
4407
+ });
4408
+ }
4409
+ console.log(`
4410
+ 【步驟 1/7】讀取 VTT 檔案並分析主題方向...
4411
+ `);
4412
+ await sendAndWait(session, `請使用 read_vtt_file 工具讀取 VTT 檔案: "${absolutePath}"
4413
+
4414
+ 讀取完成後,請仔細閱讀整個字幕內容,分析並整理出:
4415
+ 1. 這部影片的主要談論內容是什麼?
4416
+ 2. 影片的大致主題方向是什麼?
4417
+ 3. 這是什麼類型的影片?(教學、訪談、講座、會議等)
4418
+
4419
+ 請給出簡潔但完整的分析。`, eventLogger);
4420
+ console.log(`
4421
+ 【步驟 2/7】整理主題相關的關鍵字與專有名詞...
4422
+ `);
4423
+ await sendAndWait(session, `根據你剛才分析出的影片主題方向,請整理出這個主題領域中常見的:
4424
+ 1. 專業術語與關鍵字
4425
+ 2. 專有名詞(人名、產品名、技術名稱等)
4426
+ 3. 常見的縮寫與其全稱
4427
+
4428
+ 【重要】請不要參考字幕的實際內容來整理這些詞彙(因為字幕可能有轉錄錯誤)。
4429
+ 請根據你對這個主題領域的知識,列出這些詞彙的「正確寫法」,這將用於後續的字幕校正。`, eventLogger);
4430
+ console.log(`
4431
+ 【步驟 3-4/7】分析字幕正確性並進行校正...
4432
+ `);
4433
+ await sendAndWait(session, `現在請逐一分析已載入的 VTT 字幕檔案中每一段 Cue 的正確性。
4434
+
4435
+ 對於每個 Cue:
4436
+ 1. 檢查是否有潛在的錯字、同音字錯誤、轉錄錯誤
4437
+ 2. 根據上下文和你整理出的正確關鍵字/專有名詞,推理出正確的文字
4438
+ 3. 如果需要校正,請使用 batch_update_cues 工具批次更新校正後的字幕
4439
+
4440
+ 請特別注意:
4441
+ - 專業術語和專有名詞的正確性
4442
+ - 同音異義字的正確使用
4443
+ - 語句的通順和邏輯性
4444
+ - 標點符號的使用
4445
+
4446
+ 處理完成後,請報告發現了多少個需要校正的問題。`, eventLogger);
4447
+ console.log(`
4448
+ 【步驟 5/7】產生修正清單...
4449
+ `);
4450
+ await sendAndWait(session, `請整理所有剛才進行的字幕校正,使用 write_file 工具將修正清單寫入到:
4451
+ "${correctionsPath}"
4452
+
4453
+ 修正清單的格式應該包含:
4454
+ 1. 標題:字幕修正清單
4455
+ 2. 修正日期與時間
4456
+ 3. 原始檔案路徑
4457
+ 4. 修正統計(總共修正了多少處)
4458
+ 5. 每一筆修正的詳細資訊:
4459
+ - Cue 索引與時間戳
4460
+ - 原始文字
4461
+ - 校正後文字
4462
+ - 修正原因說明
4463
+
4464
+ 請以清晰易讀的格式呈現。`, eventLogger);
4465
+ console.log(`
4466
+ 【儲存校正後的 VTT 檔案】
4467
+ `);
4468
+ await sendAndWait(session, `請使用 save_vtt 工具將校正後的字幕儲存到:
4469
+ "${correctedVttPath}"`, eventLogger);
4470
+ console.log(`
4471
+ 【步驟 6/7】建立分段章節...
4472
+ `);
4473
+ await sendAndWait(session, `你現在是一個 **Video Chapter Segmenter**,負責分析字幕內容並將影片分割成清晰、合理的章節。
4474
+
4475
+ ## 分析準則
4476
+ - **主題轉換**: 識別主題或討論重點的變化
4477
+ - **敘事變化**: 檢測故事進展、場景變化或情節發展
4478
+ - **主題轉移**: 識別語氣、情緒或概念焦點的變化
4479
+ - **說話者變化**: 注意不同說話者或觀點之間的轉換
4480
+ - **明確的轉場提示**: 考慮字幕中提到的明確轉換(例如「接下來...」、「下一個主題」)
4481
+
4482
+ ## 章節標題要求
4483
+ - **簡潔**: 每個標題最多 10 個字
4484
+ - **描述性**: 捕捉該段落內容的本質
4485
+ - **行動導向**: 盡可能使用主動語態
4486
+ - **風格一致**: 所有標題保持統一的格式和語調
4487
+
4488
+ ## 輸出格式要求
4489
+ - **嚴格格式**: \`HH:mm:ss 章節標題\`
4490
+ - **第一章節**: 必須以 \`00:00:00 開始\` 開頭
4491
+ - **時間精確度**: 使用字幕檔案中的精確時間戳
4492
+ - **每行一章**: 每個章節獨立一行
4493
+ - **無額外格式**: 不使用項目符號、編號或特殊字元
4494
+
4495
+ ## 限制條件
4496
+ - **最少章節**: 3 個章節(包含「開始」)
4497
+ - **最多章節**: 15 個章節
4498
+ - **最短時長**: 每個章節通常至少 30 秒(自然斷點例外)
4499
+ - **完整覆蓋**: 確保從頭到尾完整覆蓋影片
4500
+
4501
+ ## 輸出範例
4502
+ \`\`\`
4503
+ 00:00:00 開始
4504
+ 00:00:16 開發過程的混亂
4505
+ 00:00:28 規格驅動開發的啟發
4506
+ 00:00:38 規格驅動開發主題曲
4507
+ 00:01:03 AI輔助與測試先行
4508
+ 00:01:38 團隊協作的重要性
4509
+ 00:02:04 從混沌到清晰的轉變
4510
+ 00:02:29 終章:持續改進的承諾
4511
+ \`\`\`
4512
+
4513
+ 請根據校正後的字幕內容,深入分析並自動建立分段章節。
4514
+ 使用 write_file 工具將章節資訊寫入到:
4515
+ "${chaptersPath}"
4516
+
4517
+ 請只輸出章節清單,格式如上述範例。`, eventLogger);
4518
+ console.log(`
4519
+ 【步驟 7/7】產生內容總結...
4520
+ `);
4521
+ await sendAndWait(session, `請根據校正後的字幕內容,用一段話總結這部影片的主要內容。
4522
+
4523
+ 總結應該:
4524
+ 1. 概括影片的核心主題
4525
+ 2. 提及主要討論的重點
4526
+ 3. 簡述影片的價值或目標受眾
4527
+
4528
+ 請使用 write_file 工具將總結寫入到:
4529
+ "${summaryPath}"
4530
+
4531
+ 總結字數建議在 200-500 字之間,力求簡潔但資訊完整。`, eventLogger);
4532
+ await session.destroy();
4533
+ await client.stop();
4534
+ console.log("=".repeat(60));
4535
+ console.log("字幕校正完成!");
4536
+ console.log("=".repeat(60));
4537
+ console.log(`校正後字幕: ${correctedVttPath}`);
4538
+ console.log(`修正清單: ${correctionsPath}`);
4539
+ console.log(`章節資訊: ${chaptersPath}`);
4540
+ console.log(`內容總結: ${summaryPath}`);
4541
+ console.log("=".repeat(60));
4542
+ return {
4543
+ success: true,
4544
+ correctedVttPath,
4545
+ correctionsPath,
4546
+ chaptersPath,
4547
+ summaryPath
4548
+ };
4549
+ } catch (error) {
4550
+ await client.stop();
4551
+ return {
4552
+ success: false,
4553
+ error: String(error)
4554
+ };
4555
+ } finally {
4556
+ eventLogger?.close();
4557
+ }
4558
+ }
4559
+
4560
+ // src/index.ts
4561
+ function printUsage() {
4562
+ console.log(`
4563
+ 字幕校正代理人 - 使用說明
4564
+ ========================
4565
+
4566
+ 使用方式:
4567
+ subtitle-correction-agent <vtt-file-path> [options]
4568
+ subtitle-correction-agent --version
4569
+
4570
+ 參數:
4571
+ <vtt-file-path> VTT 字幕檔案的路徑 (必須)
4572
+
4573
+ 選項:
4574
+ --output-dir <dir> 指定輸出目錄 (預設為 VTT 檔案所在目錄)
4575
+ --version, -v 顯示版本與環境資訊
4576
+ --help, -h 顯示此說明
4577
+
4578
+ 範例:
4579
+ subtitle-correction-agent ./video.vtt
4580
+ subtitle-correction-agent ./video.vtt --output-dir ./output
4581
+ subtitle-correction-agent --version
4582
+ npx @willh/subtitle-correction-agent ./video.vtt
4583
+ subtitle-correction-agent "C:\\Videos\\lecture.vtt"
4584
+
4585
+ 輸出檔案:
4586
+ {filename}-corrected.vtt 校正後的字幕檔案
4587
+ {filename}-corrections.txt 修正清單
4588
+ {filename}-chapters.txt 章節資訊
4589
+ {filename}-summary.txt 內容總結
4590
+
4591
+ 環境變數:
4592
+ AZURE_OPENAI_ENDPOINT Azure OpenAI 端點 URL
4593
+ AZURE_OPENAI_API_KEY Azure OpenAI API 金鑰
4594
+ AZURE_OPENAI_DEPLOYMENT Azure OpenAI 部署名稱
4595
+ AZURE_OPENAI_API_VERSION API 版本 (預設: 2024-10-21)
4596
+ `);
4597
+ }
4598
+ function parseArgs(args) {
4599
+ const result = {
4600
+ help: false,
4601
+ version: false
4602
+ };
4603
+ for (let i = 0;i < args.length; i++) {
4604
+ const arg = args[i];
4605
+ if (arg === "--help" || arg === "-h") {
4606
+ result.help = true;
4607
+ } else if (arg === "--version" || arg === "-v") {
4608
+ result.version = true;
4609
+ } else if (arg === "--output-dir" && i + 1 < args.length) {
4610
+ result.outputDir = args[++i];
4611
+ } else if (!arg.startsWith("-") && !result.vttFilePath) {
4612
+ result.vttFilePath = arg;
4613
+ }
4614
+ }
4615
+ return result;
4616
+ }
4617
+ function resolveProjectRoot() {
4618
+ const currentFile = fileURLToPath(import.meta.url);
4619
+ let dir = path5.dirname(currentFile);
4620
+ while (true) {
4621
+ const candidate = path5.join(dir, "package.json");
4622
+ if (fs5.existsSync(candidate)) {
4623
+ return dir;
4624
+ }
4625
+ const parent = path5.dirname(dir);
4626
+ if (parent === dir) {
4627
+ return null;
4628
+ }
4629
+ dir = parent;
4630
+ }
4631
+ }
4632
+ function readJsonFile(filePath) {
4633
+ try {
4634
+ const raw = fs5.readFileSync(filePath, "utf-8");
4635
+ return JSON.parse(raw);
4636
+ } catch {
4637
+ return null;
4638
+ }
4639
+ }
4640
+ function resolveAppVersion(projectRoot) {
4641
+ if (!projectRoot) {
4642
+ return "未知";
4643
+ }
4644
+ const pkgJson = readJsonFile(path5.join(projectRoot, "package.json"));
4645
+ if (pkgJson && typeof pkgJson.version === "string") {
4646
+ return pkgJson.version;
4647
+ }
4648
+ return "未知";
4649
+ }
4650
+ function resolveCopilotSdkVersion(projectRoot) {
4651
+ if (!projectRoot) {
4652
+ return "未知";
4653
+ }
4654
+ const modulePath = path5.join(projectRoot, "node_modules", "@github", "copilot-sdk", "package.json");
4655
+ const moduleJson = readJsonFile(modulePath);
4656
+ if (moduleJson && typeof moduleJson.version === "string") {
4657
+ return moduleJson.version;
4658
+ }
4659
+ const pkgJson = readJsonFile(path5.join(projectRoot, "package.json"));
4660
+ if (!pkgJson) {
4661
+ return "未知";
4662
+ }
4663
+ const dependencies = pkgJson.dependencies;
4664
+ const devDependencies = pkgJson.devDependencies;
4665
+ return dependencies?.["@github/copilot-sdk"] || devDependencies?.["@github/copilot-sdk"] || "未知";
4666
+ }
4667
+ function maskSecret(value) {
4668
+ if (!value) {
4669
+ return "未設定";
4670
+ }
4671
+ if (value.length <= 8) {
4672
+ return "*".repeat(value.length);
4673
+ }
4674
+ return `${value.slice(0, 4)}...${value.slice(-4)}`;
4675
+ }
4676
+ function formatEnvValue(value) {
4677
+ if (!value) {
4678
+ return "未設定";
4679
+ }
4680
+ return value;
4681
+ }
4682
+ function getEndpointHost(endpoint) {
4683
+ try {
4684
+ return new URL(endpoint).host || endpoint;
4685
+ } catch {
4686
+ return endpoint;
4687
+ }
4688
+ }
4689
+ function printVersionInfo() {
4690
+ const projectRoot = resolveProjectRoot();
4691
+ const appVersion = resolveAppVersion(projectRoot);
4692
+ const sdkVersion = resolveCopilotSdkVersion(projectRoot);
4693
+ const nodeVersion = process.version;
4694
+ const platform = `${process.platform} ${process.arch}`;
4695
+ const cwd = process.cwd();
4696
+ const endpoint = process.env.AZURE_OPENAI_ENDPOINT;
4697
+ const deployment = process.env.AZURE_OPENAI_DEPLOYMENT;
4698
+ const apiVersion = process.env.AZURE_OPENAI_API_VERSION || "2024-10-21";
4699
+ const apiKey = process.env.AZURE_OPENAI_API_KEY;
4700
+ const isAzureConfigured = endpoint && apiKey && deployment;
4701
+ console.log(`
4702
+ 字幕校正代理人 - 版本資訊
4703
+ ========================
4704
+ 版本: ${appVersion}
4705
+ Node.js: ${nodeVersion}
4706
+ 平台: ${platform}
4707
+ 工作目錄: ${cwd}
4708
+
4709
+ 環境變數
4710
+ --------
4711
+ AZURE_OPENAI_ENDPOINT: ${endpoint ? formatEnvValue(endpoint) : "未設定"}
4712
+ AZURE_OPENAI_API_KEY: ${maskSecret(apiKey)}
4713
+ AZURE_OPENAI_DEPLOYMENT: ${formatEnvValue(deployment)}
4714
+ AZURE_OPENAI_API_VERSION: ${formatEnvValue(process.env.AZURE_OPENAI_API_VERSION)}
4715
+ TELEGRAM_BOT_TOKEN: ${maskSecret(process.env.TELEGRAM_BOT_TOKEN)}
4716
+ TELEGRAM_STARTUP_CHAT_ID: ${formatEnvValue(process.env.TELEGRAM_STARTUP_CHAT_ID)}
4717
+ OWNER_CHAT_ID: ${formatEnvValue(process.env.OWNER_CHAT_ID)}
4718
+ BOT_MAX_CONCURRENT: ${formatEnvValue(process.env.BOT_MAX_CONCURRENT)}
4719
+ KEEP_TEMP_FILES: ${formatEnvValue(process.env.KEEP_TEMP_FILES)}
4720
+ BOT_LOG_LEVEL: ${formatEnvValue(process.env.BOT_LOG_LEVEL)}
4721
+ BOT_DEBUG: ${formatEnvValue(process.env.BOT_DEBUG)}
4722
+ BOT_DATA_DIR: ${formatEnvValue(process.env.BOT_DATA_DIR)}
4723
+
4724
+ Copilot SDK
4725
+ -----------
4726
+ SDK 版本: ${sdkVersion}
4727
+ Model: ${isAzureConfigured ? formatEnvValue(deployment) : "(Default)"}
4728
+ Streaming: true
4729
+ Provider: ${isAzureConfigured ? "Azure OpenAI" : "GitHub Copilot CLI (Default)"}
4730
+ ${isAzureConfigured ? `Provider.baseUrl: ${endpoint ? getEndpointHost(endpoint) : "未設定"}
4731
+ Provider.apiVersion: ${apiVersion}
4732
+ Provider.apiKey: ${maskSecret(apiKey)}` : ""}
4733
+ `);
4734
+ }
4735
+ async function main() {
4736
+ const args = parseArgs(process.argv.slice(2));
4737
+ if (args.version) {
4738
+ printVersionInfo();
4739
+ process.exit(0);
4740
+ }
4741
+ if (args.help || !args.vttFilePath) {
4742
+ printUsage();
4743
+ process.exit(args.help ? 0 : 1);
4744
+ }
4745
+ const vttFilePath = path5.resolve(args.vttFilePath);
4746
+ if (!fs5.existsSync(vttFilePath)) {
4747
+ console.error(`錯誤: 找不到檔案 "${vttFilePath}"`);
4748
+ process.exit(1);
4749
+ }
4750
+ if (!vttFilePath.toLowerCase().endsWith(".vtt")) {
4751
+ console.error(`錯誤: 檔案必須是 .vtt 格式`);
4752
+ process.exit(1);
4753
+ }
4754
+ const vttDir = path5.dirname(vttFilePath);
4755
+ process.chdir(vttDir);
4756
+ console.log(`工作目錄: ${vttDir}`);
4757
+ const result = await runSubtitleCorrectionAgent({
4758
+ vttFilePath,
4759
+ outputDir: args.outputDir
4760
+ });
4761
+ if (!result.success) {
4762
+ console.error(`錯誤: ${result.error}`);
4763
+ process.exit(1);
4764
+ }
4765
+ process.exit(0);
4766
+ }
4767
+ var isDirectRun = (() => {
4768
+ const metaMain = __require.main == __require.module;
4769
+ if (typeof metaMain === "boolean") {
4770
+ return metaMain;
4771
+ }
4772
+ const entryPath = fileURLToPath(import.meta.url);
4773
+ return Boolean(process.argv[1]) && path5.resolve(process.argv[1]) === path5.resolve(entryPath);
4774
+ })();
4775
+ if (isDirectRun) {
4776
+ main().catch((error) => {
4777
+ console.error("未預期的錯誤:", error);
4778
+ process.exit(1);
4779
+ });
4780
+ }
4781
+ export {
4782
+ parseArgs
4783
+ };