@przeprogramowani/10x-cli 0.2.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 (3) hide show
  1. package/README.md +71 -0
  2. package/dist/index.mjs +4464 -0
  3. package/package.json +45 -0
package/dist/index.mjs ADDED
@@ -0,0 +1,4464 @@
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/sisteransi/src/index.js
23
+ var require_src = __commonJS((exports, module) => {
24
+ var ESC = "\x1B";
25
+ var CSI = `${ESC}[`;
26
+ var beep = "\x07";
27
+ var cursor = {
28
+ to(x, y) {
29
+ if (!y)
30
+ return `${CSI}${x + 1}G`;
31
+ return `${CSI}${y + 1};${x + 1}H`;
32
+ },
33
+ move(x, y) {
34
+ let ret = "";
35
+ if (x < 0)
36
+ ret += `${CSI}${-x}D`;
37
+ else if (x > 0)
38
+ ret += `${CSI}${x}C`;
39
+ if (y < 0)
40
+ ret += `${CSI}${-y}A`;
41
+ else if (y > 0)
42
+ ret += `${CSI}${y}B`;
43
+ return ret;
44
+ },
45
+ up: (count = 1) => `${CSI}${count}A`,
46
+ down: (count = 1) => `${CSI}${count}B`,
47
+ forward: (count = 1) => `${CSI}${count}C`,
48
+ backward: (count = 1) => `${CSI}${count}D`,
49
+ nextLine: (count = 1) => `${CSI}E`.repeat(count),
50
+ prevLine: (count = 1) => `${CSI}F`.repeat(count),
51
+ left: `${CSI}G`,
52
+ hide: `${CSI}?25l`,
53
+ show: `${CSI}?25h`,
54
+ save: `${ESC}7`,
55
+ restore: `${ESC}8`
56
+ };
57
+ var scroll = {
58
+ up: (count = 1) => `${CSI}S`.repeat(count),
59
+ down: (count = 1) => `${CSI}T`.repeat(count)
60
+ };
61
+ var erase = {
62
+ screen: `${CSI}2J`,
63
+ up: (count = 1) => `${CSI}1J`.repeat(count),
64
+ down: (count = 1) => `${CSI}J`.repeat(count),
65
+ line: `${CSI}2K`,
66
+ lineEnd: `${CSI}K`,
67
+ lineStart: `${CSI}1K`,
68
+ lines(count) {
69
+ let clear = "";
70
+ for (let i = 0;i < count; i++)
71
+ clear += this.line + (i < count - 1 ? cursor.up() : "");
72
+ if (count)
73
+ clear += cursor.left;
74
+ return clear;
75
+ }
76
+ };
77
+ module.exports = { cursor, scroll, erase, beep };
78
+ });
79
+
80
+ // node_modules/picocolors/picocolors.js
81
+ var require_picocolors = __commonJS((exports, module) => {
82
+ var p = process || {};
83
+ var argv = p.argv || [];
84
+ var env = p.env || {};
85
+ var isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
86
+ var formatter = (open, close, replace = open) => (input) => {
87
+ let string = "" + input, index = string.indexOf(close, open.length);
88
+ return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
89
+ };
90
+ var replaceClose = (string, close, replace, index) => {
91
+ let result = "", cursor = 0;
92
+ do {
93
+ result += string.substring(cursor, index) + replace;
94
+ cursor = index + close.length;
95
+ index = string.indexOf(close, cursor);
96
+ } while (~index);
97
+ return result + string.substring(cursor);
98
+ };
99
+ var createColors = (enabled = isColorSupported) => {
100
+ let f = enabled ? formatter : () => String;
101
+ return {
102
+ isColorSupported: enabled,
103
+ reset: f("\x1B[0m", "\x1B[0m"),
104
+ bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
105
+ dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
106
+ italic: f("\x1B[3m", "\x1B[23m"),
107
+ underline: f("\x1B[4m", "\x1B[24m"),
108
+ inverse: f("\x1B[7m", "\x1B[27m"),
109
+ hidden: f("\x1B[8m", "\x1B[28m"),
110
+ strikethrough: f("\x1B[9m", "\x1B[29m"),
111
+ black: f("\x1B[30m", "\x1B[39m"),
112
+ red: f("\x1B[31m", "\x1B[39m"),
113
+ green: f("\x1B[32m", "\x1B[39m"),
114
+ yellow: f("\x1B[33m", "\x1B[39m"),
115
+ blue: f("\x1B[34m", "\x1B[39m"),
116
+ magenta: f("\x1B[35m", "\x1B[39m"),
117
+ cyan: f("\x1B[36m", "\x1B[39m"),
118
+ white: f("\x1B[37m", "\x1B[39m"),
119
+ gray: f("\x1B[90m", "\x1B[39m"),
120
+ bgBlack: f("\x1B[40m", "\x1B[49m"),
121
+ bgRed: f("\x1B[41m", "\x1B[49m"),
122
+ bgGreen: f("\x1B[42m", "\x1B[49m"),
123
+ bgYellow: f("\x1B[43m", "\x1B[49m"),
124
+ bgBlue: f("\x1B[44m", "\x1B[49m"),
125
+ bgMagenta: f("\x1B[45m", "\x1B[49m"),
126
+ bgCyan: f("\x1B[46m", "\x1B[49m"),
127
+ bgWhite: f("\x1B[47m", "\x1B[49m"),
128
+ blackBright: f("\x1B[90m", "\x1B[39m"),
129
+ redBright: f("\x1B[91m", "\x1B[39m"),
130
+ greenBright: f("\x1B[92m", "\x1B[39m"),
131
+ yellowBright: f("\x1B[93m", "\x1B[39m"),
132
+ blueBright: f("\x1B[94m", "\x1B[39m"),
133
+ magentaBright: f("\x1B[95m", "\x1B[39m"),
134
+ cyanBright: f("\x1B[96m", "\x1B[39m"),
135
+ whiteBright: f("\x1B[97m", "\x1B[39m"),
136
+ bgBlackBright: f("\x1B[100m", "\x1B[49m"),
137
+ bgRedBright: f("\x1B[101m", "\x1B[49m"),
138
+ bgGreenBright: f("\x1B[102m", "\x1B[49m"),
139
+ bgYellowBright: f("\x1B[103m", "\x1B[49m"),
140
+ bgBlueBright: f("\x1B[104m", "\x1B[49m"),
141
+ bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
142
+ bgCyanBright: f("\x1B[106m", "\x1B[49m"),
143
+ bgWhiteBright: f("\x1B[107m", "\x1B[49m")
144
+ };
145
+ };
146
+ module.exports = createColors();
147
+ module.exports.createColors = createColors;
148
+ });
149
+
150
+ // node_modules/graceful-fs/polyfills.js
151
+ var require_polyfills = __commonJS((exports, module) => {
152
+ var constants = __require("constants");
153
+ var origCwd = process.cwd;
154
+ var cwd = null;
155
+ var platform2 = process.env.GRACEFUL_FS_PLATFORM || process.platform;
156
+ process.cwd = function() {
157
+ if (!cwd)
158
+ cwd = origCwd.call(process);
159
+ return cwd;
160
+ };
161
+ try {
162
+ process.cwd();
163
+ } catch (er) {}
164
+ if (typeof process.chdir === "function") {
165
+ chdir = process.chdir;
166
+ process.chdir = function(d2) {
167
+ cwd = null;
168
+ chdir.call(process, d2);
169
+ };
170
+ if (Object.setPrototypeOf)
171
+ Object.setPrototypeOf(process.chdir, chdir);
172
+ }
173
+ var chdir;
174
+ module.exports = patch;
175
+ function patch(fs) {
176
+ if (constants.hasOwnProperty("O_SYMLINK") && process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
177
+ patchLchmod(fs);
178
+ }
179
+ if (!fs.lutimes) {
180
+ patchLutimes(fs);
181
+ }
182
+ fs.chown = chownFix(fs.chown);
183
+ fs.fchown = chownFix(fs.fchown);
184
+ fs.lchown = chownFix(fs.lchown);
185
+ fs.chmod = chmodFix(fs.chmod);
186
+ fs.fchmod = chmodFix(fs.fchmod);
187
+ fs.lchmod = chmodFix(fs.lchmod);
188
+ fs.chownSync = chownFixSync(fs.chownSync);
189
+ fs.fchownSync = chownFixSync(fs.fchownSync);
190
+ fs.lchownSync = chownFixSync(fs.lchownSync);
191
+ fs.chmodSync = chmodFixSync(fs.chmodSync);
192
+ fs.fchmodSync = chmodFixSync(fs.fchmodSync);
193
+ fs.lchmodSync = chmodFixSync(fs.lchmodSync);
194
+ fs.stat = statFix(fs.stat);
195
+ fs.fstat = statFix(fs.fstat);
196
+ fs.lstat = statFix(fs.lstat);
197
+ fs.statSync = statFixSync(fs.statSync);
198
+ fs.fstatSync = statFixSync(fs.fstatSync);
199
+ fs.lstatSync = statFixSync(fs.lstatSync);
200
+ if (fs.chmod && !fs.lchmod) {
201
+ fs.lchmod = function(path, mode, cb) {
202
+ if (cb)
203
+ process.nextTick(cb);
204
+ };
205
+ fs.lchmodSync = function() {};
206
+ }
207
+ if (fs.chown && !fs.lchown) {
208
+ fs.lchown = function(path, uid, gid, cb) {
209
+ if (cb)
210
+ process.nextTick(cb);
211
+ };
212
+ fs.lchownSync = function() {};
213
+ }
214
+ if (platform2 === "win32") {
215
+ fs.rename = typeof fs.rename !== "function" ? fs.rename : function(fs$rename) {
216
+ function rename(from, to, cb) {
217
+ var start = Date.now();
218
+ var backoff = 0;
219
+ fs$rename(from, to, function CB(er) {
220
+ if (er && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY") && Date.now() - start < 60000) {
221
+ setTimeout(function() {
222
+ fs.stat(to, function(stater, st) {
223
+ if (stater && stater.code === "ENOENT")
224
+ fs$rename(from, to, CB);
225
+ else
226
+ cb(er);
227
+ });
228
+ }, backoff);
229
+ if (backoff < 100)
230
+ backoff += 10;
231
+ return;
232
+ }
233
+ if (cb)
234
+ cb(er);
235
+ });
236
+ }
237
+ if (Object.setPrototypeOf)
238
+ Object.setPrototypeOf(rename, fs$rename);
239
+ return rename;
240
+ }(fs.rename);
241
+ }
242
+ fs.read = typeof fs.read !== "function" ? fs.read : function(fs$read) {
243
+ function read(fd, buffer, offset, length, position, callback_) {
244
+ var callback;
245
+ if (callback_ && typeof callback_ === "function") {
246
+ var eagCounter = 0;
247
+ callback = function(er, _2, __) {
248
+ if (er && er.code === "EAGAIN" && eagCounter < 10) {
249
+ eagCounter++;
250
+ return fs$read.call(fs, fd, buffer, offset, length, position, callback);
251
+ }
252
+ callback_.apply(this, arguments);
253
+ };
254
+ }
255
+ return fs$read.call(fs, fd, buffer, offset, length, position, callback);
256
+ }
257
+ if (Object.setPrototypeOf)
258
+ Object.setPrototypeOf(read, fs$read);
259
+ return read;
260
+ }(fs.read);
261
+ fs.readSync = typeof fs.readSync !== "function" ? fs.readSync : function(fs$readSync) {
262
+ return function(fd, buffer, offset, length, position) {
263
+ var eagCounter = 0;
264
+ while (true) {
265
+ try {
266
+ return fs$readSync.call(fs, fd, buffer, offset, length, position);
267
+ } catch (er) {
268
+ if (er.code === "EAGAIN" && eagCounter < 10) {
269
+ eagCounter++;
270
+ continue;
271
+ }
272
+ throw er;
273
+ }
274
+ }
275
+ };
276
+ }(fs.readSync);
277
+ function patchLchmod(fs2) {
278
+ fs2.lchmod = function(path, mode, callback) {
279
+ fs2.open(path, constants.O_WRONLY | constants.O_SYMLINK, mode, function(err, fd) {
280
+ if (err) {
281
+ if (callback)
282
+ callback(err);
283
+ return;
284
+ }
285
+ fs2.fchmod(fd, mode, function(err2) {
286
+ fs2.close(fd, function(err22) {
287
+ if (callback)
288
+ callback(err2 || err22);
289
+ });
290
+ });
291
+ });
292
+ };
293
+ fs2.lchmodSync = function(path, mode) {
294
+ var fd = fs2.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode);
295
+ var threw = true;
296
+ var ret;
297
+ try {
298
+ ret = fs2.fchmodSync(fd, mode);
299
+ threw = false;
300
+ } finally {
301
+ if (threw) {
302
+ try {
303
+ fs2.closeSync(fd);
304
+ } catch (er) {}
305
+ } else {
306
+ fs2.closeSync(fd);
307
+ }
308
+ }
309
+ return ret;
310
+ };
311
+ }
312
+ function patchLutimes(fs2) {
313
+ if (constants.hasOwnProperty("O_SYMLINK") && fs2.futimes) {
314
+ fs2.lutimes = function(path, at, mt, cb) {
315
+ fs2.open(path, constants.O_SYMLINK, function(er, fd) {
316
+ if (er) {
317
+ if (cb)
318
+ cb(er);
319
+ return;
320
+ }
321
+ fs2.futimes(fd, at, mt, function(er2) {
322
+ fs2.close(fd, function(er22) {
323
+ if (cb)
324
+ cb(er2 || er22);
325
+ });
326
+ });
327
+ });
328
+ };
329
+ fs2.lutimesSync = function(path, at, mt) {
330
+ var fd = fs2.openSync(path, constants.O_SYMLINK);
331
+ var ret;
332
+ var threw = true;
333
+ try {
334
+ ret = fs2.futimesSync(fd, at, mt);
335
+ threw = false;
336
+ } finally {
337
+ if (threw) {
338
+ try {
339
+ fs2.closeSync(fd);
340
+ } catch (er) {}
341
+ } else {
342
+ fs2.closeSync(fd);
343
+ }
344
+ }
345
+ return ret;
346
+ };
347
+ } else if (fs2.futimes) {
348
+ fs2.lutimes = function(_a, _b, _c, cb) {
349
+ if (cb)
350
+ process.nextTick(cb);
351
+ };
352
+ fs2.lutimesSync = function() {};
353
+ }
354
+ }
355
+ function chmodFix(orig) {
356
+ if (!orig)
357
+ return orig;
358
+ return function(target, mode, cb) {
359
+ return orig.call(fs, target, mode, function(er) {
360
+ if (chownErOk(er))
361
+ er = null;
362
+ if (cb)
363
+ cb.apply(this, arguments);
364
+ });
365
+ };
366
+ }
367
+ function chmodFixSync(orig) {
368
+ if (!orig)
369
+ return orig;
370
+ return function(target, mode) {
371
+ try {
372
+ return orig.call(fs, target, mode);
373
+ } catch (er) {
374
+ if (!chownErOk(er))
375
+ throw er;
376
+ }
377
+ };
378
+ }
379
+ function chownFix(orig) {
380
+ if (!orig)
381
+ return orig;
382
+ return function(target, uid, gid, cb) {
383
+ return orig.call(fs, target, uid, gid, function(er) {
384
+ if (chownErOk(er))
385
+ er = null;
386
+ if (cb)
387
+ cb.apply(this, arguments);
388
+ });
389
+ };
390
+ }
391
+ function chownFixSync(orig) {
392
+ if (!orig)
393
+ return orig;
394
+ return function(target, uid, gid) {
395
+ try {
396
+ return orig.call(fs, target, uid, gid);
397
+ } catch (er) {
398
+ if (!chownErOk(er))
399
+ throw er;
400
+ }
401
+ };
402
+ }
403
+ function statFix(orig) {
404
+ if (!orig)
405
+ return orig;
406
+ return function(target, options, cb) {
407
+ if (typeof options === "function") {
408
+ cb = options;
409
+ options = null;
410
+ }
411
+ function callback(er, stats) {
412
+ if (stats) {
413
+ if (stats.uid < 0)
414
+ stats.uid += 4294967296;
415
+ if (stats.gid < 0)
416
+ stats.gid += 4294967296;
417
+ }
418
+ if (cb)
419
+ cb.apply(this, arguments);
420
+ }
421
+ return options ? orig.call(fs, target, options, callback) : orig.call(fs, target, callback);
422
+ };
423
+ }
424
+ function statFixSync(orig) {
425
+ if (!orig)
426
+ return orig;
427
+ return function(target, options) {
428
+ var stats = options ? orig.call(fs, target, options) : orig.call(fs, target);
429
+ if (stats) {
430
+ if (stats.uid < 0)
431
+ stats.uid += 4294967296;
432
+ if (stats.gid < 0)
433
+ stats.gid += 4294967296;
434
+ }
435
+ return stats;
436
+ };
437
+ }
438
+ function chownErOk(er) {
439
+ if (!er)
440
+ return true;
441
+ if (er.code === "ENOSYS")
442
+ return true;
443
+ var nonroot = !process.getuid || process.getuid() !== 0;
444
+ if (nonroot) {
445
+ if (er.code === "EINVAL" || er.code === "EPERM")
446
+ return true;
447
+ }
448
+ return false;
449
+ }
450
+ }
451
+ });
452
+
453
+ // node_modules/graceful-fs/legacy-streams.js
454
+ var require_legacy_streams = __commonJS((exports, module) => {
455
+ var Stream = __require("stream").Stream;
456
+ module.exports = legacy;
457
+ function legacy(fs) {
458
+ return {
459
+ ReadStream,
460
+ WriteStream
461
+ };
462
+ function ReadStream(path, options) {
463
+ if (!(this instanceof ReadStream))
464
+ return new ReadStream(path, options);
465
+ Stream.call(this);
466
+ var self = this;
467
+ this.path = path;
468
+ this.fd = null;
469
+ this.readable = true;
470
+ this.paused = false;
471
+ this.flags = "r";
472
+ this.mode = 438;
473
+ this.bufferSize = 64 * 1024;
474
+ options = options || {};
475
+ var keys = Object.keys(options);
476
+ for (var index = 0, length = keys.length;index < length; index++) {
477
+ var key = keys[index];
478
+ this[key] = options[key];
479
+ }
480
+ if (this.encoding)
481
+ this.setEncoding(this.encoding);
482
+ if (this.start !== undefined) {
483
+ if (typeof this.start !== "number") {
484
+ throw TypeError("start must be a Number");
485
+ }
486
+ if (this.end === undefined) {
487
+ this.end = Infinity;
488
+ } else if (typeof this.end !== "number") {
489
+ throw TypeError("end must be a Number");
490
+ }
491
+ if (this.start > this.end) {
492
+ throw new Error("start must be <= end");
493
+ }
494
+ this.pos = this.start;
495
+ }
496
+ if (this.fd !== null) {
497
+ process.nextTick(function() {
498
+ self._read();
499
+ });
500
+ return;
501
+ }
502
+ fs.open(this.path, this.flags, this.mode, function(err, fd) {
503
+ if (err) {
504
+ self.emit("error", err);
505
+ self.readable = false;
506
+ return;
507
+ }
508
+ self.fd = fd;
509
+ self.emit("open", fd);
510
+ self._read();
511
+ });
512
+ }
513
+ function WriteStream(path, options) {
514
+ if (!(this instanceof WriteStream))
515
+ return new WriteStream(path, options);
516
+ Stream.call(this);
517
+ this.path = path;
518
+ this.fd = null;
519
+ this.writable = true;
520
+ this.flags = "w";
521
+ this.encoding = "binary";
522
+ this.mode = 438;
523
+ this.bytesWritten = 0;
524
+ options = options || {};
525
+ var keys = Object.keys(options);
526
+ for (var index = 0, length = keys.length;index < length; index++) {
527
+ var key = keys[index];
528
+ this[key] = options[key];
529
+ }
530
+ if (this.start !== undefined) {
531
+ if (typeof this.start !== "number") {
532
+ throw TypeError("start must be a Number");
533
+ }
534
+ if (this.start < 0) {
535
+ throw new Error("start must be >= zero");
536
+ }
537
+ this.pos = this.start;
538
+ }
539
+ this.busy = false;
540
+ this._queue = [];
541
+ if (this.fd === null) {
542
+ this._open = fs.open;
543
+ this._queue.push([this._open, this.path, this.flags, this.mode, undefined]);
544
+ this.flush();
545
+ }
546
+ }
547
+ }
548
+ });
549
+
550
+ // node_modules/graceful-fs/clone.js
551
+ var require_clone = __commonJS((exports, module) => {
552
+ module.exports = clone;
553
+ var getPrototypeOf = Object.getPrototypeOf || function(obj) {
554
+ return obj.__proto__;
555
+ };
556
+ function clone(obj) {
557
+ if (obj === null || typeof obj !== "object")
558
+ return obj;
559
+ if (obj instanceof Object)
560
+ var copy = { __proto__: getPrototypeOf(obj) };
561
+ else
562
+ var copy = Object.create(null);
563
+ Object.getOwnPropertyNames(obj).forEach(function(key) {
564
+ Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key));
565
+ });
566
+ return copy;
567
+ }
568
+ });
569
+
570
+ // node_modules/graceful-fs/graceful-fs.js
571
+ var require_graceful_fs = __commonJS((exports, module) => {
572
+ var fs = __require("fs");
573
+ var polyfills = require_polyfills();
574
+ var legacy = require_legacy_streams();
575
+ var clone = require_clone();
576
+ var util = __require("util");
577
+ var gracefulQueue;
578
+ var previousSymbol;
579
+ if (typeof Symbol === "function" && typeof Symbol.for === "function") {
580
+ gracefulQueue = Symbol.for("graceful-fs.queue");
581
+ previousSymbol = Symbol.for("graceful-fs.previous");
582
+ } else {
583
+ gracefulQueue = "___graceful-fs.queue";
584
+ previousSymbol = "___graceful-fs.previous";
585
+ }
586
+ function noop() {}
587
+ function publishQueue(context, queue2) {
588
+ Object.defineProperty(context, gracefulQueue, {
589
+ get: function() {
590
+ return queue2;
591
+ }
592
+ });
593
+ }
594
+ var debug = noop;
595
+ if (util.debuglog)
596
+ debug = util.debuglog("gfs4");
597
+ else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ""))
598
+ debug = function() {
599
+ var m3 = util.format.apply(util, arguments);
600
+ m3 = "GFS4: " + m3.split(/\n/).join(`
601
+ GFS4: `);
602
+ console.error(m3);
603
+ };
604
+ if (!fs[gracefulQueue]) {
605
+ queue = global[gracefulQueue] || [];
606
+ publishQueue(fs, queue);
607
+ fs.close = function(fs$close) {
608
+ function close(fd, cb) {
609
+ return fs$close.call(fs, fd, function(err) {
610
+ if (!err) {
611
+ resetQueue();
612
+ }
613
+ if (typeof cb === "function")
614
+ cb.apply(this, arguments);
615
+ });
616
+ }
617
+ Object.defineProperty(close, previousSymbol, {
618
+ value: fs$close
619
+ });
620
+ return close;
621
+ }(fs.close);
622
+ fs.closeSync = function(fs$closeSync) {
623
+ function closeSync(fd) {
624
+ fs$closeSync.apply(fs, arguments);
625
+ resetQueue();
626
+ }
627
+ Object.defineProperty(closeSync, previousSymbol, {
628
+ value: fs$closeSync
629
+ });
630
+ return closeSync;
631
+ }(fs.closeSync);
632
+ if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) {
633
+ process.on("exit", function() {
634
+ debug(fs[gracefulQueue]);
635
+ __require("assert").equal(fs[gracefulQueue].length, 0);
636
+ });
637
+ }
638
+ }
639
+ var queue;
640
+ if (!global[gracefulQueue]) {
641
+ publishQueue(global, fs[gracefulQueue]);
642
+ }
643
+ module.exports = patch(clone(fs));
644
+ if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) {
645
+ module.exports = patch(fs);
646
+ fs.__patched = true;
647
+ }
648
+ function patch(fs2) {
649
+ polyfills(fs2);
650
+ fs2.gracefulify = patch;
651
+ fs2.createReadStream = createReadStream;
652
+ fs2.createWriteStream = createWriteStream;
653
+ var fs$readFile = fs2.readFile;
654
+ fs2.readFile = readFile;
655
+ function readFile(path, options, cb) {
656
+ if (typeof options === "function")
657
+ cb = options, options = null;
658
+ return go$readFile(path, options, cb);
659
+ function go$readFile(path2, options2, cb2, startTime) {
660
+ return fs$readFile(path2, options2, function(err) {
661
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
662
+ enqueue([go$readFile, [path2, options2, cb2], err, startTime || Date.now(), Date.now()]);
663
+ else {
664
+ if (typeof cb2 === "function")
665
+ cb2.apply(this, arguments);
666
+ }
667
+ });
668
+ }
669
+ }
670
+ var fs$writeFile = fs2.writeFile;
671
+ fs2.writeFile = writeFile;
672
+ function writeFile(path, data, options, cb) {
673
+ if (typeof options === "function")
674
+ cb = options, options = null;
675
+ return go$writeFile(path, data, options, cb);
676
+ function go$writeFile(path2, data2, options2, cb2, startTime) {
677
+ return fs$writeFile(path2, data2, options2, function(err) {
678
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
679
+ enqueue([go$writeFile, [path2, data2, options2, cb2], err, startTime || Date.now(), Date.now()]);
680
+ else {
681
+ if (typeof cb2 === "function")
682
+ cb2.apply(this, arguments);
683
+ }
684
+ });
685
+ }
686
+ }
687
+ var fs$appendFile = fs2.appendFile;
688
+ if (fs$appendFile)
689
+ fs2.appendFile = appendFile;
690
+ function appendFile(path, data, options, cb) {
691
+ if (typeof options === "function")
692
+ cb = options, options = null;
693
+ return go$appendFile(path, data, options, cb);
694
+ function go$appendFile(path2, data2, options2, cb2, startTime) {
695
+ return fs$appendFile(path2, data2, options2, function(err) {
696
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
697
+ enqueue([go$appendFile, [path2, data2, options2, cb2], err, startTime || Date.now(), Date.now()]);
698
+ else {
699
+ if (typeof cb2 === "function")
700
+ cb2.apply(this, arguments);
701
+ }
702
+ });
703
+ }
704
+ }
705
+ var fs$copyFile = fs2.copyFile;
706
+ if (fs$copyFile)
707
+ fs2.copyFile = copyFile;
708
+ function copyFile(src, dest, flags, cb) {
709
+ if (typeof flags === "function") {
710
+ cb = flags;
711
+ flags = 0;
712
+ }
713
+ return go$copyFile(src, dest, flags, cb);
714
+ function go$copyFile(src2, dest2, flags2, cb2, startTime) {
715
+ return fs$copyFile(src2, dest2, flags2, function(err) {
716
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
717
+ enqueue([go$copyFile, [src2, dest2, flags2, cb2], err, startTime || Date.now(), Date.now()]);
718
+ else {
719
+ if (typeof cb2 === "function")
720
+ cb2.apply(this, arguments);
721
+ }
722
+ });
723
+ }
724
+ }
725
+ var fs$readdir = fs2.readdir;
726
+ fs2.readdir = readdir;
727
+ var noReaddirOptionVersions = /^v[0-5]\./;
728
+ function readdir(path, options, cb) {
729
+ if (typeof options === "function")
730
+ cb = options, options = null;
731
+ var go$readdir = noReaddirOptionVersions.test(process.version) ? function go$readdir2(path2, options2, cb2, startTime) {
732
+ return fs$readdir(path2, fs$readdirCallback(path2, options2, cb2, startTime));
733
+ } : function go$readdir2(path2, options2, cb2, startTime) {
734
+ return fs$readdir(path2, options2, fs$readdirCallback(path2, options2, cb2, startTime));
735
+ };
736
+ return go$readdir(path, options, cb);
737
+ function fs$readdirCallback(path2, options2, cb2, startTime) {
738
+ return function(err, files) {
739
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
740
+ enqueue([
741
+ go$readdir,
742
+ [path2, options2, cb2],
743
+ err,
744
+ startTime || Date.now(),
745
+ Date.now()
746
+ ]);
747
+ else {
748
+ if (files && files.sort)
749
+ files.sort();
750
+ if (typeof cb2 === "function")
751
+ cb2.call(this, err, files);
752
+ }
753
+ };
754
+ }
755
+ }
756
+ if (process.version.substr(0, 4) === "v0.8") {
757
+ var legStreams = legacy(fs2);
758
+ ReadStream = legStreams.ReadStream;
759
+ WriteStream = legStreams.WriteStream;
760
+ }
761
+ var fs$ReadStream = fs2.ReadStream;
762
+ if (fs$ReadStream) {
763
+ ReadStream.prototype = Object.create(fs$ReadStream.prototype);
764
+ ReadStream.prototype.open = ReadStream$open;
765
+ }
766
+ var fs$WriteStream = fs2.WriteStream;
767
+ if (fs$WriteStream) {
768
+ WriteStream.prototype = Object.create(fs$WriteStream.prototype);
769
+ WriteStream.prototype.open = WriteStream$open;
770
+ }
771
+ Object.defineProperty(fs2, "ReadStream", {
772
+ get: function() {
773
+ return ReadStream;
774
+ },
775
+ set: function(val) {
776
+ ReadStream = val;
777
+ },
778
+ enumerable: true,
779
+ configurable: true
780
+ });
781
+ Object.defineProperty(fs2, "WriteStream", {
782
+ get: function() {
783
+ return WriteStream;
784
+ },
785
+ set: function(val) {
786
+ WriteStream = val;
787
+ },
788
+ enumerable: true,
789
+ configurable: true
790
+ });
791
+ var FileReadStream = ReadStream;
792
+ Object.defineProperty(fs2, "FileReadStream", {
793
+ get: function() {
794
+ return FileReadStream;
795
+ },
796
+ set: function(val) {
797
+ FileReadStream = val;
798
+ },
799
+ enumerable: true,
800
+ configurable: true
801
+ });
802
+ var FileWriteStream = WriteStream;
803
+ Object.defineProperty(fs2, "FileWriteStream", {
804
+ get: function() {
805
+ return FileWriteStream;
806
+ },
807
+ set: function(val) {
808
+ FileWriteStream = val;
809
+ },
810
+ enumerable: true,
811
+ configurable: true
812
+ });
813
+ function ReadStream(path, options) {
814
+ if (this instanceof ReadStream)
815
+ return fs$ReadStream.apply(this, arguments), this;
816
+ else
817
+ return ReadStream.apply(Object.create(ReadStream.prototype), arguments);
818
+ }
819
+ function ReadStream$open() {
820
+ var that = this;
821
+ open(that.path, that.flags, that.mode, function(err, fd) {
822
+ if (err) {
823
+ if (that.autoClose)
824
+ that.destroy();
825
+ that.emit("error", err);
826
+ } else {
827
+ that.fd = fd;
828
+ that.emit("open", fd);
829
+ that.read();
830
+ }
831
+ });
832
+ }
833
+ function WriteStream(path, options) {
834
+ if (this instanceof WriteStream)
835
+ return fs$WriteStream.apply(this, arguments), this;
836
+ else
837
+ return WriteStream.apply(Object.create(WriteStream.prototype), arguments);
838
+ }
839
+ function WriteStream$open() {
840
+ var that = this;
841
+ open(that.path, that.flags, that.mode, function(err, fd) {
842
+ if (err) {
843
+ that.destroy();
844
+ that.emit("error", err);
845
+ } else {
846
+ that.fd = fd;
847
+ that.emit("open", fd);
848
+ }
849
+ });
850
+ }
851
+ function createReadStream(path, options) {
852
+ return new fs2.ReadStream(path, options);
853
+ }
854
+ function createWriteStream(path, options) {
855
+ return new fs2.WriteStream(path, options);
856
+ }
857
+ var fs$open = fs2.open;
858
+ fs2.open = open;
859
+ function open(path, flags, mode, cb) {
860
+ if (typeof mode === "function")
861
+ cb = mode, mode = null;
862
+ return go$open(path, flags, mode, cb);
863
+ function go$open(path2, flags2, mode2, cb2, startTime) {
864
+ return fs$open(path2, flags2, mode2, function(err, fd) {
865
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
866
+ enqueue([go$open, [path2, flags2, mode2, cb2], err, startTime || Date.now(), Date.now()]);
867
+ else {
868
+ if (typeof cb2 === "function")
869
+ cb2.apply(this, arguments);
870
+ }
871
+ });
872
+ }
873
+ }
874
+ return fs2;
875
+ }
876
+ function enqueue(elem) {
877
+ debug("ENQUEUE", elem[0].name, elem[1]);
878
+ fs[gracefulQueue].push(elem);
879
+ retry();
880
+ }
881
+ var retryTimer;
882
+ function resetQueue() {
883
+ var now = Date.now();
884
+ for (var i = 0;i < fs[gracefulQueue].length; ++i) {
885
+ if (fs[gracefulQueue][i].length > 2) {
886
+ fs[gracefulQueue][i][3] = now;
887
+ fs[gracefulQueue][i][4] = now;
888
+ }
889
+ }
890
+ retry();
891
+ }
892
+ function retry() {
893
+ clearTimeout(retryTimer);
894
+ retryTimer = undefined;
895
+ if (fs[gracefulQueue].length === 0)
896
+ return;
897
+ var elem = fs[gracefulQueue].shift();
898
+ var fn = elem[0];
899
+ var args = elem[1];
900
+ var err = elem[2];
901
+ var startTime = elem[3];
902
+ var lastTime = elem[4];
903
+ if (startTime === undefined) {
904
+ debug("RETRY", fn.name, args);
905
+ fn.apply(null, args);
906
+ } else if (Date.now() - startTime >= 60000) {
907
+ debug("TIMEOUT", fn.name, args);
908
+ var cb = args.pop();
909
+ if (typeof cb === "function")
910
+ cb.call(null, err);
911
+ } else {
912
+ var sinceAttempt = Date.now() - lastTime;
913
+ var sinceStart = Math.max(lastTime - startTime, 1);
914
+ var desiredDelay = Math.min(sinceStart * 1.2, 100);
915
+ if (sinceAttempt >= desiredDelay) {
916
+ debug("RETRY", fn.name, args);
917
+ fn.apply(null, args.concat([startTime]));
918
+ } else {
919
+ fs[gracefulQueue].push(elem);
920
+ }
921
+ }
922
+ if (retryTimer === undefined) {
923
+ retryTimer = setTimeout(retry, 0);
924
+ }
925
+ }
926
+ });
927
+
928
+ // node_modules/retry/lib/retry_operation.js
929
+ var require_retry_operation = __commonJS((exports, module) => {
930
+ function RetryOperation(timeouts, options) {
931
+ if (typeof options === "boolean") {
932
+ options = { forever: options };
933
+ }
934
+ this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
935
+ this._timeouts = timeouts;
936
+ this._options = options || {};
937
+ this._maxRetryTime = options && options.maxRetryTime || Infinity;
938
+ this._fn = null;
939
+ this._errors = [];
940
+ this._attempts = 1;
941
+ this._operationTimeout = null;
942
+ this._operationTimeoutCb = null;
943
+ this._timeout = null;
944
+ this._operationStart = null;
945
+ if (this._options.forever) {
946
+ this._cachedTimeouts = this._timeouts.slice(0);
947
+ }
948
+ }
949
+ module.exports = RetryOperation;
950
+ RetryOperation.prototype.reset = function() {
951
+ this._attempts = 1;
952
+ this._timeouts = this._originalTimeouts;
953
+ };
954
+ RetryOperation.prototype.stop = function() {
955
+ if (this._timeout) {
956
+ clearTimeout(this._timeout);
957
+ }
958
+ this._timeouts = [];
959
+ this._cachedTimeouts = null;
960
+ };
961
+ RetryOperation.prototype.retry = function(err) {
962
+ if (this._timeout) {
963
+ clearTimeout(this._timeout);
964
+ }
965
+ if (!err) {
966
+ return false;
967
+ }
968
+ var currentTime = new Date().getTime();
969
+ if (err && currentTime - this._operationStart >= this._maxRetryTime) {
970
+ this._errors.unshift(new Error("RetryOperation timeout occurred"));
971
+ return false;
972
+ }
973
+ this._errors.push(err);
974
+ var timeout = this._timeouts.shift();
975
+ if (timeout === undefined) {
976
+ if (this._cachedTimeouts) {
977
+ this._errors.splice(this._errors.length - 1, this._errors.length);
978
+ this._timeouts = this._cachedTimeouts.slice(0);
979
+ timeout = this._timeouts.shift();
980
+ } else {
981
+ return false;
982
+ }
983
+ }
984
+ var self = this;
985
+ var timer = setTimeout(function() {
986
+ self._attempts++;
987
+ if (self._operationTimeoutCb) {
988
+ self._timeout = setTimeout(function() {
989
+ self._operationTimeoutCb(self._attempts);
990
+ }, self._operationTimeout);
991
+ if (self._options.unref) {
992
+ self._timeout.unref();
993
+ }
994
+ }
995
+ self._fn(self._attempts);
996
+ }, timeout);
997
+ if (this._options.unref) {
998
+ timer.unref();
999
+ }
1000
+ return true;
1001
+ };
1002
+ RetryOperation.prototype.attempt = function(fn, timeoutOps) {
1003
+ this._fn = fn;
1004
+ if (timeoutOps) {
1005
+ if (timeoutOps.timeout) {
1006
+ this._operationTimeout = timeoutOps.timeout;
1007
+ }
1008
+ if (timeoutOps.cb) {
1009
+ this._operationTimeoutCb = timeoutOps.cb;
1010
+ }
1011
+ }
1012
+ var self = this;
1013
+ if (this._operationTimeoutCb) {
1014
+ this._timeout = setTimeout(function() {
1015
+ self._operationTimeoutCb();
1016
+ }, self._operationTimeout);
1017
+ }
1018
+ this._operationStart = new Date().getTime();
1019
+ this._fn(this._attempts);
1020
+ };
1021
+ RetryOperation.prototype.try = function(fn) {
1022
+ console.log("Using RetryOperation.try() is deprecated");
1023
+ this.attempt(fn);
1024
+ };
1025
+ RetryOperation.prototype.start = function(fn) {
1026
+ console.log("Using RetryOperation.start() is deprecated");
1027
+ this.attempt(fn);
1028
+ };
1029
+ RetryOperation.prototype.start = RetryOperation.prototype.try;
1030
+ RetryOperation.prototype.errors = function() {
1031
+ return this._errors;
1032
+ };
1033
+ RetryOperation.prototype.attempts = function() {
1034
+ return this._attempts;
1035
+ };
1036
+ RetryOperation.prototype.mainError = function() {
1037
+ if (this._errors.length === 0) {
1038
+ return null;
1039
+ }
1040
+ var counts = {};
1041
+ var mainError = null;
1042
+ var mainErrorCount = 0;
1043
+ for (var i = 0;i < this._errors.length; i++) {
1044
+ var error = this._errors[i];
1045
+ var message = error.message;
1046
+ var count = (counts[message] || 0) + 1;
1047
+ counts[message] = count;
1048
+ if (count >= mainErrorCount) {
1049
+ mainError = error;
1050
+ mainErrorCount = count;
1051
+ }
1052
+ }
1053
+ return mainError;
1054
+ };
1055
+ });
1056
+
1057
+ // node_modules/retry/lib/retry.js
1058
+ var require_retry = __commonJS((exports) => {
1059
+ var RetryOperation = require_retry_operation();
1060
+ exports.operation = function(options) {
1061
+ var timeouts = exports.timeouts(options);
1062
+ return new RetryOperation(timeouts, {
1063
+ forever: options && options.forever,
1064
+ unref: options && options.unref,
1065
+ maxRetryTime: options && options.maxRetryTime
1066
+ });
1067
+ };
1068
+ exports.timeouts = function(options) {
1069
+ if (options instanceof Array) {
1070
+ return [].concat(options);
1071
+ }
1072
+ var opts = {
1073
+ retries: 10,
1074
+ factor: 2,
1075
+ minTimeout: 1 * 1000,
1076
+ maxTimeout: Infinity,
1077
+ randomize: false
1078
+ };
1079
+ for (var key in options) {
1080
+ opts[key] = options[key];
1081
+ }
1082
+ if (opts.minTimeout > opts.maxTimeout) {
1083
+ throw new Error("minTimeout is greater than maxTimeout");
1084
+ }
1085
+ var timeouts = [];
1086
+ for (var i = 0;i < opts.retries; i++) {
1087
+ timeouts.push(this.createTimeout(i, opts));
1088
+ }
1089
+ if (options && options.forever && !timeouts.length) {
1090
+ timeouts.push(this.createTimeout(i, opts));
1091
+ }
1092
+ timeouts.sort(function(a2, b2) {
1093
+ return a2 - b2;
1094
+ });
1095
+ return timeouts;
1096
+ };
1097
+ exports.createTimeout = function(attempt, opts) {
1098
+ var random = opts.randomize ? Math.random() + 1 : 1;
1099
+ var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
1100
+ timeout = Math.min(timeout, opts.maxTimeout);
1101
+ return timeout;
1102
+ };
1103
+ exports.wrap = function(obj, options, methods) {
1104
+ if (options instanceof Array) {
1105
+ methods = options;
1106
+ options = null;
1107
+ }
1108
+ if (!methods) {
1109
+ methods = [];
1110
+ for (var key in obj) {
1111
+ if (typeof obj[key] === "function") {
1112
+ methods.push(key);
1113
+ }
1114
+ }
1115
+ }
1116
+ for (var i = 0;i < methods.length; i++) {
1117
+ var method = methods[i];
1118
+ var original = obj[method];
1119
+ obj[method] = function retryWrapper(original2) {
1120
+ var op = exports.operation(options);
1121
+ var args = Array.prototype.slice.call(arguments, 1);
1122
+ var callback = args.pop();
1123
+ args.push(function(err) {
1124
+ if (op.retry(err)) {
1125
+ return;
1126
+ }
1127
+ if (err) {
1128
+ arguments[0] = op.mainError();
1129
+ }
1130
+ callback.apply(this, arguments);
1131
+ });
1132
+ op.attempt(function() {
1133
+ original2.apply(obj, args);
1134
+ });
1135
+ }.bind(obj, original);
1136
+ obj[method].options = options;
1137
+ }
1138
+ };
1139
+ });
1140
+
1141
+ // node_modules/signal-exit/signals.js
1142
+ var require_signals = __commonJS((exports, module) => {
1143
+ module.exports = [
1144
+ "SIGABRT",
1145
+ "SIGALRM",
1146
+ "SIGHUP",
1147
+ "SIGINT",
1148
+ "SIGTERM"
1149
+ ];
1150
+ if (process.platform !== "win32") {
1151
+ module.exports.push("SIGVTALRM", "SIGXCPU", "SIGXFSZ", "SIGUSR2", "SIGTRAP", "SIGSYS", "SIGQUIT", "SIGIOT");
1152
+ }
1153
+ if (process.platform === "linux") {
1154
+ module.exports.push("SIGIO", "SIGPOLL", "SIGPWR", "SIGSTKFLT", "SIGUNUSED");
1155
+ }
1156
+ });
1157
+
1158
+ // node_modules/signal-exit/index.js
1159
+ var require_signal_exit = __commonJS((exports, module) => {
1160
+ var process2 = global.process;
1161
+ var processOk = function(process3) {
1162
+ 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";
1163
+ };
1164
+ if (!processOk(process2)) {
1165
+ module.exports = function() {
1166
+ return function() {};
1167
+ };
1168
+ } else {
1169
+ assert = __require("assert");
1170
+ signals = require_signals();
1171
+ isWin = /^win/i.test(process2.platform);
1172
+ EE = __require("events");
1173
+ if (typeof EE !== "function") {
1174
+ EE = EE.EventEmitter;
1175
+ }
1176
+ if (process2.__signal_exit_emitter__) {
1177
+ emitter = process2.__signal_exit_emitter__;
1178
+ } else {
1179
+ emitter = process2.__signal_exit_emitter__ = new EE;
1180
+ emitter.count = 0;
1181
+ emitter.emitted = {};
1182
+ }
1183
+ if (!emitter.infinite) {
1184
+ emitter.setMaxListeners(Infinity);
1185
+ emitter.infinite = true;
1186
+ }
1187
+ module.exports = function(cb, opts) {
1188
+ if (!processOk(global.process)) {
1189
+ return function() {};
1190
+ }
1191
+ assert.equal(typeof cb, "function", "a callback must be provided for exit handler");
1192
+ if (loaded === false) {
1193
+ load();
1194
+ }
1195
+ var ev = "exit";
1196
+ if (opts && opts.alwaysLast) {
1197
+ ev = "afterexit";
1198
+ }
1199
+ var remove = function() {
1200
+ emitter.removeListener(ev, cb);
1201
+ if (emitter.listeners("exit").length === 0 && emitter.listeners("afterexit").length === 0) {
1202
+ unload();
1203
+ }
1204
+ };
1205
+ emitter.on(ev, cb);
1206
+ return remove;
1207
+ };
1208
+ unload = function unload2() {
1209
+ if (!loaded || !processOk(global.process)) {
1210
+ return;
1211
+ }
1212
+ loaded = false;
1213
+ signals.forEach(function(sig) {
1214
+ try {
1215
+ process2.removeListener(sig, sigListeners[sig]);
1216
+ } catch (er) {}
1217
+ });
1218
+ process2.emit = originalProcessEmit;
1219
+ process2.reallyExit = originalProcessReallyExit;
1220
+ emitter.count -= 1;
1221
+ };
1222
+ module.exports.unload = unload;
1223
+ emit = function emit2(event, code, signal) {
1224
+ if (emitter.emitted[event]) {
1225
+ return;
1226
+ }
1227
+ emitter.emitted[event] = true;
1228
+ emitter.emit(event, code, signal);
1229
+ };
1230
+ sigListeners = {};
1231
+ signals.forEach(function(sig) {
1232
+ sigListeners[sig] = function listener() {
1233
+ if (!processOk(global.process)) {
1234
+ return;
1235
+ }
1236
+ var listeners = process2.listeners(sig);
1237
+ if (listeners.length === emitter.count) {
1238
+ unload();
1239
+ emit("exit", null, sig);
1240
+ emit("afterexit", null, sig);
1241
+ if (isWin && sig === "SIGHUP") {
1242
+ sig = "SIGINT";
1243
+ }
1244
+ process2.kill(process2.pid, sig);
1245
+ }
1246
+ };
1247
+ });
1248
+ module.exports.signals = function() {
1249
+ return signals;
1250
+ };
1251
+ loaded = false;
1252
+ load = function load2() {
1253
+ if (loaded || !processOk(global.process)) {
1254
+ return;
1255
+ }
1256
+ loaded = true;
1257
+ emitter.count += 1;
1258
+ signals = signals.filter(function(sig) {
1259
+ try {
1260
+ process2.on(sig, sigListeners[sig]);
1261
+ return true;
1262
+ } catch (er) {
1263
+ return false;
1264
+ }
1265
+ });
1266
+ process2.emit = processEmit;
1267
+ process2.reallyExit = processReallyExit;
1268
+ };
1269
+ module.exports.load = load;
1270
+ originalProcessReallyExit = process2.reallyExit;
1271
+ processReallyExit = function processReallyExit2(code) {
1272
+ if (!processOk(global.process)) {
1273
+ return;
1274
+ }
1275
+ process2.exitCode = code || 0;
1276
+ emit("exit", process2.exitCode, null);
1277
+ emit("afterexit", process2.exitCode, null);
1278
+ originalProcessReallyExit.call(process2, process2.exitCode);
1279
+ };
1280
+ originalProcessEmit = process2.emit;
1281
+ processEmit = function processEmit2(ev, arg) {
1282
+ if (ev === "exit" && processOk(global.process)) {
1283
+ if (arg !== undefined) {
1284
+ process2.exitCode = arg;
1285
+ }
1286
+ var ret = originalProcessEmit.apply(this, arguments);
1287
+ emit("exit", process2.exitCode, null);
1288
+ emit("afterexit", process2.exitCode, null);
1289
+ return ret;
1290
+ } else {
1291
+ return originalProcessEmit.apply(this, arguments);
1292
+ }
1293
+ };
1294
+ }
1295
+ var assert;
1296
+ var signals;
1297
+ var isWin;
1298
+ var EE;
1299
+ var emitter;
1300
+ var unload;
1301
+ var emit;
1302
+ var sigListeners;
1303
+ var loaded;
1304
+ var load;
1305
+ var originalProcessReallyExit;
1306
+ var processReallyExit;
1307
+ var originalProcessEmit;
1308
+ var processEmit;
1309
+ });
1310
+
1311
+ // node_modules/proper-lockfile/lib/mtime-precision.js
1312
+ var require_mtime_precision = __commonJS((exports, module) => {
1313
+ var cacheSymbol = Symbol();
1314
+ function probe(file, fs, callback) {
1315
+ const cachedPrecision = fs[cacheSymbol];
1316
+ if (cachedPrecision) {
1317
+ return fs.stat(file, (err, stat) => {
1318
+ if (err) {
1319
+ return callback(err);
1320
+ }
1321
+ callback(null, stat.mtime, cachedPrecision);
1322
+ });
1323
+ }
1324
+ const mtime = new Date(Math.ceil(Date.now() / 1000) * 1000 + 5);
1325
+ fs.utimes(file, mtime, mtime, (err) => {
1326
+ if (err) {
1327
+ return callback(err);
1328
+ }
1329
+ fs.stat(file, (err2, stat) => {
1330
+ if (err2) {
1331
+ return callback(err2);
1332
+ }
1333
+ const precision = stat.mtime.getTime() % 1000 === 0 ? "s" : "ms";
1334
+ Object.defineProperty(fs, cacheSymbol, { value: precision });
1335
+ callback(null, stat.mtime, precision);
1336
+ });
1337
+ });
1338
+ }
1339
+ function getMtime(precision) {
1340
+ let now = Date.now();
1341
+ if (precision === "s") {
1342
+ now = Math.ceil(now / 1000) * 1000;
1343
+ }
1344
+ return new Date(now);
1345
+ }
1346
+ exports.probe = probe;
1347
+ exports.getMtime = getMtime;
1348
+ });
1349
+
1350
+ // node_modules/proper-lockfile/lib/lockfile.js
1351
+ var require_lockfile = __commonJS((exports, module) => {
1352
+ var path = __require("path");
1353
+ var fs = require_graceful_fs();
1354
+ var retry = require_retry();
1355
+ var onExit = require_signal_exit();
1356
+ var mtimePrecision = require_mtime_precision();
1357
+ var locks = {};
1358
+ function getLockFile(file, options) {
1359
+ return options.lockfilePath || `${file}.lock`;
1360
+ }
1361
+ function resolveCanonicalPath(file, options, callback) {
1362
+ if (!options.realpath) {
1363
+ return callback(null, path.resolve(file));
1364
+ }
1365
+ options.fs.realpath(file, callback);
1366
+ }
1367
+ function acquireLock(file, options, callback) {
1368
+ const lockfilePath = getLockFile(file, options);
1369
+ options.fs.mkdir(lockfilePath, (err) => {
1370
+ if (!err) {
1371
+ return mtimePrecision.probe(lockfilePath, options.fs, (err2, mtime, mtimePrecision2) => {
1372
+ if (err2) {
1373
+ options.fs.rmdir(lockfilePath, () => {});
1374
+ return callback(err2);
1375
+ }
1376
+ callback(null, mtime, mtimePrecision2);
1377
+ });
1378
+ }
1379
+ if (err.code !== "EEXIST") {
1380
+ return callback(err);
1381
+ }
1382
+ if (options.stale <= 0) {
1383
+ return callback(Object.assign(new Error("Lock file is already being held"), { code: "ELOCKED", file }));
1384
+ }
1385
+ options.fs.stat(lockfilePath, (err2, stat) => {
1386
+ if (err2) {
1387
+ if (err2.code === "ENOENT") {
1388
+ return acquireLock(file, { ...options, stale: 0 }, callback);
1389
+ }
1390
+ return callback(err2);
1391
+ }
1392
+ if (!isLockStale(stat, options)) {
1393
+ return callback(Object.assign(new Error("Lock file is already being held"), { code: "ELOCKED", file }));
1394
+ }
1395
+ removeLock(file, options, (err3) => {
1396
+ if (err3) {
1397
+ return callback(err3);
1398
+ }
1399
+ acquireLock(file, { ...options, stale: 0 }, callback);
1400
+ });
1401
+ });
1402
+ });
1403
+ }
1404
+ function isLockStale(stat, options) {
1405
+ return stat.mtime.getTime() < Date.now() - options.stale;
1406
+ }
1407
+ function removeLock(file, options, callback) {
1408
+ options.fs.rmdir(getLockFile(file, options), (err) => {
1409
+ if (err && err.code !== "ENOENT") {
1410
+ return callback(err);
1411
+ }
1412
+ callback();
1413
+ });
1414
+ }
1415
+ function updateLock(file, options) {
1416
+ const lock2 = locks[file];
1417
+ if (lock2.updateTimeout) {
1418
+ return;
1419
+ }
1420
+ lock2.updateDelay = lock2.updateDelay || options.update;
1421
+ lock2.updateTimeout = setTimeout(() => {
1422
+ lock2.updateTimeout = null;
1423
+ options.fs.stat(lock2.lockfilePath, (err, stat) => {
1424
+ const isOverThreshold = lock2.lastUpdate + options.stale < Date.now();
1425
+ if (err) {
1426
+ if (err.code === "ENOENT" || isOverThreshold) {
1427
+ return setLockAsCompromised(file, lock2, Object.assign(err, { code: "ECOMPROMISED" }));
1428
+ }
1429
+ lock2.updateDelay = 1000;
1430
+ return updateLock(file, options);
1431
+ }
1432
+ const isMtimeOurs = lock2.mtime.getTime() === stat.mtime.getTime();
1433
+ if (!isMtimeOurs) {
1434
+ return setLockAsCompromised(file, lock2, Object.assign(new Error("Unable to update lock within the stale threshold"), { code: "ECOMPROMISED" }));
1435
+ }
1436
+ const mtime = mtimePrecision.getMtime(lock2.mtimePrecision);
1437
+ options.fs.utimes(lock2.lockfilePath, mtime, mtime, (err2) => {
1438
+ const isOverThreshold2 = lock2.lastUpdate + options.stale < Date.now();
1439
+ if (lock2.released) {
1440
+ return;
1441
+ }
1442
+ if (err2) {
1443
+ if (err2.code === "ENOENT" || isOverThreshold2) {
1444
+ return setLockAsCompromised(file, lock2, Object.assign(err2, { code: "ECOMPROMISED" }));
1445
+ }
1446
+ lock2.updateDelay = 1000;
1447
+ return updateLock(file, options);
1448
+ }
1449
+ lock2.mtime = mtime;
1450
+ lock2.lastUpdate = Date.now();
1451
+ lock2.updateDelay = null;
1452
+ updateLock(file, options);
1453
+ });
1454
+ });
1455
+ }, lock2.updateDelay);
1456
+ if (lock2.updateTimeout.unref) {
1457
+ lock2.updateTimeout.unref();
1458
+ }
1459
+ }
1460
+ function setLockAsCompromised(file, lock2, err) {
1461
+ lock2.released = true;
1462
+ if (lock2.updateTimeout) {
1463
+ clearTimeout(lock2.updateTimeout);
1464
+ }
1465
+ if (locks[file] === lock2) {
1466
+ delete locks[file];
1467
+ }
1468
+ lock2.options.onCompromised(err);
1469
+ }
1470
+ function lock(file, options, callback) {
1471
+ options = {
1472
+ stale: 1e4,
1473
+ update: null,
1474
+ realpath: true,
1475
+ retries: 0,
1476
+ fs,
1477
+ onCompromised: (err) => {
1478
+ throw err;
1479
+ },
1480
+ ...options
1481
+ };
1482
+ options.retries = options.retries || 0;
1483
+ options.retries = typeof options.retries === "number" ? { retries: options.retries } : options.retries;
1484
+ options.stale = Math.max(options.stale || 0, 2000);
1485
+ options.update = options.update == null ? options.stale / 2 : options.update || 0;
1486
+ options.update = Math.max(Math.min(options.update, options.stale / 2), 1000);
1487
+ resolveCanonicalPath(file, options, (err, file2) => {
1488
+ if (err) {
1489
+ return callback(err);
1490
+ }
1491
+ const operation = retry.operation(options.retries);
1492
+ operation.attempt(() => {
1493
+ acquireLock(file2, options, (err2, mtime, mtimePrecision2) => {
1494
+ if (operation.retry(err2)) {
1495
+ return;
1496
+ }
1497
+ if (err2) {
1498
+ return callback(operation.mainError());
1499
+ }
1500
+ const lock2 = locks[file2] = {
1501
+ lockfilePath: getLockFile(file2, options),
1502
+ mtime,
1503
+ mtimePrecision: mtimePrecision2,
1504
+ options,
1505
+ lastUpdate: Date.now()
1506
+ };
1507
+ updateLock(file2, options);
1508
+ callback(null, (releasedCallback) => {
1509
+ if (lock2.released) {
1510
+ return releasedCallback && releasedCallback(Object.assign(new Error("Lock is already released"), { code: "ERELEASED" }));
1511
+ }
1512
+ unlock(file2, { ...options, realpath: false }, releasedCallback);
1513
+ });
1514
+ });
1515
+ });
1516
+ });
1517
+ }
1518
+ function unlock(file, options, callback) {
1519
+ options = {
1520
+ fs,
1521
+ realpath: true,
1522
+ ...options
1523
+ };
1524
+ resolveCanonicalPath(file, options, (err, file2) => {
1525
+ if (err) {
1526
+ return callback(err);
1527
+ }
1528
+ const lock2 = locks[file2];
1529
+ if (!lock2) {
1530
+ return callback(Object.assign(new Error("Lock is not acquired/owned by you"), { code: "ENOTACQUIRED" }));
1531
+ }
1532
+ lock2.updateTimeout && clearTimeout(lock2.updateTimeout);
1533
+ lock2.released = true;
1534
+ delete locks[file2];
1535
+ removeLock(file2, options, callback);
1536
+ });
1537
+ }
1538
+ function check(file, options, callback) {
1539
+ options = {
1540
+ stale: 1e4,
1541
+ realpath: true,
1542
+ fs,
1543
+ ...options
1544
+ };
1545
+ options.stale = Math.max(options.stale || 0, 2000);
1546
+ resolveCanonicalPath(file, options, (err, file2) => {
1547
+ if (err) {
1548
+ return callback(err);
1549
+ }
1550
+ options.fs.stat(getLockFile(file2, options), (err2, stat) => {
1551
+ if (err2) {
1552
+ return err2.code === "ENOENT" ? callback(null, false) : callback(err2);
1553
+ }
1554
+ return callback(null, !isLockStale(stat, options));
1555
+ });
1556
+ });
1557
+ }
1558
+ function getLocks() {
1559
+ return locks;
1560
+ }
1561
+ onExit(() => {
1562
+ for (const file in locks) {
1563
+ const options = locks[file].options;
1564
+ try {
1565
+ options.fs.rmdirSync(getLockFile(file, options));
1566
+ } catch (e2) {}
1567
+ }
1568
+ });
1569
+ exports.lock = lock;
1570
+ exports.unlock = unlock;
1571
+ exports.check = check;
1572
+ exports.getLocks = getLocks;
1573
+ });
1574
+
1575
+ // node_modules/proper-lockfile/lib/adapter.js
1576
+ var require_adapter = __commonJS((exports, module) => {
1577
+ var fs = require_graceful_fs();
1578
+ function createSyncFs(fs2) {
1579
+ const methods = ["mkdir", "realpath", "stat", "rmdir", "utimes"];
1580
+ const newFs = { ...fs2 };
1581
+ methods.forEach((method) => {
1582
+ newFs[method] = (...args) => {
1583
+ const callback = args.pop();
1584
+ let ret;
1585
+ try {
1586
+ ret = fs2[`${method}Sync`](...args);
1587
+ } catch (err) {
1588
+ return callback(err);
1589
+ }
1590
+ callback(null, ret);
1591
+ };
1592
+ });
1593
+ return newFs;
1594
+ }
1595
+ function toPromise(method) {
1596
+ return (...args) => new Promise((resolve, reject) => {
1597
+ args.push((err, result) => {
1598
+ if (err) {
1599
+ reject(err);
1600
+ } else {
1601
+ resolve(result);
1602
+ }
1603
+ });
1604
+ method(...args);
1605
+ });
1606
+ }
1607
+ function toSync(method) {
1608
+ return (...args) => {
1609
+ let err;
1610
+ let result;
1611
+ args.push((_err, _result) => {
1612
+ err = _err;
1613
+ result = _result;
1614
+ });
1615
+ method(...args);
1616
+ if (err) {
1617
+ throw err;
1618
+ }
1619
+ return result;
1620
+ };
1621
+ }
1622
+ function toSyncOptions(options) {
1623
+ options = { ...options };
1624
+ options.fs = createSyncFs(options.fs || fs);
1625
+ if (typeof options.retries === "number" && options.retries > 0 || options.retries && typeof options.retries.retries === "number" && options.retries.retries > 0) {
1626
+ throw Object.assign(new Error("Cannot use retries with the sync api"), { code: "ESYNC" });
1627
+ }
1628
+ return options;
1629
+ }
1630
+ module.exports = {
1631
+ toPromise,
1632
+ toSync,
1633
+ toSyncOptions
1634
+ };
1635
+ });
1636
+
1637
+ // node_modules/proper-lockfile/index.js
1638
+ var require_proper_lockfile = __commonJS((exports, module) => {
1639
+ var lockfile = require_lockfile();
1640
+ var { toPromise, toSync, toSyncOptions } = require_adapter();
1641
+ async function lock(file, options) {
1642
+ const release = await toPromise(lockfile.lock)(file, options);
1643
+ return toPromise(release);
1644
+ }
1645
+ function lockSync(file, options) {
1646
+ const release = toSync(lockfile.lock)(file, toSyncOptions(options));
1647
+ return toSync(release);
1648
+ }
1649
+ function unlock(file, options) {
1650
+ return toPromise(lockfile.unlock)(file, options);
1651
+ }
1652
+ function unlockSync(file, options) {
1653
+ return toSync(lockfile.unlock)(file, toSyncOptions(options));
1654
+ }
1655
+ function check(file, options) {
1656
+ return toPromise(lockfile.check)(file, options);
1657
+ }
1658
+ function checkSync(file, options) {
1659
+ return toSync(lockfile.check)(file, toSyncOptions(options));
1660
+ }
1661
+ module.exports = lock;
1662
+ module.exports.lock = lock;
1663
+ module.exports.unlock = unlock;
1664
+ module.exports.lockSync = lockSync;
1665
+ module.exports.unlockSync = unlockSync;
1666
+ module.exports.check = check;
1667
+ module.exports.checkSync = checkSync;
1668
+ });
1669
+
1670
+ // node_modules/cac/dist/index.js
1671
+ function toArr(any) {
1672
+ return any == null ? [] : Array.isArray(any) ? any : [any];
1673
+ }
1674
+ function toVal(out, key, val, opts) {
1675
+ var x, old = out[key], nxt = ~opts.string.indexOf(key) ? val == null || val === true ? "" : String(val) : typeof val === "boolean" ? val : ~opts.boolean.indexOf(key) ? val === "false" ? false : val === "true" || (out._.push((x = +val, x * 0 === 0) ? x : val), !!val) : (x = +val, x * 0 === 0) ? x : val;
1676
+ out[key] = old == null ? nxt : Array.isArray(old) ? old.concat(nxt) : [old, nxt];
1677
+ }
1678
+ function lib_default(args, opts) {
1679
+ args = args || [];
1680
+ opts = opts || {};
1681
+ var k, arr, arg, name, val, out = { _: [] };
1682
+ var i = 0, j = 0, idx = 0, len = args.length;
1683
+ const alibi = opts.alias !== undefined;
1684
+ const strict = opts.unknown !== undefined;
1685
+ const defaults = opts.default !== undefined;
1686
+ opts.alias = opts.alias || {};
1687
+ opts.string = toArr(opts.string);
1688
+ opts.boolean = toArr(opts.boolean);
1689
+ if (alibi)
1690
+ for (k in opts.alias) {
1691
+ arr = opts.alias[k] = toArr(opts.alias[k]);
1692
+ for (i = 0;i < arr.length; i++)
1693
+ (opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
1694
+ }
1695
+ for (i = opts.boolean.length;i-- > 0; ) {
1696
+ arr = opts.alias[opts.boolean[i]] || [];
1697
+ for (j = arr.length;j-- > 0; )
1698
+ opts.boolean.push(arr[j]);
1699
+ }
1700
+ for (i = opts.string.length;i-- > 0; ) {
1701
+ arr = opts.alias[opts.string[i]] || [];
1702
+ for (j = arr.length;j-- > 0; )
1703
+ opts.string.push(arr[j]);
1704
+ }
1705
+ if (defaults)
1706
+ for (k in opts.default) {
1707
+ name = typeof opts.default[k];
1708
+ arr = opts.alias[k] = opts.alias[k] || [];
1709
+ if (opts[name] !== undefined) {
1710
+ opts[name].push(k);
1711
+ for (i = 0;i < arr.length; i++)
1712
+ opts[name].push(arr[i]);
1713
+ }
1714
+ }
1715
+ const keys = strict ? Object.keys(opts.alias) : [];
1716
+ for (i = 0;i < len; i++) {
1717
+ arg = args[i];
1718
+ if (arg === "--") {
1719
+ out._ = out._.concat(args.slice(++i));
1720
+ break;
1721
+ }
1722
+ for (j = 0;j < arg.length; j++)
1723
+ if (arg.charCodeAt(j) !== 45)
1724
+ break;
1725
+ if (j === 0)
1726
+ out._.push(arg);
1727
+ else if (arg.substring(j, j + 3) === "no-") {
1728
+ name = arg.substring(j + 3);
1729
+ if (strict && !~keys.indexOf(name))
1730
+ return opts.unknown(arg);
1731
+ out[name] = false;
1732
+ } else {
1733
+ for (idx = j + 1;idx < arg.length; idx++)
1734
+ if (arg.charCodeAt(idx) === 61)
1735
+ break;
1736
+ name = arg.substring(j, idx);
1737
+ val = arg.substring(++idx) || i + 1 === len || ("" + args[i + 1]).charCodeAt(0) === 45 || args[++i];
1738
+ arr = j === 2 ? [name] : name;
1739
+ for (idx = 0;idx < arr.length; idx++) {
1740
+ name = arr[idx];
1741
+ if (strict && !~keys.indexOf(name))
1742
+ return opts.unknown("-".repeat(j) + name);
1743
+ toVal(out, name, idx + 1 < arr.length || val, opts);
1744
+ }
1745
+ }
1746
+ }
1747
+ if (defaults) {
1748
+ for (k in opts.default)
1749
+ if (out[k] === undefined)
1750
+ out[k] = opts.default[k];
1751
+ }
1752
+ if (alibi)
1753
+ for (k in out) {
1754
+ arr = opts.alias[k] || [];
1755
+ while (arr.length > 0)
1756
+ out[arr.shift()] = out[k];
1757
+ }
1758
+ return out;
1759
+ }
1760
+ function removeBrackets(v) {
1761
+ return v.replace(/[<[].+/, "").trim();
1762
+ }
1763
+ function findAllBrackets(v) {
1764
+ const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g;
1765
+ const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g;
1766
+ const res = [];
1767
+ const parse = (match) => {
1768
+ let variadic = false;
1769
+ let value = match[1];
1770
+ if (value.startsWith("...")) {
1771
+ value = value.slice(3);
1772
+ variadic = true;
1773
+ }
1774
+ return {
1775
+ required: match[0].startsWith("<"),
1776
+ value,
1777
+ variadic
1778
+ };
1779
+ };
1780
+ let angledMatch;
1781
+ while (angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v))
1782
+ res.push(parse(angledMatch));
1783
+ let squareMatch;
1784
+ while (squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v))
1785
+ res.push(parse(squareMatch));
1786
+ return res;
1787
+ }
1788
+ function getMriOptions(options) {
1789
+ const result = {
1790
+ alias: {},
1791
+ boolean: []
1792
+ };
1793
+ for (const [index, option] of options.entries()) {
1794
+ if (option.names.length > 1)
1795
+ result.alias[option.names[0]] = option.names.slice(1);
1796
+ if (option.isBoolean)
1797
+ if (option.negated) {
1798
+ if (!options.some((o, i) => {
1799
+ return i !== index && o.names.some((name) => option.names.includes(name)) && typeof o.required === "boolean";
1800
+ }))
1801
+ result.boolean.push(option.names[0]);
1802
+ } else
1803
+ result.boolean.push(option.names[0]);
1804
+ }
1805
+ return result;
1806
+ }
1807
+ function findLongest(arr) {
1808
+ return arr.sort((a, b) => {
1809
+ return a.length > b.length ? -1 : 1;
1810
+ })[0];
1811
+ }
1812
+ function padRight(str, length) {
1813
+ return str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`;
1814
+ }
1815
+ function camelcase(input) {
1816
+ return input.replaceAll(/([a-z])-([a-z])/g, (_, p1, p2) => {
1817
+ return p1 + p2.toUpperCase();
1818
+ });
1819
+ }
1820
+ function setDotProp(obj, keys, val) {
1821
+ let current = obj;
1822
+ for (let i = 0;i < keys.length; i++) {
1823
+ const key = keys[i];
1824
+ if (i === keys.length - 1) {
1825
+ current[key] = val;
1826
+ return;
1827
+ }
1828
+ if (current[key] == null) {
1829
+ const nextKeyIsArrayIndex = +keys[i + 1] > -1;
1830
+ current[key] = nextKeyIsArrayIndex ? [] : {};
1831
+ }
1832
+ current = current[key];
1833
+ }
1834
+ }
1835
+ function setByType(obj, transforms) {
1836
+ for (const key of Object.keys(transforms)) {
1837
+ const transform = transforms[key];
1838
+ if (transform.shouldTransform) {
1839
+ obj[key] = [obj[key]].flat();
1840
+ if (typeof transform.transformFunction === "function")
1841
+ obj[key] = obj[key].map(transform.transformFunction);
1842
+ }
1843
+ }
1844
+ }
1845
+ function getFileName(input) {
1846
+ const m = /([^\\/]+)$/.exec(input);
1847
+ return m ? m[1] : "";
1848
+ }
1849
+ function camelcaseOptionName(name) {
1850
+ return name.split(".").map((v, i) => {
1851
+ return i === 0 ? camelcase(v) : v;
1852
+ }).join(".");
1853
+ }
1854
+ var CACError = class extends Error {
1855
+ constructor(message) {
1856
+ super(message);
1857
+ this.name = "CACError";
1858
+ if (typeof Error.captureStackTrace !== "function")
1859
+ this.stack = new Error(message).stack;
1860
+ }
1861
+ };
1862
+ var Option = class {
1863
+ rawName;
1864
+ description;
1865
+ name;
1866
+ names;
1867
+ isBoolean;
1868
+ required;
1869
+ config;
1870
+ negated;
1871
+ constructor(rawName, description, config) {
1872
+ this.rawName = rawName;
1873
+ this.description = description;
1874
+ this.config = Object.assign({}, config);
1875
+ rawName = rawName.replaceAll(".*", "");
1876
+ this.negated = false;
1877
+ this.names = removeBrackets(rawName).split(",").map((v) => {
1878
+ let name = v.trim().replace(/^-{1,2}/, "");
1879
+ if (name.startsWith("no-")) {
1880
+ this.negated = true;
1881
+ name = name.replace(/^no-/, "");
1882
+ }
1883
+ return camelcaseOptionName(name);
1884
+ }).sort((a, b) => a.length > b.length ? 1 : -1);
1885
+ this.name = this.names.at(-1);
1886
+ if (this.negated && this.config.default == null)
1887
+ this.config.default = true;
1888
+ if (rawName.includes("<"))
1889
+ this.required = true;
1890
+ else if (rawName.includes("["))
1891
+ this.required = false;
1892
+ else
1893
+ this.isBoolean = true;
1894
+ }
1895
+ };
1896
+ var runtimeProcessArgs;
1897
+ var runtimeInfo;
1898
+ if (typeof process !== "undefined") {
1899
+ let runtimeName;
1900
+ if (typeof Deno !== "undefined" && typeof Deno.version?.deno === "string")
1901
+ runtimeName = "deno";
1902
+ else if (typeof Bun !== "undefined" && typeof Bun.version === "string")
1903
+ runtimeName = "bun";
1904
+ else
1905
+ runtimeName = "node";
1906
+ runtimeInfo = `${process.platform}-${process.arch} ${runtimeName}-${process.version}`;
1907
+ runtimeProcessArgs = process.argv;
1908
+ } else if (typeof navigator === "undefined")
1909
+ runtimeInfo = `unknown`;
1910
+ else
1911
+ runtimeInfo = `${navigator.platform} ${navigator.userAgent}`;
1912
+ var Command = class {
1913
+ rawName;
1914
+ description;
1915
+ config;
1916
+ cli;
1917
+ options;
1918
+ aliasNames;
1919
+ name;
1920
+ args;
1921
+ commandAction;
1922
+ usageText;
1923
+ versionNumber;
1924
+ examples;
1925
+ helpCallback;
1926
+ globalCommand;
1927
+ constructor(rawName, description, config = {}, cli) {
1928
+ this.rawName = rawName;
1929
+ this.description = description;
1930
+ this.config = config;
1931
+ this.cli = cli;
1932
+ this.options = [];
1933
+ this.aliasNames = [];
1934
+ this.name = removeBrackets(rawName);
1935
+ this.args = findAllBrackets(rawName);
1936
+ this.examples = [];
1937
+ }
1938
+ usage(text) {
1939
+ this.usageText = text;
1940
+ return this;
1941
+ }
1942
+ allowUnknownOptions() {
1943
+ this.config.allowUnknownOptions = true;
1944
+ return this;
1945
+ }
1946
+ ignoreOptionDefaultValue() {
1947
+ this.config.ignoreOptionDefaultValue = true;
1948
+ return this;
1949
+ }
1950
+ version(version, customFlags = "-v, --version") {
1951
+ this.versionNumber = version;
1952
+ this.option(customFlags, "Display version number");
1953
+ return this;
1954
+ }
1955
+ example(example) {
1956
+ this.examples.push(example);
1957
+ return this;
1958
+ }
1959
+ option(rawName, description, config) {
1960
+ const option = new Option(rawName, description, config);
1961
+ this.options.push(option);
1962
+ return this;
1963
+ }
1964
+ alias(name) {
1965
+ this.aliasNames.push(name);
1966
+ return this;
1967
+ }
1968
+ action(callback) {
1969
+ this.commandAction = callback;
1970
+ return this;
1971
+ }
1972
+ isMatched(name) {
1973
+ return this.name === name || this.aliasNames.includes(name);
1974
+ }
1975
+ get isDefaultCommand() {
1976
+ return this.name === "" || this.aliasNames.includes("!");
1977
+ }
1978
+ get isGlobalCommand() {
1979
+ return this instanceof GlobalCommand;
1980
+ }
1981
+ hasOption(name) {
1982
+ name = name.split(".")[0];
1983
+ return this.options.find((option) => {
1984
+ return option.names.includes(name);
1985
+ });
1986
+ }
1987
+ outputHelp() {
1988
+ const { name, commands } = this.cli;
1989
+ const { versionNumber, options: globalOptions, helpCallback } = this.cli.globalCommand;
1990
+ let sections = [{ body: `${name}${versionNumber ? `/${versionNumber}` : ""}` }];
1991
+ sections.push({
1992
+ title: "Usage",
1993
+ body: ` $ ${name} ${this.usageText || this.rawName}`
1994
+ });
1995
+ if ((this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0) {
1996
+ const longestCommandName = findLongest(commands.map((command) => command.rawName));
1997
+ sections.push({
1998
+ title: "Commands",
1999
+ body: commands.map((command) => {
2000
+ return ` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`;
2001
+ }).join(`
2002
+ `)
2003
+ }, {
2004
+ title: `For more info, run any command with the \`--help\` flag`,
2005
+ body: commands.map((command) => ` $ ${name}${command.name === "" ? "" : ` ${command.name}`} --help`).join(`
2006
+ `)
2007
+ });
2008
+ }
2009
+ let options = this.isGlobalCommand ? globalOptions : [...this.options, ...globalOptions || []];
2010
+ if (!this.isGlobalCommand && !this.isDefaultCommand)
2011
+ options = options.filter((option) => option.name !== "version");
2012
+ if (options.length > 0) {
2013
+ const longestOptionName = findLongest(options.map((option) => option.rawName));
2014
+ sections.push({
2015
+ title: "Options",
2016
+ body: options.map((option) => {
2017
+ return ` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${option.config.default === undefined ? "" : `(default: ${option.config.default})`}`;
2018
+ }).join(`
2019
+ `)
2020
+ });
2021
+ }
2022
+ if (this.examples.length > 0)
2023
+ sections.push({
2024
+ title: "Examples",
2025
+ body: this.examples.map((example) => {
2026
+ if (typeof example === "function")
2027
+ return example(name);
2028
+ return example;
2029
+ }).join(`
2030
+ `)
2031
+ });
2032
+ if (helpCallback)
2033
+ sections = helpCallback(sections) || sections;
2034
+ console.info(sections.map((section) => {
2035
+ return section.title ? `${section.title}:
2036
+ ${section.body}` : section.body;
2037
+ }).join(`
2038
+
2039
+ `));
2040
+ }
2041
+ outputVersion() {
2042
+ const { name } = this.cli;
2043
+ const { versionNumber } = this.cli.globalCommand;
2044
+ if (versionNumber)
2045
+ console.info(`${name}/${versionNumber} ${runtimeInfo}`);
2046
+ }
2047
+ checkRequiredArgs() {
2048
+ const minimalArgsCount = this.args.filter((arg) => arg.required).length;
2049
+ if (this.cli.args.length < minimalArgsCount)
2050
+ throw new CACError(`missing required args for command \`${this.rawName}\``);
2051
+ }
2052
+ checkUnknownOptions() {
2053
+ const { options, globalCommand } = this.cli;
2054
+ if (!this.config.allowUnknownOptions) {
2055
+ for (const name of Object.keys(options))
2056
+ if (name !== "--" && !this.hasOption(name) && !globalCommand.hasOption(name))
2057
+ throw new CACError(`Unknown option \`${name.length > 1 ? `--${name}` : `-${name}`}\``);
2058
+ }
2059
+ }
2060
+ checkOptionValue() {
2061
+ const { options: parsedOptions, globalCommand } = this.cli;
2062
+ const options = [...globalCommand.options, ...this.options];
2063
+ for (const option of options) {
2064
+ const value = parsedOptions[option.name.split(".")[0]];
2065
+ if (option.required) {
2066
+ const hasNegated = options.some((o) => o.negated && o.names.includes(option.name));
2067
+ if (value === true || value === false && !hasNegated)
2068
+ throw new CACError(`option \`${option.rawName}\` value is missing`);
2069
+ }
2070
+ }
2071
+ }
2072
+ checkUnusedArgs() {
2073
+ const maximumArgsCount = this.args.some((arg) => arg.variadic) ? Infinity : this.args.length;
2074
+ if (maximumArgsCount < this.cli.args.length)
2075
+ throw new CACError(`Unused args: ${this.cli.args.slice(maximumArgsCount).map((arg) => `\`${arg}\``).join(", ")}`);
2076
+ }
2077
+ };
2078
+ var GlobalCommand = class extends Command {
2079
+ constructor(cli) {
2080
+ super("@@global@@", "", {}, cli);
2081
+ }
2082
+ };
2083
+ var CAC = class extends EventTarget {
2084
+ name;
2085
+ commands;
2086
+ globalCommand;
2087
+ matchedCommand;
2088
+ matchedCommandName;
2089
+ rawArgs;
2090
+ args;
2091
+ options;
2092
+ showHelpOnExit;
2093
+ showVersionOnExit;
2094
+ constructor(name = "") {
2095
+ super();
2096
+ this.name = name;
2097
+ this.commands = [];
2098
+ this.rawArgs = [];
2099
+ this.args = [];
2100
+ this.options = {};
2101
+ this.globalCommand = new GlobalCommand(this);
2102
+ this.globalCommand.usage("<command> [options]");
2103
+ }
2104
+ usage(text) {
2105
+ this.globalCommand.usage(text);
2106
+ return this;
2107
+ }
2108
+ command(rawName, description, config) {
2109
+ const command = new Command(rawName, description || "", config, this);
2110
+ command.globalCommand = this.globalCommand;
2111
+ this.commands.push(command);
2112
+ return command;
2113
+ }
2114
+ option(rawName, description, config) {
2115
+ this.globalCommand.option(rawName, description, config);
2116
+ return this;
2117
+ }
2118
+ help(callback) {
2119
+ this.globalCommand.option("-h, --help", "Display this message");
2120
+ this.globalCommand.helpCallback = callback;
2121
+ this.showHelpOnExit = true;
2122
+ return this;
2123
+ }
2124
+ version(version, customFlags = "-v, --version") {
2125
+ this.globalCommand.version(version, customFlags);
2126
+ this.showVersionOnExit = true;
2127
+ return this;
2128
+ }
2129
+ example(example) {
2130
+ this.globalCommand.example(example);
2131
+ return this;
2132
+ }
2133
+ outputHelp() {
2134
+ if (this.matchedCommand)
2135
+ this.matchedCommand.outputHelp();
2136
+ else
2137
+ this.globalCommand.outputHelp();
2138
+ }
2139
+ outputVersion() {
2140
+ this.globalCommand.outputVersion();
2141
+ }
2142
+ setParsedInfo({ args, options }, matchedCommand, matchedCommandName) {
2143
+ this.args = args;
2144
+ this.options = options;
2145
+ if (matchedCommand)
2146
+ this.matchedCommand = matchedCommand;
2147
+ if (matchedCommandName)
2148
+ this.matchedCommandName = matchedCommandName;
2149
+ return this;
2150
+ }
2151
+ unsetMatchedCommand() {
2152
+ this.matchedCommand = undefined;
2153
+ this.matchedCommandName = undefined;
2154
+ }
2155
+ parse(argv, { run = true } = {}) {
2156
+ if (!argv) {
2157
+ if (!runtimeProcessArgs)
2158
+ throw new Error("No argv provided and runtime process argv is not available.");
2159
+ argv = runtimeProcessArgs;
2160
+ }
2161
+ this.rawArgs = argv;
2162
+ if (!this.name)
2163
+ this.name = argv[1] ? getFileName(argv[1]) : "cli";
2164
+ let shouldParse = true;
2165
+ for (const command of this.commands) {
2166
+ const parsed = this.mri(argv.slice(2), command);
2167
+ const commandName = parsed.args[0];
2168
+ if (command.isMatched(commandName)) {
2169
+ shouldParse = false;
2170
+ const parsedInfo = {
2171
+ ...parsed,
2172
+ args: parsed.args.slice(1)
2173
+ };
2174
+ this.setParsedInfo(parsedInfo, command, commandName);
2175
+ this.dispatchEvent(new CustomEvent(`command:${commandName}`, { detail: command }));
2176
+ }
2177
+ }
2178
+ if (shouldParse) {
2179
+ for (const command of this.commands)
2180
+ if (command.isDefaultCommand) {
2181
+ shouldParse = false;
2182
+ const parsed = this.mri(argv.slice(2), command);
2183
+ this.setParsedInfo(parsed, command);
2184
+ this.dispatchEvent(new CustomEvent("command:!", { detail: command }));
2185
+ }
2186
+ }
2187
+ if (shouldParse) {
2188
+ const parsed = this.mri(argv.slice(2));
2189
+ this.setParsedInfo(parsed);
2190
+ }
2191
+ if (this.options.help && this.showHelpOnExit) {
2192
+ this.outputHelp();
2193
+ run = false;
2194
+ this.unsetMatchedCommand();
2195
+ }
2196
+ if (this.options.version && this.showVersionOnExit && this.matchedCommandName == null) {
2197
+ this.outputVersion();
2198
+ run = false;
2199
+ this.unsetMatchedCommand();
2200
+ }
2201
+ const parsedArgv = {
2202
+ args: this.args,
2203
+ options: this.options
2204
+ };
2205
+ if (run)
2206
+ this.runMatchedCommand();
2207
+ if (!this.matchedCommand && this.args[0])
2208
+ this.dispatchEvent(new CustomEvent("command:*", { detail: this.args[0] }));
2209
+ return parsedArgv;
2210
+ }
2211
+ mri(argv, command) {
2212
+ const cliOptions = [...this.globalCommand.options, ...command ? command.options : []];
2213
+ const mriOptions = getMriOptions(cliOptions);
2214
+ let argsAfterDoubleDashes = [];
2215
+ const doubleDashesIndex = argv.indexOf("--");
2216
+ if (doubleDashesIndex !== -1) {
2217
+ argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1);
2218
+ argv = argv.slice(0, doubleDashesIndex);
2219
+ }
2220
+ let parsed = lib_default(argv, mriOptions);
2221
+ parsed = Object.keys(parsed).reduce((res, name) => {
2222
+ return {
2223
+ ...res,
2224
+ [camelcaseOptionName(name)]: parsed[name]
2225
+ };
2226
+ }, { _: [] });
2227
+ const args = parsed._;
2228
+ const options = { "--": argsAfterDoubleDashes };
2229
+ const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue;
2230
+ const transforms = Object.create(null);
2231
+ for (const cliOption of cliOptions) {
2232
+ if (!ignoreDefault && cliOption.config.default !== undefined)
2233
+ for (const name of cliOption.names)
2234
+ options[name] = cliOption.config.default;
2235
+ if (Array.isArray(cliOption.config.type) && transforms[cliOption.name] === undefined) {
2236
+ transforms[cliOption.name] = Object.create(null);
2237
+ transforms[cliOption.name].shouldTransform = true;
2238
+ transforms[cliOption.name].transformFunction = cliOption.config.type[0];
2239
+ }
2240
+ }
2241
+ for (const key of Object.keys(parsed))
2242
+ if (key !== "_") {
2243
+ setDotProp(options, key.split("."), parsed[key]);
2244
+ setByType(options, transforms);
2245
+ }
2246
+ return {
2247
+ args,
2248
+ options
2249
+ };
2250
+ }
2251
+ runMatchedCommand() {
2252
+ const { args, options, matchedCommand: command } = this;
2253
+ if (!command || !command.commandAction)
2254
+ return;
2255
+ command.checkUnknownOptions();
2256
+ command.checkOptionValue();
2257
+ command.checkRequiredArgs();
2258
+ command.checkUnusedArgs();
2259
+ const actionArgs = [];
2260
+ command.args.forEach((arg, index) => {
2261
+ if (arg.variadic)
2262
+ actionArgs.push(args.slice(index));
2263
+ else
2264
+ actionArgs.push(args[index]);
2265
+ });
2266
+ actionArgs.push(options);
2267
+ return command.commandAction.apply(this, actionArgs);
2268
+ }
2269
+ };
2270
+ var cac = (name = "") => new CAC(name);
2271
+ // package.json
2272
+ var package_default = {
2273
+ name: "@przeprogramowani/10x-cli",
2274
+ version: "0.2.0",
2275
+ description: "Open-source CLI for 10xDevs course content",
2276
+ type: "module",
2277
+ bin: {
2278
+ "10x": "./dist/index.mjs"
2279
+ },
2280
+ files: [
2281
+ "dist",
2282
+ "README.md",
2283
+ "LICENSE"
2284
+ ],
2285
+ scripts: {
2286
+ dev: "bun run src/index.ts",
2287
+ build: "bun build src/index.ts --outfile dist/index.mjs --target node",
2288
+ "build:binary": "bun build --compile --minify src/index.ts --outfile dist/10x",
2289
+ "generate-types": "bun run scripts/generate-types.ts",
2290
+ typecheck: "tsc --noEmit",
2291
+ test: "bun test",
2292
+ lint: "bun run --bun node_modules/oxlint/bin/oxlint ."
2293
+ },
2294
+ dependencies: {
2295
+ "@clack/prompts": "^0.9.1",
2296
+ cac: "^7.0.0",
2297
+ "proper-lockfile": "^4.1.2"
2298
+ },
2299
+ devDependencies: {
2300
+ "@types/bun": "^1.3.12",
2301
+ "@types/node": "^22.0.0",
2302
+ "@types/proper-lockfile": "^4.1.4",
2303
+ "conventional-changelog-angular": "^8.3.1",
2304
+ "conventional-commits-parser": "^6.4.0",
2305
+ "conventional-recommended-bump": "^11.2.0",
2306
+ "openapi-typescript": "^7.4.0",
2307
+ oxlint: "^0.16.0",
2308
+ typescript: "^5.5.0"
2309
+ },
2310
+ engines: {
2311
+ node: ">=20"
2312
+ },
2313
+ publishConfig: {
2314
+ access: "public"
2315
+ }
2316
+ };
2317
+
2318
+ // node_modules/@clack/core/dist/index.mjs
2319
+ var import_sisteransi = __toESM(require_src(), 1);
2320
+ var import_picocolors = __toESM(require_picocolors(), 1);
2321
+ import { stdin as $, stdout as j } from "node:process";
2322
+ import * as f from "node:readline";
2323
+ import M from "node:readline";
2324
+ import { WriteStream as U } from "node:tty";
2325
+ function J({ onlyFirst: t = false } = {}) {
2326
+ const F = ["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))", "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");
2327
+ return new RegExp(F, t ? undefined : "g");
2328
+ }
2329
+ var Q = J();
2330
+ function T(t) {
2331
+ if (typeof t != "string")
2332
+ throw new TypeError(`Expected a \`string\`, got \`${typeof t}\``);
2333
+ return t.replace(Q, "");
2334
+ }
2335
+ function O(t) {
2336
+ return t && t.__esModule && Object.prototype.hasOwnProperty.call(t, "default") ? t.default : t;
2337
+ }
2338
+ var P = { exports: {} };
2339
+ (function(t) {
2340
+ var u = {};
2341
+ t.exports = u, u.eastAsianWidth = function(e) {
2342
+ var s = e.charCodeAt(0), i = e.length == 2 ? e.charCodeAt(1) : 0, D = s;
2343
+ return 55296 <= s && s <= 56319 && 56320 <= i && i <= 57343 && (s &= 1023, i &= 1023, D = s << 10 | i, D += 65536), D == 12288 || 65281 <= D && D <= 65376 || 65504 <= D && D <= 65510 ? "F" : D == 8361 || 65377 <= D && D <= 65470 || 65474 <= D && D <= 65479 || 65482 <= D && D <= 65487 || 65490 <= D && D <= 65495 || 65498 <= D && D <= 65500 || 65512 <= D && D <= 65518 ? "H" : 4352 <= D && D <= 4447 || 4515 <= D && D <= 4519 || 4602 <= D && D <= 4607 || 9001 <= D && D <= 9002 || 11904 <= D && D <= 11929 || 11931 <= D && D <= 12019 || 12032 <= D && D <= 12245 || 12272 <= D && D <= 12283 || 12289 <= D && D <= 12350 || 12353 <= D && D <= 12438 || 12441 <= D && D <= 12543 || 12549 <= D && D <= 12589 || 12593 <= D && D <= 12686 || 12688 <= D && D <= 12730 || 12736 <= D && D <= 12771 || 12784 <= D && D <= 12830 || 12832 <= D && D <= 12871 || 12880 <= D && D <= 13054 || 13056 <= D && D <= 19903 || 19968 <= D && D <= 42124 || 42128 <= D && D <= 42182 || 43360 <= D && D <= 43388 || 44032 <= D && D <= 55203 || 55216 <= D && D <= 55238 || 55243 <= D && D <= 55291 || 63744 <= D && D <= 64255 || 65040 <= D && D <= 65049 || 65072 <= D && D <= 65106 || 65108 <= D && D <= 65126 || 65128 <= D && D <= 65131 || 110592 <= D && D <= 110593 || 127488 <= D && D <= 127490 || 127504 <= D && D <= 127546 || 127552 <= D && D <= 127560 || 127568 <= D && D <= 127569 || 131072 <= D && D <= 194367 || 177984 <= D && D <= 196605 || 196608 <= D && D <= 262141 ? "W" : 32 <= D && D <= 126 || 162 <= D && D <= 163 || 165 <= D && D <= 166 || D == 172 || D == 175 || 10214 <= D && D <= 10221 || 10629 <= D && D <= 10630 ? "Na" : D == 161 || D == 164 || 167 <= D && D <= 168 || D == 170 || 173 <= D && D <= 174 || 176 <= D && D <= 180 || 182 <= D && D <= 186 || 188 <= D && D <= 191 || D == 198 || D == 208 || 215 <= D && D <= 216 || 222 <= D && D <= 225 || D == 230 || 232 <= D && D <= 234 || 236 <= D && D <= 237 || D == 240 || 242 <= D && D <= 243 || 247 <= D && D <= 250 || D == 252 || D == 254 || D == 257 || D == 273 || D == 275 || D == 283 || 294 <= D && D <= 295 || D == 299 || 305 <= D && D <= 307 || D == 312 || 319 <= D && D <= 322 || D == 324 || 328 <= D && D <= 331 || D == 333 || 338 <= D && D <= 339 || 358 <= D && D <= 359 || D == 363 || D == 462 || D == 464 || D == 466 || D == 468 || D == 470 || D == 472 || D == 474 || D == 476 || D == 593 || D == 609 || D == 708 || D == 711 || 713 <= D && D <= 715 || D == 717 || D == 720 || 728 <= D && D <= 731 || D == 733 || D == 735 || 768 <= D && D <= 879 || 913 <= D && D <= 929 || 931 <= D && D <= 937 || 945 <= D && D <= 961 || 963 <= D && D <= 969 || D == 1025 || 1040 <= D && D <= 1103 || D == 1105 || D == 8208 || 8211 <= D && D <= 8214 || 8216 <= D && D <= 8217 || 8220 <= D && D <= 8221 || 8224 <= D && D <= 8226 || 8228 <= D && D <= 8231 || D == 8240 || 8242 <= D && D <= 8243 || D == 8245 || D == 8251 || D == 8254 || D == 8308 || D == 8319 || 8321 <= D && D <= 8324 || D == 8364 || D == 8451 || D == 8453 || D == 8457 || D == 8467 || D == 8470 || 8481 <= D && D <= 8482 || D == 8486 || D == 8491 || 8531 <= D && D <= 8532 || 8539 <= D && D <= 8542 || 8544 <= D && D <= 8555 || 8560 <= D && D <= 8569 || D == 8585 || 8592 <= D && D <= 8601 || 8632 <= D && D <= 8633 || D == 8658 || D == 8660 || D == 8679 || D == 8704 || 8706 <= D && D <= 8707 || 8711 <= D && D <= 8712 || D == 8715 || D == 8719 || D == 8721 || D == 8725 || D == 8730 || 8733 <= D && D <= 8736 || D == 8739 || D == 8741 || 8743 <= D && D <= 8748 || D == 8750 || 8756 <= D && D <= 8759 || 8764 <= D && D <= 8765 || D == 8776 || D == 8780 || D == 8786 || 8800 <= D && D <= 8801 || 8804 <= D && D <= 8807 || 8810 <= D && D <= 8811 || 8814 <= D && D <= 8815 || 8834 <= D && D <= 8835 || 8838 <= D && D <= 8839 || D == 8853 || D == 8857 || D == 8869 || D == 8895 || D == 8978 || 9312 <= D && D <= 9449 || 9451 <= D && D <= 9547 || 9552 <= D && D <= 9587 || 9600 <= D && D <= 9615 || 9618 <= D && D <= 9621 || 9632 <= D && D <= 9633 || 9635 <= D && D <= 9641 || 9650 <= D && D <= 9651 || 9654 <= D && D <= 9655 || 9660 <= D && D <= 9661 || 9664 <= D && D <= 9665 || 9670 <= D && D <= 9672 || D == 9675 || 9678 <= D && D <= 9681 || 9698 <= D && D <= 9701 || D == 9711 || 9733 <= D && D <= 9734 || D == 9737 || 9742 <= D && D <= 9743 || 9748 <= D && D <= 9749 || D == 9756 || D == 9758 || D == 9792 || D == 9794 || 9824 <= D && D <= 9825 || 9827 <= D && D <= 9829 || 9831 <= D && D <= 9834 || 9836 <= D && D <= 9837 || D == 9839 || 9886 <= D && D <= 9887 || 9918 <= D && D <= 9919 || 9924 <= D && D <= 9933 || 9935 <= D && D <= 9953 || D == 9955 || 9960 <= D && D <= 9983 || D == 10045 || D == 10071 || 10102 <= D && D <= 10111 || 11093 <= D && D <= 11097 || 12872 <= D && D <= 12879 || 57344 <= D && D <= 63743 || 65024 <= D && D <= 65039 || D == 65533 || 127232 <= D && D <= 127242 || 127248 <= D && D <= 127277 || 127280 <= D && D <= 127337 || 127344 <= D && D <= 127386 || 917760 <= D && D <= 917999 || 983040 <= D && D <= 1048573 || 1048576 <= D && D <= 1114109 ? "A" : "N";
2344
+ }, u.characterLength = function(e) {
2345
+ var s = this.eastAsianWidth(e);
2346
+ return s == "F" || s == "W" || s == "A" ? 2 : 1;
2347
+ };
2348
+ function F(e) {
2349
+ return e.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g) || [];
2350
+ }
2351
+ u.length = function(e) {
2352
+ for (var s = F(e), i = 0, D = 0;D < s.length; D++)
2353
+ i = i + this.characterLength(s[D]);
2354
+ return i;
2355
+ }, u.slice = function(e, s, i) {
2356
+ textLen = u.length(e), s = s || 0, i = i || 1, s < 0 && (s = textLen + s), i < 0 && (i = textLen + i);
2357
+ for (var D = "", C = 0, o = F(e), E = 0;E < o.length; E++) {
2358
+ var a = o[E], n = u.length(a);
2359
+ if (C >= s - (n == 2 ? 1 : 0))
2360
+ if (C + n <= i)
2361
+ D += a;
2362
+ else
2363
+ break;
2364
+ C += n;
2365
+ }
2366
+ return D;
2367
+ };
2368
+ })(P);
2369
+ var X = P.exports;
2370
+ var DD = O(X);
2371
+ var uD = function() {
2372
+ return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g;
2373
+ };
2374
+ var FD = O(uD);
2375
+ function A(t, u = {}) {
2376
+ if (typeof t != "string" || t.length === 0 || (u = { ambiguousIsNarrow: true, ...u }, t = T(t), t.length === 0))
2377
+ return 0;
2378
+ t = t.replace(FD(), " ");
2379
+ const F = u.ambiguousIsNarrow ? 1 : 2;
2380
+ let e = 0;
2381
+ for (const s of t) {
2382
+ const i = s.codePointAt(0);
2383
+ if (i <= 31 || i >= 127 && i <= 159 || i >= 768 && i <= 879)
2384
+ continue;
2385
+ switch (DD.eastAsianWidth(s)) {
2386
+ case "F":
2387
+ case "W":
2388
+ e += 2;
2389
+ break;
2390
+ case "A":
2391
+ e += F;
2392
+ break;
2393
+ default:
2394
+ e += 1;
2395
+ }
2396
+ }
2397
+ return e;
2398
+ }
2399
+ var m = 10;
2400
+ var L = (t = 0) => (u) => `\x1B[${u + t}m`;
2401
+ var N = (t = 0) => (u) => `\x1B[${38 + t};5;${u}m`;
2402
+ var I = (t = 0) => (u, F, e) => `\x1B[${38 + t};2;${u};${F};${e}m`;
2403
+ var r = { modifier: { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], overline: [53, 55], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29] }, color: { black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], blackBright: [90, 39], gray: [90, 39], grey: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39] }, bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgGray: [100, 49], bgGrey: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49] } };
2404
+ Object.keys(r.modifier);
2405
+ var tD = Object.keys(r.color);
2406
+ var eD = Object.keys(r.bgColor);
2407
+ [...tD, ...eD];
2408
+ function sD() {
2409
+ const t = new Map;
2410
+ for (const [u, F] of Object.entries(r)) {
2411
+ for (const [e, s] of Object.entries(F))
2412
+ r[e] = { open: `\x1B[${s[0]}m`, close: `\x1B[${s[1]}m` }, F[e] = r[e], t.set(s[0], s[1]);
2413
+ Object.defineProperty(r, u, { value: F, enumerable: false });
2414
+ }
2415
+ return Object.defineProperty(r, "codes", { value: t, enumerable: false }), r.color.close = "\x1B[39m", r.bgColor.close = "\x1B[49m", r.color.ansi = L(), r.color.ansi256 = N(), r.color.ansi16m = I(), r.bgColor.ansi = L(m), r.bgColor.ansi256 = N(m), r.bgColor.ansi16m = I(m), Object.defineProperties(r, { rgbToAnsi256: { value: (u, F, e) => u === F && F === e ? u < 8 ? 16 : u > 248 ? 231 : Math.round((u - 8) / 247 * 24) + 232 : 16 + 36 * Math.round(u / 255 * 5) + 6 * Math.round(F / 255 * 5) + Math.round(e / 255 * 5), enumerable: false }, hexToRgb: { value: (u) => {
2416
+ const F = /[a-f\d]{6}|[a-f\d]{3}/i.exec(u.toString(16));
2417
+ if (!F)
2418
+ return [0, 0, 0];
2419
+ let [e] = F;
2420
+ e.length === 3 && (e = [...e].map((i) => i + i).join(""));
2421
+ const s = Number.parseInt(e, 16);
2422
+ return [s >> 16 & 255, s >> 8 & 255, s & 255];
2423
+ }, enumerable: false }, hexToAnsi256: { value: (u) => r.rgbToAnsi256(...r.hexToRgb(u)), enumerable: false }, ansi256ToAnsi: { value: (u) => {
2424
+ if (u < 8)
2425
+ return 30 + u;
2426
+ if (u < 16)
2427
+ return 90 + (u - 8);
2428
+ let F, e, s;
2429
+ if (u >= 232)
2430
+ F = ((u - 232) * 10 + 8) / 255, e = F, s = F;
2431
+ else {
2432
+ u -= 16;
2433
+ const C = u % 36;
2434
+ F = Math.floor(u / 36) / 5, e = Math.floor(C / 6) / 5, s = C % 6 / 5;
2435
+ }
2436
+ const i = Math.max(F, e, s) * 2;
2437
+ if (i === 0)
2438
+ return 30;
2439
+ let D = 30 + (Math.round(s) << 2 | Math.round(e) << 1 | Math.round(F));
2440
+ return i === 2 && (D += 60), D;
2441
+ }, enumerable: false }, rgbToAnsi: { value: (u, F, e) => r.ansi256ToAnsi(r.rgbToAnsi256(u, F, e)), enumerable: false }, hexToAnsi: { value: (u) => r.ansi256ToAnsi(r.hexToAnsi256(u)), enumerable: false } }), r;
2442
+ }
2443
+ var iD = sD();
2444
+ var v = new Set(["\x1B", "›"]);
2445
+ var CD = 39;
2446
+ var w = "\x07";
2447
+ var W = "[";
2448
+ var rD = "]";
2449
+ var R = "m";
2450
+ var y = `${rD}8;;`;
2451
+ var V = (t) => `${v.values().next().value}${W}${t}${R}`;
2452
+ var z = (t) => `${v.values().next().value}${y}${t}${w}`;
2453
+ var ED = (t) => t.split(" ").map((u) => A(u));
2454
+ var _ = (t, u, F) => {
2455
+ const e = [...u];
2456
+ let s = false, i = false, D = A(T(t[t.length - 1]));
2457
+ for (const [C, o] of e.entries()) {
2458
+ const E = A(o);
2459
+ if (D + E <= F ? t[t.length - 1] += o : (t.push(o), D = 0), v.has(o) && (s = true, i = e.slice(C + 1).join("").startsWith(y)), s) {
2460
+ i ? o === w && (s = false, i = false) : o === R && (s = false);
2461
+ continue;
2462
+ }
2463
+ D += E, D === F && C < e.length - 1 && (t.push(""), D = 0);
2464
+ }
2465
+ !D && t[t.length - 1].length > 0 && t.length > 1 && (t[t.length - 2] += t.pop());
2466
+ };
2467
+ var nD = (t) => {
2468
+ const u = t.split(" ");
2469
+ let F = u.length;
2470
+ for (;F > 0 && !(A(u[F - 1]) > 0); )
2471
+ F--;
2472
+ return F === u.length ? t : u.slice(0, F).join(" ") + u.slice(F).join("");
2473
+ };
2474
+ var oD = (t, u, F = {}) => {
2475
+ if (F.trim !== false && t.trim() === "")
2476
+ return "";
2477
+ let e = "", s, i;
2478
+ const D = ED(t);
2479
+ let C = [""];
2480
+ for (const [E, a] of t.split(" ").entries()) {
2481
+ F.trim !== false && (C[C.length - 1] = C[C.length - 1].trimStart());
2482
+ let n = A(C[C.length - 1]);
2483
+ if (E !== 0 && (n >= u && (F.wordWrap === false || F.trim === false) && (C.push(""), n = 0), (n > 0 || F.trim === false) && (C[C.length - 1] += " ", n++)), F.hard && D[E] > u) {
2484
+ const B = u - n, p = 1 + Math.floor((D[E] - B - 1) / u);
2485
+ Math.floor((D[E] - 1) / u) < p && C.push(""), _(C, a, u);
2486
+ continue;
2487
+ }
2488
+ if (n + D[E] > u && n > 0 && D[E] > 0) {
2489
+ if (F.wordWrap === false && n < u) {
2490
+ _(C, a, u);
2491
+ continue;
2492
+ }
2493
+ C.push("");
2494
+ }
2495
+ if (n + D[E] > u && F.wordWrap === false) {
2496
+ _(C, a, u);
2497
+ continue;
2498
+ }
2499
+ C[C.length - 1] += a;
2500
+ }
2501
+ F.trim !== false && (C = C.map((E) => nD(E)));
2502
+ const o = [...C.join(`
2503
+ `)];
2504
+ for (const [E, a] of o.entries()) {
2505
+ if (e += a, v.has(a)) {
2506
+ const { groups: B } = new RegExp(`(?:\\${W}(?<code>\\d+)m|\\${y}(?<uri>.*)${w})`).exec(o.slice(E).join("")) || { groups: {} };
2507
+ if (B.code !== undefined) {
2508
+ const p = Number.parseFloat(B.code);
2509
+ s = p === CD ? undefined : p;
2510
+ } else
2511
+ B.uri !== undefined && (i = B.uri.length === 0 ? undefined : B.uri);
2512
+ }
2513
+ const n = iD.codes.get(Number(s));
2514
+ o[E + 1] === `
2515
+ ` ? (i && (e += z("")), s && n && (e += V(n))) : a === `
2516
+ ` && (s && n && (e += V(s)), i && (e += z(i)));
2517
+ }
2518
+ return e;
2519
+ };
2520
+ function G(t, u, F) {
2521
+ return String(t).normalize().replace(/\r\n/g, `
2522
+ `).split(`
2523
+ `).map((e) => oD(e, u, F)).join(`
2524
+ `);
2525
+ }
2526
+ var aD = ["up", "down", "left", "right", "space", "enter", "cancel"];
2527
+ var c = { actions: new Set(aD), aliases: new Map([["k", "up"], ["j", "down"], ["h", "left"], ["l", "right"], ["\x03", "cancel"], ["escape", "cancel"]]) };
2528
+ function k(t, u) {
2529
+ if (typeof t == "string")
2530
+ return c.aliases.get(t) === u;
2531
+ for (const F of t)
2532
+ if (F !== undefined && k(F, u))
2533
+ return true;
2534
+ return false;
2535
+ }
2536
+ function lD(t, u) {
2537
+ if (t === u)
2538
+ return;
2539
+ const F = t.split(`
2540
+ `), e = u.split(`
2541
+ `), s = [];
2542
+ for (let i = 0;i < Math.max(F.length, e.length); i++)
2543
+ F[i] !== e[i] && s.push(i);
2544
+ return s;
2545
+ }
2546
+ var xD = globalThis.process.platform.startsWith("win");
2547
+ var S = Symbol("clack:cancel");
2548
+ function BD(t) {
2549
+ return t === S;
2550
+ }
2551
+ function d(t, u) {
2552
+ const F = t;
2553
+ F.isTTY && F.setRawMode(u);
2554
+ }
2555
+ function cD({ input: t = $, output: u = j, overwrite: F = true, hideCursor: e = true } = {}) {
2556
+ const s = f.createInterface({ input: t, output: u, prompt: "", tabSize: 1 });
2557
+ f.emitKeypressEvents(t, s), t.isTTY && t.setRawMode(true);
2558
+ const i = (D, { name: C, sequence: o }) => {
2559
+ const E = String(D);
2560
+ if (k([E, C, o], "cancel")) {
2561
+ e && u.write(import_sisteransi.cursor.show), process.exit(0);
2562
+ return;
2563
+ }
2564
+ if (!F)
2565
+ return;
2566
+ const a = C === "return" ? 0 : -1, n = C === "return" ? -1 : 0;
2567
+ f.moveCursor(u, a, n, () => {
2568
+ f.clearLine(u, 1, () => {
2569
+ t.once("keypress", i);
2570
+ });
2571
+ });
2572
+ };
2573
+ return e && u.write(import_sisteransi.cursor.hide), t.once("keypress", i), () => {
2574
+ t.off("keypress", i), e && u.write(import_sisteransi.cursor.show), t.isTTY && !xD && t.setRawMode(false), s.terminal = false, s.close();
2575
+ };
2576
+ }
2577
+ var AD = Object.defineProperty;
2578
+ var pD = (t, u, F) => (u in t) ? AD(t, u, { enumerable: true, configurable: true, writable: true, value: F }) : t[u] = F;
2579
+ var h = (t, u, F) => (pD(t, typeof u != "symbol" ? u + "" : u, F), F);
2580
+
2581
+ class x {
2582
+ constructor(u, F = true) {
2583
+ h(this, "input"), h(this, "output"), h(this, "_abortSignal"), h(this, "rl"), h(this, "opts"), h(this, "_render"), h(this, "_track", false), h(this, "_prevFrame", ""), h(this, "_subscribers", new Map), h(this, "_cursor", 0), h(this, "state", "initial"), h(this, "error", ""), h(this, "value");
2584
+ const { input: e = $, output: s = j, render: i, signal: D, ...C } = u;
2585
+ this.opts = C, this.onKeypress = this.onKeypress.bind(this), this.close = this.close.bind(this), this.render = this.render.bind(this), this._render = i.bind(this), this._track = F, this._abortSignal = D, this.input = e, this.output = s;
2586
+ }
2587
+ unsubscribe() {
2588
+ this._subscribers.clear();
2589
+ }
2590
+ setSubscriber(u, F) {
2591
+ const e = this._subscribers.get(u) ?? [];
2592
+ e.push(F), this._subscribers.set(u, e);
2593
+ }
2594
+ on(u, F) {
2595
+ this.setSubscriber(u, { cb: F });
2596
+ }
2597
+ once(u, F) {
2598
+ this.setSubscriber(u, { cb: F, once: true });
2599
+ }
2600
+ emit(u, ...F) {
2601
+ const e = this._subscribers.get(u) ?? [], s = [];
2602
+ for (const i of e)
2603
+ i.cb(...F), i.once && s.push(() => e.splice(e.indexOf(i), 1));
2604
+ for (const i of s)
2605
+ i();
2606
+ }
2607
+ prompt() {
2608
+ return new Promise((u, F) => {
2609
+ if (this._abortSignal) {
2610
+ if (this._abortSignal.aborted)
2611
+ return this.state = "cancel", this.close(), u(S);
2612
+ this._abortSignal.addEventListener("abort", () => {
2613
+ this.state = "cancel", this.close();
2614
+ }, { once: true });
2615
+ }
2616
+ const e = new U(0);
2617
+ e._write = (s, i, D) => {
2618
+ this._track && (this.value = this.rl?.line.replace(/\t/g, ""), this._cursor = this.rl?.cursor ?? 0, this.emit("value", this.value)), D();
2619
+ }, this.input.pipe(e), this.rl = M.createInterface({ input: this.input, output: e, tabSize: 2, prompt: "", escapeCodeTimeout: 50 }), M.emitKeypressEvents(this.input, this.rl), this.rl.prompt(), this.opts.initialValue !== undefined && this._track && this.rl.write(this.opts.initialValue), this.input.on("keypress", this.onKeypress), d(this.input, true), this.output.on("resize", this.render), this.render(), this.once("submit", () => {
2620
+ this.output.write(import_sisteransi.cursor.show), this.output.off("resize", this.render), d(this.input, false), u(this.value);
2621
+ }), this.once("cancel", () => {
2622
+ this.output.write(import_sisteransi.cursor.show), this.output.off("resize", this.render), d(this.input, false), u(S);
2623
+ });
2624
+ });
2625
+ }
2626
+ onKeypress(u, F) {
2627
+ if (this.state === "error" && (this.state = "active"), F?.name && (!this._track && c.aliases.has(F.name) && this.emit("cursor", c.aliases.get(F.name)), c.actions.has(F.name) && this.emit("cursor", F.name)), u && (u.toLowerCase() === "y" || u.toLowerCase() === "n") && this.emit("confirm", u.toLowerCase() === "y"), u === "\t" && this.opts.placeholder && (this.value || (this.rl?.write(this.opts.placeholder), this.emit("value", this.opts.placeholder))), u && this.emit("key", u.toLowerCase()), F?.name === "return") {
2628
+ if (this.opts.validate) {
2629
+ const e = this.opts.validate(this.value);
2630
+ e && (this.error = e instanceof Error ? e.message : e, this.state = "error", this.rl?.write(this.value));
2631
+ }
2632
+ this.state !== "error" && (this.state = "submit");
2633
+ }
2634
+ k([u, F?.name, F?.sequence], "cancel") && (this.state = "cancel"), (this.state === "submit" || this.state === "cancel") && this.emit("finalize"), this.render(), (this.state === "submit" || this.state === "cancel") && this.close();
2635
+ }
2636
+ close() {
2637
+ this.input.unpipe(), this.input.removeListener("keypress", this.onKeypress), this.output.write(`
2638
+ `), d(this.input, false), this.rl?.close(), this.rl = undefined, this.emit(`${this.state}`, this.value), this.unsubscribe();
2639
+ }
2640
+ restoreCursor() {
2641
+ const u = G(this._prevFrame, process.stdout.columns, { hard: true }).split(`
2642
+ `).length - 1;
2643
+ this.output.write(import_sisteransi.cursor.move(-999, u * -1));
2644
+ }
2645
+ render() {
2646
+ const u = G(this._render(this) ?? "", process.stdout.columns, { hard: true });
2647
+ if (u !== this._prevFrame) {
2648
+ if (this.state === "initial")
2649
+ this.output.write(import_sisteransi.cursor.hide);
2650
+ else {
2651
+ const F = lD(this._prevFrame, u);
2652
+ if (this.restoreCursor(), F && F?.length === 1) {
2653
+ const e = F[0];
2654
+ this.output.write(import_sisteransi.cursor.move(0, e)), this.output.write(import_sisteransi.erase.lines(1));
2655
+ const s = u.split(`
2656
+ `);
2657
+ this.output.write(s[e]), this._prevFrame = u, this.output.write(import_sisteransi.cursor.move(0, s.length - e - 1));
2658
+ return;
2659
+ }
2660
+ if (F && F?.length > 1) {
2661
+ const e = F[0];
2662
+ this.output.write(import_sisteransi.cursor.move(0, e)), this.output.write(import_sisteransi.erase.down());
2663
+ const s = u.split(`
2664
+ `).slice(e);
2665
+ this.output.write(s.join(`
2666
+ `)), this._prevFrame = u;
2667
+ return;
2668
+ }
2669
+ this.output.write(import_sisteransi.erase.down());
2670
+ }
2671
+ this.output.write(u), this.state === "initial" && (this.state = "active"), this._prevFrame = u;
2672
+ }
2673
+ }
2674
+ }
2675
+ var SD = Object.defineProperty;
2676
+ var $D = (t, u, F) => (u in t) ? SD(t, u, { enumerable: true, configurable: true, writable: true, value: F }) : t[u] = F;
2677
+ var q = (t, u, F) => ($D(t, typeof u != "symbol" ? u + "" : u, F), F);
2678
+
2679
+ class jD extends x {
2680
+ constructor(u) {
2681
+ super(u, false), q(this, "options"), q(this, "cursor", 0), this.options = u.options, this.cursor = this.options.findIndex(({ value: F }) => F === u.initialValue), this.cursor === -1 && (this.cursor = 0), this.changeValue(), this.on("cursor", (F) => {
2682
+ switch (F) {
2683
+ case "left":
2684
+ case "up":
2685
+ this.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;
2686
+ break;
2687
+ case "down":
2688
+ case "right":
2689
+ this.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;
2690
+ break;
2691
+ }
2692
+ this.changeValue();
2693
+ });
2694
+ }
2695
+ get _value() {
2696
+ return this.options[this.cursor];
2697
+ }
2698
+ changeValue() {
2699
+ this.value = this._value.value;
2700
+ }
2701
+ }
2702
+ class PD extends x {
2703
+ get valueWithCursor() {
2704
+ if (this.state === "submit")
2705
+ return this.value;
2706
+ if (this.cursor >= this.value.length)
2707
+ return `${this.value}█`;
2708
+ const u = this.value.slice(0, this.cursor), [F, ...e] = this.value.slice(this.cursor);
2709
+ return `${u}${import_picocolors.default.inverse(F)}${e.join("")}`;
2710
+ }
2711
+ get cursor() {
2712
+ return this._cursor;
2713
+ }
2714
+ constructor(u) {
2715
+ super(u), this.on("finalize", () => {
2716
+ this.value || (this.value = u.defaultValue);
2717
+ });
2718
+ }
2719
+ }
2720
+
2721
+ // node_modules/@clack/prompts/dist/index.mjs
2722
+ var import_picocolors2 = __toESM(require_picocolors(), 1);
2723
+ var import_sisteransi2 = __toESM(require_src(), 1);
2724
+ import p from "node:process";
2725
+ function X2() {
2726
+ return p.platform !== "win32" ? p.env.TERM !== "linux" : !!p.env.CI || !!p.env.WT_SESSION || !!p.env.TERMINUS_SUBLIME || p.env.ConEmuTask === "{cmd::Cmder}" || p.env.TERM_PROGRAM === "Terminus-Sublime" || p.env.TERM_PROGRAM === "vscode" || p.env.TERM === "xterm-256color" || p.env.TERM === "alacritty" || p.env.TERMINAL_EMULATOR === "JetBrains-JediTerm";
2727
+ }
2728
+ var E = X2();
2729
+ var u = (s, n) => E ? s : n;
2730
+ var ee = u("◆", "*");
2731
+ var A2 = u("■", "x");
2732
+ var B = u("▲", "x");
2733
+ var S2 = u("◇", "o");
2734
+ var te = u("┌", "T");
2735
+ var a = u("│", "|");
2736
+ var m2 = u("└", "—");
2737
+ var j2 = u("●", ">");
2738
+ var R2 = u("○", " ");
2739
+ var V2 = u("◻", "[•]");
2740
+ var M2 = u("◼", "[+]");
2741
+ var G2 = u("◻", "[ ]");
2742
+ var se = u("▪", "•");
2743
+ var N2 = u("─", "-");
2744
+ var re = u("╮", "+");
2745
+ var ie = u("├", "+");
2746
+ var ne = u("╯", "+");
2747
+ var ae = u("●", "•");
2748
+ var oe = u("◆", "*");
2749
+ var ce = u("▲", "!");
2750
+ var le = u("■", "x");
2751
+ var y2 = (s) => {
2752
+ switch (s) {
2753
+ case "initial":
2754
+ case "active":
2755
+ return import_picocolors2.default.cyan(ee);
2756
+ case "cancel":
2757
+ return import_picocolors2.default.red(A2);
2758
+ case "error":
2759
+ return import_picocolors2.default.yellow(B);
2760
+ case "submit":
2761
+ return import_picocolors2.default.green(S2);
2762
+ }
2763
+ };
2764
+ var k2 = (s) => {
2765
+ const { cursor: n, options: t, style: i } = s, r2 = s.maxItems ?? Number.POSITIVE_INFINITY, c2 = Math.max(process.stdout.rows - 4, 0), o = Math.min(c2, Math.max(r2, 5));
2766
+ let l2 = 0;
2767
+ n >= l2 + o - 3 ? l2 = Math.max(Math.min(n - o + 3, t.length - o), 0) : n < l2 + 2 && (l2 = Math.max(n - 2, 0));
2768
+ const $2 = o < t.length && l2 > 0, d2 = o < t.length && l2 + o < t.length;
2769
+ return t.slice(l2, l2 + o).map((w2, b2, C) => {
2770
+ const I2 = b2 === 0 && $2, x2 = b2 === C.length - 1 && d2;
2771
+ return I2 || x2 ? import_picocolors2.default.dim("...") : i(w2, b2 + l2 === n);
2772
+ });
2773
+ };
2774
+ var ue = (s) => new PD({ validate: s.validate, placeholder: s.placeholder, defaultValue: s.defaultValue, initialValue: s.initialValue, render() {
2775
+ const n = `${import_picocolors2.default.gray(a)}
2776
+ ${y2(this.state)} ${s.message}
2777
+ `, t = s.placeholder ? import_picocolors2.default.inverse(s.placeholder[0]) + import_picocolors2.default.dim(s.placeholder.slice(1)) : import_picocolors2.default.inverse(import_picocolors2.default.hidden("_")), i = this.value ? this.valueWithCursor : t;
2778
+ switch (this.state) {
2779
+ case "error":
2780
+ return `${n.trim()}
2781
+ ${import_picocolors2.default.yellow(a)} ${i}
2782
+ ${import_picocolors2.default.yellow(m2)} ${import_picocolors2.default.yellow(this.error)}
2783
+ `;
2784
+ case "submit":
2785
+ return `${n}${import_picocolors2.default.gray(a)} ${import_picocolors2.default.dim(this.value || s.placeholder)}`;
2786
+ case "cancel":
2787
+ return `${n}${import_picocolors2.default.gray(a)} ${import_picocolors2.default.strikethrough(import_picocolors2.default.dim(this.value ?? ""))}${this.value?.trim() ? `
2788
+ ${import_picocolors2.default.gray(a)}` : ""}`;
2789
+ default:
2790
+ return `${n}${import_picocolors2.default.cyan(a)} ${i}
2791
+ ${import_picocolors2.default.cyan(m2)}
2792
+ `;
2793
+ }
2794
+ } }).prompt();
2795
+ var de = (s) => {
2796
+ const n = (t, i) => {
2797
+ const r2 = t.label ?? String(t.value);
2798
+ switch (i) {
2799
+ case "selected":
2800
+ return `${import_picocolors2.default.dim(r2)}`;
2801
+ case "active":
2802
+ return `${import_picocolors2.default.green(j2)} ${r2} ${t.hint ? import_picocolors2.default.dim(`(${t.hint})`) : ""}`;
2803
+ case "cancelled":
2804
+ return `${import_picocolors2.default.strikethrough(import_picocolors2.default.dim(r2))}`;
2805
+ default:
2806
+ return `${import_picocolors2.default.dim(R2)} ${import_picocolors2.default.dim(r2)}`;
2807
+ }
2808
+ };
2809
+ return new jD({ options: s.options, initialValue: s.initialValue, render() {
2810
+ const t = `${import_picocolors2.default.gray(a)}
2811
+ ${y2(this.state)} ${s.message}
2812
+ `;
2813
+ switch (this.state) {
2814
+ case "submit":
2815
+ return `${t}${import_picocolors2.default.gray(a)} ${n(this.options[this.cursor], "selected")}`;
2816
+ case "cancel":
2817
+ return `${t}${import_picocolors2.default.gray(a)} ${n(this.options[this.cursor], "cancelled")}
2818
+ ${import_picocolors2.default.gray(a)}`;
2819
+ default:
2820
+ return `${t}${import_picocolors2.default.cyan(a)} ${k2({ cursor: this.cursor, options: this.options, maxItems: s.maxItems, style: (i, r2) => n(i, r2 ? "active" : "inactive") }).join(`
2821
+ ${import_picocolors2.default.cyan(a)} `)}
2822
+ ${import_picocolors2.default.cyan(m2)}
2823
+ `;
2824
+ }
2825
+ } }).prompt();
2826
+ };
2827
+ var ve = (s = "") => {
2828
+ process.stdout.write(`${import_picocolors2.default.gray(m2)} ${import_picocolors2.default.red(s)}
2829
+
2830
+ `);
2831
+ };
2832
+ var we = (s = "") => {
2833
+ process.stdout.write(`${import_picocolors2.default.gray(te)} ${s}
2834
+ `);
2835
+ };
2836
+ var fe = (s = "") => {
2837
+ process.stdout.write(`${import_picocolors2.default.gray(a)}
2838
+ ${import_picocolors2.default.gray(m2)} ${s}
2839
+
2840
+ `);
2841
+ };
2842
+ var L2 = () => {
2843
+ const s = E ? ["◒", "◐", "◓", "◑"] : ["•", "o", "O", "0"], n = E ? 80 : 120, t = process.env.CI === "true";
2844
+ let i, r2, c2 = false, o = "", l2;
2845
+ const $2 = (h2) => {
2846
+ const g2 = h2 > 1 ? "Something went wrong" : "Canceled";
2847
+ c2 && P2(g2, h2);
2848
+ }, d2 = () => $2(2), w2 = () => $2(1), b2 = () => {
2849
+ process.on("uncaughtExceptionMonitor", d2), process.on("unhandledRejection", d2), process.on("SIGINT", w2), process.on("SIGTERM", w2), process.on("exit", $2);
2850
+ }, C = () => {
2851
+ process.removeListener("uncaughtExceptionMonitor", d2), process.removeListener("unhandledRejection", d2), process.removeListener("SIGINT", w2), process.removeListener("SIGTERM", w2), process.removeListener("exit", $2);
2852
+ }, I2 = () => {
2853
+ if (l2 === undefined)
2854
+ return;
2855
+ t && process.stdout.write(`
2856
+ `);
2857
+ const h2 = l2.split(`
2858
+ `);
2859
+ process.stdout.write(import_sisteransi2.cursor.move(-999, h2.length - 1)), process.stdout.write(import_sisteransi2.erase.down(h2.length));
2860
+ }, x2 = (h2) => h2.replace(/\.+$/, ""), O2 = (h2 = "") => {
2861
+ c2 = true, i = cD(), o = x2(h2), process.stdout.write(`${import_picocolors2.default.gray(a)}
2862
+ `);
2863
+ let g2 = 0, f2 = 0;
2864
+ b2(), r2 = setInterval(() => {
2865
+ if (t && o === l2)
2866
+ return;
2867
+ I2(), l2 = o;
2868
+ const W2 = import_picocolors2.default.magenta(s[g2]), _2 = t ? "..." : ".".repeat(Math.floor(f2)).slice(0, 3);
2869
+ process.stdout.write(`${W2} ${o}${_2}`), g2 = g2 + 1 < s.length ? g2 + 1 : 0, f2 = f2 < s.length ? f2 + 0.125 : 0;
2870
+ }, n);
2871
+ }, P2 = (h2 = "", g2 = 0) => {
2872
+ c2 = false, clearInterval(r2), I2();
2873
+ const f2 = g2 === 0 ? import_picocolors2.default.green(S2) : g2 === 1 ? import_picocolors2.default.red(A2) : import_picocolors2.default.red(B);
2874
+ o = x2(h2 ?? o), process.stdout.write(`${f2} ${o}
2875
+ `), C(), i();
2876
+ };
2877
+ return { start: O2, stop: P2, message: (h2 = "") => {
2878
+ o = x2(h2 ?? o);
2879
+ } };
2880
+ };
2881
+
2882
+ // src/lib/config.ts
2883
+ import {
2884
+ chmodSync,
2885
+ existsSync,
2886
+ mkdirSync,
2887
+ readFileSync,
2888
+ renameSync,
2889
+ rmSync,
2890
+ writeFileSync
2891
+ } from "node:fs";
2892
+ import { homedir, platform } from "node:os";
2893
+ import { join } from "node:path";
2894
+ var AUTH_FILE_VERSION = 1;
2895
+ function configDir() {
2896
+ if (platform() === "win32") {
2897
+ const appData = process.env["APPDATA"] ?? join(homedir(), "AppData", "Roaming");
2898
+ return join(appData, "10x-cli");
2899
+ }
2900
+ const xdg = process.env["XDG_CONFIG_HOME"];
2901
+ const base = xdg && xdg.length > 0 ? xdg : join(homedir(), ".config");
2902
+ return join(base, "10x-cli");
2903
+ }
2904
+ function authFilePath() {
2905
+ return join(configDir(), "auth.json");
2906
+ }
2907
+ function readAuth() {
2908
+ const file = authFilePath();
2909
+ if (!existsSync(file))
2910
+ return null;
2911
+ try {
2912
+ const raw = readFileSync(file, "utf8");
2913
+ const parsed = JSON.parse(raw);
2914
+ if (parsed.version !== AUTH_FILE_VERSION)
2915
+ return null;
2916
+ return parsed;
2917
+ } catch {
2918
+ return null;
2919
+ }
2920
+ }
2921
+ function saveAuth(data) {
2922
+ const dir = configDir();
2923
+ if (!existsSync(dir)) {
2924
+ mkdirSync(dir, { recursive: true, mode: 448 });
2925
+ }
2926
+ if (process.platform !== "win32") {
2927
+ try {
2928
+ chmodSync(dir, 448);
2929
+ } catch {}
2930
+ }
2931
+ const file = authFilePath();
2932
+ const tmp = `${file}.tmp`;
2933
+ rmSync(tmp, { force: true });
2934
+ writeFileSync(tmp, `${JSON.stringify(data, null, 2)}
2935
+ `, { mode: 384 });
2936
+ if (process.platform !== "win32") {
2937
+ try {
2938
+ chmodSync(tmp, 384);
2939
+ } catch {}
2940
+ }
2941
+ renameSync(tmp, file);
2942
+ }
2943
+ function deleteAuth() {
2944
+ const file = authFilePath();
2945
+ if (existsSync(file)) {
2946
+ rmSync(file, { force: true });
2947
+ }
2948
+ }
2949
+ function toolConfigPath() {
2950
+ return join(configDir(), "config.json");
2951
+ }
2952
+ function readToolConfig() {
2953
+ const file = toolConfigPath();
2954
+ if (!existsSync(file))
2955
+ return null;
2956
+ try {
2957
+ const raw = readFileSync(file, "utf8");
2958
+ const parsed = JSON.parse(raw);
2959
+ if (typeof parsed.tool !== "string")
2960
+ return null;
2961
+ return parsed;
2962
+ } catch {
2963
+ return null;
2964
+ }
2965
+ }
2966
+ function saveToolConfig(config) {
2967
+ const dir = configDir();
2968
+ if (!existsSync(dir)) {
2969
+ mkdirSync(dir, { recursive: true, mode: 448 });
2970
+ }
2971
+ const file = toolConfigPath();
2972
+ writeFileSync(file, `${JSON.stringify(config, null, 2)}
2973
+ `);
2974
+ }
2975
+
2976
+ // src/lib/api-client.ts
2977
+ var DEFAULT_API_BASE = "https://10x-toolkit-api.przeprogramowani.workers.dev";
2978
+ var PROD_HOSTNAME = "10x-toolkit-api.przeprogramowani.workers.dev";
2979
+ var DEV_HOSTNAMES = new Set(["localhost", "127.0.0.1"]);
2980
+ function resolveApiBase() {
2981
+ const override = process.env["API_BASE_URL"];
2982
+ if (!override)
2983
+ return DEFAULT_API_BASE;
2984
+ let url;
2985
+ try {
2986
+ url = new URL(override);
2987
+ } catch {
2988
+ throw new Error(`API_BASE_URL is not a valid URL: ${JSON.stringify(override)}`);
2989
+ }
2990
+ if (url.pathname !== "/" && url.pathname !== "") {
2991
+ throw new Error(`API_BASE_URL must not include a path (got ${JSON.stringify(url.pathname)})`);
2992
+ }
2993
+ if (url.search !== "" || url.hash !== "") {
2994
+ throw new Error("API_BASE_URL must not include a query string or fragment");
2995
+ }
2996
+ if (url.protocol === "https:" && url.hostname === PROD_HOSTNAME) {
2997
+ return `${url.protocol}//${url.host}`;
2998
+ }
2999
+ if (url.protocol === "http:" && DEV_HOSTNAMES.has(url.hostname)) {
3000
+ return `${url.protocol}//${url.host}`;
3001
+ }
3002
+ throw new Error(`API_BASE_URL must be ${DEFAULT_API_BASE} or http://localhost[:port] (got ${JSON.stringify(override)})`);
3003
+ }
3004
+ var DEFAULT_TIMEOUT_MS = 30000;
3005
+ async function request(method, path, body, options = {}) {
3006
+ const base = resolveApiBase();
3007
+ const url = path.startsWith("http") ? path : `${base}${path}`;
3008
+ const headers = {
3009
+ accept: "application/json",
3010
+ "user-agent": "10x-cli",
3011
+ ...options.headers
3012
+ };
3013
+ if (options.token) {
3014
+ headers.authorization = `Bearer ${options.token}`;
3015
+ }
3016
+ if (body !== undefined) {
3017
+ headers["content-type"] = "application/json";
3018
+ }
3019
+ const init = {
3020
+ method,
3021
+ headers,
3022
+ signal: options.signal ?? AbortSignal.timeout(DEFAULT_TIMEOUT_MS)
3023
+ };
3024
+ if (body !== undefined) {
3025
+ init.body = JSON.stringify(body);
3026
+ }
3027
+ let response;
3028
+ try {
3029
+ response = await fetch(url, init);
3030
+ } catch (err) {
3031
+ const message = err instanceof Error ? err.message : String(err);
3032
+ return {
3033
+ ok: false,
3034
+ status: 0,
3035
+ code: "network_error",
3036
+ error: message
3037
+ };
3038
+ }
3039
+ const text = await response.text();
3040
+ let parsed = undefined;
3041
+ if (text.length > 0) {
3042
+ try {
3043
+ parsed = JSON.parse(text);
3044
+ } catch {}
3045
+ }
3046
+ if (!response.ok) {
3047
+ const payload = parsed && typeof parsed === "object" ? parsed : undefined;
3048
+ return {
3049
+ ok: false,
3050
+ status: response.status,
3051
+ code: payload?.code ?? `http_${response.status}`,
3052
+ error: payload?.error ?? payload?.message ?? response.statusText,
3053
+ payload
3054
+ };
3055
+ }
3056
+ return { ok: true, status: response.status, data: parsed, responseHeaders: response.headers };
3057
+ }
3058
+ function apiGet(path, options = {}) {
3059
+ return request("GET", path, undefined, options);
3060
+ }
3061
+ function apiPost(path, body, options = {}) {
3062
+ return request("POST", path, body, options);
3063
+ }
3064
+
3065
+ // src/lib/auth-flow.ts
3066
+ function loginRequest(email, options = {}) {
3067
+ return apiPost("/auth/login", { email }, { signal: options.signal });
3068
+ }
3069
+ async function checkVerifySession(sessionId, options = {}) {
3070
+ const result = await apiGet(`/auth/verify?session=${encodeURIComponent(sessionId)}`, { signal: options.signal });
3071
+ if (result.ok) {
3072
+ if (result.status === 200 && result.data && "token" in result.data) {
3073
+ return { kind: "verified", tokens: result.data };
3074
+ }
3075
+ return { kind: "pending" };
3076
+ }
3077
+ if (result.status === 404) {
3078
+ return {
3079
+ kind: "expired",
3080
+ message: result.payload?.message ?? result.error ?? "Session expired"
3081
+ };
3082
+ }
3083
+ if (result.status === 0) {
3084
+ return { kind: "pending" };
3085
+ }
3086
+ return {
3087
+ kind: "error",
3088
+ code: result.code,
3089
+ message: result.error,
3090
+ status: result.status
3091
+ };
3092
+ }
3093
+ function refreshTokenRequest(refreshToken, options = {}) {
3094
+ return apiPost("/auth/refresh", { refresh_token: refreshToken }, { signal: options.signal });
3095
+ }
3096
+ var DEFAULT_INTERVAL_MS = 2000;
3097
+ var DEFAULT_TIMEOUT_MS2 = 5 * 60 * 1000;
3098
+ function defaultSleep(ms) {
3099
+ return new Promise((resolve) => setTimeout(resolve, ms));
3100
+ }
3101
+ async function pollVerifySession(sessionId, options = {}) {
3102
+ const intervalMs = options.intervalMs ?? DEFAULT_INTERVAL_MS;
3103
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
3104
+ const now = options.now ?? Date.now;
3105
+ const sleep = options.sleep ?? defaultSleep;
3106
+ const startedAt = now();
3107
+ const deadline = startedAt + timeoutMs;
3108
+ while (true) {
3109
+ if (options.signal?.aborted)
3110
+ return { kind: "aborted" };
3111
+ const remaining = deadline - now();
3112
+ options.onTick?.(Math.max(0, remaining));
3113
+ const outcome = await checkVerifySession(sessionId, { signal: options.signal });
3114
+ if (outcome.kind === "verified")
3115
+ return outcome;
3116
+ if (outcome.kind === "expired")
3117
+ return outcome;
3118
+ if (outcome.kind === "error")
3119
+ return outcome;
3120
+ if (now() + intervalMs >= deadline)
3121
+ return { kind: "timeout" };
3122
+ await sleep(intervalMs);
3123
+ }
3124
+ }
3125
+
3126
+ // src/lib/auth-guard.ts
3127
+ var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
3128
+ import { mkdirSync as mkdirSync2 } from "node:fs";
3129
+ import { dirname } from "node:path";
3130
+
3131
+ // src/lib/output.ts
3132
+ var ExitCodes = {
3133
+ SUCCESS: 0,
3134
+ ERROR: 1,
3135
+ USAGE: 2,
3136
+ AUTH_REQUIRED: 3,
3137
+ FORBIDDEN: 4,
3138
+ NOT_FOUND: 5
3139
+ };
3140
+ function resolveContext(flags) {
3141
+ return {
3142
+ json: flags.json === true || !process.stdout.isTTY,
3143
+ verbose: flags.verbose === true
3144
+ };
3145
+ }
3146
+ function output(ctx, humanMessage, data) {
3147
+ if (ctx.json) {
3148
+ process.stdout.write(`${JSON.stringify({ status: "ok", data })}
3149
+ `);
3150
+ return;
3151
+ }
3152
+ if (humanMessage) {
3153
+ process.stderr.write(`${humanMessage}
3154
+ `);
3155
+ }
3156
+ }
3157
+ function outputError(ctx, code, message, exitCode = ExitCodes.ERROR, hint) {
3158
+ if (ctx.json) {
3159
+ process.stdout.write(`${JSON.stringify({ status: "error", error: { code, message, hint } })}
3160
+ `);
3161
+ } else {
3162
+ process.stderr.write(`ERROR ${code}: ${sanitize(message)}
3163
+ `);
3164
+ if (hint) {
3165
+ process.stderr.write(` → ${sanitize(hint)}
3166
+ `);
3167
+ }
3168
+ }
3169
+ process.exit(exitCode);
3170
+ }
3171
+ function sanitize(s) {
3172
+ return s.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "").replace(/[\u0000-\u001F\u007F-\u009F]/g, "");
3173
+ }
3174
+ function verbose(ctx, message) {
3175
+ if (!ctx.verbose)
3176
+ return;
3177
+ process.stderr.write(`[verbose] ${message}
3178
+ `);
3179
+ }
3180
+
3181
+ // src/lib/auth-guard.ts
3182
+ var DEFAULT_REFRESH_WINDOW_MS = 5 * 60 * 1000;
3183
+ var LOCK_RETRIES = 5;
3184
+ var LOCK_MIN_TIMEOUT_MS = 100;
3185
+ var LOCK_MAX_TIMEOUT_MS = 1000;
3186
+ var LOCK_STALE_MS = 1e4;
3187
+ function isExpired(auth, now = new Date) {
3188
+ const expiresAt = new Date(auth.expires_at);
3189
+ if (!Number.isFinite(expiresAt.getTime()))
3190
+ return true;
3191
+ return expiresAt.getTime() <= now.getTime();
3192
+ }
3193
+ function isNearExpiry(auth, windowMs = DEFAULT_REFRESH_WINDOW_MS, now = new Date) {
3194
+ const expiresAt = new Date(auth.expires_at);
3195
+ if (!Number.isFinite(expiresAt.getTime()))
3196
+ return true;
3197
+ return expiresAt.getTime() - now.getTime() <= windowMs;
3198
+ }
3199
+ async function acquireRefreshLock(ctx, lockTarget) {
3200
+ try {
3201
+ mkdirSync2(dirname(lockTarget), { recursive: true });
3202
+ return await import_proper_lockfile.default.lock(lockTarget, {
3203
+ realpath: false,
3204
+ stale: LOCK_STALE_MS,
3205
+ retries: {
3206
+ retries: LOCK_RETRIES,
3207
+ factor: 2,
3208
+ minTimeout: LOCK_MIN_TIMEOUT_MS,
3209
+ maxTimeout: LOCK_MAX_TIMEOUT_MS
3210
+ }
3211
+ });
3212
+ } catch (err) {
3213
+ const detail = err instanceof Error ? err.message : String(err);
3214
+ outputError(ctx, "auth_lock_timeout", `Could not acquire credentials lock: ${detail}`, ExitCodes.ERROR, "Another 10x process is refreshing the session. Wait a moment and retry.");
3215
+ }
3216
+ }
3217
+ async function requireAuth(ctx, options = {}) {
3218
+ const read = options.read ?? readAuth;
3219
+ const persist = options.persist ?? saveAuth;
3220
+ const refresh = options.refresh ?? refreshTokenRequest;
3221
+ const now = options.now ?? (() => new Date);
3222
+ const windowMs = options.refreshWindowMs ?? DEFAULT_REFRESH_WINDOW_MS;
3223
+ const lockTarget = options.lockFilePath ?? authFilePath();
3224
+ const auth = read();
3225
+ if (!auth) {
3226
+ outputError(ctx, "auth_required", "Not authenticated.", ExitCodes.AUTH_REQUIRED, "Run '10x auth' to log in.");
3227
+ }
3228
+ const initialNow = now();
3229
+ if (!isExpired(auth, initialNow) && !isNearExpiry(auth, windowMs, initialNow)) {
3230
+ return auth;
3231
+ }
3232
+ const release = await acquireRefreshLock(ctx, lockTarget);
3233
+ try {
3234
+ const fresh = read();
3235
+ if (!fresh) {
3236
+ outputError(ctx, "auth_required", "Not authenticated.", ExitCodes.AUTH_REQUIRED, "Run '10x auth' to log in.");
3237
+ }
3238
+ const freshNow = now();
3239
+ const freshExpired = isExpired(fresh, freshNow);
3240
+ if (!freshExpired && !isNearExpiry(fresh, windowMs, freshNow)) {
3241
+ verbose(ctx, "another process already refreshed — using rotated token");
3242
+ return fresh;
3243
+ }
3244
+ verbose(ctx, freshExpired ? "token expired — refreshing" : "token near expiry — refreshing");
3245
+ const refreshed = await refresh(fresh.refresh_token);
3246
+ if (refreshed.ok) {
3247
+ const next = {
3248
+ version: fresh.version,
3249
+ email: fresh.email,
3250
+ access_token: refreshed.data.token,
3251
+ refresh_token: refreshed.data.refresh_token,
3252
+ expires_at: refreshed.data.expires_at,
3253
+ created_at: fresh.created_at
3254
+ };
3255
+ persist(next);
3256
+ return next;
3257
+ }
3258
+ if (!freshExpired) {
3259
+ verbose(ctx, `refresh failed (${refreshed.code}) — using existing token`);
3260
+ return fresh;
3261
+ }
3262
+ if (refreshed.status === 403) {
3263
+ outputError(ctx, "membership_revoked", refreshed.error || "Course membership has been revoked.", ExitCodes.FORBIDDEN, "Re-enroll at https://10xdevs.pl, then run '10x auth'.");
3264
+ }
3265
+ outputError(ctx, "auth_expired", "Session expired.", ExitCodes.AUTH_REQUIRED, "Run '10x auth' to re-authenticate.");
3266
+ } finally {
3267
+ try {
3268
+ await release();
3269
+ } catch {}
3270
+ }
3271
+ throw new Error("requireAuth: unreachable");
3272
+ }
3273
+
3274
+ // src/commands/auth.ts
3275
+ function registerAuthCommand(cli) {
3276
+ cli.command("auth", "Authenticate with 10xDevs via magic link").option("--email <email>", "Email address (skips interactive prompt)").option("--status", "Show current authentication state").option("--logout", "Delete locally stored credentials").action(async (options) => {
3277
+ const ctx = resolveContext(options);
3278
+ if (options.status) {
3279
+ runStatus(ctx);
3280
+ return;
3281
+ }
3282
+ if (options.logout) {
3283
+ runLogout(ctx);
3284
+ return;
3285
+ }
3286
+ await runLogin(ctx, options);
3287
+ });
3288
+ }
3289
+ function runStatus(ctx) {
3290
+ const auth = readAuth();
3291
+ if (!auth) {
3292
+ outputError(ctx, "auth_required", "You're not signed in.", ExitCodes.AUTH_REQUIRED, "Run '10x auth' to log in.");
3293
+ }
3294
+ const expired = isExpired(auth);
3295
+ const expiresAt = new Date(auth.expires_at);
3296
+ if (expired) {
3297
+ outputError(ctx, "auth_expired", `Your session for ${auth.email} has expired.`, ExitCodes.AUTH_REQUIRED, "Run '10x auth' to log in again.");
3298
+ }
3299
+ output(ctx, `Signed in as ${auth.email} — session expires ${formatExpiry(expiresAt)}.`, {
3300
+ email: auth.email,
3301
+ expires_at: auth.expires_at,
3302
+ is_valid: true
3303
+ });
3304
+ }
3305
+ function formatExpiry(expiresAt) {
3306
+ if (!Number.isFinite(expiresAt.getTime()))
3307
+ return "at an unknown time";
3308
+ const diffMs = expiresAt.getTime() - Date.now();
3309
+ if (diffMs <= 0)
3310
+ return "now";
3311
+ const days = Math.floor(diffMs / (24 * 60 * 60 * 1000));
3312
+ if (days >= 1)
3313
+ return `in ${days} day${days === 1 ? "" : "s"}`;
3314
+ const hours = Math.floor(diffMs / (60 * 60 * 1000));
3315
+ if (hours >= 1)
3316
+ return `in ${hours} hour${hours === 1 ? "" : "s"}`;
3317
+ const mins = Math.max(1, Math.floor(diffMs / (60 * 1000)));
3318
+ return `in ${mins} minute${mins === 1 ? "" : "s"}`;
3319
+ }
3320
+ function runLogout(ctx) {
3321
+ const had = readAuth() !== null;
3322
+ deleteAuth();
3323
+ output(ctx, had ? "Logged out successfully." : "Already logged out.", {
3324
+ logged_out: true,
3325
+ had_credentials: had
3326
+ });
3327
+ }
3328
+ async function runLogin(ctx, options) {
3329
+ const email = await collectEmail(ctx, options);
3330
+ if (!ctx.json)
3331
+ we("10x auth");
3332
+ const sp = ctx.json ? null : L2();
3333
+ sp?.start("Requesting magic link…");
3334
+ const login = await loginRequest(email);
3335
+ if (!login.ok) {
3336
+ sp?.stop("Magic link request failed.", 1);
3337
+ handleLoginError(ctx, login.status, login.code, login.error);
3338
+ }
3339
+ const { session_id } = login.data;
3340
+ sp?.stop(`Magic link sent to ${email}. Check your inbox.`);
3341
+ const pollSpinner = ctx.json ? null : L2();
3342
+ pollSpinner?.start("Waiting for magic link…");
3343
+ const result = await pollVerifySession(session_id, {
3344
+ onTick: (remainingMs) => {
3345
+ if (pollSpinner) {
3346
+ pollSpinner.message(`Waiting for magic link (${formatRemaining(remainingMs)} remaining)`);
3347
+ }
3348
+ }
3349
+ });
3350
+ if (result.kind === "verified") {
3351
+ pollSpinner?.stop("Authenticated.");
3352
+ const auth = {
3353
+ version: AUTH_FILE_VERSION,
3354
+ email,
3355
+ access_token: result.tokens.token,
3356
+ refresh_token: result.tokens.refresh_token,
3357
+ expires_at: result.tokens.expires_at,
3358
+ created_at: new Date().toISOString()
3359
+ };
3360
+ saveAuth(auth);
3361
+ if (!ctx.json)
3362
+ fe(`Signed in as ${email}.`);
3363
+ output(ctx, "", {
3364
+ authenticated: true,
3365
+ email,
3366
+ expires_at: auth.expires_at
3367
+ });
3368
+ return;
3369
+ }
3370
+ if (result.kind === "expired") {
3371
+ pollSpinner?.stop("Session expired.", 1);
3372
+ outputError(ctx, "session_expired", result.message || "Magic-link session expired before it was clicked.", ExitCodes.AUTH_REQUIRED, "Run '10x auth' again to request a fresh link.");
3373
+ }
3374
+ if (result.kind === "timeout") {
3375
+ pollSpinner?.stop("Timed out waiting for magic link.", 1);
3376
+ outputError(ctx, "auth_timeout", "Timed out waiting for the magic link to be clicked.", ExitCodes.ERROR, "Run '10x auth' to request a new link.");
3377
+ }
3378
+ if (result.kind === "aborted") {
3379
+ pollSpinner?.stop("Cancelled.", 1);
3380
+ outputError(ctx, "auth_cancelled", "Authentication cancelled.", ExitCodes.ERROR);
3381
+ }
3382
+ pollSpinner?.stop("Authentication failed.", 1);
3383
+ outputError(ctx, result.code || "auth_error", result.message || "Authentication failed.", ExitCodes.ERROR);
3384
+ }
3385
+ async function collectEmail(ctx, options) {
3386
+ if (options.email) {
3387
+ const trimmed = options.email.trim();
3388
+ if (!isLikelyEmail(trimmed)) {
3389
+ outputError(ctx, "invalid_email", `'${options.email}' does not look like an email address.`, ExitCodes.USAGE, "Pass your 10xDevs email, for example '10x auth --email you@example.com'.");
3390
+ }
3391
+ return trimmed;
3392
+ }
3393
+ if (ctx.json) {
3394
+ outputError(ctx, "missing_email", "Email is required in non-interactive mode.", ExitCodes.USAGE, "Pass --email, for example '10x auth --email you@example.com'.");
3395
+ }
3396
+ const answer = await ue({
3397
+ message: "Enter your 10xDevs email",
3398
+ placeholder: "you@example.com",
3399
+ validate: (value) => {
3400
+ if (!value || value.trim().length === 0)
3401
+ return "Email is required.";
3402
+ if (!isLikelyEmail(value.trim()))
3403
+ return "That does not look like an email address.";
3404
+ return;
3405
+ }
3406
+ });
3407
+ if (BD(answer)) {
3408
+ ve("Authentication cancelled.");
3409
+ outputError(ctx, "auth_cancelled", "Authentication cancelled.", ExitCodes.ERROR);
3410
+ }
3411
+ return answer.trim();
3412
+ }
3413
+ function isLikelyEmail(value) {
3414
+ return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
3415
+ }
3416
+ function formatRemaining(ms) {
3417
+ const totalSeconds = Math.max(0, Math.ceil(ms / 1000));
3418
+ const minutes = Math.floor(totalSeconds / 60);
3419
+ const seconds = totalSeconds % 60;
3420
+ return `${minutes}:${seconds.toString().padStart(2, "0")}`;
3421
+ }
3422
+ function handleLoginError(ctx, status, code, error) {
3423
+ verbose(ctx, `login failed: status=${status} code=${code}`);
3424
+ if (status === 403) {
3425
+ outputError(ctx, "no_access", "This email has no active 10xDevs course membership.", ExitCodes.FORBIDDEN, "Enroll at https://10xdevs.pl, then run '10x auth' again.");
3426
+ }
3427
+ if (status === 429) {
3428
+ outputError(ctx, "rate_limited", "Too many magic-link requests for this email.", ExitCodes.ERROR, "Wait a few minutes, then run '10x auth' again.");
3429
+ }
3430
+ if (status === 502) {
3431
+ outputError(ctx, "email_delivery_failed", "Could not send the magic-link email.", ExitCodes.ERROR, "Try '10x auth' again in a few minutes. If it keeps failing, contact support.");
3432
+ }
3433
+ if (status === 0) {
3434
+ outputError(ctx, "network_error", "Could not reach the 10x-toolkit API.", ExitCodes.ERROR, "Check your internet connection and run '10x auth' again.");
3435
+ }
3436
+ outputError(ctx, code || "auth_error", "Authentication failed.", ExitCodes.ERROR, error ? `Server said: ${error}` : undefined);
3437
+ }
3438
+
3439
+ // src/commands/doctor.ts
3440
+ import { existsSync as existsSync2, accessSync, constants } from "node:fs";
3441
+ import { join as join2 } from "node:path";
3442
+
3443
+ // src/lib/signing.ts
3444
+ import { createPublicKey, verify } from "node:crypto";
3445
+
3446
+ class SignatureError extends Error {
3447
+ constructor(message) {
3448
+ super(message);
3449
+ this.name = "SignatureError";
3450
+ }
3451
+ }
3452
+ var KEYSET = [
3453
+ {
3454
+ keyId: 1,
3455
+ publicKey: "MCowBQYDK2VwAyEANXEwq1y+9CYAJS6ze9m/c212fL4r1BauXwKdT6Zo5Ko="
3456
+ }
3457
+ ];
3458
+ var REQUIRE_SIGNATURES = true;
3459
+ function verifyBundleSignature(responseBody, signature, keyId) {
3460
+ const key = KEYSET.find((k3) => k3.keyId === keyId);
3461
+ if (!key) {
3462
+ throw new SignatureError(`Unknown signing key (key_id=${keyId}). Update your CLI: npm update -g @przeprogramowani/10x-cli`);
3463
+ }
3464
+ let pubKey;
3465
+ try {
3466
+ pubKey = createPublicKey({
3467
+ key: Buffer.from(key.publicKey, "base64"),
3468
+ format: "der",
3469
+ type: "spki"
3470
+ });
3471
+ } catch {
3472
+ throw new SignatureError("Failed to load the signing public key. Your CLI binary may be corrupted — reinstall it.");
3473
+ }
3474
+ const sig = Buffer.from(signature, "base64");
3475
+ const valid = verify(null, Buffer.from(responseBody), pubKey, sig);
3476
+ if (!valid) {
3477
+ throw new SignatureError("Bundle signature verification failed — the bundle may have been tampered with. " + "Do NOT use the content. Report this to the course team.");
3478
+ }
3479
+ }
3480
+
3481
+ // src/lib/api-content.ts
3482
+ function fetchCatalog(course, token, options = {}) {
3483
+ return apiGet(`/api/catalog/${encodeURIComponent(course)}`, { token, signal: options.signal });
3484
+ }
3485
+ function fetchModuleDetail(course, module, token, options = {}) {
3486
+ return apiGet(`/api/modules/${encodeURIComponent(course)}/${module}`, { token, signal: options.signal });
3487
+ }
3488
+ async function fetchLesson(course, lessonId, token, options = {}) {
3489
+ const result = await apiGet(`/api/lessons/${encodeURIComponent(course)}/${encodeURIComponent(lessonId)}`, { token, signal: options.signal });
3490
+ if (!result.ok)
3491
+ return result;
3492
+ const signature = result.responseHeaders.get("X-Bundle-Signature");
3493
+ const keyIdRaw = result.responseHeaders.get("X-Bundle-Key-Id");
3494
+ if (signature && keyIdRaw) {
3495
+ const keyId = Number(keyIdRaw);
3496
+ const responseBody = JSON.stringify(result.data);
3497
+ try {
3498
+ verifyBundleSignature(responseBody, signature, keyId);
3499
+ } catch (err) {
3500
+ const message = err instanceof Error ? err.message : String(err);
3501
+ return {
3502
+ ok: false,
3503
+ status: 0,
3504
+ code: err instanceof SignatureError ? "signature_error" : "signature_internal_error",
3505
+ error: message
3506
+ };
3507
+ }
3508
+ } else if (REQUIRE_SIGNATURES) {
3509
+ return {
3510
+ ok: false,
3511
+ status: 0,
3512
+ code: "signature_missing",
3513
+ error: "Bundle is missing a signature. The API may be misconfigured or compromised. " + "Do NOT use the content. Report this to the course team."
3514
+ };
3515
+ } else {
3516
+ process.stderr.write(`Warning: bundle is not signed. Signature verification skipped.
3517
+ `);
3518
+ }
3519
+ return result;
3520
+ }
3521
+ async function fetchHealth(options = {}) {
3522
+ const timeoutMs = options.timeoutMs ?? 5000;
3523
+ const controller = new AbortController;
3524
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
3525
+ const started = Date.now();
3526
+ try {
3527
+ const result = await apiGet("/health", { signal: controller.signal });
3528
+ const latencyMs = Date.now() - started;
3529
+ return { ...result, latencyMs };
3530
+ } catch (err) {
3531
+ const latencyMs = Date.now() - started;
3532
+ const aborted = controller.signal.aborted;
3533
+ return {
3534
+ ok: false,
3535
+ status: 0,
3536
+ code: aborted ? "timeout" : "network_error",
3537
+ error: err instanceof Error ? err.message : String(err),
3538
+ latencyMs
3539
+ };
3540
+ } finally {
3541
+ clearTimeout(timer);
3542
+ }
3543
+ }
3544
+ function apiBaseUrl() {
3545
+ return resolveApiBase();
3546
+ }
3547
+
3548
+ // src/lib/format.ts
3549
+ function formatReleaseAt(iso, now = new Date) {
3550
+ const date = new Date(iso);
3551
+ if (!Number.isFinite(date.getTime()))
3552
+ return iso;
3553
+ const absolute = date.toLocaleDateString("en-US", {
3554
+ year: "numeric",
3555
+ month: "long",
3556
+ day: "numeric",
3557
+ timeZone: "UTC"
3558
+ });
3559
+ const msPerDay = 24 * 60 * 60 * 1000;
3560
+ const startOfTarget = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
3561
+ const startOfNow = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
3562
+ const days = Math.round((startOfTarget - startOfNow) / msPerDay);
3563
+ if (days <= 0)
3564
+ return absolute;
3565
+ if (days === 1)
3566
+ return `${absolute} (tomorrow)`;
3567
+ return `${absolute} (in ${days} days)`;
3568
+ }
3569
+
3570
+ // src/commands/doctor.ts
3571
+ var EX_CONFIG = 78;
3572
+ function registerDoctorCommand(cli) {
3573
+ cli.command("doctor", "Diagnose auth, API, config, and .claude/ state").action(async (options) => {
3574
+ const ctx = resolveContext(options);
3575
+ await runDoctor(ctx);
3576
+ });
3577
+ }
3578
+ async function runDoctor(ctx) {
3579
+ verbose(ctx, "running doctor checks");
3580
+ const checks = [];
3581
+ checks.push(checkAuth());
3582
+ checks.push(await checkApiConnectivity());
3583
+ checks.push(checkConfigDirectory());
3584
+ checks.push(checkCliVersion());
3585
+ checks.push(checkClaudeDirectory());
3586
+ const failed = checks.filter((c2) => c2.status === "fail").length;
3587
+ const passed = checks.filter((c2) => c2.status === "pass").length;
3588
+ const warned = checks.filter((c2) => c2.status === "warn").length;
3589
+ if (ctx.json) {
3590
+ const overall = failed > 0 ? "error" : warned > 0 ? "warn" : "ok";
3591
+ const envelope = {
3592
+ overall,
3593
+ passed,
3594
+ failed,
3595
+ warned,
3596
+ checks: checks.map((c2) => ({
3597
+ name: c2.name,
3598
+ status: c2.status,
3599
+ message: c2.message,
3600
+ hint: c2.hint,
3601
+ details: c2.details ?? {}
3602
+ }))
3603
+ };
3604
+ process.stdout.write(`${JSON.stringify({ status: "ok", data: envelope })}
3605
+ `);
3606
+ if (failed > 0)
3607
+ process.exit(EX_CONFIG);
3608
+ return;
3609
+ }
3610
+ const lines = [];
3611
+ for (const c2 of checks) {
3612
+ const icon = c2.status === "pass" ? "✓" : c2.status === "warn" ? "!" : "✗";
3613
+ lines.push(`${icon} ${c2.label}: ${c2.message}`);
3614
+ if (c2.hint)
3615
+ lines.push(` → ${c2.hint}`);
3616
+ }
3617
+ lines.push("");
3618
+ const summary = [`${passed} passed`];
3619
+ if (warned > 0)
3620
+ summary.push(`${warned} warning${warned === 1 ? "" : "s"}`);
3621
+ if (failed > 0)
3622
+ summary.push(`${failed} failed`);
3623
+ lines.push(summary.join(", "));
3624
+ output(ctx, lines.join(`
3625
+ `), undefined);
3626
+ if (failed > 0) {
3627
+ process.exit(EX_CONFIG);
3628
+ }
3629
+ }
3630
+ function checkAuth() {
3631
+ const auth = readAuth();
3632
+ if (!auth) {
3633
+ return {
3634
+ name: "auth",
3635
+ label: "Auth",
3636
+ status: "fail",
3637
+ message: "You're not signed in.",
3638
+ hint: "Run '10x auth' to log in."
3639
+ };
3640
+ }
3641
+ if (isExpired(auth)) {
3642
+ return {
3643
+ name: "auth",
3644
+ label: "Auth",
3645
+ status: "fail",
3646
+ message: `Your session for ${auth.email} has expired.`,
3647
+ hint: "Run '10x auth' to log in again.",
3648
+ details: { email: auth.email, expires_at: auth.expires_at }
3649
+ };
3650
+ }
3651
+ const nearExpiry = isNearExpiry(auth);
3652
+ const prettyDate = formatReleaseAt(auth.expires_at);
3653
+ if (nearExpiry) {
3654
+ return {
3655
+ name: "auth",
3656
+ label: "Auth",
3657
+ status: "warn",
3658
+ message: `Signed in as ${auth.email}, but the session expires ${prettyDate.toLowerCase()}.`,
3659
+ hint: "The next command will transparently refresh the token.",
3660
+ details: { email: auth.email, expires_at: auth.expires_at }
3661
+ };
3662
+ }
3663
+ return {
3664
+ name: "auth",
3665
+ label: "Auth",
3666
+ status: "pass",
3667
+ message: `Signed in as ${auth.email} — session expires ${prettyDate.toLowerCase()}.`,
3668
+ details: { email: auth.email, expires_at: auth.expires_at }
3669
+ };
3670
+ }
3671
+ async function checkApiConnectivity() {
3672
+ const base = apiBaseUrl();
3673
+ const result = await fetchHealth({ timeoutMs: 5000 });
3674
+ if (result.ok) {
3675
+ return {
3676
+ name: "api",
3677
+ label: "API",
3678
+ status: "pass",
3679
+ message: `${base} reachable (${result.latencyMs} ms).`,
3680
+ details: { url: base, latencyMs: result.latencyMs, status: result.status }
3681
+ };
3682
+ }
3683
+ if (result.code === "timeout") {
3684
+ return {
3685
+ name: "api",
3686
+ label: "API",
3687
+ status: "fail",
3688
+ message: `${base} did not respond within 5s.`,
3689
+ hint: "Check your internet connection, then run '10x doctor' again.",
3690
+ details: { url: base, code: result.code, error: result.error }
3691
+ };
3692
+ }
3693
+ return {
3694
+ name: "api",
3695
+ label: "API",
3696
+ status: "fail",
3697
+ message: `${base} is unreachable.`,
3698
+ hint: "Check your internet connection, then run '10x doctor' again.",
3699
+ details: { url: base, code: result.code, error: result.error }
3700
+ };
3701
+ }
3702
+ function checkConfigDirectory() {
3703
+ const dir = configDir();
3704
+ if (!existsSync2(dir)) {
3705
+ return {
3706
+ name: "config",
3707
+ label: "Config",
3708
+ status: "pass",
3709
+ message: `${dir} will be created on first '10x auth'.`,
3710
+ details: { path: dir, exists: false }
3711
+ };
3712
+ }
3713
+ try {
3714
+ accessSync(dir, constants.W_OK);
3715
+ return {
3716
+ name: "config",
3717
+ label: "Config",
3718
+ status: "pass",
3719
+ message: `${dir} is writable.`,
3720
+ details: { path: dir, exists: true }
3721
+ };
3722
+ } catch (err) {
3723
+ return {
3724
+ name: "config",
3725
+ label: "Config",
3726
+ status: "fail",
3727
+ message: `${dir} is not writable.`,
3728
+ hint: `Fix directory permissions, then run '10x doctor' again. (${err instanceof Error ? err.message : String(err)})`,
3729
+ details: { path: dir, exists: true }
3730
+ };
3731
+ }
3732
+ }
3733
+ function checkCliVersion() {
3734
+ return {
3735
+ name: "version",
3736
+ label: "Version",
3737
+ status: "pass",
3738
+ message: `10x-cli ${package_default.version}.`,
3739
+ details: { version: package_default.version }
3740
+ };
3741
+ }
3742
+ function checkClaudeDirectory() {
3743
+ const cwd = process.cwd();
3744
+ const claudeDir = join2(cwd, ".claude");
3745
+ if (!existsSync2(claudeDir)) {
3746
+ return {
3747
+ name: "claude",
3748
+ label: "Claude",
3749
+ status: "fail",
3750
+ message: `.claude/ was not found in ${cwd}.`,
3751
+ hint: "Run '10x doctor' from a project directory that already has a .claude/ folder.",
3752
+ details: { path: claudeDir, exists: false }
3753
+ };
3754
+ }
3755
+ try {
3756
+ accessSync(claudeDir, constants.W_OK);
3757
+ return {
3758
+ name: "claude",
3759
+ label: "Claude",
3760
+ status: "pass",
3761
+ message: `${claudeDir} is writable.`,
3762
+ details: { path: claudeDir, exists: true }
3763
+ };
3764
+ } catch (err) {
3765
+ return {
3766
+ name: "claude",
3767
+ label: "Claude",
3768
+ status: "fail",
3769
+ message: `${claudeDir} is not writable.`,
3770
+ hint: `Fix directory permissions, then run '10x doctor' again. (${err instanceof Error ? err.message : String(err)})`,
3771
+ details: { path: claudeDir, exists: true }
3772
+ };
3773
+ }
3774
+ }
3775
+
3776
+ // src/lib/lesson-ref.ts
3777
+ var MIN_MODULE = 1;
3778
+ var MAX_MODULE = 5;
3779
+ var LESSON_REF_RE = /^m(\d+)l(\d+)$/;
3780
+ var MODULE_REF_RE = /^(?:m)?(\d+)$/;
3781
+ function parseLessonRef(raw) {
3782
+ if (typeof raw !== "string")
3783
+ return null;
3784
+ const match = LESSON_REF_RE.exec(raw);
3785
+ if (!match)
3786
+ return null;
3787
+ const module = Number.parseInt(match[1], 10);
3788
+ const lesson = Number.parseInt(match[2], 10);
3789
+ if (!Number.isFinite(module) || !Number.isFinite(lesson))
3790
+ return null;
3791
+ if (module < MIN_MODULE || module > MAX_MODULE)
3792
+ return null;
3793
+ if (lesson < 1)
3794
+ return null;
3795
+ return { lessonId: `m${module}l${lesson}`, module, lesson };
3796
+ }
3797
+ function parseModuleRef(raw) {
3798
+ if (typeof raw !== "string")
3799
+ return null;
3800
+ const match = MODULE_REF_RE.exec(raw);
3801
+ if (!match)
3802
+ return null;
3803
+ const module = Number.parseInt(match[1], 10);
3804
+ if (!Number.isFinite(module))
3805
+ return null;
3806
+ if (module < MIN_MODULE || module > MAX_MODULE)
3807
+ return null;
3808
+ return module;
3809
+ }
3810
+
3811
+ // src/lib/tool-profile.ts
3812
+ var PROFILES = {
3813
+ "claude-code": {
3814
+ toolId: "claude-code",
3815
+ displayName: "Claude Code",
3816
+ skillPath: (n) => `.claude/skills/${n}/SKILL.md`,
3817
+ promptPath: (n) => `.claude/prompts/${n}.md`,
3818
+ configPath: (n) => `.claude/config-templates/${n}`,
3819
+ rulesFile: "CLAUDE.md",
3820
+ manifestDir: ".claude",
3821
+ sentinelBegin: "<!-- BEGIN @przeprogramowani/10x-cli -->",
3822
+ sentinelEnd: "<!-- END @przeprogramowani/10x-cli -->"
3823
+ },
3824
+ cursor: {
3825
+ toolId: "cursor",
3826
+ displayName: "Cursor",
3827
+ skillPath: (n) => `.cursor/skills/${n}/SKILL.md`,
3828
+ promptPath: (n) => `.cursor/prompts/${n}.md`,
3829
+ configPath: (n) => `.cursor/config-templates/${n}`,
3830
+ rulesFile: ".cursor/rules/10x-course.mdc",
3831
+ manifestDir: ".cursor",
3832
+ sentinelBegin: "<!-- BEGIN @przeprogramowani/10x-cli -->",
3833
+ sentinelEnd: "<!-- END @przeprogramowani/10x-cli -->"
3834
+ },
3835
+ copilot: {
3836
+ toolId: "copilot",
3837
+ displayName: "GitHub Copilot",
3838
+ skillPath: (n) => `.github/skills/${n}/SKILL.md`,
3839
+ promptPath: (n) => `.github/prompts/${n}.md`,
3840
+ configPath: (n) => `.github/config-templates/${n}`,
3841
+ rulesFile: ".github/copilot-instructions.md",
3842
+ manifestDir: ".github",
3843
+ sentinelBegin: "<!-- BEGIN @przeprogramowani/10x-cli -->",
3844
+ sentinelEnd: "<!-- END @przeprogramowani/10x-cli -->"
3845
+ },
3846
+ codex: {
3847
+ toolId: "codex",
3848
+ displayName: "Codex CLI",
3849
+ skillPath: (n) => `.agents/skills/${n}/SKILL.md`,
3850
+ promptPath: (n) => `.agents/prompts/${n}.md`,
3851
+ configPath: (n) => `.agents/config-templates/${n}`,
3852
+ rulesFile: "AGENTS.md",
3853
+ manifestDir: ".agents",
3854
+ sentinelBegin: "<!-- BEGIN @przeprogramowani/10x-cli -->",
3855
+ sentinelEnd: "<!-- END @przeprogramowani/10x-cli -->"
3856
+ },
3857
+ generic: {
3858
+ toolId: "generic",
3859
+ displayName: "Other / Generic",
3860
+ skillPath: (n) => `.ai/skills/${n}/SKILL.md`,
3861
+ promptPath: (n) => `.ai/prompts/${n}.md`,
3862
+ configPath: (n) => `.ai/config-templates/${n}`,
3863
+ rulesFile: "AGENTS.md",
3864
+ manifestDir: ".ai",
3865
+ sentinelBegin: "<!-- BEGIN @przeprogramowani/10x-cli -->",
3866
+ sentinelEnd: "<!-- END @przeprogramowani/10x-cli -->"
3867
+ }
3868
+ };
3869
+ var DEFAULT_TOOL = "claude-code";
3870
+
3871
+ // src/lib/tool-prompt.ts
3872
+ async function resolveToolProfile(flagOverride) {
3873
+ if (flagOverride) {
3874
+ const profile = PROFILES[flagOverride];
3875
+ if (!profile) {
3876
+ throw new Error(`Unknown tool '${flagOverride}'. Supported: ${Object.keys(PROFILES).join(", ")}`);
3877
+ }
3878
+ return profile;
3879
+ }
3880
+ const config = readToolConfig();
3881
+ if (config?.tool && PROFILES[config.tool]) {
3882
+ return PROFILES[config.tool];
3883
+ }
3884
+ if (process.stdout.isTTY) {
3885
+ const choice = await de({
3886
+ message: "Which AI coding tool do you use?",
3887
+ options: Object.values(PROFILES).map((profile) => ({
3888
+ value: profile.toolId,
3889
+ label: profile.displayName,
3890
+ hint: profile.toolId === DEFAULT_TOOL ? "default" : undefined
3891
+ })),
3892
+ initialValue: DEFAULT_TOOL
3893
+ });
3894
+ if (BD(choice)) {
3895
+ ve("Using default (Claude Code).");
3896
+ return PROFILES[DEFAULT_TOOL];
3897
+ }
3898
+ saveToolConfig({ tool: choice });
3899
+ return PROFILES[choice];
3900
+ }
3901
+ return PROFILES[DEFAULT_TOOL];
3902
+ }
3903
+
3904
+ // src/lib/writer.ts
3905
+ import {
3906
+ existsSync as existsSync4,
3907
+ mkdirSync as mkdirSync4,
3908
+ readFileSync as readFileSync3,
3909
+ rmSync as rmSync2,
3910
+ writeFileSync as writeFileSync3
3911
+ } from "node:fs";
3912
+ import { dirname as dirname3, join as join4 } from "node:path";
3913
+
3914
+ // src/lib/manifest.ts
3915
+ import { existsSync as existsSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "node:fs";
3916
+ import { dirname as dirname2, join as join3 } from "node:path";
3917
+ var MANIFEST_FILENAME = ".10x-cli-manifest.json";
3918
+ var CLI_PACKAGE_NAME = "@przeprogramowani/10x-cli";
3919
+ function readManifest(dir) {
3920
+ const manifestPath = join3(dir, MANIFEST_FILENAME);
3921
+ if (!existsSync3(manifestPath))
3922
+ return null;
3923
+ let raw;
3924
+ try {
3925
+ raw = readFileSync2(manifestPath, "utf8");
3926
+ } catch {
3927
+ return null;
3928
+ }
3929
+ let parsed;
3930
+ try {
3931
+ parsed = JSON.parse(raw);
3932
+ } catch {
3933
+ return null;
3934
+ }
3935
+ if (!isManifest(parsed))
3936
+ return null;
3937
+ return parsed;
3938
+ }
3939
+ function writeManifest(dir, manifest) {
3940
+ if (!existsSync3(dir)) {
3941
+ mkdirSync3(dir, { recursive: true });
3942
+ }
3943
+ const manifestPath = join3(dir, MANIFEST_FILENAME);
3944
+ mkdirSync3(dirname2(manifestPath), { recursive: true });
3945
+ writeFileSync2(manifestPath, `${JSON.stringify(manifest, null, 2)}
3946
+ `);
3947
+ }
3948
+ function isManifest(value) {
3949
+ if (typeof value !== "object" || value === null)
3950
+ return false;
3951
+ const v2 = value;
3952
+ if (v2["package"] !== CLI_PACKAGE_NAME)
3953
+ return false;
3954
+ if (typeof v2["version"] !== "string")
3955
+ return false;
3956
+ if (typeof v2["lastApplied"] !== "string")
3957
+ return false;
3958
+ if (typeof v2["lessonId"] !== "string")
3959
+ return false;
3960
+ if (typeof v2["course"] !== "string")
3961
+ return false;
3962
+ const files = v2["files"];
3963
+ if (typeof files !== "object" || files === null)
3964
+ return false;
3965
+ const f2 = files;
3966
+ return isStringArray(f2["skills"]) && isStringArray(f2["prompts"]) && isStringArray(f2["configs"]);
3967
+ }
3968
+ function isStringArray(value) {
3969
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
3970
+ }
3971
+
3972
+ // src/lib/sentinel-migration.ts
3973
+ var OLD_BEGIN = "<!-- BEGIN @przeprogramowani/10x-toolkit -->";
3974
+ var OLD_END = "<!-- END @przeprogramowani/10x-toolkit -->";
3975
+ function applyRulesBlockWithMarkers(existingContent, rulesBody, beginMarker, endMarker) {
3976
+ for (const marker of [OLD_BEGIN, OLD_END, beginMarker, endMarker]) {
3977
+ if (rulesBody.includes(marker)) {
3978
+ throw new Error(`rules body contains a sentinel marker (${JSON.stringify(marker)}) — refusing to write to prevent rules file corruption`);
3979
+ }
3980
+ }
3981
+ const warnings = [];
3982
+ let content = existingContent;
3983
+ content = stripBlock(content, OLD_BEGIN, OLD_END, "@przeprogramowani/10x-toolkit", warnings);
3984
+ content = stripBlock(content, beginMarker, endMarker, "@przeprogramowani/10x-cli", warnings);
3985
+ content = content.replace(/\n{3,}/g, `
3986
+
3987
+ `).trim();
3988
+ const block = `${beginMarker}
3989
+
3990
+ ${rulesBody.trim()}
3991
+
3992
+ ${endMarker}`;
3993
+ const result = content.length > 0 ? `${content}
3994
+
3995
+ ${block}
3996
+ ` : `${block}
3997
+ `;
3998
+ return { content: result, warnings };
3999
+ }
4000
+ function stripBlock(content, begin, end, label, warnings) {
4001
+ const beginIdx = content.indexOf(begin);
4002
+ const endIdx = content.indexOf(end);
4003
+ if (beginIdx !== -1 && endIdx !== -1 && endIdx > beginIdx) {
4004
+ return content.slice(0, beginIdx) + content.slice(endIdx + end.length);
4005
+ }
4006
+ if (beginIdx !== -1 && endIdx === -1) {
4007
+ warnings.push(`CLAUDE.md has an orphan ${label} BEGIN marker; truncating from the marker onward.`);
4008
+ return content.slice(0, beginIdx);
4009
+ }
4010
+ if (beginIdx === -1 && endIdx !== -1) {
4011
+ warnings.push(`CLAUDE.md has an orphan ${label} END marker; truncating content before the marker.`);
4012
+ return content.slice(0, endIdx);
4013
+ }
4014
+ if (beginIdx !== -1 && endIdx !== -1 && endIdx < beginIdx) {
4015
+ warnings.push(`CLAUDE.md has out-of-order ${label} markers; repairing by truncating to the first marker.`);
4016
+ return content.slice(0, Math.min(beginIdx, endIdx));
4017
+ }
4018
+ return content;
4019
+ }
4020
+
4021
+ // src/lib/writer.ts
4022
+ var CLI_VERSION = package_default.version;
4023
+ var DEFAULT_COURSE = "10xdevs3";
4024
+ function applyBundle(bundle, projectRoot, options = {}) {
4025
+ const dryRun = options.dryRun === true;
4026
+ const course = options.course ?? DEFAULT_COURSE;
4027
+ const profile = options.profile ?? PROFILES[DEFAULT_TOOL];
4028
+ const manifestDir = join4(projectRoot, profile.manifestDir);
4029
+ const prevManifest = readManifest(manifestDir);
4030
+ for (const skill of bundle.skills)
4031
+ assertSafeName(skill.name, "skill");
4032
+ for (const prompt of bundle.prompts)
4033
+ assertSafeName(prompt.name, "prompt");
4034
+ for (const config of bundle.configs)
4035
+ assertSafeName(config.name, "config");
4036
+ const skills = bundle.skills.map((skill) => {
4037
+ const target = join4(projectRoot, profile.skillPath(skill.name));
4038
+ const action = computeFileAction(target, skill.content);
4039
+ if (!dryRun && action !== "unchanged") {
4040
+ writeFileAt(target, skill.content);
4041
+ }
4042
+ return { name: skill.name, path: target, action };
4043
+ });
4044
+ const prompts = bundle.prompts.map((prompt) => {
4045
+ const target = join4(projectRoot, profile.promptPath(prompt.name));
4046
+ const action = computeFileAction(target, prompt.content);
4047
+ if (!dryRun && action !== "unchanged") {
4048
+ writeFileAt(target, prompt.content);
4049
+ }
4050
+ return { name: prompt.name, path: target, action };
4051
+ });
4052
+ const rulesFilePath = join4(projectRoot, profile.rulesFile);
4053
+ const existingRules = readFileOrEmpty(rulesFilePath);
4054
+ let rulesAction;
4055
+ if (bundle.rules.length === 0) {
4056
+ rulesAction = "unchanged";
4057
+ } else {
4058
+ const rulesBody = bundle.rules.map((r2) => r2.content.trim()).join(`
4059
+
4060
+ `);
4061
+ const { content: newRules } = applyRulesBlockWithMarkers(existingRules, rulesBody, profile.sentinelBegin, profile.sentinelEnd);
4062
+ if (newRules === existingRules) {
4063
+ rulesAction = "unchanged";
4064
+ } else if (existingRules.length === 0) {
4065
+ rulesAction = "created";
4066
+ } else {
4067
+ rulesAction = "updated";
4068
+ }
4069
+ if (!dryRun && rulesAction !== "unchanged") {
4070
+ writeFileAt(rulesFilePath, newRules);
4071
+ }
4072
+ }
4073
+ const configs = bundle.configs.map((config) => {
4074
+ const target = join4(projectRoot, profile.configPath(config.name));
4075
+ const action = existsSync4(target) ? "skipped" : "created";
4076
+ if (!dryRun && action === "created") {
4077
+ writeFileAt(target, config.content);
4078
+ }
4079
+ return { name: config.name, path: target, action };
4080
+ });
4081
+ if (!dryRun) {
4082
+ const removed = computeRemovals(prevManifest, bundle, profile, projectRoot);
4083
+ for (const entry of removed.skills)
4084
+ rmSync2(entry.path, { recursive: true, force: true });
4085
+ for (const entry of removed.prompts)
4086
+ rmSync2(entry.path, { force: true });
4087
+ for (const entry of removed.configs)
4088
+ rmSync2(entry.path, { force: true });
4089
+ }
4090
+ if (!dryRun) {
4091
+ const nextManifest = {
4092
+ package: CLI_PACKAGE_NAME,
4093
+ version: CLI_VERSION,
4094
+ lastApplied: new Date().toISOString(),
4095
+ lessonId: bundle.lessonId,
4096
+ course,
4097
+ tool: profile.toolId,
4098
+ files: {
4099
+ skills: bundle.skills.map((s) => s.name),
4100
+ prompts: bundle.prompts.map((p2) => `${p2.name}.md`),
4101
+ configs: bundle.configs.map((c2) => c2.name)
4102
+ }
4103
+ };
4104
+ writeManifest(manifestDir, nextManifest);
4105
+ }
4106
+ return {
4107
+ skills,
4108
+ prompts,
4109
+ rules: { action: rulesAction },
4110
+ configs
4111
+ };
4112
+ }
4113
+ function computeFileAction(filePath, newContent) {
4114
+ if (!existsSync4(filePath))
4115
+ return "created";
4116
+ let current;
4117
+ try {
4118
+ current = readFileSync3(filePath, "utf8");
4119
+ } catch {
4120
+ return "updated";
4121
+ }
4122
+ return current === newContent ? "unchanged" : "updated";
4123
+ }
4124
+ function readFileOrEmpty(filePath) {
4125
+ if (!existsSync4(filePath))
4126
+ return "";
4127
+ try {
4128
+ return readFileSync3(filePath, "utf8");
4129
+ } catch {
4130
+ return "";
4131
+ }
4132
+ }
4133
+ function writeFileAt(filePath, content) {
4134
+ mkdirSync4(dirname3(filePath), { recursive: true });
4135
+ writeFileSync3(filePath, content);
4136
+ }
4137
+ function computeRemovals(prevManifest, bundle, profile, projectRoot) {
4138
+ const empty = { skills: [], prompts: [], configs: [] };
4139
+ if (!prevManifest)
4140
+ return empty;
4141
+ const currentSkills = new Set(bundle.skills.map((s) => s.name));
4142
+ const currentPrompts = new Set(bundle.prompts.map((p2) => `${p2.name}.md`));
4143
+ const currentConfigs = new Set(bundle.configs.map((c2) => c2.name));
4144
+ const removed = { skills: [], prompts: [], configs: [] };
4145
+ for (const skillName of prevManifest.files.skills) {
4146
+ if (currentSkills.has(skillName))
4147
+ continue;
4148
+ if (!isSafeName(skillName))
4149
+ continue;
4150
+ const skillTarget = join4(projectRoot, profile.skillPath(skillName));
4151
+ removed.skills.push({ name: skillName, path: dirname3(skillTarget) });
4152
+ }
4153
+ for (const promptFile of prevManifest.files.prompts) {
4154
+ if (currentPrompts.has(promptFile))
4155
+ continue;
4156
+ if (!isSafeName(promptFile))
4157
+ continue;
4158
+ const promptName = promptFile.replace(/\.md$/, "");
4159
+ removed.prompts.push({
4160
+ name: promptFile,
4161
+ path: join4(projectRoot, profile.promptPath(promptName))
4162
+ });
4163
+ }
4164
+ for (const configFile of prevManifest.files.configs) {
4165
+ if (currentConfigs.has(configFile))
4166
+ continue;
4167
+ if (!isSafeName(configFile))
4168
+ continue;
4169
+ removed.configs.push({
4170
+ name: configFile,
4171
+ path: join4(projectRoot, profile.configPath(configFile))
4172
+ });
4173
+ }
4174
+ return removed;
4175
+ }
4176
+ function detectOrphanedArtifacts(projectRoot, currentProfile) {
4177
+ for (const profile of Object.values(PROFILES)) {
4178
+ if (profile.toolId === currentProfile.toolId)
4179
+ continue;
4180
+ const otherManifest = join4(projectRoot, profile.manifestDir, MANIFEST_FILENAME);
4181
+ if (existsSync4(otherManifest)) {
4182
+ return `Found existing 10x artifacts in ${profile.manifestDir}/ from ${profile.displayName}.
4183
+ Manually remove ${profile.manifestDir}/ if you no longer need it.
4184
+ Your new artifacts will be written to ${currentProfile.manifestDir}/`;
4185
+ }
4186
+ }
4187
+ return null;
4188
+ }
4189
+ function assertSafeName(name, kind) {
4190
+ if (!isSafeName(name)) {
4191
+ throw new Error(`refused to write unsafe ${kind} name ${JSON.stringify(name)} — must not be empty, contain path separators, or start with '.'`);
4192
+ }
4193
+ }
4194
+ function isSafeName(name) {
4195
+ if (typeof name !== "string" || name.length === 0)
4196
+ return false;
4197
+ if (name.startsWith("."))
4198
+ return false;
4199
+ if (name.includes("/") || name.includes("\\"))
4200
+ return false;
4201
+ if (name.includes("\x00"))
4202
+ return false;
4203
+ if (name.includes(":"))
4204
+ return false;
4205
+ if (/[<>"|?*]/.test(name))
4206
+ return false;
4207
+ if (/[. ]$/.test(name))
4208
+ return false;
4209
+ const base = name.split(".")[0].toUpperCase();
4210
+ if (/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/.test(base))
4211
+ return false;
4212
+ return true;
4213
+ }
4214
+
4215
+ // src/commands/get.ts
4216
+ var DEFAULT_COURSE2 = "10xdevs3";
4217
+ function registerGetCommand(cli) {
4218
+ cli.command("get <ref>", "Fetch and apply a lesson pack").option("--dry-run", "Show what would be written without touching the filesystem").option("--course <course>", "Override the course slug (default: 10xdevs3)").option("--tool <tool>", "AI coding tool (claude-code, cursor, copilot, codex, generic)").action(async (ref, options) => {
4219
+ const ctx = resolveContext(options);
4220
+ await runGet(ctx, ref, options);
4221
+ });
4222
+ }
4223
+ async function runGet(ctx, ref, options) {
4224
+ const parsed = parseLessonRef(ref);
4225
+ if (!parsed) {
4226
+ outputError(ctx, "invalid_lesson_ref", `'${ref}' is not a valid lesson reference.`, ExitCodes.USAGE, "Use the form 'm<module>l<lesson>', for example 'm1l1' or 'm2l3'.");
4227
+ }
4228
+ const auth = await requireAuth(ctx);
4229
+ const course = options.course ?? DEFAULT_COURSE2;
4230
+ const profile = await resolveToolProfile(options.tool);
4231
+ verbose(ctx, `fetching lesson ${course}/${parsed.lessonId}`);
4232
+ const result = await fetchLesson(course, parsed.lessonId, auth.access_token);
4233
+ if (!result.ok) {
4234
+ handleLessonError(ctx, result.status, result.code, result.error, result.payload);
4235
+ }
4236
+ const orphanWarning = detectOrphanedArtifacts(process.cwd(), profile);
4237
+ if (orphanWarning)
4238
+ verbose(ctx, orphanWarning);
4239
+ const bundle = result.data;
4240
+ const writeResult = applyBundle(bundle, process.cwd(), {
4241
+ dryRun: options.dryRun === true,
4242
+ profile
4243
+ });
4244
+ renderGetResult(ctx, bundle, writeResult, options.dryRun === true, profile);
4245
+ }
4246
+ function handleLessonError(ctx, status, code, error, payload) {
4247
+ verbose(ctx, `lesson fetch failed: status=${status} code=${code}`);
4248
+ if (status === 403) {
4249
+ const moduleNum = payload?.["module"];
4250
+ const releaseAt = payload?.["releaseAt"];
4251
+ const hasModule = typeof moduleNum === "number";
4252
+ const hasRelease = typeof releaseAt === "string";
4253
+ let message;
4254
+ if (hasModule && hasRelease) {
4255
+ message = `Module ${moduleNum} unlocks on ${formatReleaseAt(releaseAt)}.`;
4256
+ } else if (hasModule) {
4257
+ message = `Module ${moduleNum} is locked.`;
4258
+ } else if (hasRelease) {
4259
+ message = `This module unlocks on ${formatReleaseAt(releaseAt)}.`;
4260
+ } else {
4261
+ message = "This module is locked.";
4262
+ }
4263
+ outputError(ctx, "module_locked", message, ExitCodes.FORBIDDEN, "Run '10x list' to see what's available now.");
4264
+ }
4265
+ if (status === 404) {
4266
+ outputError(ctx, "lesson_not_found", "Couldn't find that lesson.", ExitCodes.NOT_FOUND, "Run '10x list' to see available modules, then '10x list 1' to see lessons inside module 1.");
4267
+ }
4268
+ if (status === 401) {
4269
+ outputError(ctx, "auth_required", "Your session is no longer valid.", ExitCodes.AUTH_REQUIRED, "Run '10x auth' to log in again.");
4270
+ }
4271
+ if (code === "signature_error" || code === "signature_missing" || code === "signature_internal_error") {
4272
+ outputError(ctx, code, error, ExitCodes.ERROR);
4273
+ }
4274
+ if (status === 0) {
4275
+ outputError(ctx, "network_error", "Could not reach the 10x-toolkit API.", ExitCodes.ERROR, "Check your internet connection and run the command again.");
4276
+ }
4277
+ outputError(ctx, code || "lesson_fetch_failed", "Failed to fetch the lesson bundle.", ExitCodes.ERROR, error ? `Server said: ${error}` : undefined);
4278
+ }
4279
+ function renderGetResult(ctx, bundle, writeResult, dryRun, profile) {
4280
+ if (ctx.json) {
4281
+ output(ctx, "", {
4282
+ lessonId: bundle.lessonId,
4283
+ title: bundle.title,
4284
+ summary: bundle.summary,
4285
+ tool: profile.toolId,
4286
+ dry_run: dryRun,
4287
+ writes: {
4288
+ skills: writeResult.skills,
4289
+ prompts: writeResult.prompts,
4290
+ rules: writeResult.rules,
4291
+ configs: writeResult.configs
4292
+ },
4293
+ counts: {
4294
+ skills: writeResult.skills.length,
4295
+ prompts: writeResult.prompts.length,
4296
+ rules: bundle.rules.length,
4297
+ configs: writeResult.configs.length
4298
+ }
4299
+ });
4300
+ return;
4301
+ }
4302
+ const targetDir = profile.manifestDir;
4303
+ const lines = [];
4304
+ lines.push(`${bundle.lessonId} — ${bundle.title}`);
4305
+ if (bundle.summary)
4306
+ lines.push(bundle.summary);
4307
+ lines.push("");
4308
+ lines.push(dryRun ? `Would write to ${targetDir}/:` : `Wrote to ${targetDir}/:`);
4309
+ for (const skill of writeResult.skills) {
4310
+ lines.push(` [${skill.action}] skill ${skill.path}`);
4311
+ }
4312
+ for (const prompt of writeResult.prompts) {
4313
+ lines.push(` [${prompt.action}] prompt ${prompt.path}`);
4314
+ }
4315
+ if (bundle.rules.length > 0) {
4316
+ lines.push(` [${writeResult.rules.action}] rules ${profile.rulesFile} (${bundle.rules.length} block${bundle.rules.length === 1 ? "" : "s"})`);
4317
+ }
4318
+ for (const config of writeResult.configs) {
4319
+ lines.push(` [${config.action}] config ${config.path}`);
4320
+ }
4321
+ output(ctx, lines.join(`
4322
+ `), undefined);
4323
+ }
4324
+
4325
+ // src/commands/list.ts
4326
+ var DEFAULT_COURSE3 = "10xdevs3";
4327
+ function registerListCommand(cli) {
4328
+ cli.command("list [module]", "Browse available modules and lessons").option("--course <course>", "Override the course slug (default: 10xdevs3)").action(async (moduleArg, options) => {
4329
+ const ctx = resolveContext(options);
4330
+ await runList(ctx, moduleArg, options);
4331
+ });
4332
+ }
4333
+ async function runList(ctx, moduleArg, options) {
4334
+ const auth = await requireAuth(ctx);
4335
+ const course = options.course ?? DEFAULT_COURSE3;
4336
+ if (moduleArg === undefined) {
4337
+ await listAllModules(ctx, course, auth.access_token);
4338
+ return;
4339
+ }
4340
+ const module = parseModuleRef(moduleArg);
4341
+ if (module === null) {
4342
+ outputError(ctx, "invalid_module", `'${moduleArg}' is not a valid module reference.`, ExitCodes.USAGE, `Pass a module between ${MIN_MODULE} and ${MAX_MODULE}, for example '10x list 1' or '10x list m1'.`);
4343
+ }
4344
+ await listModuleDetail(ctx, course, module, auth.access_token);
4345
+ }
4346
+ async function listAllModules(ctx, course, token) {
4347
+ verbose(ctx, `fetching catalog for ${course}`);
4348
+ const result = await fetchCatalog(course, token);
4349
+ if (!result.ok) {
4350
+ handleListError(ctx, result.status, result.code, result.error);
4351
+ }
4352
+ renderCatalog(ctx, result.data);
4353
+ }
4354
+ async function listModuleDetail(ctx, course, module, token) {
4355
+ verbose(ctx, `fetching module detail ${course}/${module}`);
4356
+ const result = await fetchModuleDetail(course, module, token);
4357
+ if (!result.ok) {
4358
+ handleListError(ctx, result.status, result.code, result.error);
4359
+ }
4360
+ renderModuleDetail(ctx, result.data);
4361
+ }
4362
+ function handleListError(ctx, status, code, error) {
4363
+ if (status === 404) {
4364
+ outputError(ctx, "not_found", "Couldn't find that course or module.", ExitCodes.NOT_FOUND, "Run '10x list' to see available modules.");
4365
+ }
4366
+ if (status === 401) {
4367
+ outputError(ctx, "auth_required", "Your session is no longer valid.", ExitCodes.AUTH_REQUIRED, "Run '10x auth' to log in again.");
4368
+ }
4369
+ if (status === 0) {
4370
+ outputError(ctx, "network_error", "Could not reach the 10x-toolkit API.", ExitCodes.ERROR, "Check your internet connection and run '10x list' again.");
4371
+ }
4372
+ outputError(ctx, code || "list_failed", "Failed to load the catalog.", ExitCodes.ERROR, error ? `Server said: ${error}` : undefined);
4373
+ }
4374
+ function renderCatalog(ctx, catalog) {
4375
+ const lessonCountByModule = new Map;
4376
+ for (const lesson of catalog.lessons) {
4377
+ lessonCountByModule.set(lesson.module, (lessonCountByModule.get(lesson.module) ?? 0) + 1);
4378
+ }
4379
+ if (ctx.json) {
4380
+ output(ctx, "", {
4381
+ course: catalog.course,
4382
+ modules: catalog.modules.map((m3) => ({
4383
+ module: m3.module,
4384
+ title: m3.title,
4385
+ state: m3.effectiveState,
4386
+ releaseAt: m3.releaseAt,
4387
+ lessonCount: lessonCountByModule.get(m3.module) ?? 0
4388
+ }))
4389
+ });
4390
+ return;
4391
+ }
4392
+ if (catalog.modules.length === 0) {
4393
+ output(ctx, `No modules available in '${catalog.course}'.`, undefined);
4394
+ return;
4395
+ }
4396
+ const exampleModule = catalog.modules.find((m3) => m3.effectiveState === "unlocked")?.module ?? catalog.modules[0]?.module ?? 1;
4397
+ const lines = [];
4398
+ lines.push(`Course: ${catalog.course}`);
4399
+ lines.push("");
4400
+ for (const m3 of catalog.modules) {
4401
+ lines.push(formatModuleRow(m3, lessonCountByModule.get(m3.module) ?? 0));
4402
+ }
4403
+ lines.push("");
4404
+ lines.push(`See lessons in a module: 10x list ${exampleModule} (or '10x list m${exampleModule}')`);
4405
+ output(ctx, lines.join(`
4406
+ `), undefined);
4407
+ }
4408
+ function formatModuleRow(m3, lessonCount) {
4409
+ const icon = m3.effectiveState === "unlocked" ? "✓" : "✗";
4410
+ const state = m3.effectiveState === "unlocked" ? "unlocked" : `locked — unlocks ${formatReleaseAt(m3.releaseAt)}`;
4411
+ const label = `Module ${m3.module}: ${m3.title}`;
4412
+ return ` ${icon} ${label} — ${lessonCount} lesson${lessonCount === 1 ? "" : "s"} [${state}]`;
4413
+ }
4414
+ function renderModuleDetail(ctx, module) {
4415
+ if (ctx.json) {
4416
+ output(ctx, "", {
4417
+ module: module.module,
4418
+ title: module.title,
4419
+ state: module.effectiveState,
4420
+ releaseAt: module.releaseAt,
4421
+ lessons: module.lessons.map((l2) => ({
4422
+ lessonId: l2.lessonId,
4423
+ lesson: l2.lesson,
4424
+ title: l2.title,
4425
+ summary: l2.summary
4426
+ }))
4427
+ });
4428
+ return;
4429
+ }
4430
+ const stateLabel = module.effectiveState === "unlocked" ? "unlocked" : `locked — unlocks ${formatReleaseAt(module.releaseAt)}`;
4431
+ const lines = [];
4432
+ lines.push(`Module ${module.module}: ${module.title} [${stateLabel}]`);
4433
+ lines.push("");
4434
+ if (module.lessons.length === 0) {
4435
+ lines.push(" (no lessons in this module)");
4436
+ } else {
4437
+ for (const l2 of module.lessons) {
4438
+ lines.push(` ${l2.lessonId} — ${l2.title}`);
4439
+ if (l2.summary)
4440
+ lines.push(` ${l2.summary}`);
4441
+ }
4442
+ }
4443
+ output(ctx, lines.join(`
4444
+ `), undefined);
4445
+ }
4446
+
4447
+ // src/index.ts
4448
+ var cli = cac("10x");
4449
+ cli.option("--json", "Output as JSON (auto-detected when piped)");
4450
+ cli.option("--verbose", "Show detailed output on stderr");
4451
+ registerAuthCommand(cli);
4452
+ registerGetCommand(cli);
4453
+ registerListCommand(cli);
4454
+ registerDoctorCommand(cli);
4455
+ cli.help();
4456
+ cli.version(package_default.version);
4457
+ try {
4458
+ cli.parse();
4459
+ } catch (err) {
4460
+ const message = err instanceof Error ? err.message : String(err);
4461
+ process.stderr.write(`ERROR usage: ${message}
4462
+ `);
4463
+ process.exit(2);
4464
+ }