@kscs-inc/cli 0.0.0-stage → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/kscs.mjs ADDED
@@ -0,0 +1,2015 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as npmCreateRequire } from 'node:module'; const require = npmCreateRequire(import.meta.url);
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
10
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
11
+ }) : x)(function(x) {
12
+ if (typeof require !== "undefined") return require.apply(this, arguments);
13
+ throw Error('Dynamic require of "' + x + '" is not supported');
14
+ });
15
+ var __commonJS = (cb, mod) => function __require2() {
16
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
27
+ // If the importer is in node compatibility mode or this is not an ESM
28
+ // file that has been converted to a CommonJS file using a Babel-
29
+ // compatible transform (i.e. "__esModule" has not been set), then set
30
+ // "default" to the CommonJS "module.exports" for node compatibility.
31
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
32
+ mod
33
+ ));
34
+
35
+ // ../../../../../code/node_modules/.pnpm/pend@1.2.0/node_modules/pend/index.js
36
+ var require_pend = __commonJS({
37
+ "../../../../../code/node_modules/.pnpm/pend@1.2.0/node_modules/pend/index.js"(exports, module) {
38
+ module.exports = Pend;
39
+ function Pend() {
40
+ this.pending = 0;
41
+ this.max = Infinity;
42
+ this.listeners = [];
43
+ this.waiting = [];
44
+ this.error = null;
45
+ }
46
+ Pend.prototype.go = function(fn) {
47
+ if (this.pending < this.max) {
48
+ pendGo(this, fn);
49
+ } else {
50
+ this.waiting.push(fn);
51
+ }
52
+ };
53
+ Pend.prototype.wait = function(cb) {
54
+ if (this.pending === 0) {
55
+ cb(this.error);
56
+ } else {
57
+ this.listeners.push(cb);
58
+ }
59
+ };
60
+ Pend.prototype.hold = function() {
61
+ return pendHold(this);
62
+ };
63
+ function pendHold(self) {
64
+ self.pending += 1;
65
+ var called = false;
66
+ return onCb;
67
+ function onCb(err) {
68
+ if (called) throw new Error("callback called twice");
69
+ called = true;
70
+ self.error = self.error || err;
71
+ self.pending -= 1;
72
+ if (self.waiting.length > 0 && self.pending < self.max) {
73
+ pendGo(self, self.waiting.shift());
74
+ } else if (self.pending === 0) {
75
+ var listeners = self.listeners;
76
+ self.listeners = [];
77
+ listeners.forEach(cbListener);
78
+ }
79
+ }
80
+ function cbListener(listener) {
81
+ listener(self.error);
82
+ }
83
+ }
84
+ function pendGo(self, fn) {
85
+ fn(pendHold(self));
86
+ }
87
+ }
88
+ });
89
+
90
+ // ../../../../../code/node_modules/.pnpm/yauzl@3.4.0/node_modules/yauzl/fd-slicer.js
91
+ var require_fd_slicer = __commonJS({
92
+ "../../../../../code/node_modules/.pnpm/yauzl@3.4.0/node_modules/yauzl/fd-slicer.js"(exports) {
93
+ var fs = __require("fs");
94
+ var util = __require("util");
95
+ var stream = __require("stream");
96
+ var Readable = stream.Readable;
97
+ var PassThrough = stream.PassThrough;
98
+ var Pend = require_pend();
99
+ var EventEmitter = __require("events").EventEmitter;
100
+ exports.BufferSlicer = BufferSlicer;
101
+ exports.FdSlicer = FdSlicer;
102
+ util.inherits(FdSlicer, EventEmitter);
103
+ function FdSlicer(fd) {
104
+ EventEmitter.call(this);
105
+ this.fd = fd;
106
+ this.pend = new Pend();
107
+ this.pend.max = 1;
108
+ this.refCount = 0;
109
+ }
110
+ FdSlicer.prototype.read = function(buffer, offset, length, position, callback) {
111
+ var self = this;
112
+ self.pend.go(function(cb) {
113
+ fs.read(self.fd, buffer, offset, length, position, function(err, bytesRead, buffer2) {
114
+ cb();
115
+ callback(err, bytesRead, buffer2);
116
+ });
117
+ });
118
+ };
119
+ FdSlicer.prototype.createReadStream = function(options2) {
120
+ return new ReadStream(this, options2);
121
+ };
122
+ FdSlicer.prototype.ref = function() {
123
+ this.refCount += 1;
124
+ };
125
+ FdSlicer.prototype.unref = function() {
126
+ var self = this;
127
+ self.refCount -= 1;
128
+ if (self.refCount < 0) throw new Error("invalid unref");
129
+ if (self.refCount > 0) return;
130
+ fs.close(self.fd, onCloseDone);
131
+ function onCloseDone(err) {
132
+ if (err) {
133
+ self.emit("error", err);
134
+ } else {
135
+ self.emit("close");
136
+ }
137
+ }
138
+ };
139
+ util.inherits(ReadStream, Readable);
140
+ function ReadStream(context, options2) {
141
+ options2 = options2 || {};
142
+ Readable.call(this, options2);
143
+ this.context = context;
144
+ this.context.ref();
145
+ this.start = options2.start || 0;
146
+ this.endOffset = options2.end;
147
+ this.pos = this.start;
148
+ }
149
+ ReadStream.prototype._read = function(n) {
150
+ var self = this;
151
+ var toRead = Math.min(self._readableState.highWaterMark, n);
152
+ if (self.endOffset != null) {
153
+ toRead = Math.min(toRead, self.endOffset - self.pos);
154
+ }
155
+ if (toRead <= 0) {
156
+ self.push(null);
157
+ this._cleanup();
158
+ return;
159
+ }
160
+ self.context.pend.go(function(cb) {
161
+ var buffer = Buffer.allocUnsafe(toRead);
162
+ fs.read(self.context.fd, buffer, 0, toRead, self.pos, function(err, bytesRead) {
163
+ if (err) {
164
+ self.destroy(err);
165
+ } else if (bytesRead === 0) {
166
+ self.push(null);
167
+ self._cleanup();
168
+ } else {
169
+ self.pos += bytesRead;
170
+ self.push(buffer.slice(0, bytesRead));
171
+ }
172
+ cb();
173
+ });
174
+ });
175
+ };
176
+ ReadStream.prototype._destroy = function(err, cb) {
177
+ this._cleanup();
178
+ cb(err);
179
+ };
180
+ ReadStream.prototype._cleanup = function() {
181
+ if (this.context != null) {
182
+ this.context.unref();
183
+ this.context = null;
184
+ }
185
+ };
186
+ util.inherits(BufferSlicer, EventEmitter);
187
+ function BufferSlicer(buffer) {
188
+ EventEmitter.call(this);
189
+ this.refCount = 0;
190
+ this.buffer = buffer;
191
+ }
192
+ BufferSlicer.prototype.read = function(buffer, offset, length, position, callback) {
193
+ if (!(0 <= offset && offset <= buffer.length)) throw new RangeError("offset outside buffer: 0 <= " + offset + " <= " + buffer.length);
194
+ if (position < 0) throw new RangeError("position is negative: " + position);
195
+ if (offset + length > buffer.length) {
196
+ length = buffer.length - offset;
197
+ }
198
+ if (position + length > this.buffer.length) {
199
+ length = this.buffer.length - position;
200
+ }
201
+ if (length <= 0) {
202
+ setImmediate(function() {
203
+ callback(null, 0);
204
+ });
205
+ return;
206
+ }
207
+ this.buffer.copy(buffer, offset, position, position + length);
208
+ setImmediate(function() {
209
+ callback(null, length);
210
+ });
211
+ };
212
+ BufferSlicer.prototype.createReadStream = function(options2) {
213
+ options2 = options2 || {};
214
+ var readStream = new PassThrough(options2);
215
+ readStream.start = options2.start || 0;
216
+ readStream.endOffset = options2.end;
217
+ readStream.pos = readStream.endOffset || this.buffer.length;
218
+ var entireSlice = this.buffer.slice(readStream.start, readStream.pos);
219
+ var maxChunkSize = 65536;
220
+ var offset = 0;
221
+ while (true) {
222
+ var nextOffset = offset + maxChunkSize;
223
+ if (nextOffset >= entireSlice.length) {
224
+ if (offset < entireSlice.length) {
225
+ readStream.write(entireSlice.slice(offset, entireSlice.length));
226
+ }
227
+ break;
228
+ }
229
+ readStream.write(entireSlice.slice(offset, nextOffset));
230
+ offset = nextOffset;
231
+ }
232
+ readStream.end();
233
+ return readStream;
234
+ };
235
+ BufferSlicer.prototype.ref = function() {
236
+ this.refCount += 1;
237
+ };
238
+ BufferSlicer.prototype.unref = function() {
239
+ this.refCount -= 1;
240
+ if (this.refCount < 0) {
241
+ throw new Error("invalid unref");
242
+ }
243
+ };
244
+ }
245
+ });
246
+
247
+ // ../../../../../code/node_modules/.pnpm/yauzl@3.4.0/node_modules/yauzl/crc32.js
248
+ var require_crc32 = __commonJS({
249
+ "../../../../../code/node_modules/.pnpm/yauzl@3.4.0/node_modules/yauzl/crc32.js"(exports, module) {
250
+ var CRC_TABLE = new Int32Array([
251
+ 0,
252
+ 1996959894,
253
+ 3993919788,
254
+ 2567524794,
255
+ 124634137,
256
+ 1886057615,
257
+ 3915621685,
258
+ 2657392035,
259
+ 249268274,
260
+ 2044508324,
261
+ 3772115230,
262
+ 2547177864,
263
+ 162941995,
264
+ 2125561021,
265
+ 3887607047,
266
+ 2428444049,
267
+ 498536548,
268
+ 1789927666,
269
+ 4089016648,
270
+ 2227061214,
271
+ 450548861,
272
+ 1843258603,
273
+ 4107580753,
274
+ 2211677639,
275
+ 325883990,
276
+ 1684777152,
277
+ 4251122042,
278
+ 2321926636,
279
+ 335633487,
280
+ 1661365465,
281
+ 4195302755,
282
+ 2366115317,
283
+ 997073096,
284
+ 1281953886,
285
+ 3579855332,
286
+ 2724688242,
287
+ 1006888145,
288
+ 1258607687,
289
+ 3524101629,
290
+ 2768942443,
291
+ 901097722,
292
+ 1119000684,
293
+ 3686517206,
294
+ 2898065728,
295
+ 853044451,
296
+ 1172266101,
297
+ 3705015759,
298
+ 2882616665,
299
+ 651767980,
300
+ 1373503546,
301
+ 3369554304,
302
+ 3218104598,
303
+ 565507253,
304
+ 1454621731,
305
+ 3485111705,
306
+ 3099436303,
307
+ 671266974,
308
+ 1594198024,
309
+ 3322730930,
310
+ 2970347812,
311
+ 795835527,
312
+ 1483230225,
313
+ 3244367275,
314
+ 3060149565,
315
+ 1994146192,
316
+ 31158534,
317
+ 2563907772,
318
+ 4023717930,
319
+ 1907459465,
320
+ 112637215,
321
+ 2680153253,
322
+ 3904427059,
323
+ 2013776290,
324
+ 251722036,
325
+ 2517215374,
326
+ 3775830040,
327
+ 2137656763,
328
+ 141376813,
329
+ 2439277719,
330
+ 3865271297,
331
+ 1802195444,
332
+ 476864866,
333
+ 2238001368,
334
+ 4066508878,
335
+ 1812370925,
336
+ 453092731,
337
+ 2181625025,
338
+ 4111451223,
339
+ 1706088902,
340
+ 314042704,
341
+ 2344532202,
342
+ 4240017532,
343
+ 1658658271,
344
+ 366619977,
345
+ 2362670323,
346
+ 4224994405,
347
+ 1303535960,
348
+ 984961486,
349
+ 2747007092,
350
+ 3569037538,
351
+ 1256170817,
352
+ 1037604311,
353
+ 2765210733,
354
+ 3554079995,
355
+ 1131014506,
356
+ 879679996,
357
+ 2909243462,
358
+ 3663771856,
359
+ 1141124467,
360
+ 855842277,
361
+ 2852801631,
362
+ 3708648649,
363
+ 1342533948,
364
+ 654459306,
365
+ 3188396048,
366
+ 3373015174,
367
+ 1466479909,
368
+ 544179635,
369
+ 3110523913,
370
+ 3462522015,
371
+ 1591671054,
372
+ 702138776,
373
+ 2966460450,
374
+ 3352799412,
375
+ 1504918807,
376
+ 783551873,
377
+ 3082640443,
378
+ 3233442989,
379
+ 3988292384,
380
+ 2596254646,
381
+ 62317068,
382
+ 1957810842,
383
+ 3939845945,
384
+ 2647816111,
385
+ 81470997,
386
+ 1943803523,
387
+ 3814918930,
388
+ 2489596804,
389
+ 225274430,
390
+ 2053790376,
391
+ 3826175755,
392
+ 2466906013,
393
+ 167816743,
394
+ 2097651377,
395
+ 4027552580,
396
+ 2265490386,
397
+ 503444072,
398
+ 1762050814,
399
+ 4150417245,
400
+ 2154129355,
401
+ 426522225,
402
+ 1852507879,
403
+ 4275313526,
404
+ 2312317920,
405
+ 282753626,
406
+ 1742555852,
407
+ 4189708143,
408
+ 2394877945,
409
+ 397917763,
410
+ 1622183637,
411
+ 3604390888,
412
+ 2714866558,
413
+ 953729732,
414
+ 1340076626,
415
+ 3518719985,
416
+ 2797360999,
417
+ 1068828381,
418
+ 1219638859,
419
+ 3624741850,
420
+ 2936675148,
421
+ 906185462,
422
+ 1090812512,
423
+ 3747672003,
424
+ 2825379669,
425
+ 829329135,
426
+ 1181335161,
427
+ 3412177804,
428
+ 3160834842,
429
+ 628085408,
430
+ 1382605366,
431
+ 3423369109,
432
+ 3138078467,
433
+ 570562233,
434
+ 1426400815,
435
+ 3317316542,
436
+ 2998733608,
437
+ 733239954,
438
+ 1555261956,
439
+ 3268935591,
440
+ 3050360625,
441
+ 752459403,
442
+ 1541320221,
443
+ 2607071920,
444
+ 3965973030,
445
+ 1969922972,
446
+ 40735498,
447
+ 2617837225,
448
+ 3943577151,
449
+ 1913087877,
450
+ 83908371,
451
+ 2512341634,
452
+ 3803740692,
453
+ 2075208622,
454
+ 213261112,
455
+ 2463272603,
456
+ 3855990285,
457
+ 2094854071,
458
+ 198958881,
459
+ 2262029012,
460
+ 4057260610,
461
+ 1759359992,
462
+ 534414190,
463
+ 2176718541,
464
+ 4139329115,
465
+ 1873836001,
466
+ 414664567,
467
+ 2282248934,
468
+ 4279200368,
469
+ 1711684554,
470
+ 285281116,
471
+ 2405801727,
472
+ 4167216745,
473
+ 1634467795,
474
+ 376229701,
475
+ 2685067896,
476
+ 3608007406,
477
+ 1308918612,
478
+ 956543938,
479
+ 2808555105,
480
+ 3495958263,
481
+ 1231636301,
482
+ 1047427035,
483
+ 2932959818,
484
+ 3654703836,
485
+ 1088359270,
486
+ 936918e3,
487
+ 2847714899,
488
+ 3736837829,
489
+ 1202900863,
490
+ 817233897,
491
+ 3183342108,
492
+ 3401237130,
493
+ 1404277552,
494
+ 615818150,
495
+ 3134207493,
496
+ 3453421203,
497
+ 1423857449,
498
+ 601450431,
499
+ 3009837614,
500
+ 3294710456,
501
+ 1567103746,
502
+ 711928724,
503
+ 3020668471,
504
+ 3272380065,
505
+ 1510334235,
506
+ 755167117
507
+ ]);
508
+ function crc32(buf) {
509
+ let crc = -1;
510
+ for (let x of buf) {
511
+ crc = CRC_TABLE[(crc ^ x) & 255] ^ crc >>> 8;
512
+ }
513
+ return (crc ^ -1) >>> 0;
514
+ }
515
+ module.exports = crc32;
516
+ }
517
+ });
518
+
519
+ // ../../../../../code/node_modules/.pnpm/yauzl@3.4.0/node_modules/yauzl/index.js
520
+ var require_yauzl = __commonJS({
521
+ "../../../../../code/node_modules/.pnpm/yauzl@3.4.0/node_modules/yauzl/index.js"(exports) {
522
+ var fs = __require("fs");
523
+ var zlib = __require("zlib");
524
+ var fd_slicer = require_fd_slicer();
525
+ var util = __require("util");
526
+ var EventEmitter = __require("events").EventEmitter;
527
+ var Transform2 = __require("stream").Transform;
528
+ var PassThrough = __require("stream").PassThrough;
529
+ var Writable = __require("stream").Writable;
530
+ var crc32 = typeof zlib.crc32 === "function" ? zlib.crc32 : require_crc32();
531
+ exports.open = open3;
532
+ exports.fromFd = fromFd;
533
+ exports.fromBuffer = fromBuffer;
534
+ exports.fromRandomAccessReader = fromRandomAccessReader;
535
+ exports.openPromise = openPromise;
536
+ exports.fromFdPromise = fromFdPromise;
537
+ exports.fromBufferPromise = fromBufferPromise;
538
+ exports.fromRandomAccessReaderPromise = fromRandomAccessReaderPromise;
539
+ exports.dosDateTimeToDate = dosDateTimeToDate;
540
+ exports.getFileNameLowLevel = getFileNameLowLevel;
541
+ exports.validateFileName = validateFileName;
542
+ exports.parseExtraFields = parseExtraFields;
543
+ exports.ZipFile = ZipFile;
544
+ exports.Entry = Entry;
545
+ exports.LocalFileHeader = LocalFileHeader;
546
+ exports.RandomAccessReader = RandomAccessReader;
547
+ function openPromise(path, options2) {
548
+ return new Promise((resolve4, reject) => {
549
+ open3(path, { ...options2, lazyEntries: true }, function(err, zipfile) {
550
+ if (err) return reject(err);
551
+ resolve4(zipfile);
552
+ });
553
+ });
554
+ }
555
+ function fromFdPromise(fd, options2) {
556
+ return new Promise((resolve4, reject) => {
557
+ fromFd(fd, { ...options2, lazyEntries: true }, function(err, zipfile) {
558
+ if (err) return reject(err);
559
+ resolve4(zipfile);
560
+ });
561
+ });
562
+ }
563
+ function fromBufferPromise(buffer, options2) {
564
+ return new Promise((resolve4, reject) => {
565
+ fromBuffer(buffer, { ...options2, lazyEntries: true }, function(err, zipfile) {
566
+ if (err) return reject(err);
567
+ resolve4(zipfile);
568
+ });
569
+ });
570
+ }
571
+ function fromRandomAccessReaderPromise(reader, totalSize, options2) {
572
+ return new Promise((resolve4, reject) => {
573
+ fromRandomAccessReader(reader, totalSize, { ...options2, lazyEntries: true }, function(err, zipfile) {
574
+ if (err) return reject(err);
575
+ resolve4(zipfile);
576
+ });
577
+ });
578
+ }
579
+ function open3(path, options2, callback) {
580
+ if (typeof options2 === "function") {
581
+ callback = options2;
582
+ options2 = null;
583
+ }
584
+ if (options2 == null) options2 = {};
585
+ if (options2.autoClose == null) options2.autoClose = true;
586
+ if (options2.lazyEntries == null) options2.lazyEntries = false;
587
+ if (options2.decodeStrings == null) options2.decodeStrings = true;
588
+ if (options2.validateEntrySizes == null) options2.validateEntrySizes = true;
589
+ if (options2.strictFileNames == null) options2.strictFileNames = false;
590
+ if (callback == null) callback = defaultCallback;
591
+ fs.open(path, "r", function(err, fd) {
592
+ if (err) return callback(err);
593
+ fromFd(fd, options2, function(err2, zipfile) {
594
+ if (err2) fs.close(fd, defaultCallback);
595
+ callback(err2, zipfile);
596
+ });
597
+ });
598
+ }
599
+ function fromFd(fd, options2, callback) {
600
+ if (typeof options2 === "function") {
601
+ callback = options2;
602
+ options2 = null;
603
+ }
604
+ if (options2 == null) options2 = {};
605
+ if (options2.autoClose == null) options2.autoClose = false;
606
+ if (options2.lazyEntries == null) options2.lazyEntries = false;
607
+ if (options2.decodeStrings == null) options2.decodeStrings = true;
608
+ if (options2.validateEntrySizes == null) options2.validateEntrySizes = true;
609
+ if (options2.strictFileNames == null) options2.strictFileNames = false;
610
+ if (callback == null) callback = defaultCallback;
611
+ fs.fstat(fd, function(err, stats) {
612
+ if (err) return callback(err);
613
+ var reader = new fd_slicer.FdSlicer(fd);
614
+ fromRandomAccessReader(reader, stats.size, options2, callback);
615
+ });
616
+ }
617
+ function fromBuffer(buffer, options2, callback) {
618
+ if (typeof options2 === "function") {
619
+ callback = options2;
620
+ options2 = null;
621
+ }
622
+ if (options2 == null) options2 = {};
623
+ options2.autoClose = false;
624
+ if (options2.lazyEntries == null) options2.lazyEntries = false;
625
+ if (options2.decodeStrings == null) options2.decodeStrings = true;
626
+ if (options2.validateEntrySizes == null) options2.validateEntrySizes = true;
627
+ if (options2.strictFileNames == null) options2.strictFileNames = false;
628
+ var reader = new fd_slicer.BufferSlicer(buffer);
629
+ fromRandomAccessReader(reader, buffer.length, options2, callback);
630
+ }
631
+ function fromRandomAccessReader(reader, totalSize, options2, callback) {
632
+ if (typeof options2 === "function") {
633
+ callback = options2;
634
+ options2 = null;
635
+ }
636
+ if (options2 == null) options2 = {};
637
+ if (options2.autoClose == null) options2.autoClose = true;
638
+ if (options2.lazyEntries == null) options2.lazyEntries = false;
639
+ if (options2.decodeStrings == null) options2.decodeStrings = true;
640
+ var decodeStrings = !!options2.decodeStrings;
641
+ if (options2.validateEntrySizes == null) options2.validateEntrySizes = true;
642
+ if (options2.strictFileNames == null) options2.strictFileNames = false;
643
+ if (callback == null) callback = defaultCallback;
644
+ if (typeof totalSize !== "number") throw new Error("expected totalSize parameter to be a number");
645
+ if (totalSize > Number.MAX_SAFE_INTEGER) {
646
+ throw new Error("zip file too large. only file sizes up to 2^52 are supported due to JavaScript's Number type being an IEEE 754 double.");
647
+ }
648
+ reader.ref();
649
+ var eocdrWithoutCommentSize = 22;
650
+ var zip64EocdlSize = 20;
651
+ var maxCommentSize = 65535;
652
+ var bufferSize = Math.min(zip64EocdlSize + eocdrWithoutCommentSize + maxCommentSize, totalSize);
653
+ var buffer = newBuffer(bufferSize);
654
+ var bufferReadStart = totalSize - buffer.length;
655
+ readAndAssertNoEof(reader, buffer, 0, bufferSize, bufferReadStart, function(err) {
656
+ if (err) return callback(err);
657
+ for (var i = bufferSize - eocdrWithoutCommentSize; i >= 0; i -= 1) {
658
+ if (buffer.readUInt32LE(i) !== 101010256) continue;
659
+ var eocdrBuffer = buffer.subarray(i);
660
+ var diskNumber = eocdrBuffer.readUInt16LE(4);
661
+ var entryCount = eocdrBuffer.readUInt16LE(10);
662
+ var centralDirectoryOffset = eocdrBuffer.readUInt32LE(16);
663
+ var commentLength = eocdrBuffer.readUInt16LE(20);
664
+ var expectedCommentLength = eocdrBuffer.length - eocdrWithoutCommentSize;
665
+ if (commentLength !== expectedCommentLength) {
666
+ return callback(new Error("Invalid comment length. Expected: " + expectedCommentLength + ". Found: " + commentLength + ". Are there extra bytes at the end of the file? Or is the end of central dir signature `PK\u263A\u263B` in the comment?"));
667
+ }
668
+ var comment = decodeStrings ? decodeBuffer(eocdrBuffer.subarray(22), false) : eocdrBuffer.subarray(22);
669
+ if (i - zip64EocdlSize >= 0 && buffer.readUInt32LE(i - zip64EocdlSize) === 117853008) {
670
+ var zip64EocdlBuffer = buffer.subarray(i - zip64EocdlSize, i - zip64EocdlSize + zip64EocdlSize);
671
+ var zip64EocdrOffset = readUInt64LE(zip64EocdlBuffer, 8);
672
+ var zip64EocdrBuffer = newBuffer(56);
673
+ return readAndAssertNoEof(reader, zip64EocdrBuffer, 0, zip64EocdrBuffer.length, zip64EocdrOffset, function(err2) {
674
+ if (err2) return callback(err2);
675
+ if (zip64EocdrBuffer.readUInt32LE(0) !== 101075792) {
676
+ return callback(new Error("invalid zip64 end of central directory record signature"));
677
+ }
678
+ diskNumber = zip64EocdrBuffer.readUInt32LE(16);
679
+ if (diskNumber !== 0) {
680
+ return callback(new Error("multi-disk zip files are not supported: found disk number: " + diskNumber));
681
+ }
682
+ entryCount = readUInt64LE(zip64EocdrBuffer, 32);
683
+ centralDirectoryOffset = readUInt64LE(zip64EocdrBuffer, 48);
684
+ return callback(null, new ZipFile(reader, centralDirectoryOffset, totalSize, entryCount, comment, options2.autoClose, options2.lazyEntries, decodeStrings, options2.validateEntrySizes, options2.strictFileNames));
685
+ });
686
+ }
687
+ if (diskNumber !== 0) {
688
+ return callback(new Error("multi-disk zip files are not supported: found disk number: " + diskNumber));
689
+ }
690
+ return callback(null, new ZipFile(reader, centralDirectoryOffset, totalSize, entryCount, comment, options2.autoClose, options2.lazyEntries, decodeStrings, options2.validateEntrySizes, options2.strictFileNames));
691
+ }
692
+ callback(new Error("End of central directory record signature not found. Either not a zip file, or file is truncated."));
693
+ });
694
+ }
695
+ util.inherits(ZipFile, EventEmitter);
696
+ function ZipFile(reader, centralDirectoryOffset, fileSize, entryCount, comment, autoClose, lazyEntries, decodeStrings, validateEntrySizes, strictFileNames) {
697
+ var self = this;
698
+ EventEmitter.call(self);
699
+ self.reader = reader;
700
+ self.reader.on("error", function(err) {
701
+ emitError(self, err);
702
+ });
703
+ self.reader.once("close", function() {
704
+ self.emit("close");
705
+ });
706
+ self.readEntryCursor = centralDirectoryOffset;
707
+ self.fileSize = fileSize;
708
+ self.entryCount = entryCount;
709
+ self.comment = comment;
710
+ self.entriesRead = 0;
711
+ self.autoClose = !!autoClose;
712
+ self.lazyEntries = !!lazyEntries;
713
+ self.decodeStrings = !!decodeStrings;
714
+ self.validateEntrySizes = !!validateEntrySizes;
715
+ self.strictFileNames = !!strictFileNames;
716
+ self.isOpen = true;
717
+ self.emittedError = false;
718
+ self.hasEachEntryBeenCalled = false;
719
+ if (!self.lazyEntries) self._readEntry();
720
+ }
721
+ ZipFile.prototype.close = function() {
722
+ if (!this.isOpen) return;
723
+ this.isOpen = false;
724
+ this.reader.unref();
725
+ };
726
+ function emitErrorAndAutoClose(self, err) {
727
+ if (self.autoClose) self.close();
728
+ emitError(self, err);
729
+ }
730
+ function emitError(self, err) {
731
+ if (self.emittedError) return;
732
+ self.emittedError = true;
733
+ self.emit("error", err);
734
+ }
735
+ ZipFile.prototype.readEntry = function() {
736
+ if (!this.lazyEntries) throw new Error("readEntry() called without lazyEntries:true");
737
+ this._readEntry();
738
+ };
739
+ ZipFile.prototype._readEntry = function() {
740
+ var self = this;
741
+ if (self.entryCount === self.entriesRead) {
742
+ setImmediate(function() {
743
+ if (self.autoClose) self.close();
744
+ if (self.emittedError) return;
745
+ self.emit("end");
746
+ });
747
+ return;
748
+ }
749
+ if (self.emittedError) return;
750
+ var buffer = newBuffer(46);
751
+ readAndAssertNoEof(self.reader, buffer, 0, buffer.length, self.readEntryCursor, function(err) {
752
+ if (err) return emitErrorAndAutoClose(self, err);
753
+ if (self.emittedError) return;
754
+ var entry = new Entry();
755
+ var signature = buffer.readUInt32LE(0);
756
+ if (signature !== 33639248) return emitErrorAndAutoClose(self, new Error("invalid central directory file header signature: 0x" + signature.toString(16)));
757
+ entry.versionMadeBy = buffer.readUInt16LE(4);
758
+ entry.versionNeededToExtract = buffer.readUInt16LE(6);
759
+ entry.generalPurposeBitFlag = buffer.readUInt16LE(8);
760
+ entry.compressionMethod = buffer.readUInt16LE(10);
761
+ entry.lastModFileTime = buffer.readUInt16LE(12);
762
+ entry.lastModFileDate = buffer.readUInt16LE(14);
763
+ entry.crc32 = buffer.readUInt32LE(16);
764
+ entry.compressedSize = buffer.readUInt32LE(20);
765
+ entry.uncompressedSize = buffer.readUInt32LE(24);
766
+ entry.fileNameLength = buffer.readUInt16LE(28);
767
+ entry.extraFieldLength = buffer.readUInt16LE(30);
768
+ entry.fileCommentLength = buffer.readUInt16LE(32);
769
+ entry.internalFileAttributes = buffer.readUInt16LE(36);
770
+ entry.externalFileAttributes = buffer.readUInt32LE(38);
771
+ entry.relativeOffsetOfLocalHeader = buffer.readUInt32LE(42);
772
+ if (entry.generalPurposeBitFlag & 64) return emitErrorAndAutoClose(self, new Error("strong encryption is not supported"));
773
+ self.readEntryCursor += 46;
774
+ buffer = newBuffer(entry.fileNameLength + entry.extraFieldLength + entry.fileCommentLength);
775
+ readAndAssertNoEof(self.reader, buffer, 0, buffer.length, self.readEntryCursor, function(err2) {
776
+ if (err2) return emitErrorAndAutoClose(self, err2);
777
+ if (self.emittedError) return;
778
+ entry.fileNameRaw = buffer.subarray(0, entry.fileNameLength);
779
+ var fileCommentStart = entry.fileNameLength + entry.extraFieldLength;
780
+ entry.extraFieldRaw = buffer.subarray(entry.fileNameLength, fileCommentStart);
781
+ entry.fileCommentRaw = buffer.subarray(fileCommentStart, fileCommentStart + entry.fileCommentLength);
782
+ try {
783
+ entry.extraFields = parseExtraFields(entry.extraFieldRaw);
784
+ } catch (err3) {
785
+ return emitErrorAndAutoClose(self, err3);
786
+ }
787
+ if (self.decodeStrings) {
788
+ var isUtf8 = (entry.generalPurposeBitFlag & 2048) !== 0;
789
+ entry.fileComment = decodeBuffer(entry.fileCommentRaw, isUtf8);
790
+ entry.fileName = getFileNameLowLevel(entry.generalPurposeBitFlag, entry.fileNameRaw, entry.extraFields, self.strictFileNames);
791
+ var errorMessage = validateFileName(entry.fileName);
792
+ if (errorMessage != null) return emitErrorAndAutoClose(self, new Error(errorMessage));
793
+ } else {
794
+ entry.fileComment = entry.fileCommentRaw;
795
+ entry.fileName = entry.fileNameRaw;
796
+ }
797
+ entry.comment = entry.fileComment;
798
+ self.readEntryCursor += buffer.length;
799
+ self.entriesRead += 1;
800
+ for (var i = 0; i < entry.extraFields.length; i++) {
801
+ var extraField = entry.extraFields[i];
802
+ if (extraField.id !== 1) continue;
803
+ var zip64EiefBuffer = extraField.data;
804
+ var index = 0;
805
+ if (entry.uncompressedSize === 4294967295) {
806
+ if (index + 8 > zip64EiefBuffer.length) {
807
+ return emitErrorAndAutoClose(self, new Error("zip64 extended information extra field does not include uncompressed size"));
808
+ }
809
+ entry.uncompressedSize = readUInt64LE(zip64EiefBuffer, index);
810
+ index += 8;
811
+ }
812
+ if (entry.compressedSize === 4294967295) {
813
+ if (index + 8 > zip64EiefBuffer.length) {
814
+ return emitErrorAndAutoClose(self, new Error("zip64 extended information extra field does not include compressed size"));
815
+ }
816
+ entry.compressedSize = readUInt64LE(zip64EiefBuffer, index);
817
+ index += 8;
818
+ }
819
+ if (entry.relativeOffsetOfLocalHeader === 4294967295) {
820
+ if (index + 8 > zip64EiefBuffer.length) {
821
+ return emitErrorAndAutoClose(self, new Error("zip64 extended information extra field does not include relative header offset"));
822
+ }
823
+ entry.relativeOffsetOfLocalHeader = readUInt64LE(zip64EiefBuffer, index);
824
+ index += 8;
825
+ }
826
+ break;
827
+ }
828
+ if (self.validateEntrySizes && entry.compressionMethod === 0) {
829
+ var expectedCompressedSize = entry.uncompressedSize;
830
+ if (entry.isEncrypted()) {
831
+ expectedCompressedSize += 12;
832
+ }
833
+ if (entry.compressedSize !== expectedCompressedSize) {
834
+ var msg = "compressed/uncompressed size mismatch for stored file: " + entry.compressedSize + " != " + entry.uncompressedSize;
835
+ return emitErrorAndAutoClose(self, new Error(msg));
836
+ }
837
+ }
838
+ self.emit("entry", entry);
839
+ if (!self.lazyEntries) self._readEntry();
840
+ });
841
+ });
842
+ };
843
+ ZipFile.prototype.eachEntry = function() {
844
+ const self = this;
845
+ if (!self.lazyEntries) throw new Error("eachEntry() requires lazyEntries: true");
846
+ if (self.hasEachEntryBeenCalled) throw new Error("eachEntry() must only be called once per ZipFile");
847
+ self.hasEachEntryBeenCalled = true;
848
+ let pendingResolveReject = null;
849
+ self.on("entry", onEntry);
850
+ self.on("end", onEnd);
851
+ self.on("error", onError);
852
+ function cleanup() {
853
+ self.removeListener("entry", onEntry);
854
+ self.removeListener("end", onEnd);
855
+ self.removeListener("error", onError);
856
+ if (self.autoClose) self.close();
857
+ }
858
+ function onEntry(entry) {
859
+ let { resolve: resolve4 } = pendingResolveReject;
860
+ pendingResolveReject = null;
861
+ resolve4({ value: entry });
862
+ }
863
+ function onEnd() {
864
+ let { resolve: resolve4 } = pendingResolveReject;
865
+ pendingResolveReject = null;
866
+ cleanup();
867
+ resolve4({ done: true });
868
+ }
869
+ function onError(err) {
870
+ let { reject } = pendingResolveReject;
871
+ pendingResolveReject = null;
872
+ cleanup();
873
+ reject(err);
874
+ }
875
+ return {
876
+ [Symbol.asyncIterator]() {
877
+ return this;
878
+ },
879
+ next() {
880
+ const promise = new Promise((resolve4, reject) => {
881
+ if (pendingResolveReject != null) throw new Error("next() called before previous Promise was resolved.");
882
+ pendingResolveReject = { resolve: resolve4, reject };
883
+ });
884
+ self.readEntry();
885
+ return promise;
886
+ },
887
+ return(value) {
888
+ cleanup();
889
+ return Promise.resolve({ done: true, value });
890
+ },
891
+ throw(value) {
892
+ cleanup();
893
+ return Promise.reject(value);
894
+ }
895
+ };
896
+ };
897
+ ZipFile.prototype.openReadStream = function(entry, options2, callback) {
898
+ var self = this;
899
+ var relativeStart = 0;
900
+ var relativeEnd = entry.compressedSize;
901
+ if (callback == null) {
902
+ callback = options2;
903
+ options2 = null;
904
+ }
905
+ if (options2 == null) {
906
+ options2 = {};
907
+ } else {
908
+ if (options2.decodeFileData === false) {
909
+ if (options2.decrypt != null) {
910
+ throw new Error("cannot use options.decrypt when options.decodeFileData === false");
911
+ }
912
+ if (options2.decompress != null) {
913
+ throw new Error("cannot use options.decompress when options.decodeFileData === false");
914
+ }
915
+ } else {
916
+ if (options2.decrypt != null) {
917
+ if (!entry.isEncrypted()) {
918
+ throw new Error("options.decrypt can only be specified for encrypted entries. See also option decodeFileData.");
919
+ }
920
+ if (options2.decrypt !== false) throw new Error("invalid options.decrypt value: " + options2.decrypt);
921
+ if (entry.isCompressed()) {
922
+ if (options2.decompress !== false) throw new Error("entry is encrypted and compressed, and options.decompress !== false. See also option decodeFileData.");
923
+ }
924
+ }
925
+ if (options2.decompress != null) {
926
+ if (!entry.isCompressed()) {
927
+ throw new Error("options.decompress can only be specified for compressed entries. See also option decodeFileData.");
928
+ }
929
+ if (!(options2.decompress === false || options2.decompress === true)) {
930
+ throw new Error("invalid options.decompress value: " + options2.decompress);
931
+ }
932
+ decompress = options2.decompress;
933
+ }
934
+ }
935
+ if (options2.start != null) {
936
+ relativeStart = options2.start;
937
+ if (relativeStart < 0) throw new Error("options.start < 0");
938
+ if (relativeStart > entry.compressedSize) throw new Error("options.start > entry.compressedSize");
939
+ }
940
+ if (options2.end != null) {
941
+ relativeEnd = options2.end;
942
+ if (relativeEnd < 0) throw new Error("options.end < 0");
943
+ if (relativeEnd > entry.compressedSize) throw new Error("options.end > entry.compressedSize");
944
+ if (relativeEnd < relativeStart) throw new Error("options.end < options.start");
945
+ }
946
+ }
947
+ var rawMode = options2.decodeFileData === false || // Explicitly requested raw.
948
+ (entry.compressionMethod === 0 || // Naturally without compression.
949
+ entry.compressionMethod === 8 && options2.decompress === false) && (!entry.isEncrypted() || // Naturally without encryption.
950
+ options2.decrypt === false);
951
+ if (options2.start != null || options2.end != null) {
952
+ if (!rawMode) throw new Error("start/end range require options.decodeFileData === false for non-trivial encoded entries.");
953
+ }
954
+ if (!self.isOpen) return callback(new Error("closed"));
955
+ if (entry.isEncrypted() && !rawMode) {
956
+ if (options2.decrypt !== false) return callback(new Error("entry is encrypted, and options.decodeFileData !== false"));
957
+ }
958
+ var decompress;
959
+ if (rawMode) {
960
+ decompress = false;
961
+ } else if (entry.compressionMethod === 8) {
962
+ decompress = options2.decodeFileData !== true;
963
+ } else {
964
+ return callback(new Error("unsupported compression method: " + entry.compressionMethod));
965
+ }
966
+ self.readLocalFileHeader(entry, { minimal: true }, function(err, localFileHeader) {
967
+ if (err) return callback(err);
968
+ self.openReadStreamLowLevel(
969
+ localFileHeader.fileDataStart,
970
+ entry.compressedSize,
971
+ relativeStart,
972
+ relativeEnd,
973
+ decompress,
974
+ entry.uncompressedSize,
975
+ callback
976
+ );
977
+ });
978
+ };
979
+ ZipFile.prototype.openReadStreamLowLevel = function(fileDataStart, compressedSize, relativeStart, relativeEnd, decompress, uncompressedSize, callback) {
980
+ var self = this;
981
+ var fileDataEnd = fileDataStart + compressedSize;
982
+ var readStream = self.reader.createReadStream({
983
+ start: fileDataStart + relativeStart,
984
+ end: fileDataStart + relativeEnd
985
+ });
986
+ var endpointStream = readStream;
987
+ if (decompress) {
988
+ var destroyed = false;
989
+ var inflateFilter = zlib.createInflateRaw();
990
+ readStream.on("error", function(err) {
991
+ setImmediate(function() {
992
+ if (!destroyed) inflateFilter.emit("error", err);
993
+ });
994
+ });
995
+ readStream.pipe(inflateFilter);
996
+ if (self.validateEntrySizes) {
997
+ endpointStream = new AssertByteCountStream(uncompressedSize);
998
+ inflateFilter.on("error", function(err) {
999
+ setImmediate(function() {
1000
+ if (!destroyed) endpointStream.emit("error", err);
1001
+ });
1002
+ });
1003
+ inflateFilter.pipe(endpointStream);
1004
+ } else {
1005
+ endpointStream = inflateFilter;
1006
+ }
1007
+ installDestroyFn(endpointStream, function() {
1008
+ destroyed = true;
1009
+ if (inflateFilter !== endpointStream) inflateFilter.unpipe(endpointStream);
1010
+ readStream.unpipe(inflateFilter);
1011
+ readStream.destroy();
1012
+ });
1013
+ }
1014
+ callback(null, endpointStream);
1015
+ };
1016
+ ZipFile.prototype.readLocalFileHeader = function(entry, options2, callback) {
1017
+ var self = this;
1018
+ if (callback == null) {
1019
+ callback = options2;
1020
+ options2 = null;
1021
+ }
1022
+ if (options2 == null) options2 = {};
1023
+ self.reader.ref();
1024
+ var buffer = newBuffer(30);
1025
+ readAndAssertNoEof(self.reader, buffer, 0, buffer.length, entry.relativeOffsetOfLocalHeader, function(err) {
1026
+ try {
1027
+ if (err) return callback(err);
1028
+ var signature = buffer.readUInt32LE(0);
1029
+ if (signature !== 67324752) {
1030
+ return callback(new Error("invalid local file header signature: 0x" + signature.toString(16)));
1031
+ }
1032
+ var fileNameLength = buffer.readUInt16LE(26);
1033
+ var extraFieldLength = buffer.readUInt16LE(28);
1034
+ var fileDataStart = entry.relativeOffsetOfLocalHeader + 30 + fileNameLength + extraFieldLength;
1035
+ if (fileDataStart + entry.compressedSize > self.fileSize) {
1036
+ return callback(new Error("file data overflows file bounds: " + fileDataStart + " + " + entry.compressedSize + " > " + self.fileSize));
1037
+ }
1038
+ if (options2.minimal) {
1039
+ return callback(null, { fileDataStart });
1040
+ }
1041
+ var localFileHeader = new LocalFileHeader();
1042
+ localFileHeader.fileDataStart = fileDataStart;
1043
+ localFileHeader.versionNeededToExtract = buffer.readUInt16LE(4);
1044
+ localFileHeader.generalPurposeBitFlag = buffer.readUInt16LE(6);
1045
+ localFileHeader.compressionMethod = buffer.readUInt16LE(8);
1046
+ localFileHeader.lastModFileTime = buffer.readUInt16LE(10);
1047
+ localFileHeader.lastModFileDate = buffer.readUInt16LE(12);
1048
+ localFileHeader.crc32 = buffer.readUInt32LE(14);
1049
+ localFileHeader.compressedSize = buffer.readUInt32LE(18);
1050
+ localFileHeader.uncompressedSize = buffer.readUInt32LE(22);
1051
+ localFileHeader.fileNameLength = fileNameLength;
1052
+ localFileHeader.extraFieldLength = extraFieldLength;
1053
+ buffer = newBuffer(fileNameLength + extraFieldLength);
1054
+ self.reader.ref();
1055
+ readAndAssertNoEof(self.reader, buffer, 0, buffer.length, entry.relativeOffsetOfLocalHeader + 30, function(err2) {
1056
+ try {
1057
+ if (err2) return callback(err2);
1058
+ localFileHeader.fileName = buffer.subarray(0, fileNameLength);
1059
+ localFileHeader.extraField = buffer.subarray(fileNameLength);
1060
+ return callback(null, localFileHeader);
1061
+ } finally {
1062
+ self.reader.unref();
1063
+ }
1064
+ });
1065
+ } finally {
1066
+ self.reader.unref();
1067
+ }
1068
+ });
1069
+ };
1070
+ ZipFile.prototype.openReadStreamPromise = function(entry, options2) {
1071
+ return new Promise((resolve4, reject) => {
1072
+ this.openReadStream(entry, options2, function(err, readStream) {
1073
+ if (err) return reject(err);
1074
+ resolve4(readStream);
1075
+ });
1076
+ });
1077
+ };
1078
+ ZipFile.prototype.openReadStreamLowLevelPromise = function(fileDataStart, compressedSize, relativeStart, relativeEnd, decompress, uncompressedSize) {
1079
+ return new Promise((resolve4, reject) => {
1080
+ this.openReadStream(fileDataStart, compressedSize, relativeStart, relativeEnd, decompress, uncompressedSize, function(err, readStream) {
1081
+ if (err) return reject(err);
1082
+ resolve4(readStream);
1083
+ });
1084
+ });
1085
+ };
1086
+ ZipFile.prototype.readLocalFileHeaderPromise = function(entry, options2) {
1087
+ return new Promise((resolve4, reject) => {
1088
+ this.readLocalFileHeader(entry, options2, function(err, localFileHeader) {
1089
+ if (err) return reject(err);
1090
+ resolve4(localFileHeader);
1091
+ });
1092
+ });
1093
+ };
1094
+ function Entry() {
1095
+ }
1096
+ Entry.prototype.getLastModDate = function(options2) {
1097
+ if (options2 == null) options2 = {};
1098
+ if (!options2.forceDosFormat) {
1099
+ for (var i = 0; i < this.extraFields.length; i++) {
1100
+ var extraField = this.extraFields[i];
1101
+ if (extraField.id === 21589) {
1102
+ var data = extraField.data;
1103
+ if (data.length < 5) continue;
1104
+ var flags = data[0];
1105
+ var HAS_MTIME = 1;
1106
+ if (!(flags & HAS_MTIME)) continue;
1107
+ var posixTimestamp = data.readInt32LE(1);
1108
+ return new Date(posixTimestamp * 1e3);
1109
+ } else if (extraField.id === 10) {
1110
+ var data = extraField.data;
1111
+ if (data.length !== 32) continue;
1112
+ if (data.readUInt16LE(4) !== 1) continue;
1113
+ if (data.readUInt16LE(6) !== 24) continue;
1114
+ var hundredNanoSecondsSince1601 = data.readUInt32LE(8) + 4294967296 * data.readInt32LE(12);
1115
+ var millisecondsSince1970 = hundredNanoSecondsSince1601 / 1e4 - 116444736e5;
1116
+ return new Date(millisecondsSince1970);
1117
+ }
1118
+ }
1119
+ }
1120
+ return dosDateTimeToDate(this.lastModFileDate, this.lastModFileTime, options2.timezone);
1121
+ };
1122
+ Entry.prototype.canDecodeFileData = function() {
1123
+ return !this.isEncrypted() && (this.compressionMethod === 0 || this.compressionMethod === 8);
1124
+ };
1125
+ Entry.prototype.isEncrypted = function() {
1126
+ return (this.generalPurposeBitFlag & 1) !== 0;
1127
+ };
1128
+ Entry.prototype.isCompressed = function() {
1129
+ return this.compressionMethod === 8;
1130
+ };
1131
+ function LocalFileHeader() {
1132
+ }
1133
+ function dosDateTimeToDate(date, time, timezone) {
1134
+ var day = date & 31;
1135
+ var month = (date >> 5 & 15) - 1;
1136
+ var year = (date >> 9 & 127) + 1980;
1137
+ var millisecond = 0;
1138
+ var second = (time & 31) * 2;
1139
+ var minute = time >> 5 & 63;
1140
+ var hour = time >> 11 & 31;
1141
+ if (timezone == null || timezone === "local") {
1142
+ return new Date(year, month, day, hour, minute, second, millisecond);
1143
+ } else if (timezone === "UTC") {
1144
+ return new Date(Date.UTC(year, month, day, hour, minute, second, millisecond));
1145
+ } else {
1146
+ throw new Error("unrecognized options.timezone: " + options.timezone);
1147
+ }
1148
+ }
1149
+ function getFileNameLowLevel(generalPurposeBitFlag, fileNameBuffer, extraFields, strictFileNames) {
1150
+ var fileName = null;
1151
+ for (var i = 0; i < extraFields.length; i++) {
1152
+ var extraField = extraFields[i];
1153
+ if (extraField.id === 28789) {
1154
+ if (extraField.data.length < 6) {
1155
+ continue;
1156
+ }
1157
+ if (extraField.data.readUInt8(0) !== 1) {
1158
+ continue;
1159
+ }
1160
+ var oldNameCrc32 = extraField.data.readUInt32LE(1);
1161
+ if (crc32(fileNameBuffer) !== oldNameCrc32) {
1162
+ continue;
1163
+ }
1164
+ fileName = decodeBuffer(extraField.data.subarray(5), true);
1165
+ break;
1166
+ }
1167
+ }
1168
+ if (fileName == null) {
1169
+ var isUtf8 = (generalPurposeBitFlag & 2048) !== 0;
1170
+ fileName = decodeBuffer(fileNameBuffer, isUtf8);
1171
+ }
1172
+ if (!strictFileNames) {
1173
+ fileName = fileName.replace(/\\/g, "/");
1174
+ }
1175
+ return fileName;
1176
+ }
1177
+ function validateFileName(fileName) {
1178
+ if (fileName.indexOf("\\") !== -1) {
1179
+ return "invalid characters in fileName: " + fileName;
1180
+ }
1181
+ if (/^[a-zA-Z]:/.test(fileName) || /^\//.test(fileName)) {
1182
+ return "absolute path: " + fileName;
1183
+ }
1184
+ if (fileName.split("/").indexOf("..") !== -1) {
1185
+ return "invalid relative path: " + fileName;
1186
+ }
1187
+ return null;
1188
+ }
1189
+ function parseExtraFields(extraFieldBuffer) {
1190
+ var extraFields = [];
1191
+ var i = 0;
1192
+ while (i < extraFieldBuffer.length - 3) {
1193
+ var headerId = extraFieldBuffer.readUInt16LE(i + 0);
1194
+ var dataSize = extraFieldBuffer.readUInt16LE(i + 2);
1195
+ var dataStart = i + 4;
1196
+ var dataEnd = dataStart + dataSize;
1197
+ if (dataEnd > extraFieldBuffer.length) throw new Error("extra field length exceeds extra field buffer size");
1198
+ var dataBuffer = extraFieldBuffer.subarray(dataStart, dataEnd);
1199
+ extraFields.push({
1200
+ id: headerId,
1201
+ data: dataBuffer
1202
+ });
1203
+ i = dataEnd;
1204
+ }
1205
+ return extraFields;
1206
+ }
1207
+ function readAndAssertNoEof(reader, buffer, offset, length, position, callback) {
1208
+ if (length === 0) {
1209
+ return setImmediate(function() {
1210
+ callback(null, newBuffer(0));
1211
+ });
1212
+ }
1213
+ reader.read(buffer, offset, length, position, function(err, bytesRead) {
1214
+ if (err) return callback(err);
1215
+ if (bytesRead < length) {
1216
+ return callback(new Error("unexpected EOF"));
1217
+ }
1218
+ callback();
1219
+ });
1220
+ }
1221
+ util.inherits(AssertByteCountStream, Transform2);
1222
+ function AssertByteCountStream(byteCount) {
1223
+ Transform2.call(this);
1224
+ this.actualByteCount = 0;
1225
+ this.expectedByteCount = byteCount;
1226
+ }
1227
+ AssertByteCountStream.prototype._transform = function(chunk, encoding, cb) {
1228
+ this.actualByteCount += chunk.length;
1229
+ if (this.actualByteCount > this.expectedByteCount) {
1230
+ var msg = "too many bytes in the stream. expected " + this.expectedByteCount + ". got at least " + this.actualByteCount;
1231
+ return cb(new Error(msg));
1232
+ }
1233
+ cb(null, chunk);
1234
+ };
1235
+ AssertByteCountStream.prototype._flush = function(cb) {
1236
+ if (this.actualByteCount < this.expectedByteCount) {
1237
+ var msg = "not enough bytes in the stream. expected " + this.expectedByteCount + ". got only " + this.actualByteCount;
1238
+ return cb(new Error(msg));
1239
+ }
1240
+ cb();
1241
+ };
1242
+ util.inherits(RandomAccessReader, EventEmitter);
1243
+ function RandomAccessReader() {
1244
+ EventEmitter.call(this);
1245
+ this.refCount = 0;
1246
+ }
1247
+ RandomAccessReader.prototype.ref = function() {
1248
+ this.refCount += 1;
1249
+ };
1250
+ RandomAccessReader.prototype.unref = function() {
1251
+ var self = this;
1252
+ self.refCount -= 1;
1253
+ if (self.refCount > 0) return;
1254
+ if (self.refCount < 0) throw new Error("invalid unref");
1255
+ self.close(onCloseDone);
1256
+ function onCloseDone(err) {
1257
+ if (err) return self.emit("error", err);
1258
+ self.emit("close");
1259
+ }
1260
+ };
1261
+ RandomAccessReader.prototype.createReadStream = function(options2) {
1262
+ if (options2 == null) options2 = {};
1263
+ var start = options2.start;
1264
+ var end = options2.end;
1265
+ if (start === end) {
1266
+ var emptyStream = new PassThrough();
1267
+ setImmediate(function() {
1268
+ emptyStream.end();
1269
+ });
1270
+ return emptyStream;
1271
+ }
1272
+ var stream = this._readStreamForRange(start, end);
1273
+ var destroyed = false;
1274
+ var refUnrefFilter = new RefUnrefFilter(this);
1275
+ stream.on("error", function(err) {
1276
+ setImmediate(function() {
1277
+ if (!destroyed) refUnrefFilter.emit("error", err);
1278
+ });
1279
+ });
1280
+ installDestroyFn(refUnrefFilter, function() {
1281
+ stream.unpipe(refUnrefFilter);
1282
+ refUnrefFilter.unref();
1283
+ stream.destroy();
1284
+ });
1285
+ var byteCounter = new AssertByteCountStream(end - start);
1286
+ refUnrefFilter.on("error", function(err) {
1287
+ setImmediate(function() {
1288
+ if (!destroyed) byteCounter.emit("error", err);
1289
+ });
1290
+ });
1291
+ installDestroyFn(byteCounter, function() {
1292
+ destroyed = true;
1293
+ refUnrefFilter.unpipe(byteCounter);
1294
+ refUnrefFilter.destroy();
1295
+ });
1296
+ return stream.pipe(refUnrefFilter).pipe(byteCounter);
1297
+ };
1298
+ RandomAccessReader.prototype._readStreamForRange = function(start, end) {
1299
+ throw new Error("not implemented");
1300
+ };
1301
+ RandomAccessReader.prototype.read = function(buffer, offset, length, position, callback) {
1302
+ var readStream = this.createReadStream({ start: position, end: position + length });
1303
+ var writeStream = new Writable();
1304
+ var written = 0;
1305
+ writeStream._write = function(chunk, encoding, cb) {
1306
+ chunk.copy(buffer, offset + written, 0, chunk.length);
1307
+ written += chunk.length;
1308
+ cb();
1309
+ };
1310
+ writeStream.on("finish", callback);
1311
+ readStream.on("error", function(error) {
1312
+ callback(error);
1313
+ });
1314
+ readStream.pipe(writeStream);
1315
+ };
1316
+ RandomAccessReader.prototype.close = function(callback) {
1317
+ setImmediate(callback);
1318
+ };
1319
+ util.inherits(RefUnrefFilter, PassThrough);
1320
+ function RefUnrefFilter(context) {
1321
+ PassThrough.call(this);
1322
+ this.context = context;
1323
+ this.context.ref();
1324
+ this.unreffedYet = false;
1325
+ }
1326
+ RefUnrefFilter.prototype._flush = function(cb) {
1327
+ this.unref();
1328
+ cb();
1329
+ };
1330
+ RefUnrefFilter.prototype.unref = function(cb) {
1331
+ if (this.unreffedYet) return;
1332
+ this.unreffedYet = true;
1333
+ this.context.unref();
1334
+ };
1335
+ var cp437 = "\0\u263A\u263B\u2665\u2666\u2663\u2660\u2022\u25D8\u25CB\u25D9\u2642\u2640\u266A\u266B\u263C\u25BA\u25C4\u2195\u203C\xB6\xA7\u25AC\u21A8\u2191\u2193\u2192\u2190\u221F\u2194\u25B2\u25BC !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u2302\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xA2\xA3\xA5\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0";
1336
+ function decodeBuffer(buffer, isUtf8) {
1337
+ if (isUtf8) {
1338
+ return buffer.toString("utf8");
1339
+ } else {
1340
+ var result = "";
1341
+ for (var i = 0; i < buffer.length; i++) {
1342
+ result += cp437[buffer[i]];
1343
+ }
1344
+ return result;
1345
+ }
1346
+ }
1347
+ function readUInt64LE(buffer, offset) {
1348
+ var lower32 = buffer.readUInt32LE(offset);
1349
+ var upper32 = buffer.readUInt32LE(offset + 4);
1350
+ return upper32 * 4294967296 + lower32;
1351
+ }
1352
+ var newBuffer;
1353
+ if (typeof Buffer.allocUnsafe === "function") {
1354
+ newBuffer = function(len) {
1355
+ return Buffer.allocUnsafe(len);
1356
+ };
1357
+ } else {
1358
+ newBuffer = function(len) {
1359
+ return new Buffer(len);
1360
+ };
1361
+ }
1362
+ function installDestroyFn(stream, fn) {
1363
+ if (typeof stream.destroy === "function") {
1364
+ stream._destroy = function(err, cb) {
1365
+ fn();
1366
+ if (cb != null) cb(err);
1367
+ };
1368
+ } else {
1369
+ stream.destroy = fn;
1370
+ }
1371
+ }
1372
+ function defaultCallback(err) {
1373
+ if (err) throw err;
1374
+ }
1375
+ }
1376
+ });
1377
+
1378
+ // cli/src/service/installation/npm.entry.ts
1379
+ import { dirname as dirname2, resolve as resolve3 } from "node:path";
1380
+ import { fileURLToPath } from "node:url";
1381
+
1382
+ // cli/src/common/config/release-trust.config.ts
1383
+ var RELEASE_TRUST = Object.freeze({
1384
+ /** 唯一信任根标识;未知标识拒绝,不接受远端下发公钥。 */
1385
+ keyId: "kscs-release-20261023",
1386
+ /** Ed25519 SPKI公钥,必须与受控发布签名私钥匹配。 */
1387
+ publicKey: "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEA8I4Ah9NG3c3CZ9nShiflqAhAyh6xU13SALWlqxwYKJI=\n-----END PUBLIC KEY-----\n"
1388
+ });
1389
+ var NPM_PACKAGE_NAME = "@kscs-inc/cli";
1390
+
1391
+ // cli/src/service/installation/npm-bootstrap.service.ts
1392
+ import { spawn } from "node:child_process";
1393
+ import { createHash as createHash3 } from "node:crypto";
1394
+ import { lstat as lstat2, mkdtemp, readFile, realpath as realpath2, rm } from "node:fs/promises";
1395
+ import { tmpdir } from "node:os";
1396
+ import { join as join3, resolve as resolve2 } from "node:path";
1397
+ import { parseArgs } from "node:util";
1398
+
1399
+ // cli/src/common/client/installation-download.client.ts
1400
+ import { createHash as createHash2, randomUUID } from "node:crypto";
1401
+ import { createReadStream, createWriteStream } from "node:fs";
1402
+ import { open } from "node:fs/promises";
1403
+ import { Transform } from "node:stream";
1404
+ import { pipeline } from "node:stream/promises";
1405
+
1406
+ // cli/src/common/client/release-signature.client.ts
1407
+ import { createHash, createPublicKey, verify } from "node:crypto";
1408
+ function verifyReleaseSignature(bytes, envelope, expectedPath, trust = RELEASE_TRUST, nowSeconds = Math.floor(Date.now() / 1e3)) {
1409
+ if (!envelope || typeof envelope !== "object" || Array.isArray(envelope))
1410
+ throw new Error("\u53D1\u884C\u7B7E\u540D\u683C\u5F0F\u65E0\u6548");
1411
+ const value = envelope;
1412
+ if (value.algorithm !== "Ed25519" || value.key_id !== trust.keyId || typeof value.payload !== "string" || typeof value.signature !== "string")
1413
+ throw new Error("\u53D1\u884C\u7B7E\u540D\u7B97\u6CD5\u6216\u4FE1\u4EFB\u6839\u65E0\u6548");
1414
+ const payload = Buffer.from(value.payload, "base64");
1415
+ const signature = Buffer.from(value.signature, "base64");
1416
+ if (payload.length > 8192 || signature.length !== 64 || payload.toString("base64") !== value.payload || signature.toString("base64") !== value.signature)
1417
+ throw new Error("\u53D1\u884C\u7B7E\u540D\u5B57\u8282\u683C\u5F0F\u65E0\u6548");
1418
+ const publicKey = createPublicKey(trust.publicKey);
1419
+ if (publicKey.asymmetricKeyType !== "ed25519" || !verify(null, payload, publicKey, signature))
1420
+ throw new Error("\u53D1\u884C\u7B7E\u540D\u9A8C\u8BC1\u5931\u8D25");
1421
+ const identity = JSON.parse(payload.toString("utf8"));
1422
+ if (!identity || typeof identity !== "object" || Array.isArray(identity))
1423
+ throw new Error("\u7B7E\u540D\u58F0\u660E\u683C\u5F0F\u65E0\u6548");
1424
+ const data = identity;
1425
+ if (data.schema_version !== 1 || data.path !== expectedPath || data.sha256 !== createHash("sha256").update(bytes).digest("hex"))
1426
+ throw new Error("\u7B7E\u540D\u58F0\u660E\u4E0E\u53D1\u884C\u6587\u4EF6\u4E0D\u4E00\u81F4");
1427
+ if (!Number.isSafeInteger(data.issued_at) || !Number.isSafeInteger(data.expires_at) || Number(data.issued_at) > nowSeconds + 300 || Number(data.expires_at) <= nowSeconds || Number(data.expires_at) <= Number(data.issued_at))
1428
+ throw new Error("\u53D1\u884C\u7B7E\u540D\u5DF2\u8FC7\u671F\u6216\u7B7E\u53D1\u65F6\u95F4\u65E0\u6548\uFF0C\u8BF7\u4F7F\u7528\u5B98\u7F51\u6700\u65B0\u5B89\u88C5\u5165\u53E3");
1429
+ return {
1430
+ schema_version: 1,
1431
+ path: expectedPath,
1432
+ sha256: String(data.sha256),
1433
+ issued_at: Number(data.issued_at),
1434
+ expires_at: Number(data.expires_at)
1435
+ };
1436
+ }
1437
+
1438
+ // cli/src/common/client/installation-download.client.ts
1439
+ function checkedDownloadUrl(value, allowLocal = false) {
1440
+ const url = new URL(value);
1441
+ const local = allowLocal && url.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname);
1442
+ if (url.protocol !== "https:" && !local || url.username || url.password || url.hash)
1443
+ throw new Error("\u4E0B\u8F7D\u5FC5\u987B\u4F7F\u7528HTTPS\uFF1B\u672C\u5730\u9A8C\u6536\u4EC5\u5141\u8BB8\u56DE\u73AFHTTP");
1444
+ return url;
1445
+ }
1446
+ function sameOriginUrl(value, base, allowLocal = false) {
1447
+ const url = checkedDownloadUrl(new URL(value, base).href, allowLocal);
1448
+ if (url.origin !== checkedDownloadUrl(base, allowLocal).origin) throw new Error("\u62D2\u7EDD\u8DE8\u57DF\u53D1\u884C\u6E90");
1449
+ return url.href;
1450
+ }
1451
+ async function downloadResponse(url, allowLocal, timeoutMs) {
1452
+ let target = checkedDownloadUrl(url, allowLocal).href;
1453
+ const signal = AbortSignal.timeout(timeoutMs);
1454
+ for (let redirects = 0; redirects <= 5; redirects += 1) {
1455
+ let response;
1456
+ try {
1457
+ response = await fetch(target, {
1458
+ redirect: "manual",
1459
+ signal,
1460
+ headers: { "User-Agent": "kscs-node-installer/1" }
1461
+ });
1462
+ } catch (error) {
1463
+ const cause = error instanceof Error ? error.cause : void 0;
1464
+ const code = cause && typeof cause === "object" && "code" in cause ? cause.code : void 0;
1465
+ const reason = typeof code === "string" && /^[A-Z][A-Z0-9_]{1,63}$/.test(code) ? code : signal.aborted ? "DOWNLOAD_TIMEOUT" : "NETWORK_ERROR";
1466
+ throw new Error(
1467
+ `\u4E0B\u8F7D\u8FDE\u63A5\u5931\u8D25\uFF08${reason}\uFF09\uFF1A${new URL(target).origin}\uFF1B\u8BF7\u68C0\u67E5\u7F51\u7EDC\u3001\u4EE3\u7406\u4E0E\u8BC1\u4E66\u540E\u91CD\u8BD5\u3002\u539F\u5BA2\u6237\u7AEF\u4E0E\u914D\u7F6E\u4E0D\u4F1A\u56E0\u4E0B\u8F7D\u5931\u8D25\u88AB\u66FF\u6362\u3002`,
1468
+ { cause: error }
1469
+ );
1470
+ }
1471
+ if ([301, 302, 303, 307, 308].includes(response.status)) {
1472
+ await response.body?.cancel();
1473
+ const location = response.headers.get("location");
1474
+ if (!location) throw new Error("\u4E0B\u8F7D\u91CD\u5B9A\u5411\u7F3A\u5C11\u5730\u5740");
1475
+ target = sameOriginUrl(location, target, allowLocal);
1476
+ continue;
1477
+ }
1478
+ if (!response.ok || !response.body) {
1479
+ await response.body?.cancel();
1480
+ throw new Error(`\u4E0B\u8F7DHTTP\u72B6\u6001\u5F02\u5E38\uFF1A${response.status}`);
1481
+ }
1482
+ return response;
1483
+ }
1484
+ throw new Error("\u4E0B\u8F7D\u91CD\u5B9A\u5411\u6B21\u6570\u8D85\u9650");
1485
+ }
1486
+ async function downloadBytes(url, limit, allowLocal = false, timeoutMs = 6e4) {
1487
+ const response = await downloadResponse(url, allowLocal, timeoutMs);
1488
+ const chunks = [];
1489
+ let size = 0;
1490
+ for await (const chunk of response.body) {
1491
+ size += chunk.length;
1492
+ if (size > limit) throw new Error("\u4E0B\u8F7D\u8D85\u8FC7\u5141\u8BB8\u5927\u5C0F");
1493
+ chunks.push(chunk);
1494
+ }
1495
+ return Buffer.concat(chunks);
1496
+ }
1497
+ async function downloadFile(url, path, limit, allowLocal = false, onProgress) {
1498
+ let size = 0;
1499
+ onProgress?.(size, "downloading");
1500
+ try {
1501
+ const response = await downloadResponse(url, allowLocal, 6e4);
1502
+ const budget = new Transform({
1503
+ transform(chunk, _encoding, callback) {
1504
+ size += chunk.length;
1505
+ if (size <= limit) onProgress?.(size, "downloading");
1506
+ callback(size > limit ? new Error("\u4E0B\u8F7D\u8D85\u8FC7\u5141\u8BB8\u5927\u5C0F") : null, chunk);
1507
+ }
1508
+ });
1509
+ await pipeline(response.body, budget, createWriteStream(path, { flags: "wx", mode: 384 }));
1510
+ const file = await open(path, "r+");
1511
+ try {
1512
+ await file.sync();
1513
+ } finally {
1514
+ await file.close();
1515
+ }
1516
+ onProgress?.(size, "downloaded");
1517
+ return size;
1518
+ } catch (error) {
1519
+ onProgress?.(size, "failed");
1520
+ throw error;
1521
+ }
1522
+ }
1523
+ async function fileDigest(path) {
1524
+ const hash = createHash2("sha256");
1525
+ for await (const chunk of createReadStream(path)) hash.update(chunk);
1526
+ return hash.digest("hex");
1527
+ }
1528
+ async function downloadVerifiedRelease(url, limit, allowLocal = false, timeoutMs = 6e4) {
1529
+ const target = checkedDownloadUrl(url, allowLocal);
1530
+ const bytes = await downloadBytes(url, limit, allowLocal, timeoutMs);
1531
+ if (!(allowLocal && target.protocol === "http:")) {
1532
+ const envelope = await downloadBytes(url + ".signature.json", 16384, false, timeoutMs);
1533
+ verifyReleaseSignature(bytes, JSON.parse(envelope.toString("utf8")), target.pathname);
1534
+ }
1535
+ return bytes;
1536
+ }
1537
+
1538
+ // cli/src/common/client/installation-archive.client.ts
1539
+ var import_yauzl = __toESM(require_yauzl(), 1);
1540
+ import { createWriteStream as createWriteStream2 } from "node:fs";
1541
+ import { chmod, lstat, mkdir, open as open2, readdir, realpath } from "node:fs/promises";
1542
+ import { dirname, join, resolve } from "node:path";
1543
+ import { pipeline as pipeline2 } from "node:stream/promises";
1544
+ var MAX_ARCHIVE_FILES = 3e4;
1545
+ var MAX_EXPANDED_BYTES = 1024 * 1024 * 1024;
1546
+ function validateArchivePath(name) {
1547
+ const parts = name.replace(/\/$/, "").split("/");
1548
+ if (!name || /[\\:\x00-\x1f]/.test(name) || parts.some(
1549
+ (part) => !part || part === "." || part === ".." || /[. ]$/.test(part) || /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\..*)?$/i.test(part)
1550
+ ))
1551
+ throw new Error("\u5B89\u88C5\u5305\u5305\u542B\u8D8A\u754C\u6216\u4FDD\u7559\u8DEF\u5F84");
1552
+ return parts;
1553
+ }
1554
+ async function unpackArchive(archive, destination) {
1555
+ const zip = await new Promise(
1556
+ (accept, reject) => import_yauzl.default.open(
1557
+ archive,
1558
+ { lazyEntries: true, autoClose: false, strictFileNames: true },
1559
+ (error, value) => error || !value ? reject(error ?? new Error("\u65E0\u6CD5\u8BFB\u53D6ZIP")) : accept(value)
1560
+ )
1561
+ );
1562
+ const entries = [];
1563
+ const names = /* @__PURE__ */ new Set();
1564
+ let size = 0;
1565
+ try {
1566
+ await new Promise((accept, reject) => {
1567
+ zip.on("error", reject);
1568
+ zip.on("end", accept);
1569
+ zip.on("entry", (entry) => {
1570
+ try {
1571
+ const parts = validateArchivePath(entry.fileName);
1572
+ const kind = entry.externalFileAttributes >>> 16 & 61440;
1573
+ const canonical = parts.join("/").toLowerCase();
1574
+ size += entry.uncompressedSize;
1575
+ if (parts[0] !== "kscs-cli" || names.has(canonical) || ![0, 32768, 16384].includes(kind) || entry.generalPurposeBitFlag & 1 || entries.length >= MAX_ARCHIVE_FILES || size > MAX_EXPANDED_BYTES)
1576
+ throw new Error("\u5B89\u88C5\u5305\u542B\u94FE\u63A5\u3001\u91CD\u590D\u3001\u52A0\u5BC6\u6587\u4EF6\u6216\u5C55\u5F00\u89C4\u6A21\u8D85\u9650");
1577
+ names.add(canonical);
1578
+ entries.push(entry);
1579
+ zip.readEntry();
1580
+ } catch (error) {
1581
+ reject(error);
1582
+ }
1583
+ });
1584
+ zip.readEntry();
1585
+ });
1586
+ await mkdir(destination, { recursive: true, mode: 448 });
1587
+ if (await realpath(destination) !== resolve(destination))
1588
+ throw new Error("\u89E3\u5305\u76EE\u6807\u4E0D\u80FD\u5305\u542B\u94FE\u63A5");
1589
+ for (const entry of entries) {
1590
+ const target = join(destination, ...validateArchivePath(entry.fileName));
1591
+ if (entry.fileName.endsWith("/")) {
1592
+ await mkdir(target, { recursive: true, mode: 448 });
1593
+ continue;
1594
+ }
1595
+ await mkdir(dirname(target), { recursive: true, mode: 448 });
1596
+ if (await realpath(dirname(target)) !== resolve(dirname(target)))
1597
+ throw new Error("\u89E3\u5305\u7236\u76EE\u5F55\u4E0D\u80FD\u5305\u542B\u94FE\u63A5");
1598
+ const stream = await new Promise(
1599
+ (accept, reject) => zip.openReadStream(
1600
+ entry,
1601
+ (error, value) => error || !value ? reject(error ?? new Error("\u65E0\u6CD5\u8BFB\u53D6ZIP\u6761\u76EE")) : accept(value)
1602
+ )
1603
+ );
1604
+ await pipeline2(stream, createWriteStream2(target, { flags: "wx", mode: 384 }));
1605
+ const file = await open2(target, "r+");
1606
+ try {
1607
+ await file.sync();
1608
+ } finally {
1609
+ await file.close();
1610
+ }
1611
+ await chmod(target, entry.externalFileAttributes >>> 16 & 73 ? 448 : 384);
1612
+ }
1613
+ } finally {
1614
+ zip.close();
1615
+ }
1616
+ }
1617
+ async function verifyReleaseFiles(application, expected) {
1618
+ if (await realpath(application) !== resolve(application))
1619
+ throw new Error("\u5B89\u88C5\u76EE\u5F55\u4E0D\u80FD\u5305\u542B\u94FE\u63A5");
1620
+ const paths = /* @__PURE__ */ new Set();
1621
+ const aliases = /* @__PURE__ */ new Set();
1622
+ for (const entry of expected) {
1623
+ const name = validateArchivePath(entry.path).join("/");
1624
+ if (paths.has(name) || aliases.has(name.toLowerCase())) throw new Error("\u6587\u4EF6\u6E05\u5355\u5305\u542B\u91CD\u590D\u8DEF\u5F84");
1625
+ paths.add(name);
1626
+ aliases.add(name.toLowerCase());
1627
+ const target = join(application, name);
1628
+ if (!(await lstat(target)).isFile() || await realpath(target) !== resolve(target) || await fileDigest(target) !== entry.sha256)
1629
+ throw new Error("\u5B89\u88C5\u6587\u4EF6\u6821\u9A8C\u5931\u8D25\uFF1A" + name);
1630
+ }
1631
+ const actual = /* @__PURE__ */ new Set();
1632
+ async function walk(directory, prefix) {
1633
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
1634
+ const name = prefix + entry.name;
1635
+ if (entry.isDirectory()) await walk(join(directory, entry.name), name + "/");
1636
+ else if (entry.isFile()) actual.add(name);
1637
+ else throw new Error("\u5B89\u88C5\u76EE\u5F55\u4E0D\u5141\u8BB8\u94FE\u63A5\u6216\u7279\u6B8A\u6587\u4EF6");
1638
+ }
1639
+ }
1640
+ await walk(application, "");
1641
+ if (actual.size !== paths.size || [...actual].some((name) => !paths.has(name)))
1642
+ throw new Error("\u5B89\u88C5\u76EE\u5F55\u6587\u4EF6\u4E0E\u6E05\u5355\u4E0D\u4E00\u81F4");
1643
+ }
1644
+
1645
+ // cli/src/common/config/installation-paths.config.ts
1646
+ import { homedir } from "node:os";
1647
+ import { join as join2 } from "node:path";
1648
+ function launcherPath(root) {
1649
+ return join2(root, process.platform === "win32" ? "bin/kscs.cmd" : "bin/kscs");
1650
+ }
1651
+ function defaultInstallRoot(mode, userDirectory = homedir()) {
1652
+ return process.platform === "win32" ? join2(process.env.LOCALAPPDATA ?? join2(userDirectory, "AppData/Local"), "kscs-cli", mode) : join2(userDirectory, ".local/share/kscs-cli", mode);
1653
+ }
1654
+
1655
+ // cli/src/service/installation/installation-target.constants.ts
1656
+ var INSTALL_MODES = ["personal", "team"];
1657
+ var INSTALL_PLATFORMS = ["darwin", "linux", "win32"];
1658
+ var INSTALL_ARCHITECTURES = ["x64", "arm64"];
1659
+
1660
+ // cli/src/service/installation/installation.model.ts
1661
+ var BUILD_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,100}$/;
1662
+ var SHA256_PATTERN = /^[a-f0-9]{64}$/;
1663
+ var MAX_DOWNLOAD_BYTES = 512 * 1024 * 1024;
1664
+ function jsonObject(value) {
1665
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("\u9884\u671FJSON\u5BF9\u8C61");
1666
+ return value;
1667
+ }
1668
+ function validateTarget(value) {
1669
+ const target = jsonObject(value);
1670
+ if (!INSTALL_MODES.includes(target.mode) || !INSTALL_PLATFORMS.includes(target.platform) || !INSTALL_ARCHITECTURES.includes(target.arch) || target.mode === "team" && target.platform !== "linux")
1671
+ throw new Error("\u65E0\u6548\u53D1\u884C\u6A21\u5F0F\u6216\u5E73\u53F0");
1672
+ if (target.available !== true || typeof target.auto_update !== "boolean")
1673
+ throw new Error("\u53D1\u884C\u5236\u54C1\u672A\u653E\u884C");
1674
+ if (typeof target.build_id !== "string" || !BUILD_PATTERN.test(target.build_id))
1675
+ throw new Error("\u975E\u6CD5\u6784\u5EFA\u7F16\u53F7");
1676
+ if (!Number.isSafeInteger(target.release_sequence) || Number(target.release_sequence) <= 0)
1677
+ throw new Error("\u53D1\u884C\u5E8F\u53F7\u65E0\u6548");
1678
+ for (const [key, maximum] of [
1679
+ ["version", 64],
1680
+ ["summary", 160]
1681
+ ]) {
1682
+ const text = target[key];
1683
+ if (typeof text !== "string" || !text.trim() || text.length > maximum || /[\x00-\x1f]/.test(text))
1684
+ throw new Error("\u53D1\u884C\u7248\u672C\u6216\u7B80\u4ECB\u65E0\u6548");
1685
+ }
1686
+ return {
1687
+ mode: target.mode,
1688
+ platform: target.platform,
1689
+ arch: target.arch,
1690
+ available: true,
1691
+ auto_update: target.auto_update,
1692
+ build_id: target.build_id,
1693
+ release_sequence: Number(target.release_sequence),
1694
+ version: String(target.version),
1695
+ summary: String(target.summary)
1696
+ };
1697
+ }
1698
+ function validateArtifact(value) {
1699
+ const target = validateTarget(value);
1700
+ const artifact = jsonObject(value);
1701
+ if (typeof artifact.url !== "string" || typeof artifact.sha256 !== "string" || !SHA256_PATTERN.test(artifact.sha256) || !Number.isSafeInteger(artifact.size) || Number(artifact.size) <= 0 || Number(artifact.size) > MAX_DOWNLOAD_BYTES || !Array.isArray(artifact.files) || !artifact.files.length || artifact.files.length > MAX_ARCHIVE_FILES)
1702
+ throw new Error("\u53D1\u884C\u6E05\u5355\u7F3A\u5C11\u5B8C\u6574\u6027\u6821\u9A8C");
1703
+ for (const entry of artifact.files) {
1704
+ const file = jsonObject(entry);
1705
+ if (typeof file.path !== "string" || typeof file.sha256 !== "string" || !SHA256_PATTERN.test(file.sha256))
1706
+ throw new Error("\u6587\u4EF6\u6458\u8981\u65E0\u6548");
1707
+ }
1708
+ return {
1709
+ ...target,
1710
+ url: artifact.url,
1711
+ size: Number(artifact.size),
1712
+ sha256: artifact.sha256,
1713
+ files: artifact.files.map((entry) => {
1714
+ const file = jsonObject(entry);
1715
+ return { path: String(file.path), sha256: String(file.sha256) };
1716
+ })
1717
+ };
1718
+ }
1719
+
1720
+ // cli/src/service/installation/installation-progress.formatter.ts
1721
+ function createDownloadProgress(totalBytes, output = process.stderr) {
1722
+ const startedAt = performance.now();
1723
+ let lastPaint = -Infinity;
1724
+ let previousLength = 0;
1725
+ const interactive = output.isTTY === true && process.env.TERM !== "dumb";
1726
+ return (receivedBytes, status) => {
1727
+ const now = performance.now();
1728
+ const finished = status !== "downloading";
1729
+ if (!finished && now - lastPaint < (interactive ? 150 : 2e3)) return;
1730
+ lastPaint = now;
1731
+ const knownSize = Number.isFinite(totalBytes) && totalBytes > 0;
1732
+ const percent = knownSize ? Math.min(
1733
+ status === "downloaded" && receivedBytes === totalBytes ? 100 : 99,
1734
+ Math.floor(receivedBytes / totalBytes * 100)
1735
+ ) : null;
1736
+ const megabytes = (bytes) => (bytes / 1024 / 1024).toFixed(1);
1737
+ const amount = `${megabytes(receivedBytes)}${knownSize ? `/${megabytes(totalBytes)}` : ""} MB`;
1738
+ const speed = `${megabytes(receivedBytes / Math.max((now - startedAt) / 1e3, 1e-3))} MB/s`;
1739
+ const label = status === "failed" ? "\u4E0B\u8F7D\u4E2D\u65AD" : status === "downloaded" ? "\u4E0B\u8F7D\u5B8C\u6210" : "\u4E0B\u8F7D";
1740
+ const width = output.columns ?? 80;
1741
+ const barWidth = Math.max(0, Math.min(20, width - 58));
1742
+ const filled = percent === null ? 0 : Math.floor(percent / 100 * barWidth);
1743
+ const bar = barWidth && percent !== null ? `[${"=".repeat(filled)}${"-".repeat(barWidth - filled)}] ` : "";
1744
+ const line = width < 36 ? `${label} ${percent === null ? `${megabytes(receivedBytes)} MB` : `${percent}%`}` : `${label} ${bar}${percent === null ? "" : `${percent}% `}${amount}${width >= 58 ? ` \xB7 ${speed}` : ""}`;
1745
+ output.write(
1746
+ interactive ? `\r${line}${" ".repeat(Math.max(0, previousLength - line.length))}${finished ? "\n" : ""}` : `${line}
1747
+ `
1748
+ );
1749
+ previousLength = line.length;
1750
+ };
1751
+ }
1752
+
1753
+ // cli/src/service/installation/npm-bootstrap.service.ts
1754
+ async function readNpmRelease(directory) {
1755
+ const bytes = await readFile(join3(directory, "release.json"));
1756
+ if (bytes.length > 65536) throw new Error("npm\u53D1\u884C\u63CF\u8FF0\u8D85\u9650");
1757
+ const raw = JSON.parse(bytes.toString("utf8"));
1758
+ if (!raw || typeof raw !== "object") throw new Error("npm\u53D1\u884C\u63CF\u8FF0\u65E0\u6548");
1759
+ const value = raw;
1760
+ if (value.schema_version !== 1 || value.name !== NPM_PACKAGE_NAME || typeof value.version !== "string" || !/^\d+\.\d+\.\d+(?:-[a-z0-9.-]+)?$/.test(value.version) || !Array.isArray(value.targets))
1761
+ throw new Error("npm\u53D1\u884C\u63CF\u8FF0\u65E0\u6548");
1762
+ verifyReleaseSignature(
1763
+ bytes,
1764
+ JSON.parse(await readFile(join3(directory, "release.signature.json"), "utf8")),
1765
+ `/downloads/cli/node/npm/${value.version}/release.json`
1766
+ );
1767
+ const keys = /* @__PURE__ */ new Set();
1768
+ const targets = value.targets.map((target) => {
1769
+ if (!target || typeof target !== "object") throw new Error("npm\u53D1\u884C\u76EE\u6807\u65E0\u6548");
1770
+ const item = target;
1771
+ if (!INSTALL_MODES.includes(item.mode) || !INSTALL_PLATFORMS.includes(item.platform) || !INSTALL_ARCHITECTURES.includes(item.arch) || !["stable", "trial"].includes(String(item.channel)) || typeof item.manifest !== "string" || typeof item.manifest_sha256 !== "string" || !/^[a-f0-9]{64}$/.test(item.manifest_sha256) || typeof item.build_id !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,100}$/.test(item.build_id))
1772
+ throw new Error("npm\u53D1\u884C\u76EE\u6807\u5B57\u6BB5\u65E0\u6548");
1773
+ const url = new URL(item.manifest);
1774
+ if (url.origin !== "https://cli.xaweiju.com" || url.username || url.password || url.hash || url.search || !url.pathname.startsWith("/downloads/cli/node/") || !url.pathname.endsWith("/manifest.json"))
1775
+ throw new Error("npm\u53D1\u884C\u76EE\u6807\u6765\u6E90\u65E0\u6548");
1776
+ const key = `${item.mode}/${item.platform}/${item.arch}/${item.channel}`;
1777
+ if (keys.has(key)) throw new Error("npm\u53D1\u884C\u76EE\u6807\u91CD\u590D");
1778
+ keys.add(key);
1779
+ return {
1780
+ mode: item.mode,
1781
+ platform: item.platform,
1782
+ arch: item.arch,
1783
+ channel: item.channel,
1784
+ manifest: item.manifest,
1785
+ manifest_sha256: item.manifest_sha256,
1786
+ build_id: item.build_id
1787
+ };
1788
+ });
1789
+ return { schema_version: 1, name: value.name, version: value.version, targets };
1790
+ }
1791
+ async function runNpmChild(command, argumentsList) {
1792
+ return new Promise((accept, reject) => {
1793
+ const child = spawn(command, argumentsList, { stdio: "inherit", shell: false });
1794
+ const forwardInterrupt = () => {
1795
+ child.kill("SIGINT");
1796
+ };
1797
+ const forwardTerminate = () => {
1798
+ child.kill("SIGTERM");
1799
+ };
1800
+ process.on("SIGINT", forwardInterrupt);
1801
+ process.on("SIGTERM", forwardTerminate);
1802
+ const cleanup = () => {
1803
+ process.off("SIGINT", forwardInterrupt);
1804
+ process.off("SIGTERM", forwardTerminate);
1805
+ };
1806
+ child.once("error", (error) => {
1807
+ cleanup();
1808
+ reject(error);
1809
+ });
1810
+ child.once("exit", (code, signal) => {
1811
+ cleanup();
1812
+ accept(code ?? (signal === "SIGINT" ? 130 : 143));
1813
+ });
1814
+ });
1815
+ }
1816
+ async function readPrivateInstallationFile(root, filename = "installation.json") {
1817
+ try {
1818
+ const file = join3(root, filename);
1819
+ const info = await lstat2(file);
1820
+ if (!info.isFile() || info.size > 65536 || await realpath2(file) !== file || process.platform !== "win32" && (info.uid !== process.getuid?.() || info.mode & 63))
1821
+ throw new Error("\u5B89\u88C5\u5143\u6570\u636E\u4E0D\u662F\u53D7\u4FDD\u62A4\u666E\u901A\u6587\u4EF6");
1822
+ const value = JSON.parse(await readFile(file, "utf8"));
1823
+ if (!value || typeof value !== "object" || Array.isArray(value))
1824
+ throw new Error("\u5B89\u88C5\u5143\u6570\u636E\u683C\u5F0F\u65E0\u6548");
1825
+ return value;
1826
+ } catch (error) {
1827
+ if (error.code === "ENOENT") return null;
1828
+ throw error;
1829
+ }
1830
+ }
1831
+ async function nativeArchitecture() {
1832
+ if (process.platform === "darwin") {
1833
+ const { execFile } = await import("node:child_process");
1834
+ const { promisify } = await import("node:util");
1835
+ try {
1836
+ if ((await promisify(execFile)("/usr/sbin/sysctl", ["-n", "hw.optional.arm64"])).stdout.trim() === "1")
1837
+ return "arm64";
1838
+ } catch {
1839
+ }
1840
+ }
1841
+ if (process.platform === "win32") {
1842
+ const architecture = (process.env.PROCESSOR_ARCHITEW6432 ?? process.env.PROCESSOR_ARCHITECTURE ?? process.arch).toLowerCase();
1843
+ return architecture === "amd64" ? "x64" : architecture;
1844
+ }
1845
+ return process.arch;
1846
+ }
1847
+ async function installFromNpm(release, argv, onFormat) {
1848
+ const { values } = parseArgs({
1849
+ args: argv,
1850
+ options: {
1851
+ mode: { type: "string", default: "personal" },
1852
+ channel: { type: "string", default: "stable" },
1853
+ root: { type: "string" },
1854
+ config: { type: "string" },
1855
+ "skill-dir": { type: "string", multiple: true },
1856
+ "update-policy": { type: "string" },
1857
+ "no-path": { type: "boolean" },
1858
+ "verify-connection": { type: "boolean" },
1859
+ json: { type: "boolean" },
1860
+ human: { type: "boolean" }
1861
+ }
1862
+ });
1863
+ onFormat?.(values.json === true);
1864
+ if (values.json && values.human) throw new Error("--json\u4E0E--human\u4E0D\u80FD\u540C\u65F6\u4F7F\u7528");
1865
+ if (!INSTALL_MODES.includes(values.mode) || !["stable", "trial"].includes(values.channel))
1866
+ throw new Error("\u5B89\u88C5\u6A21\u5F0F\u6216\u901A\u9053\u65E0\u6548");
1867
+ const arch = await nativeArchitecture();
1868
+ const matches = release.targets.filter(
1869
+ (target2) => target2.mode === values.mode && target2.platform === process.platform && target2.arch === arch && target2.channel === values.channel
1870
+ );
1871
+ if (matches.length !== 1)
1872
+ throw new Error(
1873
+ "\u5F53\u524D\u5E73\u53F0\u6CA1\u6709\u6B63\u5F0F\u76EE\u6807\uFF1B\u5982\u786E\u8BA4\u63A5\u53D7\u672A\u5B8C\u6210\u539F\u751F\u9A8C\u6536\u7684\u8BD5\u7528\u5305\uFF0C\u8BF7\u663E\u5F0F\u4F7F\u7528 --channel trial\u3002\u7F51\u7EDC\u9519\u8BEF\u4E0D\u4F1A\u81EA\u52A8\u5207\u6362\u901A\u9053\u3002"
1874
+ );
1875
+ const target = matches[0];
1876
+ if (target.channel === "trial")
1877
+ process.stderr.write("\u6CE8\u610F\uFF1A\u5F53\u524D\u76EE\u6807\u4E3A\u8BD5\u7528\u901A\u9053\uFF0C\u539F\u751F\u9A8C\u6536\u672A\u5B8C\u6210\uFF0C\u4E0D\u542F\u7528\u81EA\u52A8\u5347\u7EA7\u3002\n");
1878
+ const root = resolve2(values.root ?? defaultInstallRoot(target.mode));
1879
+ const previous = await readPrivateInstallationFile(root);
1880
+ process.stderr.write(
1881
+ `\u6B63\u5728\u9A8C\u8BC1 ${release.name}@${release.version} \u5BF9\u5E94\u7684 ${target.mode}/${target.platform}/${target.arch} \u5BA2\u6237\u7AEF\u3002
1882
+ `
1883
+ );
1884
+ const manifest = await downloadVerifiedRelease(target.manifest, 8 * 1024 * 1024);
1885
+ if (createHash3("sha256").update(manifest).digest("hex") !== target.manifest_sha256)
1886
+ throw new Error("npm\u76EE\u6807\u4E0E\u56FA\u5B9A\u6E05\u5355\u6458\u8981\u4E0D\u4E00\u81F4");
1887
+ const data = JSON.parse(manifest.toString("utf8"));
1888
+ if (data.schema_version !== 1 || !Array.isArray(data.artifacts) || data.artifacts.length !== 1)
1889
+ throw new Error("\u56FA\u5B9A\u6E05\u5355\u5FC5\u987B\u53EA\u6709\u4E00\u4E2A\u76EE\u6807");
1890
+ const artifact = validateArtifact(data.artifacts[0]);
1891
+ if (artifact.build_id !== target.build_id || artifact.mode !== target.mode || artifact.platform !== target.platform || artifact.arch !== target.arch)
1892
+ throw new Error("npm\u76EE\u6807\u4E0E\u5236\u54C1\u8EAB\u4EFD\u4E0D\u4E00\u81F4");
1893
+ if (previous && Number(previous.release_sequence) > artifact.release_sequence)
1894
+ throw new Error("\u5DF2\u5B89\u88C5\u7248\u672C\u8F83\u65B0\uFF0C\u4FDD\u7559\u5F53\u524D\u7248\u672C\uFF1B\u666E\u901A\u5B89\u88C5\u7981\u6B62\u964D\u7EA7");
1895
+ const stage = await realpath2(await mkdtemp(join3(tmpdir(), "kscs-npm-")));
1896
+ try {
1897
+ const archive = join3(stage, "application.zip");
1898
+ process.stderr.write(`\u6B63\u5728\u4E0B\u8F7D\u5BA2\u6237\u7AEF ${artifact.version}\uFF08${artifact.build_id}\uFF09\u3002
1899
+ `);
1900
+ const size = await downloadFile(
1901
+ sameOriginUrl(artifact.url, target.manifest),
1902
+ archive,
1903
+ 512 * 1024 * 1024,
1904
+ false,
1905
+ values.json ? void 0 : createDownloadProgress(artifact.size)
1906
+ );
1907
+ if (size !== artifact.size || await fileDigest(archive) !== artifact.sha256)
1908
+ throw new Error("\u5BA2\u6237\u7AEF\u5927\u5C0F\u6216\u6458\u8981\u4E0D\u4E00\u81F4");
1909
+ await unpackArchive(archive, join3(stage, "unpacked"));
1910
+ const application = join3(stage, "unpacked/kscs-cli");
1911
+ await verifyReleaseFiles(application, artifact.files);
1912
+ const installerArguments = [
1913
+ "--mode",
1914
+ target.mode,
1915
+ "--root",
1916
+ root,
1917
+ "--manifest",
1918
+ target.manifest,
1919
+ "--manifest-sha256",
1920
+ target.manifest_sha256,
1921
+ "--expected-build",
1922
+ target.build_id,
1923
+ "--archive-path",
1924
+ archive
1925
+ ];
1926
+ if (values.json) installerArguments.push("--json");
1927
+ for (const option of ["config", "update-policy"])
1928
+ if (values[option]) installerArguments.push("--" + option, values[option]);
1929
+ for (const directory of values["skill-dir"] ?? [])
1930
+ installerArguments.push("--skill-dir", directory);
1931
+ if (values["no-path"]) installerArguments.push("--no-path");
1932
+ if (values["verify-connection"]) installerArguments.push("--verify-connection");
1933
+ if (target.channel === "trial") {
1934
+ if (values["update-policy"] === "auto") throw new Error("\u8BD5\u7528\u76EE\u6807\u7981\u6B62\u81EA\u52A8\u5347\u7EA7");
1935
+ installerArguments.push("--update-policy", "off");
1936
+ }
1937
+ const status = await runNpmChild(
1938
+ join3(application, process.platform === "win32" ? "runtime/node.exe" : "runtime/node"),
1939
+ [join3(application, "dist/service/installation/install.entry.js"), ...installerArguments]
1940
+ );
1941
+ if (status !== 0) return status;
1942
+ const receipt = await readPrivateInstallationFile(root);
1943
+ if (receipt?.build_id !== artifact.build_id || receipt.root !== root || receipt.command !== launcherPath(root))
1944
+ throw new Error("\u5B89\u88C5\u56DE\u6267\u4E0E\u76EE\u6807\u4E0D\u4E00\u81F4");
1945
+ return 0;
1946
+ } finally {
1947
+ await rm(stage, { recursive: true, force: true });
1948
+ }
1949
+ }
1950
+ async function forwardNpmCommand(argv) {
1951
+ const root = defaultInstallRoot("personal");
1952
+ const receipt = await readPrivateInstallationFile(root);
1953
+ if (!receipt || receipt.installer_runtime !== "node" || receipt.root !== root || receipt.command !== launcherPath(root) || typeof receipt.build_id !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,100}$/.test(receipt.build_id))
1954
+ throw new Error(
1955
+ "\u672A\u627E\u5230\u6709\u6548\u4E2A\u4EBA\u5B89\u88C5\uFF0C\u8BF7\u5148\u8FD0\u884C npx <\u5305\u540D>@latest install\uFF1B\u81EA\u5B9A\u4E49\u6216\u56E2\u961F\u5B89\u88C5\u8BF7\u4F7F\u7528\u56DE\u6267\u4E2D\u7684\u7EDD\u5BF9\u5165\u53E3"
1956
+ );
1957
+ const expectedApplication = join3(root, "releases", receipt.build_id);
1958
+ if (process.platform === "win32") {
1959
+ const pointer = await readPrivateInstallationFile(root, "current.json");
1960
+ if (pointer?.release !== `releases/${receipt.build_id}`)
1961
+ throw new Error("\u7248\u672C\u6307\u9488\u4E0E\u56DE\u6267\u4E0D\u4E00\u81F4");
1962
+ }
1963
+ const application = await realpath2(
1964
+ process.platform === "win32" ? expectedApplication : join3(root, "current")
1965
+ );
1966
+ if (application !== expectedApplication)
1967
+ throw new Error("\u7248\u672C\u6307\u9488\u4E0E\u56DE\u6267\u4E0D\u4E00\u81F4");
1968
+ return runNpmChild(
1969
+ join3(application, process.platform === "win32" ? "runtime/node.exe" : "runtime/node"),
1970
+ [join3(application, "dist/service/installation/update.entry.js"), "--root", root, "--", ...argv]
1971
+ );
1972
+ }
1973
+
1974
+ // cli/src/service/installation/npm.entry.ts
1975
+ var jsonOutput = false;
1976
+ async function main() {
1977
+ const argv = process.argv.slice(2);
1978
+ if (argv[0] === "--entry-version") {
1979
+ const release2 = await readNpmRelease(resolve3(dirname2(fileURLToPath(import.meta.url)), ".."));
1980
+ process.stdout.write(`${release2.name}@${release2.version}
1981
+ `);
1982
+ return;
1983
+ }
1984
+ if (!argv.length || argv[0] === "--help" || argv[0] === "-h" || argv[0] === "install" && argv.includes("--help")) {
1985
+ process.stdout.write(
1986
+ `\u65F7\u4E16\u4F20\u58F0 CLI \u5B89\u88C5\u5165\u53E3
1987
+
1988
+ \u7528\u6CD5\uFF1Anpx ${NPM_PACKAGE_NAME}@latest install [--mode personal|team] [--channel stable|trial]
1989
+ \u53EF\u9009\uFF1A--root \u79C1\u6709\u76EE\u5F55 --config \u5DF2\u6709\u914D\u7F6E --skill-dir \u6280\u80FD\u76EE\u5F55 --update-policy off|notify|auto --no-path
1990
+
1991
+ \u5B89\u88C5\u540E\uFF1Akscs --version\uFF1Bkscs auth login\uFF1Bkscs products list
1992
+ \u65E0\u9700Python\u3001Java\u6216\u7F16\u8BD1\u5668\u3002\u6CA1\u6709Node\u8BF7\u8BBF\u95EE https://cli.xaweiju.com/install/
1993
+ \u5378\u8F7Dnpm\u5165\u53E3\u4E0D\u4F1A\u5220\u9664\u5B9E\u9645\u5BA2\u6237\u7AEF\u3001\u8EAB\u4EFD\u914D\u7F6E\u6216Skill\u3002
1994
+ `
1995
+ );
1996
+ return;
1997
+ }
1998
+ if (argv[0] !== "install") {
1999
+ process.exitCode = await forwardNpmCommand(argv);
2000
+ return;
2001
+ }
2002
+ jsonOutput = argv.includes("--json") && !argv.includes("--human");
2003
+ const release = await readNpmRelease(resolve3(dirname2(fileURLToPath(import.meta.url)), ".."));
2004
+ process.exitCode = await installFromNpm(release, argv.slice(1), (json) => {
2005
+ jsonOutput = json;
2006
+ });
2007
+ }
2008
+ void main().catch((error) => {
2009
+ const message = error instanceof Error ? error.message : String(error);
2010
+ process.stderr.write(
2011
+ jsonOutput ? JSON.stringify({ installed: false, status: "installation_failed", message }) + "\n" : `\u5B89\u88C5\u5165\u53E3\u5931\u8D25\uFF1A${message}
2012
+ `
2013
+ );
2014
+ process.exitCode = 1;
2015
+ });