UNPKG

@xmcl/installer

Version:

The installers of Minecraft/Forge/Fabric/Liteloader/Quilt

1,417 lines (1,406 loc) 121 kB
var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { get: (a, b) => (typeof require !== "undefined" ? require : a)[b] }) : x)(function(x) { if (typeof require !== "undefined") return require.apply(this, arguments); throw new Error('Dynamic require of "' + x + '" is not supported'); }); var __commonJS = (cb, mod) => function __require2() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); // ../../node_modules/.pnpm/buffer-crc32@0.2.13/node_modules/buffer-crc32/index.js var require_buffer_crc32 = __commonJS({ "../../node_modules/.pnpm/buffer-crc32@0.2.13/node_modules/buffer-crc32/index.js"(exports, module) { var Buffer2 = __require("buffer").Buffer; var CRC_TABLE = [ 0, 1996959894, 3993919788, 2567524794, 124634137, 1886057615, 3915621685, 2657392035, 249268274, 2044508324, 3772115230, 2547177864, 162941995, 2125561021, 3887607047, 2428444049, 498536548, 1789927666, 4089016648, 2227061214, 450548861, 1843258603, 4107580753, 2211677639, 325883990, 1684777152, 4251122042, 2321926636, 335633487, 1661365465, 4195302755, 2366115317, 997073096, 1281953886, 3579855332, 2724688242, 1006888145, 1258607687, 3524101629, 2768942443, 901097722, 1119000684, 3686517206, 2898065728, 853044451, 1172266101, 3705015759, 2882616665, 651767980, 1373503546, 3369554304, 3218104598, 565507253, 1454621731, 3485111705, 3099436303, 671266974, 1594198024, 3322730930, 2970347812, 795835527, 1483230225, 3244367275, 3060149565, 1994146192, 31158534, 2563907772, 4023717930, 1907459465, 112637215, 2680153253, 3904427059, 2013776290, 251722036, 2517215374, 3775830040, 2137656763, 141376813, 2439277719, 3865271297, 1802195444, 476864866, 2238001368, 4066508878, 1812370925, 453092731, 2181625025, 4111451223, 1706088902, 314042704, 2344532202, 4240017532, 1658658271, 366619977, 2362670323, 4224994405, 1303535960, 984961486, 2747007092, 3569037538, 1256170817, 1037604311, 2765210733, 3554079995, 1131014506, 879679996, 2909243462, 3663771856, 1141124467, 855842277, 2852801631, 3708648649, 1342533948, 654459306, 3188396048, 3373015174, 1466479909, 544179635, 3110523913, 3462522015, 1591671054, 702138776, 2966460450, 3352799412, 1504918807, 783551873, 3082640443, 3233442989, 3988292384, 2596254646, 62317068, 1957810842, 3939845945, 2647816111, 81470997, 1943803523, 3814918930, 2489596804, 225274430, 2053790376, 3826175755, 2466906013, 167816743, 2097651377, 4027552580, 2265490386, 503444072, 1762050814, 4150417245, 2154129355, 426522225, 1852507879, 4275313526, 2312317920, 282753626, 1742555852, 4189708143, 2394877945, 397917763, 1622183637, 3604390888, 2714866558, 953729732, 1340076626, 3518719985, 2797360999, 1068828381, 1219638859, 3624741850, 2936675148, 906185462, 1090812512, 3747672003, 2825379669, 829329135, 1181335161, 3412177804, 3160834842, 628085408, 1382605366, 3423369109, 3138078467, 570562233, 1426400815, 3317316542, 2998733608, 733239954, 1555261956, 3268935591, 3050360625, 752459403, 1541320221, 2607071920, 3965973030, 1969922972, 40735498, 2617837225, 3943577151, 1913087877, 83908371, 2512341634, 3803740692, 2075208622, 213261112, 2463272603, 3855990285, 2094854071, 198958881, 2262029012, 4057260610, 1759359992, 534414190, 2176718541, 4139329115, 1873836001, 414664567, 2282248934, 4279200368, 1711684554, 285281116, 2405801727, 4167216745, 1634467795, 376229701, 2685067896, 3608007406, 1308918612, 956543938, 2808555105, 3495958263, 1231636301, 1047427035, 2932959818, 3654703836, 1088359270, 936918e3, 2847714899, 3736837829, 1202900863, 817233897, 3183342108, 3401237130, 1404277552, 615818150, 3134207493, 3453421203, 1423857449, 601450431, 3009837614, 3294710456, 1567103746, 711928724, 3020668471, 3272380065, 1510334235, 755167117 ]; if (typeof Int32Array !== "undefined") { CRC_TABLE = new Int32Array(CRC_TABLE); } function ensureBuffer(input) { if (Buffer2.isBuffer(input)) { return input; } var hasNewBufferAPI = typeof Buffer2.alloc === "function" && typeof Buffer2.from === "function"; if (typeof input === "number") { return hasNewBufferAPI ? Buffer2.alloc(input) : new Buffer2(input); } else if (typeof input === "string") { return hasNewBufferAPI ? Buffer2.from(input) : new Buffer2(input); } else { throw new Error("input must be buffer, number, or string, received " + typeof input); } } function bufferizeInt(num) { var tmp = ensureBuffer(4); tmp.writeInt32BE(num, 0); return tmp; } function _crc32(buf, previous) { buf = ensureBuffer(buf); if (Buffer2.isBuffer(previous)) { previous = previous.readUInt32BE(0); } var crc = ~~previous ^ -1; for (var n = 0; n < buf.length; n++) { crc = CRC_TABLE[(crc ^ buf[n]) & 255] ^ crc >>> 8; } return crc ^ -1; } function crc32() { return bufferizeInt(_crc32.apply(null, arguments)); } crc32.signed = function() { return _crc32.apply(null, arguments); }; crc32.unsigned = function() { return _crc32.apply(null, arguments) >>> 0; }; module.exports = crc32; } }); // ../../node_modules/.pnpm/yazl@2.5.1/node_modules/yazl/index.js var require_yazl = __commonJS({ "../../node_modules/.pnpm/yazl@2.5.1/node_modules/yazl/index.js"(exports) { var fs = __require("fs"); var Transform = __require("stream").Transform; var PassThrough = __require("stream").PassThrough; var zlib = __require("zlib"); var util = __require("util"); var EventEmitter = __require("events").EventEmitter; var crc32 = require_buffer_crc32(); exports.ZipFile = ZipFile; exports.dateToDosDateTime = dateToDosDateTime; util.inherits(ZipFile, EventEmitter); function ZipFile() { this.outputStream = new PassThrough(); this.entries = []; this.outputStreamCursor = 0; this.ended = false; this.allDone = false; this.forceZip64Eocd = false; } ZipFile.prototype.addFile = function(realPath, metadataPath, options) { var self = this; metadataPath = validateMetadataPath(metadataPath, false); if (options == null) options = {}; var entry = new Entry(metadataPath, false, options); self.entries.push(entry); fs.stat(realPath, function(err, stats) { if (err) return self.emit("error", err); if (!stats.isFile()) return self.emit("error", new Error("not a file: " + realPath)); entry.uncompressedSize = stats.size; if (options.mtime == null) entry.setLastModDate(stats.mtime); if (options.mode == null) entry.setFileAttributesMode(stats.mode); entry.setFileDataPumpFunction(function() { var readStream = fs.createReadStream(realPath); entry.state = Entry.FILE_DATA_IN_PROGRESS; readStream.on("error", function(err2) { self.emit("error", err2); }); pumpFileDataReadStream(self, entry, readStream); }); pumpEntries(self); }); }; ZipFile.prototype.addReadStream = function(readStream, metadataPath, options) { var self = this; metadataPath = validateMetadataPath(metadataPath, false); if (options == null) options = {}; var entry = new Entry(metadataPath, false, options); self.entries.push(entry); entry.setFileDataPumpFunction(function() { entry.state = Entry.FILE_DATA_IN_PROGRESS; pumpFileDataReadStream(self, entry, readStream); }); pumpEntries(self); }; ZipFile.prototype.addBuffer = function(buffer, metadataPath, options) { var self = this; metadataPath = validateMetadataPath(metadataPath, false); if (buffer.length > 1073741823) throw new Error("buffer too large: " + buffer.length + " > 1073741823"); if (options == null) options = {}; if (options.size != null) throw new Error("options.size not allowed"); var entry = new Entry(metadataPath, false, options); entry.uncompressedSize = buffer.length; entry.crc32 = crc32.unsigned(buffer); entry.crcAndFileSizeKnown = true; self.entries.push(entry); if (!entry.compress) { setCompressedBuffer(buffer); } else { zlib.deflateRaw(buffer, function(err, compressedBuffer) { setCompressedBuffer(compressedBuffer); }); } function setCompressedBuffer(compressedBuffer) { entry.compressedSize = compressedBuffer.length; entry.setFileDataPumpFunction(function() { writeToOutputStream(self, compressedBuffer); writeToOutputStream(self, entry.getDataDescriptor()); entry.state = Entry.FILE_DATA_DONE; setImmediate(function() { pumpEntries(self); }); }); pumpEntries(self); } }; ZipFile.prototype.addEmptyDirectory = function(metadataPath, options) { var self = this; metadataPath = validateMetadataPath(metadataPath, true); if (options == null) options = {}; if (options.size != null) throw new Error("options.size not allowed"); if (options.compress != null) throw new Error("options.compress not allowed"); var entry = new Entry(metadataPath, true, options); self.entries.push(entry); entry.setFileDataPumpFunction(function() { writeToOutputStream(self, entry.getDataDescriptor()); entry.state = Entry.FILE_DATA_DONE; pumpEntries(self); }); pumpEntries(self); }; var eocdrSignatureBuffer = bufferFrom([80, 75, 5, 6]); ZipFile.prototype.end = function(options, finalSizeCallback) { if (typeof options === "function") { finalSizeCallback = options; options = null; } if (options == null) options = {}; if (this.ended) return; this.ended = true; this.finalSizeCallback = finalSizeCallback; this.forceZip64Eocd = !!options.forceZip64Format; if (options.comment) { if (typeof options.comment === "string") { this.comment = encodeCp437(options.comment); } else { this.comment = options.comment; } if (this.comment.length > 65535) throw new Error("comment is too large"); if (bufferIncludes(this.comment, eocdrSignatureBuffer)) throw new Error("comment contains end of central directory record signature"); } else { this.comment = EMPTY_BUFFER; } pumpEntries(this); }; function writeToOutputStream(self, buffer) { self.outputStream.write(buffer); self.outputStreamCursor += buffer.length; } function pumpFileDataReadStream(self, entry, readStream) { var crc32Watcher = new Crc32Watcher(); var uncompressedSizeCounter = new ByteCounter(); var compressor = entry.compress ? new zlib.DeflateRaw() : new PassThrough(); var compressedSizeCounter = new ByteCounter(); readStream.pipe(crc32Watcher).pipe(uncompressedSizeCounter).pipe(compressor).pipe(compressedSizeCounter).pipe(self.outputStream, { end: false }); compressedSizeCounter.on("end", function() { entry.crc32 = crc32Watcher.crc32; if (entry.uncompressedSize == null) { entry.uncompressedSize = uncompressedSizeCounter.byteCount; } else { if (entry.uncompressedSize !== uncompressedSizeCounter.byteCount) return self.emit("error", new Error("file data stream has unexpected number of bytes")); } entry.compressedSize = compressedSizeCounter.byteCount; self.outputStreamCursor += entry.compressedSize; writeToOutputStream(self, entry.getDataDescriptor()); entry.state = Entry.FILE_DATA_DONE; pumpEntries(self); }); } function pumpEntries(self) { if (self.allDone) return; if (self.ended && self.finalSizeCallback != null) { var finalSize = calculateFinalSize(self); if (finalSize != null) { self.finalSizeCallback(finalSize); self.finalSizeCallback = null; } } var entry = getFirstNotDoneEntry(); function getFirstNotDoneEntry() { for (var i = 0; i < self.entries.length; i++) { var entry2 = self.entries[i]; if (entry2.state < Entry.FILE_DATA_DONE) return entry2; } return null; } if (entry != null) { if (entry.state < Entry.READY_TO_PUMP_FILE_DATA) return; if (entry.state === Entry.FILE_DATA_IN_PROGRESS) return; entry.relativeOffsetOfLocalHeader = self.outputStreamCursor; var localFileHeader = entry.getLocalFileHeader(); writeToOutputStream(self, localFileHeader); entry.doFileDataPump(); } else { if (self.ended) { self.offsetOfStartOfCentralDirectory = self.outputStreamCursor; self.entries.forEach(function(entry2) { var centralDirectoryRecord = entry2.getCentralDirectoryRecord(); writeToOutputStream(self, centralDirectoryRecord); }); writeToOutputStream(self, getEndOfCentralDirectoryRecord(self)); self.outputStream.end(); self.allDone = true; } } } function calculateFinalSize(self) { var pretendOutputCursor = 0; var centralDirectorySize = 0; for (var i = 0; i < self.entries.length; i++) { var entry = self.entries[i]; if (entry.compress) return -1; if (entry.state >= Entry.READY_TO_PUMP_FILE_DATA) { if (entry.uncompressedSize == null) return -1; } else { if (entry.uncompressedSize == null) return null; } entry.relativeOffsetOfLocalHeader = pretendOutputCursor; var useZip64Format = entry.useZip64Format(); pretendOutputCursor += LOCAL_FILE_HEADER_FIXED_SIZE + entry.utf8FileName.length; pretendOutputCursor += entry.uncompressedSize; if (!entry.crcAndFileSizeKnown) { if (useZip64Format) { pretendOutputCursor += ZIP64_DATA_DESCRIPTOR_SIZE; } else { pretendOutputCursor += DATA_DESCRIPTOR_SIZE; } } centralDirectorySize += CENTRAL_DIRECTORY_RECORD_FIXED_SIZE + entry.utf8FileName.length + entry.fileComment.length; if (useZip64Format) { centralDirectorySize += ZIP64_EXTENDED_INFORMATION_EXTRA_FIELD_SIZE; } } var endOfCentralDirectorySize = 0; if (self.forceZip64Eocd || self.entries.length >= 65535 || centralDirectorySize >= 65535 || pretendOutputCursor >= 4294967295) { endOfCentralDirectorySize += ZIP64_END_OF_CENTRAL_DIRECTORY_RECORD_SIZE + ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR_SIZE; } endOfCentralDirectorySize += END_OF_CENTRAL_DIRECTORY_RECORD_SIZE + self.comment.length; return pretendOutputCursor + centralDirectorySize + endOfCentralDirectorySize; } var ZIP64_END_OF_CENTRAL_DIRECTORY_RECORD_SIZE = 56; var ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR_SIZE = 20; var END_OF_CENTRAL_DIRECTORY_RECORD_SIZE = 22; function getEndOfCentralDirectoryRecord(self, actuallyJustTellMeHowLongItWouldBe) { var needZip64Format = false; var normalEntriesLength = self.entries.length; if (self.forceZip64Eocd || self.entries.length >= 65535) { normalEntriesLength = 65535; needZip64Format = true; } var sizeOfCentralDirectory = self.outputStreamCursor - self.offsetOfStartOfCentralDirectory; var normalSizeOfCentralDirectory = sizeOfCentralDirectory; if (self.forceZip64Eocd || sizeOfCentralDirectory >= 4294967295) { normalSizeOfCentralDirectory = 4294967295; needZip64Format = true; } var normalOffsetOfStartOfCentralDirectory = self.offsetOfStartOfCentralDirectory; if (self.forceZip64Eocd || self.offsetOfStartOfCentralDirectory >= 4294967295) { normalOffsetOfStartOfCentralDirectory = 4294967295; needZip64Format = true; } if (actuallyJustTellMeHowLongItWouldBe) { if (needZip64Format) { return ZIP64_END_OF_CENTRAL_DIRECTORY_RECORD_SIZE + ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR_SIZE + END_OF_CENTRAL_DIRECTORY_RECORD_SIZE; } else { return END_OF_CENTRAL_DIRECTORY_RECORD_SIZE; } } var eocdrBuffer = bufferAlloc(END_OF_CENTRAL_DIRECTORY_RECORD_SIZE + self.comment.length); eocdrBuffer.writeUInt32LE(101010256, 0); eocdrBuffer.writeUInt16LE(0, 4); eocdrBuffer.writeUInt16LE(0, 6); eocdrBuffer.writeUInt16LE(normalEntriesLength, 8); eocdrBuffer.writeUInt16LE(normalEntriesLength, 10); eocdrBuffer.writeUInt32LE(normalSizeOfCentralDirectory, 12); eocdrBuffer.writeUInt32LE(normalOffsetOfStartOfCentralDirectory, 16); eocdrBuffer.writeUInt16LE(self.comment.length, 20); self.comment.copy(eocdrBuffer, 22); if (!needZip64Format) return eocdrBuffer; var zip64EocdrBuffer = bufferAlloc(ZIP64_END_OF_CENTRAL_DIRECTORY_RECORD_SIZE); zip64EocdrBuffer.writeUInt32LE(101075792, 0); writeUInt64LE(zip64EocdrBuffer, ZIP64_END_OF_CENTRAL_DIRECTORY_RECORD_SIZE - 12, 4); zip64EocdrBuffer.writeUInt16LE(VERSION_MADE_BY, 12); zip64EocdrBuffer.writeUInt16LE(VERSION_NEEDED_TO_EXTRACT_ZIP64, 14); zip64EocdrBuffer.writeUInt32LE(0, 16); zip64EocdrBuffer.writeUInt32LE(0, 20); writeUInt64LE(zip64EocdrBuffer, self.entries.length, 24); writeUInt64LE(zip64EocdrBuffer, self.entries.length, 32); writeUInt64LE(zip64EocdrBuffer, sizeOfCentralDirectory, 40); writeUInt64LE(zip64EocdrBuffer, self.offsetOfStartOfCentralDirectory, 48); var zip64EocdlBuffer = bufferAlloc(ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR_SIZE); zip64EocdlBuffer.writeUInt32LE(117853008, 0); zip64EocdlBuffer.writeUInt32LE(0, 4); writeUInt64LE(zip64EocdlBuffer, self.outputStreamCursor, 8); zip64EocdlBuffer.writeUInt32LE(1, 16); return Buffer.concat([ zip64EocdrBuffer, zip64EocdlBuffer, eocdrBuffer ]); } function validateMetadataPath(metadataPath, isDirectory) { if (metadataPath === "") throw new Error("empty metadataPath"); metadataPath = metadataPath.replace(/\\/g, "/"); if (/^[a-zA-Z]:/.test(metadataPath) || /^\//.test(metadataPath)) throw new Error("absolute path: " + metadataPath); if (metadataPath.split("/").indexOf("..") !== -1) throw new Error("invalid relative path: " + metadataPath); var looksLikeDirectory = /\/$/.test(metadataPath); if (isDirectory) { if (!looksLikeDirectory) metadataPath += "/"; } else { if (looksLikeDirectory) throw new Error("file path cannot end with '/': " + metadataPath); } return metadataPath; } var EMPTY_BUFFER = bufferAlloc(0); function Entry(metadataPath, isDirectory, options) { this.utf8FileName = bufferFrom(metadataPath); if (this.utf8FileName.length > 65535) throw new Error("utf8 file name too long. " + utf8FileName.length + " > 65535"); this.isDirectory = isDirectory; this.state = Entry.WAITING_FOR_METADATA; this.setLastModDate(options.mtime != null ? options.mtime : /* @__PURE__ */ new Date()); if (options.mode != null) { this.setFileAttributesMode(options.mode); } else { this.setFileAttributesMode(isDirectory ? 16893 : 33204); } if (isDirectory) { this.crcAndFileSizeKnown = true; this.crc32 = 0; this.uncompressedSize = 0; this.compressedSize = 0; } else { this.crcAndFileSizeKnown = false; this.crc32 = null; this.uncompressedSize = null; this.compressedSize = null; if (options.size != null) this.uncompressedSize = options.size; } if (isDirectory) { this.compress = false; } else { this.compress = true; if (options.compress != null) this.compress = !!options.compress; } this.forceZip64Format = !!options.forceZip64Format; if (options.fileComment) { if (typeof options.fileComment === "string") { this.fileComment = bufferFrom(options.fileComment, "utf-8"); } else { this.fileComment = options.fileComment; } if (this.fileComment.length > 65535) throw new Error("fileComment is too large"); } else { this.fileComment = EMPTY_BUFFER; } } Entry.WAITING_FOR_METADATA = 0; Entry.READY_TO_PUMP_FILE_DATA = 1; Entry.FILE_DATA_IN_PROGRESS = 2; Entry.FILE_DATA_DONE = 3; Entry.prototype.setLastModDate = function(date) { var dosDateTime = dateToDosDateTime(date); this.lastModFileTime = dosDateTime.time; this.lastModFileDate = dosDateTime.date; }; Entry.prototype.setFileAttributesMode = function(mode) { if ((mode & 65535) !== mode) throw new Error("invalid mode. expected: 0 <= " + mode + " <= 65535"); this.externalFileAttributes = mode << 16 >>> 0; }; Entry.prototype.setFileDataPumpFunction = function(doFileDataPump) { this.doFileDataPump = doFileDataPump; this.state = Entry.READY_TO_PUMP_FILE_DATA; }; Entry.prototype.useZip64Format = function() { return this.forceZip64Format || this.uncompressedSize != null && this.uncompressedSize > 4294967294 || this.compressedSize != null && this.compressedSize > 4294967294 || this.relativeOffsetOfLocalHeader != null && this.relativeOffsetOfLocalHeader > 4294967294; }; var LOCAL_FILE_HEADER_FIXED_SIZE = 30; var VERSION_NEEDED_TO_EXTRACT_UTF8 = 20; var VERSION_NEEDED_TO_EXTRACT_ZIP64 = 45; var VERSION_MADE_BY = 3 << 8 | 63; var FILE_NAME_IS_UTF8 = 1 << 11; var UNKNOWN_CRC32_AND_FILE_SIZES = 1 << 3; Entry.prototype.getLocalFileHeader = function() { var crc322 = 0; var compressedSize = 0; var uncompressedSize = 0; if (this.crcAndFileSizeKnown) { crc322 = this.crc32; compressedSize = this.compressedSize; uncompressedSize = this.uncompressedSize; } var fixedSizeStuff = bufferAlloc(LOCAL_FILE_HEADER_FIXED_SIZE); var generalPurposeBitFlag = FILE_NAME_IS_UTF8; if (!this.crcAndFileSizeKnown) generalPurposeBitFlag |= UNKNOWN_CRC32_AND_FILE_SIZES; fixedSizeStuff.writeUInt32LE(67324752, 0); fixedSizeStuff.writeUInt16LE(VERSION_NEEDED_TO_EXTRACT_UTF8, 4); fixedSizeStuff.writeUInt16LE(generalPurposeBitFlag, 6); fixedSizeStuff.writeUInt16LE(this.getCompressionMethod(), 8); fixedSizeStuff.writeUInt16LE(this.lastModFileTime, 10); fixedSizeStuff.writeUInt16LE(this.lastModFileDate, 12); fixedSizeStuff.writeUInt32LE(crc322, 14); fixedSizeStuff.writeUInt32LE(compressedSize, 18); fixedSizeStuff.writeUInt32LE(uncompressedSize, 22); fixedSizeStuff.writeUInt16LE(this.utf8FileName.length, 26); fixedSizeStuff.writeUInt16LE(0, 28); return Buffer.concat([ fixedSizeStuff, // file name (variable size) this.utf8FileName // extra field (variable size) // no extra fields ]); }; var DATA_DESCRIPTOR_SIZE = 16; var ZIP64_DATA_DESCRIPTOR_SIZE = 24; Entry.prototype.getDataDescriptor = function() { if (this.crcAndFileSizeKnown) { return EMPTY_BUFFER; } if (!this.useZip64Format()) { var buffer = bufferAlloc(DATA_DESCRIPTOR_SIZE); buffer.writeUInt32LE(134695760, 0); buffer.writeUInt32LE(this.crc32, 4); buffer.writeUInt32LE(this.compressedSize, 8); buffer.writeUInt32LE(this.uncompressedSize, 12); return buffer; } else { var buffer = bufferAlloc(ZIP64_DATA_DESCRIPTOR_SIZE); buffer.writeUInt32LE(134695760, 0); buffer.writeUInt32LE(this.crc32, 4); writeUInt64LE(buffer, this.compressedSize, 8); writeUInt64LE(buffer, this.uncompressedSize, 16); return buffer; } }; var CENTRAL_DIRECTORY_RECORD_FIXED_SIZE = 46; var ZIP64_EXTENDED_INFORMATION_EXTRA_FIELD_SIZE = 28; Entry.prototype.getCentralDirectoryRecord = function() { var fixedSizeStuff = bufferAlloc(CENTRAL_DIRECTORY_RECORD_FIXED_SIZE); var generalPurposeBitFlag = FILE_NAME_IS_UTF8; if (!this.crcAndFileSizeKnown) generalPurposeBitFlag |= UNKNOWN_CRC32_AND_FILE_SIZES; var normalCompressedSize = this.compressedSize; var normalUncompressedSize = this.uncompressedSize; var normalRelativeOffsetOfLocalHeader = this.relativeOffsetOfLocalHeader; var versionNeededToExtract; var zeiefBuffer; if (this.useZip64Format()) { normalCompressedSize = 4294967295; normalUncompressedSize = 4294967295; normalRelativeOffsetOfLocalHeader = 4294967295; versionNeededToExtract = VERSION_NEEDED_TO_EXTRACT_ZIP64; zeiefBuffer = bufferAlloc(ZIP64_EXTENDED_INFORMATION_EXTRA_FIELD_SIZE); zeiefBuffer.writeUInt16LE(1, 0); zeiefBuffer.writeUInt16LE(ZIP64_EXTENDED_INFORMATION_EXTRA_FIELD_SIZE - 4, 2); writeUInt64LE(zeiefBuffer, this.uncompressedSize, 4); writeUInt64LE(zeiefBuffer, this.compressedSize, 12); writeUInt64LE(zeiefBuffer, this.relativeOffsetOfLocalHeader, 20); } else { versionNeededToExtract = VERSION_NEEDED_TO_EXTRACT_UTF8; zeiefBuffer = EMPTY_BUFFER; } fixedSizeStuff.writeUInt32LE(33639248, 0); fixedSizeStuff.writeUInt16LE(VERSION_MADE_BY, 4); fixedSizeStuff.writeUInt16LE(versionNeededToExtract, 6); fixedSizeStuff.writeUInt16LE(generalPurposeBitFlag, 8); fixedSizeStuff.writeUInt16LE(this.getCompressionMethod(), 10); fixedSizeStuff.writeUInt16LE(this.lastModFileTime, 12); fixedSizeStuff.writeUInt16LE(this.lastModFileDate, 14); fixedSizeStuff.writeUInt32LE(this.crc32, 16); fixedSizeStuff.writeUInt32LE(normalCompressedSize, 20); fixedSizeStuff.writeUInt32LE(normalUncompressedSize, 24); fixedSizeStuff.writeUInt16LE(this.utf8FileName.length, 28); fixedSizeStuff.writeUInt16LE(zeiefBuffer.length, 30); fixedSizeStuff.writeUInt16LE(this.fileComment.length, 32); fixedSizeStuff.writeUInt16LE(0, 34); fixedSizeStuff.writeUInt16LE(0, 36); fixedSizeStuff.writeUInt32LE(this.externalFileAttributes, 38); fixedSizeStuff.writeUInt32LE(normalRelativeOffsetOfLocalHeader, 42); return Buffer.concat([ fixedSizeStuff, // file name (variable size) this.utf8FileName, // extra field (variable size) zeiefBuffer, // file comment (variable size) this.fileComment ]); }; Entry.prototype.getCompressionMethod = function() { var NO_COMPRESSION = 0; var DEFLATE_COMPRESSION = 8; return this.compress ? DEFLATE_COMPRESSION : NO_COMPRESSION; }; function dateToDosDateTime(jsDate) { var date = 0; date |= jsDate.getDate() & 31; date |= (jsDate.getMonth() + 1 & 15) << 5; date |= (jsDate.getFullYear() - 1980 & 127) << 9; var time = 0; time |= Math.floor(jsDate.getSeconds() / 2); time |= (jsDate.getMinutes() & 63) << 5; time |= (jsDate.getHours() & 31) << 11; return { date, time }; } function writeUInt64LE(buffer, n, offset) { var high = Math.floor(n / 4294967296); var low = n % 4294967296; buffer.writeUInt32LE(low, offset); buffer.writeUInt32LE(high, offset + 4); } util.inherits(ByteCounter, Transform); function ByteCounter(options) { Transform.call(this, options); this.byteCount = 0; } ByteCounter.prototype._transform = function(chunk, encoding, cb) { this.byteCount += chunk.length; cb(null, chunk); }; util.inherits(Crc32Watcher, Transform); function Crc32Watcher(options) { Transform.call(this, options); this.crc32 = 0; } Crc32Watcher.prototype._transform = function(chunk, encoding, cb) { this.crc32 = crc32.unsigned(chunk, this.crc32); cb(null, chunk); }; 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"; if (cp437.length !== 256) throw new Error("assertion failure"); var reverseCp437 = null; function encodeCp437(string) { if (/^[\x20-\x7e]*$/.test(string)) { return bufferFrom(string, "utf-8"); } if (reverseCp437 == null) { reverseCp437 = {}; for (var i = 0; i < cp437.length; i++) { reverseCp437[cp437[i]] = i; } } var result = bufferAlloc(string.length); for (var i = 0; i < string.length; i++) { var b = reverseCp437[string[i]]; if (b == null) throw new Error("character not encodable in CP437: " + JSON.stringify(string[i])); result[i] = b; } return result; } function bufferAlloc(size) { bufferAlloc = modern; try { return bufferAlloc(size); } catch (e) { bufferAlloc = legacy; return bufferAlloc(size); } function modern(size2) { return Buffer.allocUnsafe(size2); } function legacy(size2) { return new Buffer(size2); } } function bufferFrom(something, encoding) { bufferFrom = modern; try { return bufferFrom(something, encoding); } catch (e) { bufferFrom = legacy; return bufferFrom(something, encoding); } function modern(something2, encoding2) { return Buffer.from(something2, encoding2); } function legacy(something2, encoding2) { return new Buffer(something2, encoding2); } } function bufferIncludes(buffer, content) { bufferIncludes = modern; try { return bufferIncludes(buffer, content); } catch (e) { bufferIncludes = legacy; return bufferIncludes(buffer, content); } function modern(buffer2, content2) { return buffer2.includes(content2); } function legacy(buffer2, content2) { for (var i = 0; i <= buffer2.length - content2.length; i++) { for (var j = 0; ; j++) { if (j === content2.length) return true; if (buffer2[i + j] !== content2[j]) break; } } return false; } } } }); // fabric.ts import { MinecraftFolder } from "@xmcl/core"; import { writeFile } from "fs/promises"; // utils.ts import { spawn } from "child_process"; import { access, mkdir, stat } from "fs/promises"; import { dirname } from "path"; import { checksum } from "@xmcl/core"; function missing(target) { return access(target).then(() => false, () => true); } async function ensureDir(target) { try { await mkdir(target); } catch (err) { const e = err; if (await stat(target).then((s) => s.isDirectory()).catch(() => false)) { return; } if (e.code === "EEXIST") { return; } if (e.code === "ENOENT") { if (dirname(target) === target) { throw e; } try { await ensureDir(dirname(target)); await mkdir(target); } catch { if (await stat(target).then((s) => s.isDirectory()).catch((e2) => false)) { return; } throw e; } return; } throw e; } } function ensureFile(target) { return ensureDir(dirname(target)); } function normalizeArray(arr = []) { return arr instanceof Array ? arr : [arr]; } function spawnProcess(spawnJavaOptions, args, options) { const process2 = ((spawnJavaOptions == null ? void 0 : spawnJavaOptions.spawn) ?? spawn)(spawnJavaOptions.java ?? "java", args, options); return waitProcess(process2); } function waitProcess(process2) { return new Promise((resolve2, reject) => { var _a, _b, _c, _d; const errorMsg = []; process2.on("error", (err) => { reject(err); }); process2.on("close", (code) => { if (code !== 0) { reject(new Error(errorMsg.join(""))); } else { resolve2(); } }); process2.on("exit", (code) => { if (code !== 0) { reject(new Error(errorMsg.join(""))); } else { resolve2(); } }); (_a = process2.stdout) == null ? void 0 : _a.setEncoding("utf-8"); (_b = process2.stdout) == null ? void 0 : _b.on("data", (buf) => { }); (_c = process2.stderr) == null ? void 0 : _c.setEncoding("utf-8"); (_d = process2.stderr) == null ? void 0 : _d.on("data", (buf) => { errorMsg.push(buf.toString()); }); }); } function joinUrl(a, b) { if (a.endsWith("/") && b.startsWith("/")) { return a + b.substring(1); } if (!a.endsWith("/") && !b.startsWith("/")) { return a + "/" + b; } return a + b; } function doFetch(o, url, init) { if (init) { init.signal = o == null ? void 0 : o.signal; } else { init = { signal: o == null ? void 0 : o.signal }; } return (o == null ? void 0 : o.fetch) ? o.fetch(url, init) : fetch(url, init); } // fabric.ts async function getFabricGames(options) { const response = await doFetch(options, `${DEFAULT_META_URL_FABRIC}/v2/game`); const body = await response.json(); return body.map((g) => g.version); } async function getFabricLoaders(options) { const response = await doFetch(options, `${DEFAULT_META_URL_FABRIC}/v2/versions/loader`); const body = response.json(); return body; } async function getLoaderArtifactListFor(minecraft, options) { const response = await doFetch(options, `${DEFAULT_META_URL_FABRIC}/v2/versions/loader/` + minecraft); const body = response.json(); return body; } async function getFabricLoaderArtifact(minecraft, loader, options) { const response = await doFetch(options, `${DEFAULT_META_URL_FABRIC}/v2/versions/loader/` + minecraft + "/" + loader); const body = response.json(); return body; } function getVersionJsonFromLoaderArtifact(loader, side, options = {}) { const mcversion = loader.intermediary.version; const id = options.versionId || `${mcversion}-fabric${loader.loader.version}`; const libraries = [ { name: loader.loader.maven, url: "https://maven.fabricmc.net/" }, { name: loader.intermediary.maven, url: "https://maven.fabricmc.net/" }, ...loader.launcherMeta.libraries.common, ...loader.launcherMeta.libraries[side] ]; const mainClass = loader.launcherMeta.mainClass[side]; const inheritsFrom = options.inheritsFrom || mcversion; return { id, inheritsFrom, mainClass, libraries, arguments: { game: [], jvm: [] }, releaseTime: (/* @__PURE__ */ new Date()).toJSON(), time: (/* @__PURE__ */ new Date()).toJSON() }; } async function installFabricByLoaderArtifact(loader, minecraft, options = {}) { const folder = MinecraftFolder.from(minecraft); const side = options.side || "client"; const version = getVersionJsonFromLoaderArtifact(loader, side, options); const jsonFile = side === "client" ? folder.getVersionJson(version.id) : folder.getVersionServerJson(version.id); await ensureFile(jsonFile); await writeFile(jsonFile, JSON.stringify(version, null, 4)); return version.id; } var DEFAULT_META_URL_FABRIC = "https://meta.fabricmc.net"; async function installFabric(options) { const side = options.side ?? "client"; const url = side === "client" ? `${DEFAULT_META_URL_FABRIC}/v2/versions/loader/${options.minecraftVersion}/${options.version}/profile/json` : `${DEFAULT_META_URL_FABRIC}/v2/versions/loader/${options.minecraftVersion}/${options.version}/server/json`; const response = await doFetch(options, url); const content = await response.json(); const minecraft = MinecraftFolder.from(options.minecraft); const versionName = `${options.minecraftVersion}-fabric${options.version}`; content.id = versionName; const jsonPath = side === "client" ? minecraft.getVersionJson(versionName) : minecraft.getVersionServerJson(versionName); await ensureFile(jsonPath); await writeFile(jsonPath, JSON.stringify(content)); return versionName; } // liteloader.ts import { MinecraftFolder as MinecraftFolder2 } from "@xmcl/core"; import { task } from "@xmcl/task"; import { readFile, writeFile as writeFile2 } from "fs/promises"; import { join } from "path"; import { request } from "undici"; var DEFAULT_VERSION_MANIFEST = "http://dl.liteloader.com/versions/versions.json"; function processLibraries(lib) { if (Object.keys(lib).length === 1 && lib.name) { if (lib.name.startsWith("org.ow2.asm")) { lib.url = "https://files.minecraftforge.net/maven/"; } } return lib; } var LiteloaderVersionList; ((LiteloaderVersionList2) => { function parse(content) { const result = JSON.parse(content); const metalist = { meta: result.meta, versions: {} }; for (const mcversion in result.versions) { const versions = metalist.versions[mcversion] = {}; const snapshots = result.versions[mcversion].snapshots; const artifacts = result.versions[mcversion].artefacts; const url = result.versions[mcversion].repo.url; if (snapshots) { const { stream, file, version, md5, timestamp, tweakClass, libraries } = snapshots["com.mumfrey:liteloader"].latest; const type = stream === "RELEASE" ? "RELEASE" : "SNAPSHOT"; versions.snapshot = { url, type, file, version, md5, timestamp, mcversion, tweakClass, libraries: libraries.map(processLibraries) }; } if (artifacts) { const { stream, file, version, md5, timestamp, tweakClass, libraries } = artifacts["com.mumfrey:liteloader"].latest; const type = stream === "RELEASE" ? "RELEASE" : "SNAPSHOT"; versions.release = { url, type, file, version, md5, timestamp, mcversion, tweakClass, libraries: libraries.map(processLibraries) }; } } return metalist; } LiteloaderVersionList2.parse = parse; })(LiteloaderVersionList || (LiteloaderVersionList = {})); var snapshotRoot = "http://dl.liteloader.com/versions/"; var releaseRoot = "http://repo.mumfrey.com/content/repositories/liteloader/"; var MissingVersionJsonError = class extends Error { constructor(version, path) { super(); this.version = version; this.path = path; this.name = "MissingVersionJson"; } }; async function getLiteloaderVersionList(options = {}) { const response = await request(DEFAULT_VERSION_MANIFEST, { dispatcher: options.dispatcher, throwOnError: true }); const body = await response.body.text(); return LiteloaderVersionList.parse(body); } function installLiteloader(versionMeta, location, options) { return installLiteloaderTask(versionMeta, location, options).startAndWait(); } function buildVersionInfo(versionMeta, mountedJSON) { const id = `${mountedJSON.id}-Liteloader${versionMeta.mcversion}-${versionMeta.version}`; const time = new Date(Number.parseInt(versionMeta.timestamp, 10) * 1e3).toISOString(); const releaseTime = time; const type = versionMeta.type; const libraries = [ { name: `com.mumfrey:liteloader:${versionMeta.version}`, url: type === "SNAPSHOT" ? snapshotRoot : releaseRoot }, ...versionMeta.libraries.map(processLibraries) ]; const mainClass = "net.minecraft.launchwrapper.Launch"; const inheritsFrom = mountedJSON.id; const jar = mountedJSON.jar || mountedJSON.id; const info = { id, time, releaseTime, type, libraries, mainClass, inheritsFrom, jar }; if (mountedJSON.arguments) { info.arguments = { game: ["--tweakClass", versionMeta.tweakClass], jvm: [] }; } else { info.minecraftArguments = `--tweakClass ${versionMeta.tweakClass} ` + mountedJSON.minecraftArguments; } return info; } function installLiteloaderTask(versionMeta, location, options = {}) { return task("installLiteloader", async function installLiteloader2() { const mc = MinecraftFolder2.from(location); const mountVersion = options.inheritsFrom || versionMeta.mcversion; const mountedJSON = await this.yield(task("resolveVersionJson", async function resolveVersionJson() { if (await missing(mc.getVersionJson(mountVersion))) { throw new MissingVersionJsonError(mountVersion, mc.getVersionJson(mountVersion)); } return readFile(mc.getVersionJson(mountVersion)).then((b) => b.toString()).then(JSON.parse); })); const versionInf = await this.yield(task("generateLiteloaderJson", async function generateLiteloaderJson() { const inf = buildVersionInfo(versionMeta, mountedJSON); inf.id = options.versionId || inf.id; inf.inheritsFrom = options.inheritsFrom || inf.inheritsFrom; const versionPath = mc.getVersionRoot(inf.id); await ensureDir(versionPath); await writeFile2(join(versionPath, inf.id + ".json"), JSON.stringify(inf, void 0, 4)); return inf; })); return versionInf.id; }); } // forge.ts var import_yazl = __toESM(require_yazl()); import { LibraryInfo as LibraryInfo2, MinecraftFolder as MinecraftFolder5, Version as VersionJson3 } from "@xmcl/core"; import { getDownloadBaseOptions as getDownloadBaseOptions2 } from "@xmcl/file-transfer"; import { parse as parseForge } from "@xmcl/forge-site-parser"; import { task as task4 } from "@xmcl/task"; import { filterEntries as filterEntries2, open as open3, openEntryReadStream, readAllEntries, readEntry as readEntry2 } from "@xmcl/unzip"; import { createWriteStream } from "fs"; import { writeFile as writeFile5 } from "fs/promises"; import { dirname as dirname3, join as join4, relative as relative3, sep as sep3 } from "path"; import { pipeline } from "stream/promises"; import { request as request2 } from "undici"; // downloadTask.ts import { download } from "@xmcl/file-transfer"; import { AbortableTask } from "@xmcl/task"; import { errors } from "undici"; var DownloadTask = class extends AbortableTask { constructor(options) { super(); this.options = options; this._from = options.url instanceof Array ? options.url[0] : options.url; this._to = options.destination; } controller; abort() { if (this.controller) { this.controller.abort(); } } process() { this.controller = new AbortController(); const signal = this.controller.signal; return download({ ...this.options, progressController: (url, chunkSize, progress, total) => { this._progress = progress; this._total = total; this._from = url.toString(); this.update(chunkSize); }, abortSignal: signal }); } isAbortedError(e) { if (e instanceof errors.RequestAbortedError || e.code === "UND_ERR_ABORTED") { return true; } return false; } }; var DownloadMultipleTask = class extends AbortableTask { constructor(options) { super(); this.options = options; this._progress = -1; this._total = -1; } controller; progresses = []; totals = []; get total() { if (this._total === -1) { this._total = this.totals.reduce((a, b) => a + b, 0); } return this._total; } get progress() { if (this._progress === -1) { this._progress = this.progresses.reduce((a, b) => a + b, 0); } return this._progress; } onFinished; async process() { this.progresses = this.options.map(() => 0); this.totals = this.options.map(() => 0); this.controller = new AbortController(); const results = await Promise.allSettled(this.options.map(async (options, i) => { var _a, _b; await download({ ...options, progressController: (url, chunkSize, written, total) => { this.progresses[i] = written; this.totals[i] = total; this._total = -1; this._progress = -1; this.update(chunkSize); this._from = url.toString(); }, abortSignal: (_a = this.controller) == null ? void 0 : _a.signal }); this.progresses[i] = this.totals[i]; this.update(0); (_b = this.onFinished) == null ? void 0 : _b.call(this, i); })); const rejecteds = results.filter((r) => r.status === "rejected"); if (rejecteds.length > 0) { if (this.isAbortedError(rejecteds[0].reason)) { throw rejecteds[0].reason; } throw new AggregateError(rejecteds.map((r) => r.reason).flatMap((r) => r instanceof AggregateError ? r.errors : r)); } } abort(isCancelled) { if (this.controller) { this.controller.abort(); } } isAbortedError(e) { if (e instanceof errors.RequestAbortedError || e.code === "UND_ERR_ABORTED") { return true; } return false; } }; // minecraft.ts import { MinecraftFolder as MinecraftFolder3, Version as VersionJson } from "@xmcl/core"; import { ChecksumNotMatchError, JsonValidator, getDownloadBaseOptions } from "@xmcl/file-transfer"; import { task as task2 } from "@xmcl/task"; import { link } from "fs"; import { readFile as readFile2, stat as stat2, writeFile as writeFile3 } from "fs/promises"; import { join as join2, relative, sep } from "path"; import { promisify } from "util"; // zipValdiator.ts import { ValidationError } from "@xmcl/file-transfer"; import { open } from "@xmcl/unzip"; var ZipValidator = class { async validate(destination, url) { try { const file = await open(destination, { autoClose: false, lazyEntries: true }); file.close(); } catch (e) { throw new ValidationError("InvalidZipError", e.message); } } }; // minecraft.ts var DEFAULT_VERSION_MANIFEST_URL = "https://launchermeta.mojang.com/mc/game/version_manifest.json"; var DEFAULT_RESOURCE_ROOT_URL = "https://resources.download.minecraft.net"; async function getVersionList(options = {}) { const response = await (options.fetch ?? fetch)(options.remote ?? DEFAULT_VERSION_MANIFEST_URL); return await response.json(); } function