@mimikkai/opencode-mimikkai-connect 1.0.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 +128 -0
  3. package/dist/index.js +2017 -0
  4. package/package.json +39 -0
package/dist/index.js ADDED
@@ -0,0 +1,2017 @@
1
+ import { createRequire } from "node:module";
2
+ var __create = Object.create;
3
+ var __getProtoOf = Object.getPrototypeOf;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ function __accessProp(key) {
8
+ return this[key];
9
+ }
10
+ var __toESMCache_node;
11
+ var __toESMCache_esm;
12
+ var __toESM = (mod, isNodeMode, target) => {
13
+ var canCache = mod != null && typeof mod === "object";
14
+ if (canCache) {
15
+ var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
16
+ var cached = cache.get(mod);
17
+ if (cached)
18
+ return cached;
19
+ }
20
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
21
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
22
+ for (let key of __getOwnPropNames(mod))
23
+ if (!__hasOwnProp.call(to, key))
24
+ __defProp(to, key, {
25
+ get: __accessProp.bind(mod, key),
26
+ enumerable: true
27
+ });
28
+ if (canCache)
29
+ cache.set(mod, to);
30
+ return to;
31
+ };
32
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
33
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
34
+
35
+ // node_modules/graceful-fs/polyfills.js
36
+ var require_polyfills = __commonJS((exports, module) => {
37
+ var constants = __require("constants");
38
+ var origCwd = process.cwd;
39
+ var cwd = null;
40
+ var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform;
41
+ process.cwd = function() {
42
+ if (!cwd)
43
+ cwd = origCwd.call(process);
44
+ return cwd;
45
+ };
46
+ try {
47
+ process.cwd();
48
+ } catch (er) {}
49
+ if (typeof process.chdir === "function") {
50
+ chdir = process.chdir;
51
+ process.chdir = function(d) {
52
+ cwd = null;
53
+ chdir.call(process, d);
54
+ };
55
+ if (Object.setPrototypeOf)
56
+ Object.setPrototypeOf(process.chdir, chdir);
57
+ }
58
+ var chdir;
59
+ module.exports = patch;
60
+ function patch(fs) {
61
+ if (constants.hasOwnProperty("O_SYMLINK") && process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
62
+ patchLchmod(fs);
63
+ }
64
+ if (!fs.lutimes) {
65
+ patchLutimes(fs);
66
+ }
67
+ fs.chown = chownFix(fs.chown);
68
+ fs.fchown = chownFix(fs.fchown);
69
+ fs.lchown = chownFix(fs.lchown);
70
+ fs.chmod = chmodFix(fs.chmod);
71
+ fs.fchmod = chmodFix(fs.fchmod);
72
+ fs.lchmod = chmodFix(fs.lchmod);
73
+ fs.chownSync = chownFixSync(fs.chownSync);
74
+ fs.fchownSync = chownFixSync(fs.fchownSync);
75
+ fs.lchownSync = chownFixSync(fs.lchownSync);
76
+ fs.chmodSync = chmodFixSync(fs.chmodSync);
77
+ fs.fchmodSync = chmodFixSync(fs.fchmodSync);
78
+ fs.lchmodSync = chmodFixSync(fs.lchmodSync);
79
+ fs.stat = statFix(fs.stat);
80
+ fs.fstat = statFix(fs.fstat);
81
+ fs.lstat = statFix(fs.lstat);
82
+ fs.statSync = statFixSync(fs.statSync);
83
+ fs.fstatSync = statFixSync(fs.fstatSync);
84
+ fs.lstatSync = statFixSync(fs.lstatSync);
85
+ if (fs.chmod && !fs.lchmod) {
86
+ fs.lchmod = function(path, mode, cb) {
87
+ if (cb)
88
+ process.nextTick(cb);
89
+ };
90
+ fs.lchmodSync = function() {};
91
+ }
92
+ if (fs.chown && !fs.lchown) {
93
+ fs.lchown = function(path, uid, gid, cb) {
94
+ if (cb)
95
+ process.nextTick(cb);
96
+ };
97
+ fs.lchownSync = function() {};
98
+ }
99
+ if (platform === "win32") {
100
+ fs.rename = typeof fs.rename !== "function" ? fs.rename : function(fs$rename) {
101
+ function rename(from, to, cb) {
102
+ var start = Date.now();
103
+ var backoff = 0;
104
+ fs$rename(from, to, function CB(er) {
105
+ if (er && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY") && Date.now() - start < 60000) {
106
+ setTimeout(function() {
107
+ fs.stat(to, function(stater, st) {
108
+ if (stater && stater.code === "ENOENT")
109
+ fs$rename(from, to, CB);
110
+ else
111
+ cb(er);
112
+ });
113
+ }, backoff);
114
+ if (backoff < 100)
115
+ backoff += 10;
116
+ return;
117
+ }
118
+ if (cb)
119
+ cb(er);
120
+ });
121
+ }
122
+ if (Object.setPrototypeOf)
123
+ Object.setPrototypeOf(rename, fs$rename);
124
+ return rename;
125
+ }(fs.rename);
126
+ }
127
+ fs.read = typeof fs.read !== "function" ? fs.read : function(fs$read) {
128
+ function read(fd, buffer, offset, length, position, callback_) {
129
+ var callback;
130
+ if (callback_ && typeof callback_ === "function") {
131
+ var eagCounter = 0;
132
+ callback = function(er, _, __) {
133
+ if (er && er.code === "EAGAIN" && eagCounter < 10) {
134
+ eagCounter++;
135
+ return fs$read.call(fs, fd, buffer, offset, length, position, callback);
136
+ }
137
+ callback_.apply(this, arguments);
138
+ };
139
+ }
140
+ return fs$read.call(fs, fd, buffer, offset, length, position, callback);
141
+ }
142
+ if (Object.setPrototypeOf)
143
+ Object.setPrototypeOf(read, fs$read);
144
+ return read;
145
+ }(fs.read);
146
+ fs.readSync = typeof fs.readSync !== "function" ? fs.readSync : function(fs$readSync) {
147
+ return function(fd, buffer, offset, length, position) {
148
+ var eagCounter = 0;
149
+ while (true) {
150
+ try {
151
+ return fs$readSync.call(fs, fd, buffer, offset, length, position);
152
+ } catch (er) {
153
+ if (er.code === "EAGAIN" && eagCounter < 10) {
154
+ eagCounter++;
155
+ continue;
156
+ }
157
+ throw er;
158
+ }
159
+ }
160
+ };
161
+ }(fs.readSync);
162
+ function patchLchmod(fs2) {
163
+ fs2.lchmod = function(path, mode, callback) {
164
+ fs2.open(path, constants.O_WRONLY | constants.O_SYMLINK, mode, function(err, fd) {
165
+ if (err) {
166
+ if (callback)
167
+ callback(err);
168
+ return;
169
+ }
170
+ fs2.fchmod(fd, mode, function(err2) {
171
+ fs2.close(fd, function(err22) {
172
+ if (callback)
173
+ callback(err2 || err22);
174
+ });
175
+ });
176
+ });
177
+ };
178
+ fs2.lchmodSync = function(path, mode) {
179
+ var fd = fs2.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode);
180
+ var threw = true;
181
+ var ret;
182
+ try {
183
+ ret = fs2.fchmodSync(fd, mode);
184
+ threw = false;
185
+ } finally {
186
+ if (threw) {
187
+ try {
188
+ fs2.closeSync(fd);
189
+ } catch (er) {}
190
+ } else {
191
+ fs2.closeSync(fd);
192
+ }
193
+ }
194
+ return ret;
195
+ };
196
+ }
197
+ function patchLutimes(fs2) {
198
+ if (constants.hasOwnProperty("O_SYMLINK") && fs2.futimes) {
199
+ fs2.lutimes = function(path, at, mt, cb) {
200
+ fs2.open(path, constants.O_SYMLINK, function(er, fd) {
201
+ if (er) {
202
+ if (cb)
203
+ cb(er);
204
+ return;
205
+ }
206
+ fs2.futimes(fd, at, mt, function(er2) {
207
+ fs2.close(fd, function(er22) {
208
+ if (cb)
209
+ cb(er2 || er22);
210
+ });
211
+ });
212
+ });
213
+ };
214
+ fs2.lutimesSync = function(path, at, mt) {
215
+ var fd = fs2.openSync(path, constants.O_SYMLINK);
216
+ var ret;
217
+ var threw = true;
218
+ try {
219
+ ret = fs2.futimesSync(fd, at, mt);
220
+ threw = false;
221
+ } finally {
222
+ if (threw) {
223
+ try {
224
+ fs2.closeSync(fd);
225
+ } catch (er) {}
226
+ } else {
227
+ fs2.closeSync(fd);
228
+ }
229
+ }
230
+ return ret;
231
+ };
232
+ } else if (fs2.futimes) {
233
+ fs2.lutimes = function(_a, _b, _c, cb) {
234
+ if (cb)
235
+ process.nextTick(cb);
236
+ };
237
+ fs2.lutimesSync = function() {};
238
+ }
239
+ }
240
+ function chmodFix(orig) {
241
+ if (!orig)
242
+ return orig;
243
+ return function(target, mode, cb) {
244
+ return orig.call(fs, target, mode, function(er) {
245
+ if (chownErOk(er))
246
+ er = null;
247
+ if (cb)
248
+ cb.apply(this, arguments);
249
+ });
250
+ };
251
+ }
252
+ function chmodFixSync(orig) {
253
+ if (!orig)
254
+ return orig;
255
+ return function(target, mode) {
256
+ try {
257
+ return orig.call(fs, target, mode);
258
+ } catch (er) {
259
+ if (!chownErOk(er))
260
+ throw er;
261
+ }
262
+ };
263
+ }
264
+ function chownFix(orig) {
265
+ if (!orig)
266
+ return orig;
267
+ return function(target, uid, gid, cb) {
268
+ return orig.call(fs, target, uid, gid, function(er) {
269
+ if (chownErOk(er))
270
+ er = null;
271
+ if (cb)
272
+ cb.apply(this, arguments);
273
+ });
274
+ };
275
+ }
276
+ function chownFixSync(orig) {
277
+ if (!orig)
278
+ return orig;
279
+ return function(target, uid, gid) {
280
+ try {
281
+ return orig.call(fs, target, uid, gid);
282
+ } catch (er) {
283
+ if (!chownErOk(er))
284
+ throw er;
285
+ }
286
+ };
287
+ }
288
+ function statFix(orig) {
289
+ if (!orig)
290
+ return orig;
291
+ return function(target, options, cb) {
292
+ if (typeof options === "function") {
293
+ cb = options;
294
+ options = null;
295
+ }
296
+ function callback(er, stats) {
297
+ if (stats) {
298
+ if (stats.uid < 0)
299
+ stats.uid += 4294967296;
300
+ if (stats.gid < 0)
301
+ stats.gid += 4294967296;
302
+ }
303
+ if (cb)
304
+ cb.apply(this, arguments);
305
+ }
306
+ return options ? orig.call(fs, target, options, callback) : orig.call(fs, target, callback);
307
+ };
308
+ }
309
+ function statFixSync(orig) {
310
+ if (!orig)
311
+ return orig;
312
+ return function(target, options) {
313
+ var stats = options ? orig.call(fs, target, options) : orig.call(fs, target);
314
+ if (stats) {
315
+ if (stats.uid < 0)
316
+ stats.uid += 4294967296;
317
+ if (stats.gid < 0)
318
+ stats.gid += 4294967296;
319
+ }
320
+ return stats;
321
+ };
322
+ }
323
+ function chownErOk(er) {
324
+ if (!er)
325
+ return true;
326
+ if (er.code === "ENOSYS")
327
+ return true;
328
+ var nonroot = !process.getuid || process.getuid() !== 0;
329
+ if (nonroot) {
330
+ if (er.code === "EINVAL" || er.code === "EPERM")
331
+ return true;
332
+ }
333
+ return false;
334
+ }
335
+ }
336
+ });
337
+
338
+ // node_modules/graceful-fs/legacy-streams.js
339
+ var require_legacy_streams = __commonJS((exports, module) => {
340
+ var Stream = __require("stream").Stream;
341
+ module.exports = legacy;
342
+ function legacy(fs) {
343
+ return {
344
+ ReadStream,
345
+ WriteStream
346
+ };
347
+ function ReadStream(path, options) {
348
+ if (!(this instanceof ReadStream))
349
+ return new ReadStream(path, options);
350
+ Stream.call(this);
351
+ var self = this;
352
+ this.path = path;
353
+ this.fd = null;
354
+ this.readable = true;
355
+ this.paused = false;
356
+ this.flags = "r";
357
+ this.mode = 438;
358
+ this.bufferSize = 64 * 1024;
359
+ options = options || {};
360
+ var keys = Object.keys(options);
361
+ for (var index = 0, length = keys.length;index < length; index++) {
362
+ var key = keys[index];
363
+ this[key] = options[key];
364
+ }
365
+ if (this.encoding)
366
+ this.setEncoding(this.encoding);
367
+ if (this.start !== undefined) {
368
+ if (typeof this.start !== "number") {
369
+ throw TypeError("start must be a Number");
370
+ }
371
+ if (this.end === undefined) {
372
+ this.end = Infinity;
373
+ } else if (typeof this.end !== "number") {
374
+ throw TypeError("end must be a Number");
375
+ }
376
+ if (this.start > this.end) {
377
+ throw new Error("start must be <= end");
378
+ }
379
+ this.pos = this.start;
380
+ }
381
+ if (this.fd !== null) {
382
+ process.nextTick(function() {
383
+ self._read();
384
+ });
385
+ return;
386
+ }
387
+ fs.open(this.path, this.flags, this.mode, function(err, fd) {
388
+ if (err) {
389
+ self.emit("error", err);
390
+ self.readable = false;
391
+ return;
392
+ }
393
+ self.fd = fd;
394
+ self.emit("open", fd);
395
+ self._read();
396
+ });
397
+ }
398
+ function WriteStream(path, options) {
399
+ if (!(this instanceof WriteStream))
400
+ return new WriteStream(path, options);
401
+ Stream.call(this);
402
+ this.path = path;
403
+ this.fd = null;
404
+ this.writable = true;
405
+ this.flags = "w";
406
+ this.encoding = "binary";
407
+ this.mode = 438;
408
+ this.bytesWritten = 0;
409
+ options = options || {};
410
+ var keys = Object.keys(options);
411
+ for (var index = 0, length = keys.length;index < length; index++) {
412
+ var key = keys[index];
413
+ this[key] = options[key];
414
+ }
415
+ if (this.start !== undefined) {
416
+ if (typeof this.start !== "number") {
417
+ throw TypeError("start must be a Number");
418
+ }
419
+ if (this.start < 0) {
420
+ throw new Error("start must be >= zero");
421
+ }
422
+ this.pos = this.start;
423
+ }
424
+ this.busy = false;
425
+ this._queue = [];
426
+ if (this.fd === null) {
427
+ this._open = fs.open;
428
+ this._queue.push([this._open, this.path, this.flags, this.mode, undefined]);
429
+ this.flush();
430
+ }
431
+ }
432
+ }
433
+ });
434
+
435
+ // node_modules/graceful-fs/clone.js
436
+ var require_clone = __commonJS((exports, module) => {
437
+ module.exports = clone;
438
+ var getPrototypeOf = Object.getPrototypeOf || function(obj) {
439
+ return obj.__proto__;
440
+ };
441
+ function clone(obj) {
442
+ if (obj === null || typeof obj !== "object")
443
+ return obj;
444
+ if (obj instanceof Object)
445
+ var copy = { __proto__: getPrototypeOf(obj) };
446
+ else
447
+ var copy = Object.create(null);
448
+ Object.getOwnPropertyNames(obj).forEach(function(key) {
449
+ Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key));
450
+ });
451
+ return copy;
452
+ }
453
+ });
454
+
455
+ // node_modules/graceful-fs/graceful-fs.js
456
+ var require_graceful_fs = __commonJS((exports, module) => {
457
+ var fs = __require("fs");
458
+ var polyfills = require_polyfills();
459
+ var legacy = require_legacy_streams();
460
+ var clone = require_clone();
461
+ var util = __require("util");
462
+ var gracefulQueue;
463
+ var previousSymbol;
464
+ if (typeof Symbol === "function" && typeof Symbol.for === "function") {
465
+ gracefulQueue = Symbol.for("graceful-fs.queue");
466
+ previousSymbol = Symbol.for("graceful-fs.previous");
467
+ } else {
468
+ gracefulQueue = "___graceful-fs.queue";
469
+ previousSymbol = "___graceful-fs.previous";
470
+ }
471
+ function noop() {}
472
+ function publishQueue(context, queue2) {
473
+ Object.defineProperty(context, gracefulQueue, {
474
+ get: function() {
475
+ return queue2;
476
+ }
477
+ });
478
+ }
479
+ var debug = noop;
480
+ if (util.debuglog)
481
+ debug = util.debuglog("gfs4");
482
+ else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ""))
483
+ debug = function() {
484
+ var m = util.format.apply(util, arguments);
485
+ m = "GFS4: " + m.split(/\n/).join(`
486
+ GFS4: `);
487
+ console.error(m);
488
+ };
489
+ if (!fs[gracefulQueue]) {
490
+ queue = global[gracefulQueue] || [];
491
+ publishQueue(fs, queue);
492
+ fs.close = function(fs$close) {
493
+ function close(fd, cb) {
494
+ return fs$close.call(fs, fd, function(err) {
495
+ if (!err) {
496
+ resetQueue();
497
+ }
498
+ if (typeof cb === "function")
499
+ cb.apply(this, arguments);
500
+ });
501
+ }
502
+ Object.defineProperty(close, previousSymbol, {
503
+ value: fs$close
504
+ });
505
+ return close;
506
+ }(fs.close);
507
+ fs.closeSync = function(fs$closeSync) {
508
+ function closeSync(fd) {
509
+ fs$closeSync.apply(fs, arguments);
510
+ resetQueue();
511
+ }
512
+ Object.defineProperty(closeSync, previousSymbol, {
513
+ value: fs$closeSync
514
+ });
515
+ return closeSync;
516
+ }(fs.closeSync);
517
+ if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) {
518
+ process.on("exit", function() {
519
+ debug(fs[gracefulQueue]);
520
+ __require("assert").equal(fs[gracefulQueue].length, 0);
521
+ });
522
+ }
523
+ }
524
+ var queue;
525
+ if (!global[gracefulQueue]) {
526
+ publishQueue(global, fs[gracefulQueue]);
527
+ }
528
+ module.exports = patch(clone(fs));
529
+ if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) {
530
+ module.exports = patch(fs);
531
+ fs.__patched = true;
532
+ }
533
+ function patch(fs2) {
534
+ polyfills(fs2);
535
+ fs2.gracefulify = patch;
536
+ fs2.createReadStream = createReadStream;
537
+ fs2.createWriteStream = createWriteStream;
538
+ var fs$readFile = fs2.readFile;
539
+ fs2.readFile = readFile;
540
+ function readFile(path, options, cb) {
541
+ if (typeof options === "function")
542
+ cb = options, options = null;
543
+ return go$readFile(path, options, cb);
544
+ function go$readFile(path2, options2, cb2, startTime) {
545
+ return fs$readFile(path2, options2, function(err) {
546
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
547
+ enqueue([go$readFile, [path2, options2, cb2], err, startTime || Date.now(), Date.now()]);
548
+ else {
549
+ if (typeof cb2 === "function")
550
+ cb2.apply(this, arguments);
551
+ }
552
+ });
553
+ }
554
+ }
555
+ var fs$writeFile = fs2.writeFile;
556
+ fs2.writeFile = writeFile;
557
+ function writeFile(path, data, options, cb) {
558
+ if (typeof options === "function")
559
+ cb = options, options = null;
560
+ return go$writeFile(path, data, options, cb);
561
+ function go$writeFile(path2, data2, options2, cb2, startTime) {
562
+ return fs$writeFile(path2, data2, options2, function(err) {
563
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
564
+ enqueue([go$writeFile, [path2, data2, options2, cb2], err, startTime || Date.now(), Date.now()]);
565
+ else {
566
+ if (typeof cb2 === "function")
567
+ cb2.apply(this, arguments);
568
+ }
569
+ });
570
+ }
571
+ }
572
+ var fs$appendFile = fs2.appendFile;
573
+ if (fs$appendFile)
574
+ fs2.appendFile = appendFile;
575
+ function appendFile(path, data, options, cb) {
576
+ if (typeof options === "function")
577
+ cb = options, options = null;
578
+ return go$appendFile(path, data, options, cb);
579
+ function go$appendFile(path2, data2, options2, cb2, startTime) {
580
+ return fs$appendFile(path2, data2, options2, function(err) {
581
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
582
+ enqueue([go$appendFile, [path2, data2, options2, cb2], err, startTime || Date.now(), Date.now()]);
583
+ else {
584
+ if (typeof cb2 === "function")
585
+ cb2.apply(this, arguments);
586
+ }
587
+ });
588
+ }
589
+ }
590
+ var fs$copyFile = fs2.copyFile;
591
+ if (fs$copyFile)
592
+ fs2.copyFile = copyFile;
593
+ function copyFile(src, dest, flags, cb) {
594
+ if (typeof flags === "function") {
595
+ cb = flags;
596
+ flags = 0;
597
+ }
598
+ return go$copyFile(src, dest, flags, cb);
599
+ function go$copyFile(src2, dest2, flags2, cb2, startTime) {
600
+ return fs$copyFile(src2, dest2, flags2, function(err) {
601
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
602
+ enqueue([go$copyFile, [src2, dest2, flags2, cb2], err, startTime || Date.now(), Date.now()]);
603
+ else {
604
+ if (typeof cb2 === "function")
605
+ cb2.apply(this, arguments);
606
+ }
607
+ });
608
+ }
609
+ }
610
+ var fs$readdir = fs2.readdir;
611
+ fs2.readdir = readdir;
612
+ var noReaddirOptionVersions = /^v[0-5]\./;
613
+ function readdir(path, options, cb) {
614
+ if (typeof options === "function")
615
+ cb = options, options = null;
616
+ var go$readdir = noReaddirOptionVersions.test(process.version) ? function go$readdir2(path2, options2, cb2, startTime) {
617
+ return fs$readdir(path2, fs$readdirCallback(path2, options2, cb2, startTime));
618
+ } : function go$readdir2(path2, options2, cb2, startTime) {
619
+ return fs$readdir(path2, options2, fs$readdirCallback(path2, options2, cb2, startTime));
620
+ };
621
+ return go$readdir(path, options, cb);
622
+ function fs$readdirCallback(path2, options2, cb2, startTime) {
623
+ return function(err, files) {
624
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
625
+ enqueue([
626
+ go$readdir,
627
+ [path2, options2, cb2],
628
+ err,
629
+ startTime || Date.now(),
630
+ Date.now()
631
+ ]);
632
+ else {
633
+ if (files && files.sort)
634
+ files.sort();
635
+ if (typeof cb2 === "function")
636
+ cb2.call(this, err, files);
637
+ }
638
+ };
639
+ }
640
+ }
641
+ if (process.version.substr(0, 4) === "v0.8") {
642
+ var legStreams = legacy(fs2);
643
+ ReadStream = legStreams.ReadStream;
644
+ WriteStream = legStreams.WriteStream;
645
+ }
646
+ var fs$ReadStream = fs2.ReadStream;
647
+ if (fs$ReadStream) {
648
+ ReadStream.prototype = Object.create(fs$ReadStream.prototype);
649
+ ReadStream.prototype.open = ReadStream$open;
650
+ }
651
+ var fs$WriteStream = fs2.WriteStream;
652
+ if (fs$WriteStream) {
653
+ WriteStream.prototype = Object.create(fs$WriteStream.prototype);
654
+ WriteStream.prototype.open = WriteStream$open;
655
+ }
656
+ Object.defineProperty(fs2, "ReadStream", {
657
+ get: function() {
658
+ return ReadStream;
659
+ },
660
+ set: function(val) {
661
+ ReadStream = val;
662
+ },
663
+ enumerable: true,
664
+ configurable: true
665
+ });
666
+ Object.defineProperty(fs2, "WriteStream", {
667
+ get: function() {
668
+ return WriteStream;
669
+ },
670
+ set: function(val) {
671
+ WriteStream = val;
672
+ },
673
+ enumerable: true,
674
+ configurable: true
675
+ });
676
+ var FileReadStream = ReadStream;
677
+ Object.defineProperty(fs2, "FileReadStream", {
678
+ get: function() {
679
+ return FileReadStream;
680
+ },
681
+ set: function(val) {
682
+ FileReadStream = val;
683
+ },
684
+ enumerable: true,
685
+ configurable: true
686
+ });
687
+ var FileWriteStream = WriteStream;
688
+ Object.defineProperty(fs2, "FileWriteStream", {
689
+ get: function() {
690
+ return FileWriteStream;
691
+ },
692
+ set: function(val) {
693
+ FileWriteStream = val;
694
+ },
695
+ enumerable: true,
696
+ configurable: true
697
+ });
698
+ function ReadStream(path, options) {
699
+ if (this instanceof ReadStream)
700
+ return fs$ReadStream.apply(this, arguments), this;
701
+ else
702
+ return ReadStream.apply(Object.create(ReadStream.prototype), arguments);
703
+ }
704
+ function ReadStream$open() {
705
+ var that = this;
706
+ open(that.path, that.flags, that.mode, function(err, fd) {
707
+ if (err) {
708
+ if (that.autoClose)
709
+ that.destroy();
710
+ that.emit("error", err);
711
+ } else {
712
+ that.fd = fd;
713
+ that.emit("open", fd);
714
+ that.read();
715
+ }
716
+ });
717
+ }
718
+ function WriteStream(path, options) {
719
+ if (this instanceof WriteStream)
720
+ return fs$WriteStream.apply(this, arguments), this;
721
+ else
722
+ return WriteStream.apply(Object.create(WriteStream.prototype), arguments);
723
+ }
724
+ function WriteStream$open() {
725
+ var that = this;
726
+ open(that.path, that.flags, that.mode, function(err, fd) {
727
+ if (err) {
728
+ that.destroy();
729
+ that.emit("error", err);
730
+ } else {
731
+ that.fd = fd;
732
+ that.emit("open", fd);
733
+ }
734
+ });
735
+ }
736
+ function createReadStream(path, options) {
737
+ return new fs2.ReadStream(path, options);
738
+ }
739
+ function createWriteStream(path, options) {
740
+ return new fs2.WriteStream(path, options);
741
+ }
742
+ var fs$open = fs2.open;
743
+ fs2.open = open;
744
+ function open(path, flags, mode, cb) {
745
+ if (typeof mode === "function")
746
+ cb = mode, mode = null;
747
+ return go$open(path, flags, mode, cb);
748
+ function go$open(path2, flags2, mode2, cb2, startTime) {
749
+ return fs$open(path2, flags2, mode2, function(err, fd) {
750
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
751
+ enqueue([go$open, [path2, flags2, mode2, cb2], err, startTime || Date.now(), Date.now()]);
752
+ else {
753
+ if (typeof cb2 === "function")
754
+ cb2.apply(this, arguments);
755
+ }
756
+ });
757
+ }
758
+ }
759
+ return fs2;
760
+ }
761
+ function enqueue(elem) {
762
+ debug("ENQUEUE", elem[0].name, elem[1]);
763
+ fs[gracefulQueue].push(elem);
764
+ retry();
765
+ }
766
+ var retryTimer;
767
+ function resetQueue() {
768
+ var now = Date.now();
769
+ for (var i = 0;i < fs[gracefulQueue].length; ++i) {
770
+ if (fs[gracefulQueue][i].length > 2) {
771
+ fs[gracefulQueue][i][3] = now;
772
+ fs[gracefulQueue][i][4] = now;
773
+ }
774
+ }
775
+ retry();
776
+ }
777
+ function retry() {
778
+ clearTimeout(retryTimer);
779
+ retryTimer = undefined;
780
+ if (fs[gracefulQueue].length === 0)
781
+ return;
782
+ var elem = fs[gracefulQueue].shift();
783
+ var fn = elem[0];
784
+ var args = elem[1];
785
+ var err = elem[2];
786
+ var startTime = elem[3];
787
+ var lastTime = elem[4];
788
+ if (startTime === undefined) {
789
+ debug("RETRY", fn.name, args);
790
+ fn.apply(null, args);
791
+ } else if (Date.now() - startTime >= 60000) {
792
+ debug("TIMEOUT", fn.name, args);
793
+ var cb = args.pop();
794
+ if (typeof cb === "function")
795
+ cb.call(null, err);
796
+ } else {
797
+ var sinceAttempt = Date.now() - lastTime;
798
+ var sinceStart = Math.max(lastTime - startTime, 1);
799
+ var desiredDelay = Math.min(sinceStart * 1.2, 100);
800
+ if (sinceAttempt >= desiredDelay) {
801
+ debug("RETRY", fn.name, args);
802
+ fn.apply(null, args.concat([startTime]));
803
+ } else {
804
+ fs[gracefulQueue].push(elem);
805
+ }
806
+ }
807
+ if (retryTimer === undefined) {
808
+ retryTimer = setTimeout(retry, 0);
809
+ }
810
+ }
811
+ });
812
+
813
+ // node_modules/retry/lib/retry_operation.js
814
+ var require_retry_operation = __commonJS((exports, module) => {
815
+ function RetryOperation(timeouts, options) {
816
+ if (typeof options === "boolean") {
817
+ options = { forever: options };
818
+ }
819
+ this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
820
+ this._timeouts = timeouts;
821
+ this._options = options || {};
822
+ this._maxRetryTime = options && options.maxRetryTime || Infinity;
823
+ this._fn = null;
824
+ this._errors = [];
825
+ this._attempts = 1;
826
+ this._operationTimeout = null;
827
+ this._operationTimeoutCb = null;
828
+ this._timeout = null;
829
+ this._operationStart = null;
830
+ if (this._options.forever) {
831
+ this._cachedTimeouts = this._timeouts.slice(0);
832
+ }
833
+ }
834
+ module.exports = RetryOperation;
835
+ RetryOperation.prototype.reset = function() {
836
+ this._attempts = 1;
837
+ this._timeouts = this._originalTimeouts;
838
+ };
839
+ RetryOperation.prototype.stop = function() {
840
+ if (this._timeout) {
841
+ clearTimeout(this._timeout);
842
+ }
843
+ this._timeouts = [];
844
+ this._cachedTimeouts = null;
845
+ };
846
+ RetryOperation.prototype.retry = function(err) {
847
+ if (this._timeout) {
848
+ clearTimeout(this._timeout);
849
+ }
850
+ if (!err) {
851
+ return false;
852
+ }
853
+ var currentTime = new Date().getTime();
854
+ if (err && currentTime - this._operationStart >= this._maxRetryTime) {
855
+ this._errors.unshift(new Error("RetryOperation timeout occurred"));
856
+ return false;
857
+ }
858
+ this._errors.push(err);
859
+ var timeout = this._timeouts.shift();
860
+ if (timeout === undefined) {
861
+ if (this._cachedTimeouts) {
862
+ this._errors.splice(this._errors.length - 1, this._errors.length);
863
+ this._timeouts = this._cachedTimeouts.slice(0);
864
+ timeout = this._timeouts.shift();
865
+ } else {
866
+ return false;
867
+ }
868
+ }
869
+ var self = this;
870
+ var timer = setTimeout(function() {
871
+ self._attempts++;
872
+ if (self._operationTimeoutCb) {
873
+ self._timeout = setTimeout(function() {
874
+ self._operationTimeoutCb(self._attempts);
875
+ }, self._operationTimeout);
876
+ if (self._options.unref) {
877
+ self._timeout.unref();
878
+ }
879
+ }
880
+ self._fn(self._attempts);
881
+ }, timeout);
882
+ if (this._options.unref) {
883
+ timer.unref();
884
+ }
885
+ return true;
886
+ };
887
+ RetryOperation.prototype.attempt = function(fn, timeoutOps) {
888
+ this._fn = fn;
889
+ if (timeoutOps) {
890
+ if (timeoutOps.timeout) {
891
+ this._operationTimeout = timeoutOps.timeout;
892
+ }
893
+ if (timeoutOps.cb) {
894
+ this._operationTimeoutCb = timeoutOps.cb;
895
+ }
896
+ }
897
+ var self = this;
898
+ if (this._operationTimeoutCb) {
899
+ this._timeout = setTimeout(function() {
900
+ self._operationTimeoutCb();
901
+ }, self._operationTimeout);
902
+ }
903
+ this._operationStart = new Date().getTime();
904
+ this._fn(this._attempts);
905
+ };
906
+ RetryOperation.prototype.try = function(fn) {
907
+ console.log("Using RetryOperation.try() is deprecated");
908
+ this.attempt(fn);
909
+ };
910
+ RetryOperation.prototype.start = function(fn) {
911
+ console.log("Using RetryOperation.start() is deprecated");
912
+ this.attempt(fn);
913
+ };
914
+ RetryOperation.prototype.start = RetryOperation.prototype.try;
915
+ RetryOperation.prototype.errors = function() {
916
+ return this._errors;
917
+ };
918
+ RetryOperation.prototype.attempts = function() {
919
+ return this._attempts;
920
+ };
921
+ RetryOperation.prototype.mainError = function() {
922
+ if (this._errors.length === 0) {
923
+ return null;
924
+ }
925
+ var counts = {};
926
+ var mainError = null;
927
+ var mainErrorCount = 0;
928
+ for (var i = 0;i < this._errors.length; i++) {
929
+ var error = this._errors[i];
930
+ var message = error.message;
931
+ var count = (counts[message] || 0) + 1;
932
+ counts[message] = count;
933
+ if (count >= mainErrorCount) {
934
+ mainError = error;
935
+ mainErrorCount = count;
936
+ }
937
+ }
938
+ return mainError;
939
+ };
940
+ });
941
+
942
+ // node_modules/retry/lib/retry.js
943
+ var require_retry = __commonJS((exports) => {
944
+ var RetryOperation = require_retry_operation();
945
+ exports.operation = function(options) {
946
+ var timeouts = exports.timeouts(options);
947
+ return new RetryOperation(timeouts, {
948
+ forever: options && options.forever,
949
+ unref: options && options.unref,
950
+ maxRetryTime: options && options.maxRetryTime
951
+ });
952
+ };
953
+ exports.timeouts = function(options) {
954
+ if (options instanceof Array) {
955
+ return [].concat(options);
956
+ }
957
+ var opts = {
958
+ retries: 10,
959
+ factor: 2,
960
+ minTimeout: 1 * 1000,
961
+ maxTimeout: Infinity,
962
+ randomize: false
963
+ };
964
+ for (var key in options) {
965
+ opts[key] = options[key];
966
+ }
967
+ if (opts.minTimeout > opts.maxTimeout) {
968
+ throw new Error("minTimeout is greater than maxTimeout");
969
+ }
970
+ var timeouts = [];
971
+ for (var i = 0;i < opts.retries; i++) {
972
+ timeouts.push(this.createTimeout(i, opts));
973
+ }
974
+ if (options && options.forever && !timeouts.length) {
975
+ timeouts.push(this.createTimeout(i, opts));
976
+ }
977
+ timeouts.sort(function(a, b) {
978
+ return a - b;
979
+ });
980
+ return timeouts;
981
+ };
982
+ exports.createTimeout = function(attempt, opts) {
983
+ var random = opts.randomize ? Math.random() + 1 : 1;
984
+ var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
985
+ timeout = Math.min(timeout, opts.maxTimeout);
986
+ return timeout;
987
+ };
988
+ exports.wrap = function(obj, options, methods) {
989
+ if (options instanceof Array) {
990
+ methods = options;
991
+ options = null;
992
+ }
993
+ if (!methods) {
994
+ methods = [];
995
+ for (var key in obj) {
996
+ if (typeof obj[key] === "function") {
997
+ methods.push(key);
998
+ }
999
+ }
1000
+ }
1001
+ for (var i = 0;i < methods.length; i++) {
1002
+ var method = methods[i];
1003
+ var original = obj[method];
1004
+ obj[method] = function retryWrapper(original2) {
1005
+ var op = exports.operation(options);
1006
+ var args = Array.prototype.slice.call(arguments, 1);
1007
+ var callback = args.pop();
1008
+ args.push(function(err) {
1009
+ if (op.retry(err)) {
1010
+ return;
1011
+ }
1012
+ if (err) {
1013
+ arguments[0] = op.mainError();
1014
+ }
1015
+ callback.apply(this, arguments);
1016
+ });
1017
+ op.attempt(function() {
1018
+ original2.apply(obj, args);
1019
+ });
1020
+ }.bind(obj, original);
1021
+ obj[method].options = options;
1022
+ }
1023
+ };
1024
+ });
1025
+
1026
+ // node_modules/signal-exit/signals.js
1027
+ var require_signals = __commonJS((exports, module) => {
1028
+ module.exports = [
1029
+ "SIGABRT",
1030
+ "SIGALRM",
1031
+ "SIGHUP",
1032
+ "SIGINT",
1033
+ "SIGTERM"
1034
+ ];
1035
+ if (process.platform !== "win32") {
1036
+ module.exports.push("SIGVTALRM", "SIGXCPU", "SIGXFSZ", "SIGUSR2", "SIGTRAP", "SIGSYS", "SIGQUIT", "SIGIOT");
1037
+ }
1038
+ if (process.platform === "linux") {
1039
+ module.exports.push("SIGIO", "SIGPOLL", "SIGPWR", "SIGSTKFLT", "SIGUNUSED");
1040
+ }
1041
+ });
1042
+
1043
+ // node_modules/signal-exit/index.js
1044
+ var require_signal_exit = __commonJS((exports, module) => {
1045
+ var process2 = global.process;
1046
+ var processOk = function(process3) {
1047
+ return process3 && typeof process3 === "object" && typeof process3.removeListener === "function" && typeof process3.emit === "function" && typeof process3.reallyExit === "function" && typeof process3.listeners === "function" && typeof process3.kill === "function" && typeof process3.pid === "number" && typeof process3.on === "function";
1048
+ };
1049
+ if (!processOk(process2)) {
1050
+ module.exports = function() {
1051
+ return function() {};
1052
+ };
1053
+ } else {
1054
+ assert = __require("assert");
1055
+ signals = require_signals();
1056
+ isWin = /^win/i.test(process2.platform);
1057
+ EE = __require("events");
1058
+ if (typeof EE !== "function") {
1059
+ EE = EE.EventEmitter;
1060
+ }
1061
+ if (process2.__signal_exit_emitter__) {
1062
+ emitter = process2.__signal_exit_emitter__;
1063
+ } else {
1064
+ emitter = process2.__signal_exit_emitter__ = new EE;
1065
+ emitter.count = 0;
1066
+ emitter.emitted = {};
1067
+ }
1068
+ if (!emitter.infinite) {
1069
+ emitter.setMaxListeners(Infinity);
1070
+ emitter.infinite = true;
1071
+ }
1072
+ module.exports = function(cb, opts) {
1073
+ if (!processOk(global.process)) {
1074
+ return function() {};
1075
+ }
1076
+ assert.equal(typeof cb, "function", "a callback must be provided for exit handler");
1077
+ if (loaded === false) {
1078
+ load();
1079
+ }
1080
+ var ev = "exit";
1081
+ if (opts && opts.alwaysLast) {
1082
+ ev = "afterexit";
1083
+ }
1084
+ var remove = function() {
1085
+ emitter.removeListener(ev, cb);
1086
+ if (emitter.listeners("exit").length === 0 && emitter.listeners("afterexit").length === 0) {
1087
+ unload();
1088
+ }
1089
+ };
1090
+ emitter.on(ev, cb);
1091
+ return remove;
1092
+ };
1093
+ unload = function unload2() {
1094
+ if (!loaded || !processOk(global.process)) {
1095
+ return;
1096
+ }
1097
+ loaded = false;
1098
+ signals.forEach(function(sig) {
1099
+ try {
1100
+ process2.removeListener(sig, sigListeners[sig]);
1101
+ } catch (er) {}
1102
+ });
1103
+ process2.emit = originalProcessEmit;
1104
+ process2.reallyExit = originalProcessReallyExit;
1105
+ emitter.count -= 1;
1106
+ };
1107
+ module.exports.unload = unload;
1108
+ emit = function emit2(event, code, signal) {
1109
+ if (emitter.emitted[event]) {
1110
+ return;
1111
+ }
1112
+ emitter.emitted[event] = true;
1113
+ emitter.emit(event, code, signal);
1114
+ };
1115
+ sigListeners = {};
1116
+ signals.forEach(function(sig) {
1117
+ sigListeners[sig] = function listener() {
1118
+ if (!processOk(global.process)) {
1119
+ return;
1120
+ }
1121
+ var listeners = process2.listeners(sig);
1122
+ if (listeners.length === emitter.count) {
1123
+ unload();
1124
+ emit("exit", null, sig);
1125
+ emit("afterexit", null, sig);
1126
+ if (isWin && sig === "SIGHUP") {
1127
+ sig = "SIGINT";
1128
+ }
1129
+ process2.kill(process2.pid, sig);
1130
+ }
1131
+ };
1132
+ });
1133
+ module.exports.signals = function() {
1134
+ return signals;
1135
+ };
1136
+ loaded = false;
1137
+ load = function load2() {
1138
+ if (loaded || !processOk(global.process)) {
1139
+ return;
1140
+ }
1141
+ loaded = true;
1142
+ emitter.count += 1;
1143
+ signals = signals.filter(function(sig) {
1144
+ try {
1145
+ process2.on(sig, sigListeners[sig]);
1146
+ return true;
1147
+ } catch (er) {
1148
+ return false;
1149
+ }
1150
+ });
1151
+ process2.emit = processEmit;
1152
+ process2.reallyExit = processReallyExit;
1153
+ };
1154
+ module.exports.load = load;
1155
+ originalProcessReallyExit = process2.reallyExit;
1156
+ processReallyExit = function processReallyExit2(code) {
1157
+ if (!processOk(global.process)) {
1158
+ return;
1159
+ }
1160
+ process2.exitCode = code || 0;
1161
+ emit("exit", process2.exitCode, null);
1162
+ emit("afterexit", process2.exitCode, null);
1163
+ originalProcessReallyExit.call(process2, process2.exitCode);
1164
+ };
1165
+ originalProcessEmit = process2.emit;
1166
+ processEmit = function processEmit2(ev, arg) {
1167
+ if (ev === "exit" && processOk(global.process)) {
1168
+ if (arg !== undefined) {
1169
+ process2.exitCode = arg;
1170
+ }
1171
+ var ret = originalProcessEmit.apply(this, arguments);
1172
+ emit("exit", process2.exitCode, null);
1173
+ emit("afterexit", process2.exitCode, null);
1174
+ return ret;
1175
+ } else {
1176
+ return originalProcessEmit.apply(this, arguments);
1177
+ }
1178
+ };
1179
+ }
1180
+ var assert;
1181
+ var signals;
1182
+ var isWin;
1183
+ var EE;
1184
+ var emitter;
1185
+ var unload;
1186
+ var emit;
1187
+ var sigListeners;
1188
+ var loaded;
1189
+ var load;
1190
+ var originalProcessReallyExit;
1191
+ var processReallyExit;
1192
+ var originalProcessEmit;
1193
+ var processEmit;
1194
+ });
1195
+
1196
+ // node_modules/proper-lockfile/lib/mtime-precision.js
1197
+ var require_mtime_precision = __commonJS((exports, module) => {
1198
+ var cacheSymbol = Symbol();
1199
+ function probe(file, fs, callback) {
1200
+ const cachedPrecision = fs[cacheSymbol];
1201
+ if (cachedPrecision) {
1202
+ return fs.stat(file, (err, stat) => {
1203
+ if (err) {
1204
+ return callback(err);
1205
+ }
1206
+ callback(null, stat.mtime, cachedPrecision);
1207
+ });
1208
+ }
1209
+ const mtime = new Date(Math.ceil(Date.now() / 1000) * 1000 + 5);
1210
+ fs.utimes(file, mtime, mtime, (err) => {
1211
+ if (err) {
1212
+ return callback(err);
1213
+ }
1214
+ fs.stat(file, (err2, stat) => {
1215
+ if (err2) {
1216
+ return callback(err2);
1217
+ }
1218
+ const precision = stat.mtime.getTime() % 1000 === 0 ? "s" : "ms";
1219
+ Object.defineProperty(fs, cacheSymbol, { value: precision });
1220
+ callback(null, stat.mtime, precision);
1221
+ });
1222
+ });
1223
+ }
1224
+ function getMtime(precision) {
1225
+ let now = Date.now();
1226
+ if (precision === "s") {
1227
+ now = Math.ceil(now / 1000) * 1000;
1228
+ }
1229
+ return new Date(now);
1230
+ }
1231
+ exports.probe = probe;
1232
+ exports.getMtime = getMtime;
1233
+ });
1234
+
1235
+ // node_modules/proper-lockfile/lib/lockfile.js
1236
+ var require_lockfile = __commonJS((exports, module) => {
1237
+ var path = __require("path");
1238
+ var fs = require_graceful_fs();
1239
+ var retry = require_retry();
1240
+ var onExit = require_signal_exit();
1241
+ var mtimePrecision = require_mtime_precision();
1242
+ var locks = {};
1243
+ function getLockFile(file, options) {
1244
+ return options.lockfilePath || `${file}.lock`;
1245
+ }
1246
+ function resolveCanonicalPath(file, options, callback) {
1247
+ if (!options.realpath) {
1248
+ return callback(null, path.resolve(file));
1249
+ }
1250
+ options.fs.realpath(file, callback);
1251
+ }
1252
+ function acquireLock(file, options, callback) {
1253
+ const lockfilePath = getLockFile(file, options);
1254
+ options.fs.mkdir(lockfilePath, (err) => {
1255
+ if (!err) {
1256
+ return mtimePrecision.probe(lockfilePath, options.fs, (err2, mtime, mtimePrecision2) => {
1257
+ if (err2) {
1258
+ options.fs.rmdir(lockfilePath, () => {});
1259
+ return callback(err2);
1260
+ }
1261
+ callback(null, mtime, mtimePrecision2);
1262
+ });
1263
+ }
1264
+ if (err.code !== "EEXIST") {
1265
+ return callback(err);
1266
+ }
1267
+ if (options.stale <= 0) {
1268
+ return callback(Object.assign(new Error("Lock file is already being held"), { code: "ELOCKED", file }));
1269
+ }
1270
+ options.fs.stat(lockfilePath, (err2, stat) => {
1271
+ if (err2) {
1272
+ if (err2.code === "ENOENT") {
1273
+ return acquireLock(file, { ...options, stale: 0 }, callback);
1274
+ }
1275
+ return callback(err2);
1276
+ }
1277
+ if (!isLockStale(stat, options)) {
1278
+ return callback(Object.assign(new Error("Lock file is already being held"), { code: "ELOCKED", file }));
1279
+ }
1280
+ removeLock(file, options, (err3) => {
1281
+ if (err3) {
1282
+ return callback(err3);
1283
+ }
1284
+ acquireLock(file, { ...options, stale: 0 }, callback);
1285
+ });
1286
+ });
1287
+ });
1288
+ }
1289
+ function isLockStale(stat, options) {
1290
+ return stat.mtime.getTime() < Date.now() - options.stale;
1291
+ }
1292
+ function removeLock(file, options, callback) {
1293
+ options.fs.rmdir(getLockFile(file, options), (err) => {
1294
+ if (err && err.code !== "ENOENT") {
1295
+ return callback(err);
1296
+ }
1297
+ callback();
1298
+ });
1299
+ }
1300
+ function updateLock(file, options) {
1301
+ const lock2 = locks[file];
1302
+ if (lock2.updateTimeout) {
1303
+ return;
1304
+ }
1305
+ lock2.updateDelay = lock2.updateDelay || options.update;
1306
+ lock2.updateTimeout = setTimeout(() => {
1307
+ lock2.updateTimeout = null;
1308
+ options.fs.stat(lock2.lockfilePath, (err, stat) => {
1309
+ const isOverThreshold = lock2.lastUpdate + options.stale < Date.now();
1310
+ if (err) {
1311
+ if (err.code === "ENOENT" || isOverThreshold) {
1312
+ return setLockAsCompromised(file, lock2, Object.assign(err, { code: "ECOMPROMISED" }));
1313
+ }
1314
+ lock2.updateDelay = 1000;
1315
+ return updateLock(file, options);
1316
+ }
1317
+ const isMtimeOurs = lock2.mtime.getTime() === stat.mtime.getTime();
1318
+ if (!isMtimeOurs) {
1319
+ return setLockAsCompromised(file, lock2, Object.assign(new Error("Unable to update lock within the stale threshold"), { code: "ECOMPROMISED" }));
1320
+ }
1321
+ const mtime = mtimePrecision.getMtime(lock2.mtimePrecision);
1322
+ options.fs.utimes(lock2.lockfilePath, mtime, mtime, (err2) => {
1323
+ const isOverThreshold2 = lock2.lastUpdate + options.stale < Date.now();
1324
+ if (lock2.released) {
1325
+ return;
1326
+ }
1327
+ if (err2) {
1328
+ if (err2.code === "ENOENT" || isOverThreshold2) {
1329
+ return setLockAsCompromised(file, lock2, Object.assign(err2, { code: "ECOMPROMISED" }));
1330
+ }
1331
+ lock2.updateDelay = 1000;
1332
+ return updateLock(file, options);
1333
+ }
1334
+ lock2.mtime = mtime;
1335
+ lock2.lastUpdate = Date.now();
1336
+ lock2.updateDelay = null;
1337
+ updateLock(file, options);
1338
+ });
1339
+ });
1340
+ }, lock2.updateDelay);
1341
+ if (lock2.updateTimeout.unref) {
1342
+ lock2.updateTimeout.unref();
1343
+ }
1344
+ }
1345
+ function setLockAsCompromised(file, lock2, err) {
1346
+ lock2.released = true;
1347
+ if (lock2.updateTimeout) {
1348
+ clearTimeout(lock2.updateTimeout);
1349
+ }
1350
+ if (locks[file] === lock2) {
1351
+ delete locks[file];
1352
+ }
1353
+ lock2.options.onCompromised(err);
1354
+ }
1355
+ function lock(file, options, callback) {
1356
+ options = {
1357
+ stale: 1e4,
1358
+ update: null,
1359
+ realpath: true,
1360
+ retries: 0,
1361
+ fs,
1362
+ onCompromised: (err) => {
1363
+ throw err;
1364
+ },
1365
+ ...options
1366
+ };
1367
+ options.retries = options.retries || 0;
1368
+ options.retries = typeof options.retries === "number" ? { retries: options.retries } : options.retries;
1369
+ options.stale = Math.max(options.stale || 0, 2000);
1370
+ options.update = options.update == null ? options.stale / 2 : options.update || 0;
1371
+ options.update = Math.max(Math.min(options.update, options.stale / 2), 1000);
1372
+ resolveCanonicalPath(file, options, (err, file2) => {
1373
+ if (err) {
1374
+ return callback(err);
1375
+ }
1376
+ const operation = retry.operation(options.retries);
1377
+ operation.attempt(() => {
1378
+ acquireLock(file2, options, (err2, mtime, mtimePrecision2) => {
1379
+ if (operation.retry(err2)) {
1380
+ return;
1381
+ }
1382
+ if (err2) {
1383
+ return callback(operation.mainError());
1384
+ }
1385
+ const lock2 = locks[file2] = {
1386
+ lockfilePath: getLockFile(file2, options),
1387
+ mtime,
1388
+ mtimePrecision: mtimePrecision2,
1389
+ options,
1390
+ lastUpdate: Date.now()
1391
+ };
1392
+ updateLock(file2, options);
1393
+ callback(null, (releasedCallback) => {
1394
+ if (lock2.released) {
1395
+ return releasedCallback && releasedCallback(Object.assign(new Error("Lock is already released"), { code: "ERELEASED" }));
1396
+ }
1397
+ unlock(file2, { ...options, realpath: false }, releasedCallback);
1398
+ });
1399
+ });
1400
+ });
1401
+ });
1402
+ }
1403
+ function unlock(file, options, callback) {
1404
+ options = {
1405
+ fs,
1406
+ realpath: true,
1407
+ ...options
1408
+ };
1409
+ resolveCanonicalPath(file, options, (err, file2) => {
1410
+ if (err) {
1411
+ return callback(err);
1412
+ }
1413
+ const lock2 = locks[file2];
1414
+ if (!lock2) {
1415
+ return callback(Object.assign(new Error("Lock is not acquired/owned by you"), { code: "ENOTACQUIRED" }));
1416
+ }
1417
+ lock2.updateTimeout && clearTimeout(lock2.updateTimeout);
1418
+ lock2.released = true;
1419
+ delete locks[file2];
1420
+ removeLock(file2, options, callback);
1421
+ });
1422
+ }
1423
+ function check(file, options, callback) {
1424
+ options = {
1425
+ stale: 1e4,
1426
+ realpath: true,
1427
+ fs,
1428
+ ...options
1429
+ };
1430
+ options.stale = Math.max(options.stale || 0, 2000);
1431
+ resolveCanonicalPath(file, options, (err, file2) => {
1432
+ if (err) {
1433
+ return callback(err);
1434
+ }
1435
+ options.fs.stat(getLockFile(file2, options), (err2, stat) => {
1436
+ if (err2) {
1437
+ return err2.code === "ENOENT" ? callback(null, false) : callback(err2);
1438
+ }
1439
+ return callback(null, !isLockStale(stat, options));
1440
+ });
1441
+ });
1442
+ }
1443
+ function getLocks() {
1444
+ return locks;
1445
+ }
1446
+ onExit(() => {
1447
+ for (const file in locks) {
1448
+ const options = locks[file].options;
1449
+ try {
1450
+ options.fs.rmdirSync(getLockFile(file, options));
1451
+ } catch (e) {}
1452
+ }
1453
+ });
1454
+ exports.lock = lock;
1455
+ exports.unlock = unlock;
1456
+ exports.check = check;
1457
+ exports.getLocks = getLocks;
1458
+ });
1459
+
1460
+ // node_modules/proper-lockfile/lib/adapter.js
1461
+ var require_adapter = __commonJS((exports, module) => {
1462
+ var fs = require_graceful_fs();
1463
+ function createSyncFs(fs2) {
1464
+ const methods = ["mkdir", "realpath", "stat", "rmdir", "utimes"];
1465
+ const newFs = { ...fs2 };
1466
+ methods.forEach((method) => {
1467
+ newFs[method] = (...args) => {
1468
+ const callback = args.pop();
1469
+ let ret;
1470
+ try {
1471
+ ret = fs2[`${method}Sync`](...args);
1472
+ } catch (err) {
1473
+ return callback(err);
1474
+ }
1475
+ callback(null, ret);
1476
+ };
1477
+ });
1478
+ return newFs;
1479
+ }
1480
+ function toPromise(method) {
1481
+ return (...args) => new Promise((resolve, reject) => {
1482
+ args.push((err, result) => {
1483
+ if (err) {
1484
+ reject(err);
1485
+ } else {
1486
+ resolve(result);
1487
+ }
1488
+ });
1489
+ method(...args);
1490
+ });
1491
+ }
1492
+ function toSync(method) {
1493
+ return (...args) => {
1494
+ let err;
1495
+ let result;
1496
+ args.push((_err, _result) => {
1497
+ err = _err;
1498
+ result = _result;
1499
+ });
1500
+ method(...args);
1501
+ if (err) {
1502
+ throw err;
1503
+ }
1504
+ return result;
1505
+ };
1506
+ }
1507
+ function toSyncOptions(options) {
1508
+ options = { ...options };
1509
+ options.fs = createSyncFs(options.fs || fs);
1510
+ if (typeof options.retries === "number" && options.retries > 0 || options.retries && typeof options.retries.retries === "number" && options.retries.retries > 0) {
1511
+ throw Object.assign(new Error("Cannot use retries with the sync api"), { code: "ESYNC" });
1512
+ }
1513
+ return options;
1514
+ }
1515
+ module.exports = {
1516
+ toPromise,
1517
+ toSync,
1518
+ toSyncOptions
1519
+ };
1520
+ });
1521
+
1522
+ // node_modules/proper-lockfile/index.js
1523
+ var require_proper_lockfile = __commonJS((exports, module) => {
1524
+ var lockfile = require_lockfile();
1525
+ var { toPromise, toSync, toSyncOptions } = require_adapter();
1526
+ async function lock(file, options) {
1527
+ const release = await toPromise(lockfile.lock)(file, options);
1528
+ return toPromise(release);
1529
+ }
1530
+ function lockSync(file, options) {
1531
+ const release = toSync(lockfile.lock)(file, toSyncOptions(options));
1532
+ return toSync(release);
1533
+ }
1534
+ function unlock(file, options) {
1535
+ return toPromise(lockfile.unlock)(file, options);
1536
+ }
1537
+ function unlockSync(file, options) {
1538
+ return toSync(lockfile.unlock)(file, toSyncOptions(options));
1539
+ }
1540
+ function check(file, options) {
1541
+ return toPromise(lockfile.check)(file, options);
1542
+ }
1543
+ function checkSync(file, options) {
1544
+ return toSync(lockfile.check)(file, toSyncOptions(options));
1545
+ }
1546
+ module.exports = lock;
1547
+ module.exports.lock = lock;
1548
+ module.exports.unlock = unlock;
1549
+ module.exports.lockSync = lockSync;
1550
+ module.exports.unlockSync = unlockSync;
1551
+ module.exports.check = check;
1552
+ module.exports.checkSync = checkSync;
1553
+ });
1554
+
1555
+ // src/constants.ts
1556
+ var MIMIKKAI_PROVIDER = "mimikkai-connect";
1557
+ var MIMIKKAI_AUTH_SERVICE_URL = "https://service.mimikkai.ru";
1558
+ var MIMIKKAI_FRONTEND_URL = "https://panel.mimikkai.ru";
1559
+ var MIMIKKAI_LITELLM_BASE_URL = "https://litellm.mimikkai.ru";
1560
+ var MIMIKKAI_CLIENT_NAME = "opencode";
1561
+
1562
+ // src/mimikkai.ts
1563
+ function rewriteVerificationUrls(data, frontendUrl) {
1564
+ const frontend = frontendUrl.replace(/\/+$/, "");
1565
+ const rewrite = (original) => {
1566
+ const parsed = new URL(original);
1567
+ const replacement = new URL(frontend);
1568
+ parsed.protocol = replacement.protocol;
1569
+ parsed.host = replacement.host;
1570
+ return parsed.toString();
1571
+ };
1572
+ return {
1573
+ ...data,
1574
+ verification_uri: rewrite(data.verification_uri),
1575
+ verification_uri_complete: rewrite(data.verification_uri_complete)
1576
+ };
1577
+ }
1578
+ function delay(ms) {
1579
+ return new Promise((resolve) => setTimeout(resolve, ms));
1580
+ }
1581
+ async function authorizeDevice() {
1582
+ const response = await fetch(`${MIMIKKAI_AUTH_SERVICE_URL}/api/auth/device/authorize`, {
1583
+ method: "POST",
1584
+ headers: { "Content-Type": "application/json" },
1585
+ body: JSON.stringify({ client_name: MIMIKKAI_CLIENT_NAME })
1586
+ });
1587
+ if (!response.ok)
1588
+ throw new Error(`Device authorize failed: ${response.status}`);
1589
+ const data = await response.json();
1590
+ return rewriteVerificationUrls(data, MIMIKKAI_FRONTEND_URL);
1591
+ }
1592
+ async function pollForToken(deviceCode, interval = 5, timeoutMs = 15 * 60 * 1000) {
1593
+ const deadline = Date.now() + timeoutMs;
1594
+ while (Date.now() < deadline) {
1595
+ const response = await fetch(`${MIMIKKAI_AUTH_SERVICE_URL}/api/auth/device/token`, {
1596
+ method: "POST",
1597
+ headers: { "Content-Type": "application/json" },
1598
+ body: JSON.stringify({ device_code: deviceCode })
1599
+ });
1600
+ if (response.status === 200) {
1601
+ return await response.json();
1602
+ }
1603
+ const body = await response.json().catch(() => ({}));
1604
+ if (response.status === 400 && body?.error === "expired_token")
1605
+ throw new Error("Device code expired");
1606
+ if (response.status === 202 && body?.error === "authorization_pending") {
1607
+ await delay(interval * 1000);
1608
+ continue;
1609
+ }
1610
+ throw new Error(`Unexpected token response: ${response.status} ${JSON.stringify(body)}`);
1611
+ }
1612
+ throw new Error("Polling timed out");
1613
+ }
1614
+ async function validateToken(token) {
1615
+ const query = `
1616
+ query UserViewer {
1617
+ userViewer {
1618
+ id
1619
+ name
1620
+ email
1621
+ }
1622
+ }`;
1623
+ const response = await fetch(`${MIMIKKAI_AUTH_SERVICE_URL}/graphql`, {
1624
+ method: "POST",
1625
+ headers: {
1626
+ "Content-Type": "application/json",
1627
+ Authorization: `Bearer ${token}`
1628
+ },
1629
+ body: JSON.stringify({ query })
1630
+ });
1631
+ if (!response.ok)
1632
+ return null;
1633
+ const data = await response.json();
1634
+ if (data.errors)
1635
+ return null;
1636
+ if (!data.data?.userViewer)
1637
+ return null;
1638
+ return data.data.userViewer;
1639
+ }
1640
+ async function fetchLitellmKey(token) {
1641
+ const query = `
1642
+ query GetUserApiKey {
1643
+ userViewer {
1644
+ id
1645
+ name
1646
+ email
1647
+ hasLitellmVirtualKey
1648
+ litellmKeyStatus
1649
+ litellmVirtualKey
1650
+ litellmKeyAlias
1651
+ litellmKeyModels
1652
+ litellmKeySpend
1653
+ litellmKeyMaxBudget
1654
+ litellmKeyExpires
1655
+ litellmKeySource
1656
+ litellmKeyMaxParallelRequests
1657
+ }
1658
+ }`;
1659
+ const response = await fetch(`${MIMIKKAI_AUTH_SERVICE_URL}/graphql`, {
1660
+ method: "POST",
1661
+ headers: {
1662
+ "Content-Type": "application/json",
1663
+ Authorization: `Bearer ${token}`
1664
+ },
1665
+ body: JSON.stringify({ query })
1666
+ });
1667
+ if (!response.ok)
1668
+ throw new Error(`Fetch litellm key failed: ${response.status}`);
1669
+ const data = await response.json();
1670
+ if (data.errors)
1671
+ throw new Error(`GraphQL errors: ${JSON.stringify(data.errors)}`);
1672
+ const viewer = data.data?.userViewer;
1673
+ if (!viewer)
1674
+ throw new Error("No userViewer in response");
1675
+ const key = viewer.litellmVirtualKey;
1676
+ if (!key || !key.startsWith("sk-") || key.includes("..."))
1677
+ throw new Error("LiteLLM virtual key is missing or masked. Please reconnect your account.");
1678
+ return key;
1679
+ }
1680
+ var DEFAULT_CONTEXT_LIMIT = 128000;
1681
+ var DEFAULT_OUTPUT_LIMIT = 16384;
1682
+ function parseModelLimits(model) {
1683
+ let context = DEFAULT_CONTEXT_LIMIT;
1684
+ let output = DEFAULT_OUTPUT_LIMIT;
1685
+ const info = model.model_info ?? {};
1686
+ const params = model.litellm_params ?? {};
1687
+ const ctxCandidates = [
1688
+ info.max_input_tokens,
1689
+ info.max_tokens,
1690
+ info.context_window,
1691
+ info.max_context_length,
1692
+ params.max_input_tokens,
1693
+ params.max_tokens
1694
+ ];
1695
+ for (const val of ctxCandidates) {
1696
+ if (typeof val === "number" && val > 0) {
1697
+ context = val;
1698
+ break;
1699
+ }
1700
+ }
1701
+ const outCandidates = [
1702
+ info.max_output_tokens,
1703
+ info.max_completion_tokens,
1704
+ params.max_output_tokens,
1705
+ params.max_completion_tokens
1706
+ ];
1707
+ for (const val of outCandidates) {
1708
+ if (typeof val === "number" && val > 0) {
1709
+ output = val;
1710
+ break;
1711
+ }
1712
+ }
1713
+ return { context, output };
1714
+ }
1715
+ function parseModelCapabilities(model) {
1716
+ const info = model.model_info ?? {};
1717
+ const supportsToolCall = info.supports_tool_call;
1718
+ const supportsReasoning = info.supports_reasoning;
1719
+ const supportsVision = info.supports_vision;
1720
+ const tool_call = typeof supportsToolCall === "boolean" ? supportsToolCall : true;
1721
+ const reasoning = typeof supportsReasoning === "boolean" ? supportsReasoning : false;
1722
+ const hasVision = typeof supportsVision === "boolean" ? supportsVision : false;
1723
+ const input = hasVision ? ["text", "image"] : ["text"];
1724
+ const output = ["text"];
1725
+ return { tool_call, reasoning, modalities: { input, output } };
1726
+ }
1727
+ async function fetchLitellmModels(apiKey) {
1728
+ const response = await fetch(`${MIMIKKAI_LITELLM_BASE_URL}/model/info`, {
1729
+ method: "GET",
1730
+ headers: {
1731
+ Authorization: `Bearer ${apiKey}`,
1732
+ Accept: "application/json"
1733
+ }
1734
+ });
1735
+ if (!response.ok)
1736
+ throw new Error(`Fetch models failed: ${response.status}`);
1737
+ const data = await response.json();
1738
+ return data.data ?? [];
1739
+ }
1740
+
1741
+ // src/storage.ts
1742
+ var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
1743
+ import { promises as fs } from "node:fs";
1744
+ import { dirname, join } from "node:path";
1745
+ import { homedir } from "node:os";
1746
+ import { randomBytes } from "node:crypto";
1747
+ function getConfigDir() {
1748
+ if (process.env.OPENCODE_CONFIG_DIR) {
1749
+ return process.env.OPENCODE_CONFIG_DIR;
1750
+ }
1751
+ const xdgConfig = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
1752
+ return join(xdgConfig, "opencode");
1753
+ }
1754
+ function getStoragePath() {
1755
+ return join(getConfigDir(), "mimikkai.json");
1756
+ }
1757
+ var LOCK_OPTIONS = {
1758
+ stale: 1e4,
1759
+ retries: {
1760
+ retries: 5,
1761
+ minTimeout: 100,
1762
+ maxTimeout: 1000,
1763
+ factor: 2
1764
+ }
1765
+ };
1766
+ async function ensureSecurePermissions(path) {
1767
+ try {
1768
+ await fs.chmod(path, 384);
1769
+ } catch {}
1770
+ }
1771
+ async function ensureFileExists(path) {
1772
+ try {
1773
+ await fs.access(path);
1774
+ } catch {
1775
+ await fs.mkdir(dirname(path), { recursive: true });
1776
+ await fs.writeFile(path, JSON.stringify({ sanctumToken: null, litellmKey: null, user: null }, null, 2), { encoding: "utf-8", mode: 384 });
1777
+ }
1778
+ }
1779
+ async function withFileLock(path, fn) {
1780
+ await ensureFileExists(path);
1781
+ let release = null;
1782
+ try {
1783
+ release = await import_proper_lockfile.default.lock(path, LOCK_OPTIONS);
1784
+ return await fn();
1785
+ } finally {
1786
+ if (release) {
1787
+ try {
1788
+ await release();
1789
+ } catch {}
1790
+ }
1791
+ }
1792
+ }
1793
+ async function loadStorage() {
1794
+ try {
1795
+ const path = getStoragePath();
1796
+ await ensureSecurePermissions(path);
1797
+ const content = await fs.readFile(path, "utf-8");
1798
+ const parsed = JSON.parse(content);
1799
+ if (!parsed || !parsed.sanctumToken)
1800
+ return null;
1801
+ return parsed;
1802
+ } catch {
1803
+ return null;
1804
+ }
1805
+ }
1806
+ async function saveStorage(storage) {
1807
+ const path = getStoragePath();
1808
+ const configDir = dirname(path);
1809
+ await fs.mkdir(configDir, { recursive: true });
1810
+ await withFileLock(path, async () => {
1811
+ const tempPath = `${path}.${randomBytes(6).toString("hex")}.tmp`;
1812
+ const content = JSON.stringify(storage, null, 2);
1813
+ try {
1814
+ await fs.writeFile(tempPath, content, { encoding: "utf-8", mode: 384 });
1815
+ await fs.rename(tempPath, path);
1816
+ } catch (error) {
1817
+ try {
1818
+ await fs.unlink(tempPath);
1819
+ } catch {}
1820
+ throw error;
1821
+ }
1822
+ });
1823
+ }
1824
+
1825
+ // src/logger.ts
1826
+ var LOG_LEVEL = process.env.LOG_LEVEL || "warn";
1827
+ function shouldLog(level) {
1828
+ const levels = ["error", "warn", "info", "debug"];
1829
+ const current = levels.indexOf(LOG_LEVEL.toLowerCase());
1830
+ const requested = levels.indexOf(level.toLowerCase());
1831
+ return requested <= current;
1832
+ }
1833
+ function logDebug(component, message, data) {
1834
+ if (shouldLog("debug"))
1835
+ console.debug(`[mimikkai:${component}] ${message}`, data !== undefined ? JSON.stringify(data) : "");
1836
+ }
1837
+ function logInfo(component, message, data) {
1838
+ if (shouldLog("info"))
1839
+ console.info(`[mimikkai:${component}] ${message}`, data !== undefined ? JSON.stringify(data) : "");
1840
+ }
1841
+ function logWarn(component, message, data) {
1842
+ if (shouldLog("warn"))
1843
+ console.warn(`[mimikkai:${component}] ${message}`, data !== undefined ? JSON.stringify(data) : "");
1844
+ }
1845
+ function logError(component, message, data) {
1846
+ if (shouldLog("error"))
1847
+ console.error(`[mimikkai:${component}] ${message}`, data !== undefined ? JSON.stringify(data) : "");
1848
+ }
1849
+
1850
+ // src/index.ts
1851
+ var FAR_FUTURE_EXPIRY_MS = 365 * 24 * 60 * 60 * 1000;
1852
+ var MimikkaiAuthPlugin = async (input) => {
1853
+ return {
1854
+ auth: {
1855
+ provider: MIMIKKAI_PROVIDER,
1856
+ loader: async (getAuth) => {
1857
+ logDebug("loader", "START");
1858
+ const latestAuth = await getAuth();
1859
+ if (latestAuth.type != "oauth") {
1860
+ logDebug("loader", "auth type is not oauth, returning empty", { type: latestAuth.type });
1861
+ return {};
1862
+ }
1863
+ const storage = await loadStorage();
1864
+ if (!storage) {
1865
+ logDebug("loader", "no storage found, returning empty");
1866
+ return {};
1867
+ }
1868
+ logDebug("loader", "validating sanctum token");
1869
+ const user = await validateToken(storage.sanctumToken);
1870
+ if (!user) {
1871
+ logWarn("loader", "sanctum token is invalid or expired, forcing re-auth");
1872
+ return {};
1873
+ }
1874
+ logDebug("loader", "token valid", { userId: user.id, email: user.email });
1875
+ if (!storage.litellmKey) {
1876
+ logWarn("loader", "no litellmKey in storage, returning empty");
1877
+ return {};
1878
+ }
1879
+ logDebug("loader", "returning apiKey from storage");
1880
+ return {
1881
+ apiKey: storage.litellmKey,
1882
+ fetch: async (input2, init) => {
1883
+ return fetch(input2, init);
1884
+ }
1885
+ };
1886
+ },
1887
+ methods: [
1888
+ {
1889
+ label: "Device Authorization",
1890
+ type: "oauth",
1891
+ authorize: async () => {
1892
+ logDebug("auth", "START authorize");
1893
+ const deviceData = await authorizeDevice();
1894
+ logDebug("auth", "device authorized", { userCode: deviceData.user_code, expiresIn: deviceData.expires_in });
1895
+ return {
1896
+ url: deviceData.verification_uri_complete,
1897
+ instructions: `Open this URL and confirm code: ${deviceData.user_code}`,
1898
+ method: "auto",
1899
+ async callback() {
1900
+ try {
1901
+ logDebug("auth", "START callback polling");
1902
+ const result = await pollForToken(deviceData.device_code, deviceData.interval, deviceData.expires_in * 1000);
1903
+ logInfo("auth", "token received", { userId: result.user.id, email: result.user.email });
1904
+ let litellmKey = null;
1905
+ try {
1906
+ logDebug("auth", "fetching litellm key");
1907
+ litellmKey = await fetchLitellmKey(result.token);
1908
+ logInfo("auth", "litellm key fetched successfully");
1909
+ } catch (keyError) {
1910
+ logWarn("auth", "failed to fetch litellm key, saving token anyway", { error: String(keyError) });
1911
+ }
1912
+ await saveStorage({
1913
+ sanctumToken: result.token,
1914
+ litellmKey,
1915
+ user: result.user
1916
+ });
1917
+ logDebug("auth", "storage saved");
1918
+ const expires = Date.now() + FAR_FUTURE_EXPIRY_MS;
1919
+ logDebug("auth", "returning success", { expiresMs: FAR_FUTURE_EXPIRY_MS });
1920
+ return {
1921
+ type: "success",
1922
+ access: result.token,
1923
+ refresh: result.token,
1924
+ expires
1925
+ };
1926
+ } catch (error) {
1927
+ logError("auth", "callback failed", { error: String(error) });
1928
+ return {
1929
+ type: "failed"
1930
+ };
1931
+ }
1932
+ }
1933
+ };
1934
+ }
1935
+ }
1936
+ ]
1937
+ },
1938
+ config: async (config) => {
1939
+ logDebug("config", "START");
1940
+ const providers = config.provider || {};
1941
+ providers[MIMIKKAI_PROVIDER] = {
1942
+ npm: "@ai-sdk/openai-compatible",
1943
+ name: "MimikkAi",
1944
+ options: { baseURL: `${MIMIKKAI_LITELLM_BASE_URL}/v1` },
1945
+ models: {
1946
+ auto: {
1947
+ id: "auto",
1948
+ name: "Auto"
1949
+ }
1950
+ }
1951
+ };
1952
+ const provider = providers[MIMIKKAI_PROVIDER];
1953
+ config.provider = providers;
1954
+ const storage = await loadStorage();
1955
+ if (!storage) {
1956
+ logDebug("config", "no storage, provider registered with empty models");
1957
+ return;
1958
+ }
1959
+ let litellmKey = storage.litellmKey;
1960
+ if (storage.sanctumToken) {
1961
+ logDebug("config", "attempting litellm key refresh");
1962
+ try {
1963
+ const freshKey = await fetchLitellmKey(storage.sanctumToken);
1964
+ if (freshKey && freshKey !== litellmKey) {
1965
+ logInfo("config", "litellm key refreshed");
1966
+ litellmKey = freshKey;
1967
+ await saveStorage({
1968
+ sanctumToken: storage.sanctumToken,
1969
+ litellmKey: freshKey,
1970
+ user: storage.user
1971
+ });
1972
+ } else {
1973
+ logDebug("config", "litellm key unchanged");
1974
+ }
1975
+ } catch (refreshError) {
1976
+ logWarn("config", "litellm key refresh failed, using stored key", { error: String(refreshError) });
1977
+ }
1978
+ }
1979
+ if (!litellmKey) {
1980
+ logWarn("config", "no litellm key available, returning with empty models");
1981
+ return;
1982
+ }
1983
+ provider.options["apiKey"] = litellmKey;
1984
+ provider.options["headers"] = {
1985
+ Authorization: `Bearer ${litellmKey}`
1986
+ };
1987
+ try {
1988
+ logDebug("config", "fetching models from litellm");
1989
+ const models = await fetchLitellmModels(litellmKey);
1990
+ logDebug("config", "models fetched", { count: models.length });
1991
+ for (const model of models) {
1992
+ const id = model.model_name;
1993
+ const limits = parseModelLimits(model);
1994
+ const caps = parseModelCapabilities(model);
1995
+ logDebug("config", "registering model", { id, limits, capabilities: caps });
1996
+ provider.models[id] = {
1997
+ id,
1998
+ name: id,
1999
+ tool_call: caps.tool_call,
2000
+ reasoning: caps.reasoning,
2001
+ limit: limits,
2002
+ modalities: caps.modalities
2003
+ };
2004
+ }
2005
+ logInfo("config", "models registered", { count: models.length });
2006
+ } catch (error) {
2007
+ logWarn("config", "failed to fetch models", { error: String(error) });
2008
+ }
2009
+ },
2010
+ dispose: async () => {
2011
+ logInfo("dispose", "plugin disposing");
2012
+ }
2013
+ };
2014
+ };
2015
+ export {
2016
+ MimikkaiAuthPlugin
2017
+ };