"use strict"; 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 __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; 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 )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // dist/index.js var dist_exports = {}; __export(dist_exports, { NapiCli: () => NapiCli, parseTriple: () => parseTriple }); module.exports = __toCommonJS(dist_exports); // dist/api/artifacts.js var import_node_path = require("node:path"); var colors2 = __toESM(require("colorette"), 1); // dist/def/artifacts.js var import_clipanion = require("clipanion"); var BaseArtifactsCommand = class extends import_clipanion.Command { static paths = [["artifacts"]]; static usage = import_clipanion.Command.Usage({ description: "Copy artifacts from Github Actions into npm packages and ready to publish" }); cwd = import_clipanion.Option.String("--cwd", process.cwd(), { description: "The working directory of where napi command will be executed in, all other paths options are relative to this path" }); configPath = import_clipanion.Option.String("--config-path,-c", { description: "Path to `napi` config json file" }); packageJsonPath = import_clipanion.Option.String("--package-json-path", "package.json", { description: "Path to `package.json`" }); outputDir = import_clipanion.Option.String("--output-dir,-o,-d", "./artifacts", { description: "Path to the folder where all built `.node` files put, same as `--output-dir` of build command" }); npmDir = import_clipanion.Option.String("--npm-dir", "npm", { description: "Path to the folder where the npm packages put" }); buildOutputDir = import_clipanion.Option.String("--build-output-dir", { description: "Path to the build output dir, only needed when targets contains `wasm32-wasi-*`" }); getOptions() { return { cwd: this.cwd, configPath: this.configPath, packageJsonPath: this.packageJsonPath, outputDir: this.outputDir, npmDir: this.npmDir, buildOutputDir: this.buildOutputDir }; } }; function applyDefaultArtifactsOptions(options) { return { cwd: process.cwd(), packageJsonPath: "package.json", outputDir: "./artifacts", npmDir: "npm", ...options }; } // dist/utils/log.js var colors = __toESM(require("colorette"), 1); var import_debug = __toESM(require("debug"), 1); import_debug.default.formatters.i = (v) => { return colors.green(v); }; var debugFactory = (namespace) => { const debug9 = (0, import_debug.default)(`napi:${namespace}`); debug9.info = (...args) => console.error(colors.black(colors.bgGreen(" INFO ")), ...args); debug9.warn = (...args) => console.error(colors.black(colors.bgYellow(" WARNING ")), ...args); debug9.error = (...args) => console.error(colors.white(colors.bgRed(" ERROR ")), ...args.map((arg) => arg instanceof Error ? arg.stack ?? arg.message : arg)); return debug9; }; var debug = debugFactory("utils"); // dist/utils/misc.js var import_node_fs = require("node:fs"); var import_node_module = require("node:module"); var import_node_util = require("node:util"); var require2 = (0, import_node_module.createRequire)(__filename); var pkgJson = require2("@chainsafe/napi-rs-cli/package.json"); var readFileAsync = (0, import_node_util.promisify)(import_node_fs.readFile); var writeFileAsync = (0, import_node_util.promisify)(import_node_fs.writeFile); var unlinkAsync = (0, import_node_util.promisify)(import_node_fs.unlink); var copyFileAsync = (0, import_node_util.promisify)(import_node_fs.copyFile); var mkdirAsync = (0, import_node_util.promisify)(import_node_fs.mkdir); var statAsync = (0, import_node_util.promisify)(import_node_fs.stat); var readdirAsync = (0, import_node_util.promisify)(import_node_fs.readdir); async function fileExists(path2) { const exists = await statAsync(path2).then(() => true).catch(() => false); return exists; } function pick(o, ...keys2) { return keys2.reduce((acc, key) => { acc[key] = o[key]; return acc; }, {}); } async function updatePackageJson(path2, partial) { const exists = await fileExists(path2); if (!exists) { debug(`File not exists ${path2}`); return; } const old = require2(path2); await writeFileAsync(path2, JSON.stringify({ ...old, ...partial }, null, 2)); } var CLI_VERSION = pkgJson.version; // dist/utils/target.js var import_node_child_process = require("node:child_process"); var UNIVERSAL_TARGETS = { "universal-apple-darwin": ["aarch64-apple-darwin", "x86_64-apple-darwin"] }; var AVAILABLE_TARGETS = [ "aarch64-apple-darwin", "aarch64-linux-android", "aarch64-unknown-linux-gnu", "aarch64-unknown-linux-musl", "aarch64-pc-windows-msvc", "x86_64-apple-darwin", "x86_64-pc-windows-msvc", "x86_64-unknown-linux-gnu", "x86_64-unknown-linux-musl", "x86_64-unknown-freebsd", "i686-pc-windows-msvc", "armv7-unknown-linux-gnueabihf", "armv7-unknown-linux-musleabihf", "armv7-linux-androideabi", "universal-apple-darwin", "riscv64gc-unknown-linux-gnu", "powerpc64le-unknown-linux-gnu", "s390x-unknown-linux-gnu", "wasm32-wasi-preview1-threads" ]; var DEFAULT_TARGETS = [ "x86_64-apple-darwin", "aarch64-apple-darwin", "x86_64-pc-windows-msvc", "x86_64-unknown-linux-gnu" ]; var TARGET_LINKER = { "aarch64-unknown-linux-musl": "aarch64-linux-musl-gcc", "riscv64gc-unknown-linux-gnu": "riscv64-linux-gnu-gcc", "powerpc64le-unknown-linux-gnu": "powerpc64le-linux-gnu-gcc", "s390x-unknown-linux-gnu": "s390x-linux-gnu-gcc" }; var CpuToNodeArch = { x86_64: "x64", aarch64: "arm64", i686: "ia32", armv7: "arm", riscv64gc: "riscv64", powerpc64le: "ppc64" }; var NodeArchToCpu = { x64: "x86_64", arm64: "aarch64", ia32: "i686", arm: "armv7", riscv64: "riscv64gc", ppc64: "powerpc64le" }; var SysToNodePlatform = { linux: "linux", freebsd: "freebsd", darwin: "darwin", windows: "win32" }; var UniArchsByPlatform = { darwin: ["x64", "arm64"] }; function parseTriple(rawTriple) { if (rawTriple === "wasm32-wasi" || rawTriple === "wasm32-wasi-preview1-threads" || rawTriple.startsWith("wasm32-wasip")) { return { triple: rawTriple, platformArchABI: "wasm32-wasi", platform: "wasi", arch: "wasm32", abi: "wasi" }; } const triple = rawTriple.endsWith("eabi") ? `${rawTriple.slice(0, -4)}-eabi` : rawTriple; const triples = triple.split("-"); let cpu; let sys; let abi = null; if (triples.length === 2) { ; [cpu, sys] = triples; } else { ; [cpu, , sys, abi = null] = triples; } const platform = SysToNodePlatform[sys] ?? sys; const arch = CpuToNodeArch[cpu] ?? cpu; return { triple: rawTriple, platformArchABI: abi ? `${platform}-${arch}-${abi}` : `${platform}-${arch}`, platform, arch, abi }; } function getSystemDefaultTarget() { const host = (0, import_node_child_process.execSync)(`rustc -vV`, { env: process.env }).toString("utf8").split("\n").find((line) => line.startsWith("host: ")); const triple = host?.slice("host: ".length); if (!triple) { throw new TypeError(`Can not parse target triple from host`); } return parseTriple(triple); } function getTargetLinker(target) { return TARGET_LINKER[target]; } function targetToEnvVar(target) { return target.replace(/-/g, "_").toUpperCase(); } // dist/utils/version.js var NapiVersion; (function(NapiVersion2) { NapiVersion2[NapiVersion2["Napi1"] = 1] = "Napi1"; NapiVersion2[NapiVersion2["Napi2"] = 2] = "Napi2"; NapiVersion2[NapiVersion2["Napi3"] = 3] = "Napi3"; NapiVersion2[NapiVersion2["Napi4"] = 4] = "Napi4"; NapiVersion2[NapiVersion2["Napi5"] = 5] = "Napi5"; NapiVersion2[NapiVersion2["Napi6"] = 6] = "Napi6"; NapiVersion2[NapiVersion2["Napi7"] = 7] = "Napi7"; NapiVersion2[NapiVersion2["Napi8"] = 8] = "Napi8"; NapiVersion2[NapiVersion2["Napi9"] = 9] = "Napi9"; })(NapiVersion || (NapiVersion = {})); var NAPI_VERSION_MATRIX = /* @__PURE__ */ new Map([ [NapiVersion.Napi1, "8.6.0 | 9.0.0 | 10.0.0"], [NapiVersion.Napi2, "8.10.0 | 9.3.0 | 10.0.0"], [NapiVersion.Napi3, "6.14.2 | 8.11.2 | 9.11.0 | 10.0.0"], [NapiVersion.Napi4, "10.16.0 | 11.8.0 | 12.0.0"], [NapiVersion.Napi5, "10.17.0 | 12.11.0 | 13.0.0"], [NapiVersion.Napi6, "10.20.0 | 12.17.0 | 14.0.0"], [NapiVersion.Napi7, "10.23.0 | 12.19.0 | 14.12.0 | 15.0.0"], [NapiVersion.Napi8, "12.22.0 | 14.17.0 | 15.12.0 | 16.0.0"], [NapiVersion.Napi9, "18.17.0 | 20.3.0 | 21.1.0"] ]); function parseNodeVersion(v) { const matches = v.match(/v?([0-9]+)\.([0-9]+)\.([0-9]+)/i); if (!matches) { throw new Error("Unknown node version number: " + v); } const [, major, minor, patch] = matches; return { major: parseInt(major), minor: parseInt(minor), patch: parseInt(patch) }; } function requiredNodeVersions(napiVersion) { const requirement = NAPI_VERSION_MATRIX.get(napiVersion); if (!requirement) { return [parseNodeVersion("10.0.0")]; } return requirement.split("|").map(parseNodeVersion); } function toEngineRequirement(versions) { const requirements = []; versions.forEach((v, i) => { let req = ""; if (i !== 0) { const lastVersion = versions[i - 1]; req += `< ${lastVersion.major + 1}`; } req += `${i === 0 ? "" : " || "}>= ${v.major}.${v.minor}.${v.patch}`; requirements.push(req); }); return requirements.join(" "); } function napiEngineRequirement(napiVersion) { return toEngineRequirement(requiredNodeVersions(napiVersion)); } // dist/utils/metadata.js var import_node_child_process2 = require("node:child_process"); var import_node_fs2 = __toESM(require("node:fs"), 1); function parseMetadata(manifestPath) { if (!import_node_fs2.default.existsSync(manifestPath)) { throw new Error(`No crate found in manifest: ${manifestPath}`); } const cmd = `cargo metadata --manifest-path ${manifestPath} --format-version 1 --no-deps`; try { const output = (0, import_node_child_process2.execSync)(cmd, { encoding: "utf-8" }); return JSON.parse(output); } catch (e) { throw new Error(`Failed to parse cargo metadata output by command: ${cmd}`, { cause: e }); } } // dist/utils/config.js var import_colorette = require("colorette"); // ../node_modules/lodash-es/_freeGlobal.js var freeGlobal = typeof global == "object" && global && global.Object === Object && global; var freeGlobal_default = freeGlobal; // ../node_modules/lodash-es/_root.js var freeSelf = typeof self == "object" && self && self.Object === Object && self; var root = freeGlobal_default || freeSelf || Function("return this")(); var root_default = root; // ../node_modules/lodash-es/_Symbol.js var Symbol2 = root_default.Symbol; var Symbol_default = Symbol2; // ../node_modules/lodash-es/_getRawTag.js var objectProto = Object.prototype; var hasOwnProperty = objectProto.hasOwnProperty; var nativeObjectToString = objectProto.toString; var symToStringTag = Symbol_default ? Symbol_default.toStringTag : void 0; function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = void 0; var unmasked = true; } catch (e) { } var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } var getRawTag_default = getRawTag; // ../node_modules/lodash-es/_objectToString.js var objectProto2 = Object.prototype; var nativeObjectToString2 = objectProto2.toString; function objectToString(value) { return nativeObjectToString2.call(value); } var objectToString_default = objectToString; // ../node_modules/lodash-es/_baseGetTag.js var nullTag = "[object Null]"; var undefinedTag = "[object Undefined]"; var symToStringTag2 = Symbol_default ? Symbol_default.toStringTag : void 0; function baseGetTag(value) { if (value == null) { return value === void 0 ? undefinedTag : nullTag; } return symToStringTag2 && symToStringTag2 in Object(value) ? getRawTag_default(value) : objectToString_default(value); } var baseGetTag_default = baseGetTag; // ../node_modules/lodash-es/isObjectLike.js function isObjectLike(value) { return value != null && typeof value == "object"; } var isObjectLike_default = isObjectLike; // ../node_modules/lodash-es/isSymbol.js var symbolTag = "[object Symbol]"; function isSymbol(value) { return typeof value == "symbol" || isObjectLike_default(value) && baseGetTag_default(value) == symbolTag; } var isSymbol_default = isSymbol; // ../node_modules/lodash-es/_arrayMap.js function arrayMap(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } var arrayMap_default = arrayMap; // ../node_modules/lodash-es/isArray.js var isArray = Array.isArray; var isArray_default = isArray; // ../node_modules/lodash-es/_baseToString.js var INFINITY = 1 / 0; var symbolProto = Symbol_default ? Symbol_default.prototype : void 0; var symbolToString = symbolProto ? symbolProto.toString : void 0; function baseToString(value) { if (typeof value == "string") { return value; } if (isArray_default(value)) { return arrayMap_default(value, baseToString) + ""; } if (isSymbol_default(value)) { return symbolToString ? symbolToString.call(value) : ""; } var result = value + ""; return result == "0" && 1 / value == -INFINITY ? "-0" : result; } var baseToString_default = baseToString; // ../node_modules/lodash-es/isObject.js function isObject(value) { var type = typeof value; return value != null && (type == "object" || type == "function"); } var isObject_default = isObject; // ../node_modules/lodash-es/identity.js function identity(value) { return value; } var identity_default = identity; // ../node_modules/lodash-es/isFunction.js var asyncTag = "[object AsyncFunction]"; var funcTag = "[object Function]"; var genTag = "[object GeneratorFunction]"; var proxyTag = "[object Proxy]"; function isFunction(value) { if (!isObject_default(value)) { return false; } var tag = baseGetTag_default(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } var isFunction_default = isFunction; // ../node_modules/lodash-es/_coreJsData.js var coreJsData = root_default["__core-js_shared__"]; var coreJsData_default = coreJsData; // ../node_modules/lodash-es/_isMasked.js var maskSrcKey = function() { var uid = /[^.]+$/.exec(coreJsData_default && coreJsData_default.keys && coreJsData_default.keys.IE_PROTO || ""); return uid ? "Symbol(src)_1." + uid : ""; }(); function isMasked(func) { return !!maskSrcKey && maskSrcKey in func; } var isMasked_default = isMasked; // ../node_modules/lodash-es/_toSource.js var funcProto = Function.prototype; var funcToString = funcProto.toString; function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) { } try { return func + ""; } catch (e) { } } return ""; } var toSource_default = toSource; // ../node_modules/lodash-es/_baseIsNative.js var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; var reIsHostCtor = /^\[object .+?Constructor\]$/; var funcProto2 = Function.prototype; var objectProto3 = Object.prototype; var funcToString2 = funcProto2.toString; var hasOwnProperty2 = objectProto3.hasOwnProperty; var reIsNative = RegExp( "^" + funcToString2.call(hasOwnProperty2).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$" ); function baseIsNative(value) { if (!isObject_default(value) || isMasked_default(value)) { return false; } var pattern = isFunction_default(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource_default(value)); } var baseIsNative_default = baseIsNative; // ../node_modules/lodash-es/_getValue.js function getValue(object, key) { return object == null ? void 0 : object[key]; } var getValue_default = getValue; // ../node_modules/lodash-es/_getNative.js function getNative(object, key) { var value = getValue_default(object, key); return baseIsNative_default(value) ? value : void 0; } var getNative_default = getNative; // ../node_modules/lodash-es/_WeakMap.js var WeakMap = getNative_default(root_default, "WeakMap"); var WeakMap_default = WeakMap; // ../node_modules/lodash-es/_baseCreate.js var objectCreate = Object.create; var baseCreate = /* @__PURE__ */ function() { function object() { } return function(proto) { if (!isObject_default(proto)) { return {}; } if (objectCreate) { return objectCreate(proto); } object.prototype = proto; var result = new object(); object.prototype = void 0; return result; }; }(); var baseCreate_default = baseCreate; // ../node_modules/lodash-es/_apply.js function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } var apply_default = apply; // ../node_modules/lodash-es/_copyArray.js function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } var copyArray_default = copyArray; // ../node_modules/lodash-es/_shortOut.js var HOT_COUNT = 800; var HOT_SPAN = 16; var nativeNow = Date.now; function shortOut(func) { var count = 0, lastCalled = 0; return function() { var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return arguments[0]; } } else { count = 0; } return func.apply(void 0, arguments); }; } var shortOut_default = shortOut; // ../node_modules/lodash-es/constant.js function constant(value) { return function() { return value; }; } var constant_default = constant; // ../node_modules/lodash-es/_defineProperty.js var defineProperty = function() { try { var func = getNative_default(Object, "defineProperty"); func({}, "", {}); return func; } catch (e) { } }(); var defineProperty_default = defineProperty; // ../node_modules/lodash-es/_baseSetToString.js var baseSetToString = !defineProperty_default ? identity_default : function(func, string) { return defineProperty_default(func, "toString", { "configurable": true, "enumerable": false, "value": constant_default(string), "writable": true }); }; var baseSetToString_default = baseSetToString; // ../node_modules/lodash-es/_setToString.js var setToString = shortOut_default(baseSetToString_default); var setToString_default = setToString; // ../node_modules/lodash-es/_arrayEach.js function arrayEach(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } var arrayEach_default = arrayEach; // ../node_modules/lodash-es/_isIndex.js var MAX_SAFE_INTEGER = 9007199254740991; var reIsUint = /^(?:0|[1-9]\d*)$/; function isIndex(value, length) { var type = typeof value; length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (type == "number" || type != "symbol" && reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); } var isIndex_default = isIndex; // ../node_modules/lodash-es/_baseAssignValue.js function baseAssignValue(object, key, value) { if (key == "__proto__" && defineProperty_default) { defineProperty_default(object, key, { "configurable": true, "enumerable": true, "value": value, "writable": true }); } else { object[key] = value; } } var baseAssignValue_default = baseAssignValue; // ../node_modules/lodash-es/eq.js function eq(value, other) { return value === other || value !== value && other !== other; } var eq_default = eq; // ../node_modules/lodash-es/_assignValue.js var objectProto4 = Object.prototype; var hasOwnProperty3 = objectProto4.hasOwnProperty; function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty3.call(object, key) && eq_default(objValue, value)) || value === void 0 && !(key in object)) { baseAssignValue_default(object, key, value); } } var assignValue_default = assignValue; // ../node_modules/lodash-es/_copyObject.js function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : void 0; if (newValue === void 0) { newValue = source[key]; } if (isNew) { baseAssignValue_default(object, key, newValue); } else { assignValue_default(object, key, newValue); } } return object; } var copyObject_default = copyObject; // ../node_modules/lodash-es/_overRest.js var nativeMax = Math.max; function overRest(func, start, transform) { start = nativeMax(start === void 0 ? func.length - 1 : start, 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } index = -1; var otherArgs = Array(start + 1); while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = transform(array); return apply_default(func, this, otherArgs); }; } var overRest_default = overRest; // ../node_modules/lodash-es/_baseRest.js function baseRest(func, start) { return setToString_default(overRest_default(func, start, identity_default), func + ""); } var baseRest_default = baseRest; // ../node_modules/lodash-es/isLength.js var MAX_SAFE_INTEGER2 = 9007199254740991; function isLength(value) { return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER2; } var isLength_default = isLength; // ../node_modules/lodash-es/isArrayLike.js function isArrayLike(value) { return value != null && isLength_default(value.length) && !isFunction_default(value); } var isArrayLike_default = isArrayLike; // ../node_modules/lodash-es/_isIterateeCall.js function isIterateeCall(value, index, object) { if (!isObject_default(object)) { return false; } var type = typeof index; if (type == "number" ? isArrayLike_default(object) && isIndex_default(index, object.length) : type == "string" && index in object) { return eq_default(object[index], value); } return false; } var isIterateeCall_default = isIterateeCall; // ../node_modules/lodash-es/_createAssigner.js function createAssigner(assigner) { return baseRest_default(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : void 0, guard = length > 2 ? sources[2] : void 0; customizer = assigner.length > 3 && typeof customizer == "function" ? (length--, customizer) : void 0; if (guard && isIterateeCall_default(sources[0], sources[1], guard)) { customizer = length < 3 ? void 0 : customizer; length = 1; } object = Object(object); while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, index, customizer); } } return object; }); } var createAssigner_default = createAssigner; // ../node_modules/lodash-es/_isPrototype.js var objectProto5 = Object.prototype; function isPrototype(value) { var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto5; return value === proto; } var isPrototype_default = isPrototype; // ../node_modules/lodash-es/_baseTimes.js function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } var baseTimes_default = baseTimes; // ../node_modules/lodash-es/_baseIsArguments.js var argsTag = "[object Arguments]"; function baseIsArguments(value) { return isObjectLike_default(value) && baseGetTag_default(value) == argsTag; } var baseIsArguments_default = baseIsArguments; // ../node_modules/lodash-es/isArguments.js var objectProto6 = Object.prototype; var hasOwnProperty4 = objectProto6.hasOwnProperty; var propertyIsEnumerable = objectProto6.propertyIsEnumerable; var isArguments = baseIsArguments_default(/* @__PURE__ */ function() { return arguments; }()) ? baseIsArguments_default : function(value) { return isObjectLike_default(value) && hasOwnProperty4.call(value, "callee") && !propertyIsEnumerable.call(value, "callee"); }; var isArguments_default = isArguments; // ../node_modules/lodash-es/stubFalse.js function stubFalse() { return false; } var stubFalse_default = stubFalse; // ../node_modules/lodash-es/isBuffer.js var freeExports = typeof exports == "object" && exports && !exports.nodeType && exports; var freeModule = freeExports && typeof module == "object" && module && !module.nodeType && module; var moduleExports = freeModule && freeModule.exports === freeExports; var Buffer2 = moduleExports ? root_default.Buffer : void 0; var nativeIsBuffer = Buffer2 ? Buffer2.isBuffer : void 0; var isBuffer = nativeIsBuffer || stubFalse_default; var isBuffer_default = isBuffer; // ../node_modules/lodash-es/_baseIsTypedArray.js var argsTag2 = "[object Arguments]"; var arrayTag = "[object Array]"; var boolTag = "[object Boolean]"; var dateTag = "[object Date]"; var errorTag = "[object Error]"; var funcTag2 = "[object Function]"; var mapTag = "[object Map]"; var numberTag = "[object Number]"; var objectTag = "[object Object]"; var regexpTag = "[object RegExp]"; var setTag = "[object Set]"; var stringTag = "[object String]"; var weakMapTag = "[object WeakMap]"; var arrayBufferTag = "[object ArrayBuffer]"; var dataViewTag = "[object DataView]"; var float32Tag = "[object Float32Array]"; var float64Tag = "[object Float64Array]"; var int8Tag = "[object Int8Array]"; var int16Tag = "[object Int16Array]"; var int32Tag = "[object Int32Array]"; var uint8Tag = "[object Uint8Array]"; var uint8ClampedTag = "[object Uint8ClampedArray]"; var uint16Tag = "[object Uint16Array]"; var uint32Tag = "[object Uint32Array]"; var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag2] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag2] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; function baseIsTypedArray(value) { return isObjectLike_default(value) && isLength_default(value.length) && !!typedArrayTags[baseGetTag_default(value)]; } var baseIsTypedArray_default = baseIsTypedArray; // ../node_modules/lodash-es/_baseUnary.js function baseUnary(func) { return function(value) { return func(value); }; } var baseUnary_default = baseUnary; // ../node_modules/lodash-es/_nodeUtil.js var freeExports2 = typeof exports == "object" && exports && !exports.nodeType && exports; var freeModule2 = freeExports2 && typeof module == "object" && module && !module.nodeType && module; var moduleExports2 = freeModule2 && freeModule2.exports === freeExports2; var freeProcess = moduleExports2 && freeGlobal_default.process; var nodeUtil = function() { try { var types = freeModule2 && freeModule2.require && freeModule2.require("util").types; if (types) { return types; } return freeProcess && freeProcess.binding && freeProcess.binding("util"); } catch (e) { } }(); var nodeUtil_default = nodeUtil; // ../node_modules/lodash-es/isTypedArray.js var nodeIsTypedArray = nodeUtil_default && nodeUtil_default.isTypedArray; var isTypedArray = nodeIsTypedArray ? baseUnary_default(nodeIsTypedArray) : baseIsTypedArray_default; var isTypedArray_default = isTypedArray; // ../node_modules/lodash-es/_arrayLikeKeys.js var objectProto7 = Object.prototype; var hasOwnProperty5 = objectProto7.hasOwnProperty; function arrayLikeKeys(value, inherited) { var isArr = isArray_default(value), isArg = !isArr && isArguments_default(value), isBuff = !isArr && !isArg && isBuffer_default(value), isType = !isArr && !isArg && !isBuff && isTypedArray_default(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes_default(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty5.call(value, key)) && !(skipIndexes && // Safari 9 has enumerable `arguments.length` in strict mode. (key == "length" || // Node.js 0.10 has enumerable non-index properties on buffers. isBuff && (key == "offset" || key == "parent") || // PhantomJS 2 has enumerable non-index properties on typed arrays. isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") || // Skip index properties. isIndex_default(key, length)))) { result.push(key); } } return result; } var arrayLikeKeys_default = arrayLikeKeys; // ../node_modules/lodash-es/_overArg.js function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } var overArg_default = overArg; // ../node_modules/lodash-es/_nativeKeys.js var nativeKeys = overArg_default(Object.keys, Object); var nativeKeys_default = nativeKeys; // ../node_modules/lodash-es/_baseKeys.js var objectProto8 = Object.prototype; var hasOwnProperty6 = objectProto8.hasOwnProperty; function baseKeys(object) { if (!isPrototype_default(object)) { return nativeKeys_default(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty6.call(object, key) && key != "constructor") { result.push(key); } } return result; } var baseKeys_default = baseKeys; // ../node_modules/lodash-es/keys.js function keys(object) { return isArrayLike_default(object) ? arrayLikeKeys_default(object) : baseKeys_default(object); } var keys_default = keys; // ../node_modules/lodash-es/_nativeKeysIn.js function nativeKeysIn(object) { var result = []; if (object != null) { for (var key in Object(object)) { result.push(key); } } return result; } var nativeKeysIn_default = nativeKeysIn; // ../node_modules/lodash-es/_baseKeysIn.js var objectProto9 = Object.prototype; var hasOwnProperty7 = objectProto9.hasOwnProperty; function baseKeysIn(object) { if (!isObject_default(object)) { return nativeKeysIn_default(object); } var isProto = isPrototype_default(object), result = []; for (var key in object) { if (!(key == "constructor" && (isProto || !hasOwnProperty7.call(object, key)))) { result.push(key); } } return result; } var baseKeysIn_default = baseKeysIn; // ../node_modules/lodash-es/keysIn.js function keysIn(object) { return isArrayLike_default(object) ? arrayLikeKeys_default(object, true) : baseKeysIn_default(object); } var keysIn_default = keysIn; // ../node_modules/lodash-es/_isKey.js var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/; var reIsPlainProp = /^\w*$/; function isKey(value, object) { if (isArray_default(value)) { return false; } var type = typeof value; if (type == "number" || type == "symbol" || type == "boolean" || value == null || isSymbol_default(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object); } var isKey_default = isKey; // ../node_modules/lodash-es/_nativeCreate.js var nativeCreate = getNative_default(Object, "create"); var nativeCreate_default = nativeCreate; // ../node_modules/lodash-es/_hashClear.js function hashClear() { this.__data__ = nativeCreate_default ? nativeCreate_default(null) : {}; this.size = 0; } var hashClear_default = hashClear; // ../node_modules/lodash-es/_hashDelete.js function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } var hashDelete_default = hashDelete; // ../node_modules/lodash-es/_hashGet.js var HASH_UNDEFINED = "__lodash_hash_undefined__"; var objectProto10 = Object.prototype; var hasOwnProperty8 = objectProto10.hasOwnProperty; function hashGet(key) { var data = this.__data__; if (nativeCreate_default) { var result = data[key]; return result === HASH_UNDEFINED ? void 0 : result; } return hasOwnProperty8.call(data, key) ? data[key] : void 0; } var hashGet_default = hashGet; // ../node_modules/lodash-es/_hashHas.js var objectProto11 = Object.prototype; var hasOwnProperty9 = objectProto11.hasOwnProperty; function hashHas(key) { var data = this.__data__; return nativeCreate_default ? data[key] !== void 0 : hasOwnProperty9.call(data, key); } var hashHas_default = hashHas; // ../node_modules/lodash-es/_hashSet.js var HASH_UNDEFINED2 = "__lodash_hash_undefined__"; function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = nativeCreate_default && value === void 0 ? HASH_UNDEFINED2 : value; return this; } var hashSet_default = hashSet; // ../node_modules/lodash-es/_Hash.js function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } Hash.prototype.clear = hashClear_default; Hash.prototype["delete"] = hashDelete_default; Hash.prototype.get = hashGet_default; Hash.prototype.has = hashHas_default; Hash.prototype.set = hashSet_default; var Hash_default = Hash; // ../node_modules/lodash-es/_listCacheClear.js function listCacheClear() { this.__data__ = []; this.size = 0; } var listCacheClear_default = listCacheClear; // ../node_modules/lodash-es/_assocIndexOf.js function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq_default(array[length][0], key)) { return length; } } return -1; } var assocIndexOf_default = assocIndexOf; // ../node_modules/lodash-es/_listCacheDelete.js var arrayProto = Array.prototype; var splice = arrayProto.splice; function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf_default(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } var listCacheDelete_default = listCacheDelete; // ../node_modules/lodash-es/_listCacheGet.js function listCacheGet(key) { var data = this.__data__, index = assocIndexOf_default(data, key); return index < 0 ? void 0 : data[index][1]; } var listCacheGet_default = listCacheGet; // ../node_modules/lodash-es/_listCacheHas.js function listCacheHas(key) { return assocIndexOf_default(this.__data__, key) > -1; } var listCacheHas_default = listCacheHas; // ../node_modules/lodash-es/_listCacheSet.js function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf_default(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; } var listCacheSet_default = listCacheSet; // ../node_modules/lodash-es/_ListCache.js function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } ListCache.prototype.clear = listCacheClear_default; ListCache.prototype["delete"] = listCacheDelete_default; ListCache.prototype.get = listCacheGet_default; ListCache.prototype.has = listCacheHas_default; ListCache.prototype.set = listCacheSet_default; var ListCache_default = ListCache; // ../node_modules/lodash-es/_Map.js var Map2 = getNative_default(root_default, "Map"); var Map_default = Map2; // ../node_modules/lodash-es/_mapCacheClear.js function mapCacheClear() { this.size = 0; this.__data__ = { "hash": new Hash_default(), "map": new (Map_default || ListCache_default)(), "string": new Hash_default() }; } var mapCacheClear_default = mapCacheClear; // ../node_modules/lodash-es/_isKeyable.js function isKeyable(value) { var type = typeof value; return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null; } var isKeyable_default = isKeyable; // ../node_modules/lodash-es/_getMapData.js function getMapData(map, key) { var data = map.__data__; return isKeyable_default(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map; } var getMapData_default = getMapData; // ../node_modules/lodash-es/_mapCacheDelete.js function mapCacheDelete(key) { var result = getMapData_default(this, key)["delete"](key); this.size -= result ? 1 : 0; return result; } var mapCacheDelete_default = mapCacheDelete; // ../node_modules/lodash-es/_mapCacheGet.js function mapCacheGet(key) { return getMapData_default(this, key).get(key); } var mapCacheGet_default = mapCacheGet; // ../node_modules/lodash-es/_mapCacheHas.js function mapCacheHas(key) { return getMapData_default(this, key).has(key); } var mapCacheHas_default = mapCacheHas; // ../node_modules/lodash-es/_mapCacheSet.js function mapCacheSet(key, value) { var data = getMapData_default(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } var mapCacheSet_default = mapCacheSet; // ../node_modules/lodash-es/_MapCache.js function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } MapCache.prototype.clear = mapCacheClear_default; MapCache.prototype["delete"] = mapCacheDelete_default; MapCache.prototype.get = mapCacheGet_default; MapCache.prototype.has = mapCacheHas_default; MapCache.prototype.set = mapCacheSet_default; var MapCache_default = MapCache; // ../node_modules/lodash-es/memoize.js var FUNC_ERROR_TEXT = "Expected a function"; function memoize(func, resolver) { if (typeof func != "function" || resolver != null && typeof resolver != "function") { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result) || cache; return result; }; memoized.cache = new (memoize.Cache || MapCache_default)(); return memoized; } memoize.Cache = MapCache_default; var memoize_default = memoize; // ../node_modules/lodash-es/_memoizeCapped.js var MAX_MEMOIZE_SIZE = 500; function memoizeCapped(func) { var result = memoize_default(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } return key; }); var cache = result.cache; return result; } var memoizeCapped_default = memoizeCapped; // ../node_modules/lodash-es/_stringToPath.js var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; var reEscapeChar = /\\(\\)?/g; var stringToPath = memoizeCapped_default(function(string) { var result = []; if (string.charCodeAt(0) === 46) { result.push(""); } string.replace(rePropName, function(match, number, quote, subString) { result.push(quote ? subString.replace(reEscapeChar, "$1") : number || match); }); return result; }); var stringToPath_default = stringToPath; // ../node_modules/lodash-es/toString.js function toString(value) { return value == null ? "" : baseToString_default(value); } var toString_default = toString; // ../node_modules/lodash-es/_castPath.js function castPath(value, object) { if (isArray_default(value)) { return value; } return isKey_default(value, object) ? [value] : stringToPath_default(toString_default(value)); } var castPath_default = castPath; // ../node_modules/lodash-es/_toKey.js var INFINITY2 = 1 / 0; function toKey(value) { if (typeof value == "string" || isSymbol_default(value)) { return value; } var result = value + ""; return result == "0" && 1 / value == -INFINITY2 ? "-0" : result; } var toKey_default = toKey; // ../node_modules/lodash-es/_baseGet.js function baseGet(object, path2) { path2 = castPath_default(path2, object); var index = 0, length = path2.length; while (object != null && index < length) { object = object[toKey_default(path2[index++])]; } return index && index == length ? object : void 0; } var baseGet_default = baseGet; // ../node_modules/lodash-es/get.js function get(object, path2, defaultValue) { var result = object == null ? void 0 : baseGet_default(object, path2); return result === void 0 ? defaultValue : result; } var get_default = get; // ../node_modules/lodash-es/_arrayPush.js function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } var arrayPush_default = arrayPush; // ../node_modules/lodash-es/_isFlattenable.js var spreadableSymbol = Symbol_default ? Symbol_default.isConcatSpreadable : void 0; function isFlattenable(value) { return isArray_default(value) || isArguments_default(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } var isFlattenable_default = isFlattenable; // ../node_modules/lodash-es/_baseFlatten.js function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = isFlattenable_default); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { baseFlatten(value, depth - 1, predicate, isStrict, result); } else { arrayPush_default(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } var baseFlatten_default = baseFlatten; // ../node_modules/lodash-es/flatten.js function flatten(array) { var length = array == null ? 0 : array.length; return length ? baseFlatten_default(array, 1) : []; } var flatten_default = flatten; // ../node_modules/lodash-es/_flatRest.js function flatRest(func) { return setToString_default(overRest_default(func, void 0, flatten_default), func + ""); } var flatRest_default = flatRest; // ../node_modules/lodash-es/_getPrototype.js var getPrototype = overArg_default(Object.getPrototypeOf, Object); var getPrototype_default = getPrototype; // ../node_modules/lodash-es/isPlainObject.js var objectTag2 = "[object Object]"; var funcProto3 = Function.prototype; var objectProto12 = Object.prototype; var funcToString3 = funcProto3.toString; var hasOwnProperty10 = objectProto12.hasOwnProperty; var objectCtorString = funcToString3.call(Object); function isPlainObject(value) { if (!isObjectLike_default(value) || baseGetTag_default(value) != objectTag2) { return false; } var proto = getPrototype_default(value); if (proto === null) { return true; } var Ctor = hasOwnProperty10.call(proto, "constructor") && proto.constructor; return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString3.call(Ctor) == objectCtorString; } var isPlainObject_default = isPlainObject; // ../node_modules/lodash-es/_baseSlice.js function baseSlice(array, start, end) { var index = -1, length = array.length; if (start < 0) { start = -start > length ? 0 : length + start; } end = end > length ? length : end; if (end < 0) { end += length; } length = start > end ? 0 : end - start >>> 0; start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } var baseSlice_default = baseSlice; // ../node_modules/lodash-es/_stackClear.js function stackClear() { this.__data__ = new ListCache_default(); this.size = 0; } var stackClear_default = stackClear; // ../node_modules/lodash-es/_stackDelete.js function stackDelete(key) { var data = this.__data__, result = data["delete"](key); this.size = data.size; return result; } var stackDelete_default = stackDelete; // ../node_modules/lodash-es/_stackGet.js function stackGet(key) { return this.__data__.get(key); } var stackGet_default = stackGet; // ../node_modules/lodash-es/_stackHas.js function stackHas(key) { return this.__data__.has(key); } var stackHas_default = stackHas; // ../node_modules/lodash-es/_stackSet.js var LARGE_ARRAY_SIZE = 200; function stackSet(key, value) { var data = this.__data__; if (data instanceof ListCache_default) { var pairs = data.__data__; if (!Map_default || pairs.length < LARGE_ARRAY_SIZE - 1) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new MapCache_default(pairs); } data.set(key, value); this.size = data.size; return this; } var stackSet_default = stackSet; // ../node_modules/lodash-es/_Stack.js function Stack(entries) { var data = this.__data__ = new ListCache_default(entries); this.size = data.size; } Stack.prototype.clear = stackClear_default; Stack.prototype["delete"] = stackDelete_default; Stack.prototype.get = stackGet_default; Stack.prototype.has = stackHas_default; Stack.prototype.set = stackSet_default; var Stack_default = Stack; // ../node_modules/lodash-es/_baseAssign.js function baseAssign(object, source) { return object && copyObject_default(source, keys_default(source), object); } var baseAssign_default = baseAssign; // ../node_modules/lodash-es/_baseAssignIn.js function baseAssignIn(object, source) { return object && copyObject_default(source, keysIn_default(source), object); } var baseAssignIn_default = baseAssignIn; // ../node_modules/lodash-es/_cloneBuffer.js var freeExports3 = typeof exports == "object" && exports && !exports.nodeType && exports; var freeModule3 = freeExports3 && typeof module == "object" && module && !module.nodeType && module; var moduleExports3 = freeModule3 && freeModule3.exports === freeExports3; var Buffer3 = moduleExports3 ? root_default.Buffer : void 0; var allocUnsafe = Buffer3 ? Buffer3.allocUnsafe : void 0; function cloneBuffer(buffer, isDeep) { if (isDeep) { return buffer.slice(); } var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); buffer.copy(result); return result; } var cloneBuffer_default = cloneBuffer; // ../node_modules/lodash-es/_arrayFilter.js function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } var arrayFilter_default = arrayFilter; // ../node_modules/lodash-es/stubArray.js function stubArray() { return []; } var stubArray_default = stubArray; // ../node_modules/lodash-es/_getSymbols.js var objectProto13 = Object.prototype; var propertyIsEnumerable2 = objectProto13.propertyIsEnumerable; var nativeGetSymbols = Object.getOwnPropertySymbols; var getSymbols = !nativeGetSymbols ? stubArray_default : function(object) { if (object == null) { return []; } object = Object(object); return arrayFilter_default(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable2.call(object, symbol); }); }; var getSymbols_default = getSymbols; // ../node_modules/lodash-es/_copySymbols.js function copySymbols(source, object) { return copyObject_default(source, getSymbols_default(source), object); } var copySymbols_default = copySymbols; // ../node_modules/lodash-es/_getSymbolsIn.js var nativeGetSymbols2 = Object.getOwnPropertySymbols; var getSymbolsIn = !nativeGetSymbols2 ? stubArray_default : function(object) { var result = []; while (object) { arrayPush_default(result, getSymbols_default(object)); object = getPrototype_default(object); } return result; }; var getSymbolsIn_default = getSymbolsIn; // ../node_modules/lodash-es/_copySymbolsIn.js function copySymbolsIn(source, object) { return copyObject_default(source, getSymbolsIn_default(source), object); } var copySymbolsIn_default = copySymbolsIn; // ../node_modules/lodash-es/_baseGetAllKeys.js function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray_default(object) ? result : arrayPush_default(result, symbolsFunc(object)); } var baseGetAllKeys_default = baseGetAllKeys; // ../node_modules/lodash-es/_getAllKeys.js function getAllKeys(object) { return baseGetAllKeys_default(object, keys_default, getSymbols_default); } var getAllKeys_default = getAllKeys; // ../node_modules/lodash-es/_getAllKeysIn.js function getAllKeysIn(object) { return baseGetAllKeys_default(object, keysIn_default, getSymbolsIn_default); } var getAllKeysIn_default = getAllKeysIn; // ../node_modules/lodash-es/_DataView.js var DataView = getNative_default(root_default, "DataView"); var DataView_default = DataView; // ../node_modules/lodash-es/_Promise.js var Promise2 = getNative_default(root_default, "Promise"); var Promise_default = Promise2; // ../node_modules/lodash-es/_Set.js var Set2 = getNative_default(root_default, "Set"); var Set_default = Set2; // ../node_modules/lodash-es/_getTag.js var mapTag2 = "[object Map]"; var objectTag3 = "[object Object]"; var promiseTag = "[object Promise]"; var setTag2 = "[object Set]"; var weakMapTag2 = "[object WeakMap]"; var dataViewTag2 = "[object DataView]"; var dataViewCtorString = toSource_default(DataView_default); var mapCtorString = toSource_default(Map_default); var promiseCtorString = toSource_default(Promise_default); var setCtorString = toSource_default(Set_default); var weakMapCtorString = toSource_default(WeakMap_default); var getTag = baseGetTag_default; if (DataView_default && getTag(new DataView_default(new ArrayBuffer(1))) != dataViewTag2 || Map_default && getTag(new Map_default()) != mapTag2 || Promise_default && getTag(Promise_default.resolve()) != promiseTag || Set_default && getTag(new Set_default()) != setTag2 || WeakMap_default && getTag(new WeakMap_default()) != weakMapTag2) { getTag = function(value) { var result = baseGetTag_default(value), Ctor = result == objectTag3 ? value.constructor : void 0, ctorString = Ctor ? toSource_default(Ctor) : ""; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag2; case mapCtorString: return mapTag2; case promiseCtorString: return promiseTag; case setCtorString: return setTag2; case weakMapCtorString: return weakMapTag2; } } return result; }; } var getTag_default = getTag; // ../node_modules/lodash-es/_initCloneArray.js var objectProto14 = Object.prototype; var hasOwnProperty11 = objectProto14.hasOwnProperty; function initCloneArray(array) { var length = array.length, result = new array.constructor(length); if (length && typeof array[0] == "string" && hasOwnProperty11.call(array, "index")) { result.index = array.index; result.input = array.input; } return result; } var initCloneArray_default = initCloneArray; // ../node_modules/lodash-es/_Uint8Array.js var Uint8Array2 = root_default.Uint8Array; var Uint8Array_default = Uint8Array2; // ../node_modules/lodash-es/_cloneArrayBuffer.js function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new Uint8Array_default(result).set(new Uint8Array_default(arrayBuffer)); return result; } var cloneArrayBuffer_default = cloneArrayBuffer; // ../node_modules/lodash-es/_cloneDataView.js function cloneDataView(dataView, isDeep) { var buffer = isDeep ? cloneArrayBuffer_default(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } var cloneDataView_default = cloneDataView; // ../node_modules/lodash-es/_cloneRegExp.js var reFlags = /\w*$/; function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result; } var cloneRegExp_default = cloneRegExp; // ../node_modules/lodash-es/_cloneSymbol.js var symbolProto2 = Symbol_default ? Symbol_default.prototype : void 0; var symbolValueOf = symbolProto2 ? symbolProto2.valueOf : void 0; function cloneSymbol(symbol) { return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; } var cloneSymbol_default = cloneSymbol; // ../node_modules/lodash-es/_cloneTypedArray.js function cloneTypedArray(typedArray, isDeep) { var buffer = isDeep ? cloneArrayBuffer_default(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); } var cloneTypedArray_default = cloneTypedArray; // ../node_modules/lodash-es/_initCloneByTag.js var boolTag2 = "[object Boolean]"; var dateTag2 = "[object Date]"; var mapTag3 = "[object Map]"; var numberTag2 = "[object Number]"; var regexpTag2 = "[object RegExp]"; var setTag3 = "[object Set]"; var stringTag2 = "[object String]"; var symbolTag2 = "[object Symbol]"; var arrayBufferTag2 = "[object ArrayBuffer]"; var dataViewTag3 = "[object DataView]"; var float32Tag2 = "[object Float32Array]"; var float64Tag2 = "[object Float64Array]"; var int8Tag2 = "[object Int8Array]"; var int16Tag2 = "[object Int16Array]"; var int32Tag2 = "[object Int32Array]"; var uint8Tag2 = "[object Uint8Array]"; var uint8ClampedTag2 = "[object Uint8ClampedArray]"; var uint16Tag2 = "[object Uint16Array]"; var uint32Tag2 = "[object Uint32Array]"; function initCloneByTag(object, tag, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag2: return cloneArrayBuffer_default(object); case boolTag2: case dateTag2: return new Ctor(+object); case dataViewTag3: return cloneDataView_default(object, isDeep); case float32Tag2: case float64Tag2: case int8Tag2: case int16Tag2: case int32Tag2: case uint8Tag2: case uint8ClampedTag2: case uint16Tag2: case uint32Tag2: return cloneTypedArray_default(object, isDeep); case mapTag3: return new Ctor(); case numberTag2: case stringTag2: return new Ctor(object); case regexpTag2: return cloneRegExp_default(object); case setTag3: return new Ctor(); case symbolTag2: return cloneSymbol_default(object); } } var initCloneByTag_default = initCloneByTag; // ../node_modules/lodash-es/_initCloneObject.js function initCloneObject(object) { return typeof object.constructor == "function" && !isPrototype_default(object) ? baseCreate_default(getPrototype_default(object)) : {}; } var initCloneObject_default = initCloneObject; // ../node_modules/lodash-es/_baseIsMap.js var mapTag4 = "[object Map]"; function baseIsMap(value) { return isObjectLike_default(value) && getTag_default(value) == mapTag4; } var baseIsMap_default = baseIsMap; // ../node_modules/lodash-es/isMap.js var nodeIsMap = nodeUtil_default && nodeUtil_default.isMap; var isMap = nodeIsMap ? baseUnary_default(nodeIsMap) : baseIsMap_default; var isMap_default = isMap; // ../node_modules/lodash-es/_baseIsSet.js var setTag4 = "[object Set]"; function baseIsSet(value) { return isObjectLike_default(value) && getTag_default(value) == setTag4; } var baseIsSet_default = baseIsSet; // ../node_modules/lodash-es/isSet.js var nodeIsSet = nodeUtil_default && nodeUtil_default.isSet; var isSet = nodeIsSet ? baseUnary_default(nodeIsSet) : baseIsSet_default; var isSet_default = isSet; // ../node_modules/lodash-es/_baseClone.js var CLONE_DEEP_FLAG = 1; var CLONE_FLAT_FLAG = 2; var CLONE_SYMBOLS_FLAG = 4; var argsTag3 = "[object Arguments]"; var arrayTag2 = "[object Array]"; var boolTag3 = "[object Boolean]"; var dateTag3 = "[object Date]"; var errorTag2 = "[object Error]"; var funcTag3 = "[object Function]"; var genTag2 = "[object GeneratorFunction]"; var mapTag5 = "[object Map]"; var numberTag3 = "[object Number]"; var objectTag4 = "[object Object]"; var regexpTag3 = "[object RegExp]"; var setTag5 = "[object Set]"; var stringTag3 = "[object String]"; var symbolTag3 = "[object Symbol]"; var weakMapTag3 = "[object WeakMap]"; var arrayBufferTag3 = "[object ArrayBuffer]"; var dataViewTag4 = "[object DataView]"; var float32Tag3 = "[object Float32Array]"; var float64Tag3 = "[object Float64Array]"; var int8Tag3 = "[object Int8Array]"; var int16Tag3 = "[object Int16Array]"; var int32Tag3 = "[object Int32Array]"; var uint8Tag3 = "[object Uint8Array]"; var uint8ClampedTag3 = "[object Uint8ClampedArray]"; var uint16Tag3 = "[object Uint16Array]"; var uint32Tag3 = "[object Uint32Array]"; var cloneableTags = {}; cloneableTags[argsTag3] = cloneableTags[arrayTag2] = cloneableTags[arrayBufferTag3] = cloneableTags[dataViewTag4] = cloneableTags[boolTag3] = cloneableTags[dateTag3] = cloneableTags[float32Tag3] = cloneableTags[float64Tag3] = cloneableTags[int8Tag3] = cloneableTags[int16Tag3] = cloneableTags[int32Tag3] = cloneableTags[mapTag5] = cloneableTags[numberTag3] = cloneableTags[objectTag4] = cloneableTags[regexpTag3] = cloneableTags[setTag5] = cloneableTags[stringTag3] = cloneableTags[symbolTag3] = cloneableTags[uint8Tag3] = cloneableTags[uint8ClampedTag3] = cloneableTags[uint16Tag3] = cloneableTags[uint32Tag3] = true; cloneableTags[errorTag2] = cloneableTags[funcTag3] = cloneableTags[weakMapTag3] = false; function baseClone(value, bitmask, customizer, key, object, stack) { var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== void 0) { return result; } if (!isObject_default(value)) { return value; } var isArr = isArray_default(value); if (isArr) { result = initCloneArray_default(value); if (!isDeep) { return copyArray_default(value, result); } } else { var tag = getTag_default(value), isFunc = tag == funcTag3 || tag == genTag2; if (isBuffer_default(value)) { return cloneBuffer_default(value, isDeep); } if (tag == objectTag4 || tag == argsTag3 || isFunc && !object) { result = isFlat || isFunc ? {} : initCloneObject_default(value); if (!isDeep) { return isFlat ? copySymbolsIn_default(value, baseAssignIn_default(result, value)) : copySymbols_default(value, baseAssign_default(result, value)); } } else { if (!cloneableTags[tag]) { return object ? value : {}; } result = initCloneByTag_default(value, tag, isDeep); } } stack || (stack = new Stack_default()); var stacked = stack.get(value); if (stacked) { return stacked; } stack.set(value, result); if (isSet_default(value)) { value.forEach(function(subValue) { result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); }); } else if (isMap_default(value)) { value.forEach(function(subValue, key2) { result.set(key2, baseClone(subValue, bitmask, customizer, key2, value, stack)); }); } var keysFunc = isFull ? isFlat ? getAllKeysIn_default : getAllKeys_default : isFlat ? keysIn_default : keys_default; var props = isArr ? void 0 : keysFunc(value); arrayEach_default(props || value, function(subValue, key2) { if (props) { key2 = subValue; subValue = value[key2]; } assignValue_default(result, key2, baseClone(subValue, bitmask, customizer, key2, value, stack)); }); return result; } var baseClone_default = baseClone; // ../node_modules/lodash-es/_setCacheAdd.js var HASH_UNDEFINED3 = "__lodash_hash_undefined__"; function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED3); return this; } var setCacheAdd_default = setCacheAdd; // ../node_modules/lodash-es/_setCacheHas.js function setCacheHas(value) { return this.__data__.has(value); } var setCacheHas_default = setCacheHas; // ../node_modules/lodash-es/_SetCache.js function SetCache(values) { var index = -1, length = values == null ? 0 : values.length; this.__data__ = new MapCache_default(); while (++index < length) { this.add(values[index]); } } SetCache.prototype.add = SetCache.prototype.push = setCacheAdd_default; SetCache.prototype.has = setCacheHas_default; var SetCache_default = SetCache; // ../node_modules/lodash-es/_arraySome.js function arraySome(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } var arraySome_default = arraySome; // ../node_modules/lodash-es/_cacheHas.js function cacheHas(cache, key) { return cache.has(key); } var cacheHas_default = cacheHas; // ../node_modules/lodash-es/_equalArrays.js var COMPARE_PARTIAL_FLAG = 1; var COMPARE_UNORDERED_FLAG = 2; function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } var arrStacked = stack.get(array); var othStacked = stack.get(other); if (arrStacked && othStacked) { return arrStacked == other && othStacked == array; } var index = -1, result = true, seen = bitmask & COMPARE_UNORDERED_FLAG ? new SetCache_default() : void 0; stack.set(array, other); stack.set(other, array); while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== void 0) { if (compared) { continue; } result = false; break; } if (seen) { if (!arraySome_default(other, function(othValue2, othIndex) { if (!cacheHas_default(seen, othIndex) && (arrValue === othValue2 || equalFunc(arrValue, othValue2, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { result = false; break; } } stack["delete"](array); stack["delete"](other); return result; } var equalArrays_default = equalArrays; // ../node_modules/lodash-es/_mapToArray.js function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } var mapToArray_default = mapToArray; // ../node_modules/lodash-es/_setToArray.js function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } var setToArray_default = setToArray; // ../node_modules/lodash-es/_equalByTag.js var COMPARE_PARTIAL_FLAG2 = 1; var COMPARE_UNORDERED_FLAG2 = 2; var boolTag4 = "[object Boolean]"; var dateTag4 = "[object Date]"; var errorTag3 = "[object Error]"; var mapTag6 = "[object Map]"; var numberTag4 = "[object Number]"; var regexpTag4 = "[object RegExp]"; var setTag6 = "[object Set]"; var stringTag4 = "[object String]"; var symbolTag4 = "[object Symbol]"; var arrayBufferTag4 = "[object ArrayBuffer]"; var dataViewTag5 = "[object DataView]"; var symbolProto3 = Symbol_default ? Symbol_default.prototype : void 0; var symbolValueOf2 = symbolProto3 ? symbolProto3.valueOf : void 0; function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag5: if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag4: if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array_default(object), new Uint8Array_default(other))) { return false; } return true; case boolTag4: case dateTag4: case numberTag4: return eq_default(+object, +other); case errorTag3: return object.name == other.name && object.message == other.message; case regexpTag4: case stringTag4: return object == other + ""; case mapTag6: var convert = mapToArray_default; case setTag6: var isPartial = bitmask & COMPARE_PARTIAL_FLAG2; convert || (convert = setToArray_default); if (object.size != other.size && !isPartial) { return false; } var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG2; stack.set(object, other); var result = equalArrays_default(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack["delete"](object); return result; case symbolTag4: if (symbolValueOf2) { return symbolValueOf2.call(object) == symbolValueOf2.call(other); } } return false; } var equalByTag_default = equalByTag; // ../node_modules/lodash-es/_equalObjects.js var COMPARE_PARTIAL_FLAG3 = 1; var objectProto15 = Object.prototype; var hasOwnProperty12 = objectProto15.hasOwnProperty; function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG3, objProps = getAllKeys_default(object), objLength = objProps.length, othProps = getAllKeys_default(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty12.call(other, key))) { return false; } } var objStacked = stack.get(object); var othStacked = stack.get(other); if (objStacked && othStacked) { return objStacked == other && othStacked == object; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } if (!(compared === void 0 ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) { result = false; break; } skipCtor || (skipCtor = key == "constructor"); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; if (objCtor != othCtor && ("constructor" in object && "constructor" in other) && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor)) { result = false; } } stack["delete"](object); stack["delete"](other); return result; } var equalObjects_default = equalObjects; // ../node_modules/lodash-es/_baseIsEqualDeep.js var COMPARE_PARTIAL_FLAG4 = 1; var argsTag4 = "[object Arguments]"; var arrayTag3 = "[object Array]"; var objectTag5 = "[object Object]"; var objectProto16 = Object.prototype; var hasOwnProperty13 = objectProto16.hasOwnProperty; function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray_default(object), othIsArr = isArray_default(other), objTag = objIsArr ? arrayTag3 : getTag_default(object), othTag = othIsArr ? arrayTag3 : getTag_default(other); objTag = objTag == argsTag4 ? objectTag5 : objTag; othTag = othTag == argsTag4 ? objectTag5 : othTag; var objIsObj = objTag == objectTag5, othIsObj = othTag == objectTag5, isSameTag = objTag == othTag; if (isSameTag && isBuffer_default(object)) { if (!isBuffer_default(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new Stack_default()); return objIsArr || isTypedArray_default(object) ? equalArrays_default(object, other, bitmask, customizer, equalFunc, stack) : equalByTag_default(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG4)) { var objIsWrapped = objIsObj && hasOwnProperty13.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty13.call(other, "__wrapped__"); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack_default()); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack_default()); return equalObjects_default(object, other, bitmask, customizer, equalFunc, stack); } var baseIsEqualDeep_default = baseIsEqualDeep; // ../node_modules/lodash-es/_baseIsEqual.js function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || !isObjectLike_default(value) && !isObjectLike_default(other)) { return value !== value && other !== other; } return baseIsEqualDeep_default(value, other, bitmask, customizer, baseIsEqual, stack); } var baseIsEqual_default = baseIsEqual; // ../node_modules/lodash-es/_baseIsMatch.js var COMPARE_PARTIAL_FLAG5 = 1; var COMPARE_UNORDERED_FLAG3 = 2; function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === void 0 && !(key in object)) { return false; } } else { var stack = new Stack_default(); if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === void 0 ? baseIsEqual_default(srcValue, objValue, COMPARE_PARTIAL_FLAG5 | COMPARE_UNORDERED_FLAG3, customizer, stack) : result)) { return false; } } } return true; } var baseIsMatch_default = baseIsMatch; // ../node_modules/lodash-es/_isStrictComparable.js function isStrictComparable(value) { return value === value && !isObject_default(value); } var isStrictComparable_default = isStrictComparable; // ../node_modules/lodash-es/_getMatchData.js function getMatchData(object) { var result = keys_default(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, isStrictComparable_default(value)]; } return result; } var getMatchData_default = getMatchData; // ../node_modules/lodash-es/_matchesStrictComparable.js function matchesStrictComparable(key, srcValue) { return function(object) { if (object == null) { return false; } return object[key] === srcValue && (srcValue !== void 0 || key in Object(object)); }; } var matchesStrictComparable_default = matchesStrictComparable; // ../node_modules/lodash-es/_baseMatches.js function baseMatches(source) { var matchData = getMatchData_default(source); if (matchData.length == 1 && matchData[0][2]) { return matchesStrictComparable_default(matchData[0][0], matchData[0][1]); } return function(object) { return object === source || baseIsMatch_default(object, source, matchData); }; } var baseMatches_default = baseMatches; // ../node_modules/lodash-es/_baseHasIn.js function baseHasIn(object, key) { return object != null && key in Object(object); } var baseHasIn_default = baseHasIn; // ../node_modules/lodash-es/_hasPath.js function hasPath(object, path2, hasFunc) { path2 = castPath_default(path2, object); var index = -1, length = path2.length, result = false; while (++index < length) { var key = toKey_default(path2[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result || ++index != length) { return result; } length = object == null ? 0 : object.length; return !!length && isLength_default(length) && isIndex_default(key, length) && (isArray_default(object) || isArguments_default(object)); } var hasPath_default = hasPath; // ../node_modules/lodash-es/hasIn.js function hasIn(object, path2) { return object != null && hasPath_default(object, path2, baseHasIn_default); } var hasIn_default = hasIn; // ../node_modules/lodash-es/_baseMatchesProperty.js var COMPARE_PARTIAL_FLAG6 = 1; var COMPARE_UNORDERED_FLAG4 = 2; function baseMatchesProperty(path2, srcValue) { if (isKey_default(path2) && isStrictComparable_default(srcValue)) { return matchesStrictComparable_default(toKey_default(path2), srcValue); } return function(object) { var objValue = get_default(object, path2); return objValue === void 0 && objValue === srcValue ? hasIn_default(object, path2) : baseIsEqual_default(srcValue, objValue, COMPARE_PARTIAL_FLAG6 | COMPARE_UNORDERED_FLAG4); }; } var baseMatchesProperty_default = baseMatchesProperty; // ../node_modules/lodash-es/_baseProperty.js function baseProperty(key) { return function(object) { return object == null ? void 0 : object[key]; }; } var baseProperty_default = baseProperty; // ../node_modules/lodash-es/_basePropertyDeep.js function basePropertyDeep(path2) { return function(object) { return baseGet_default(object, path2); }; } var basePropertyDeep_default = basePropertyDeep; // ../node_modules/lodash-es/property.js function property(path2) { return isKey_default(path2) ? baseProperty_default(toKey_default(path2)) : basePropertyDeep_default(path2); } var property_default = property; // ../node_modules/lodash-es/_baseIteratee.js function baseIteratee(value) { if (typeof value == "function") { return value; } if (value == null) { return identity_default; } if (typeof value == "object") { return isArray_default(value) ? baseMatchesProperty_default(value[0], value[1]) : baseMatches_default(value); } return property_default(value); } var baseIteratee_default = baseIteratee; // ../node_modules/lodash-es/_createBaseFor.js function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } var createBaseFor_default = createBaseFor; // ../node_modules/lodash-es/_baseFor.js var baseFor = createBaseFor_default(); var baseFor_default = baseFor; // ../node_modules/lodash-es/_baseForOwn.js function baseForOwn(object, iteratee) { return object && baseFor_default(object, iteratee, keys_default); } var baseForOwn_default = baseForOwn; // ../node_modules/lodash-es/_createBaseEach.js function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { if (collection == null) { return collection; } if (!isArrayLike_default(collection)) { return eachFunc(collection, iteratee); } var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); while (fromRight ? index-- : ++index < length) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } var createBaseEach_default = createBaseEach; // ../node_modules/lodash-es/_baseEach.js var baseEach = createBaseEach_default(baseForOwn_default); var baseEach_default = baseEach; // ../node_modules/lodash-es/_assignMergeValue.js function assignMergeValue(object, key, value) { if (value !== void 0 && !eq_default(object[key], value) || value === void 0 && !(key in object)) { baseAssignValue_default(object, key, value); } } var assignMergeValue_default = assignMergeValue; // ../node_modules/lodash-es/isArrayLikeObject.js function isArrayLikeObject(value) { return isObjectLike_default(value) && isArrayLike_default(value); } var isArrayLikeObject_default = isArrayLikeObject; // ../node_modules/lodash-es/_safeGet.js function safeGet(object, key) { if (key === "constructor" && typeof object[key] === "function") { return; } if (key == "__proto__") { return; } return object[key]; } var safeGet_default = safeGet; // ../node_modules/lodash-es/toPlainObject.js function toPlainObject(value) { return copyObject_default(value, keysIn_default(value)); } var toPlainObject_default = toPlainObject; // ../node_modules/lodash-es/_baseMergeDeep.js function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { var objValue = safeGet_default(object, key), srcValue = safeGet_default(source, key), stacked = stack.get(srcValue); if (stacked) { assignMergeValue_default(object, key, stacked); return; } var newValue = customizer ? customizer(objValue, srcValue, key + "", object, source, stack) : void 0; var isCommon = newValue === void 0; if (isCommon) { var isArr = isArray_default(srcValue), isBuff = !isArr && isBuffer_default(srcValue), isTyped = !isArr && !isBuff && isTypedArray_default(srcValue); newValue = srcValue; if (isArr || isBuff || isTyped) { if (isArray_default(objValue)) { newValue = objValue; } else if (isArrayLikeObject_default(objValue)) { newValue = copyArray_default(objValue); } else if (isBuff) { isCommon = false; newValue = cloneBuffer_default(srcValue, true); } else if (isTyped) { isCommon = false; newValue = cloneTypedArray_default(srcValue, true); } else { newValue = []; } } else if (isPlainObject_default(srcValue) || isArguments_default(srcValue)) { newValue = objValue; if (isArguments_default(objValue)) { newValue = toPlainObject_default(objValue); } else if (!isObject_default(objValue) || isFunction_default(objValue)) { newValue = initCloneObject_default(srcValue); } } else { isCommon = false; } } if (isCommon) { stack.set(srcValue, newValue); mergeFunc(newValue, srcValue, srcIndex, customizer, stack); stack["delete"](srcValue); } assignMergeValue_default(object, key, newValue); } var baseMergeDeep_default = baseMergeDeep; // ../node_modules/lodash-es/_baseMerge.js function baseMerge(object, source, srcIndex, customizer, stack) { if (object === source) { return; } baseFor_default(source, function(srcValue, key) { stack || (stack = new Stack_default()); if (isObject_default(srcValue)) { baseMergeDeep_default(object, source, key, srcIndex, baseMerge, customizer, stack); } else { var newValue = customizer ? customizer(safeGet_default(object, key), srcValue, key + "", object, source, stack) : void 0; if (newValue === void 0) { newValue = srcValue; } assignMergeValue_default(object, key, newValue); } }, keysIn_default); } var baseMerge_default = baseMerge; // ../node_modules/lodash-es/last.js function last(array) { var length = array == null ? 0 : array.length; return length ? array[length - 1] : void 0; } var last_default = last; // ../node_modules/lodash-es/_baseMap.js function baseMap(collection, iteratee) { var index = -1, result = isArrayLike_default(collection) ? Array(collection.length) : []; baseEach_default(collection, function(value, key, collection2) { result[++index] = iteratee(value, key, collection2); }); return result; } var baseMap_default = baseMap; // ../node_modules/lodash-es/_parent.js function parent(object, path2) { return path2.length < 2 ? object : baseGet_default(object, baseSlice_default(path2, 0, -1)); } var parent_default = parent; // ../node_modules/lodash-es/isNil.js function isNil(value) { return value == null; } var isNil_default = isNil; // ../node_modules/lodash-es/merge.js var merge = createAssigner_default(function(object, source, srcIndex) { baseMerge_default(object, source, srcIndex); }); var merge_default = merge; // ../node_modules/lodash-es/negate.js var FUNC_ERROR_TEXT2 = "Expected a function"; function negate(predicate) { if (typeof predicate != "function") { throw new TypeError(FUNC_ERROR_TEXT2); } return function() { var args = arguments; switch (args.length) { case 0: return !predicate.call(this); case 1: return !predicate.call(this, args[0]); case 2: return !predicate.call(this, args[0], args[1]); case 3: return !predicate.call(this, args[0], args[1], args[2]); } return !predicate.apply(this, args); }; } var negate_default = negate; // ../node_modules/lodash-es/_baseUnset.js function baseUnset(object, path2) { path2 = castPath_default(path2, object); object = parent_default(object, path2); return object == null || delete object[toKey_default(last_default(path2))]; } var baseUnset_default = baseUnset; // ../node_modules/lodash-es/_customOmitClone.js function customOmitClone(value) { return isPlainObject_default(value) ? void 0 : value; } var customOmitClone_default = customOmitClone; // ../node_modules/lodash-es/omit.js var CLONE_DEEP_FLAG2 = 1; var CLONE_FLAT_FLAG2 = 2; var CLONE_SYMBOLS_FLAG2 = 4; var omit = flatRest_default(function(object, paths) { var result = {}; if (object == null) { return result; } var isDeep = false; paths = arrayMap_default(paths, function(path2) { path2 = castPath_default(path2, object); isDeep || (isDeep = path2.length > 1); return path2; }); copyObject_default(object, getAllKeysIn_default(object), result); if (isDeep) { result = baseClone_default(result, CLONE_DEEP_FLAG2 | CLONE_FLAT_FLAG2 | CLONE_SYMBOLS_FLAG2, customOmitClone_default); } var length = paths.length; while (length--) { baseUnset_default(result, paths[length]); } return result; }); var omit_default = omit; // ../node_modules/lodash-es/_baseSet.js function baseSet(object, path2, value, customizer) { if (!isObject_default(object)) { return object; } path2 = castPath_default(path2, object); var index = -1, length = path2.length, lastIndex = length - 1, nested = object; while (nested != null && ++index < length) { var key = toKey_default(path2[index]), newValue = value; if (key === "__proto__" || key === "constructor" || key === "prototype") { return object; } if (index != lastIndex) { var objValue = nested[key]; newValue = customizer ? customizer(objValue, key, nested) : void 0; if (newValue === void 0) { newValue = isObject_default(objValue) ? objValue : isIndex_default(path2[index + 1]) ? [] : {}; } } assignValue_default(nested, key, newValue); nested = nested[key]; } return object; } var baseSet_default = baseSet; // ../node_modules/lodash-es/_basePickBy.js function basePickBy(object, paths, predicate) { var index = -1, length = paths.length, result = {}; while (++index < length) { var path2 = paths[index], value = baseGet_default(object, path2); if (predicate(value, path2)) { baseSet_default(result, castPath_default(path2, object), value); } } return result; } var basePickBy_default = basePickBy; // ../node_modules/lodash-es/pickBy.js function pickBy(object, predicate) { if (object == null) { return {}; } var props = arrayMap_default(getAllKeysIn_default(object), function(prop) { return [prop]; }); predicate = baseIteratee_default(predicate); return basePickBy_default(object, props, function(value, path2) { return predicate(value, path2[0]); }); } var pickBy_default = pickBy; // ../node_modules/lodash-es/omitBy.js function omitBy(object, predicate) { return pickBy_default(object, negate_default(baseIteratee_default(predicate))); } var omitBy_default = omitBy; // ../node_modules/lodash-es/_baseSortBy.js function baseSortBy(array, comparer) { var length = array.length; array.sort(comparer); while (length--) { array[length] = array[length].value; } return array; } var baseSortBy_default = baseSortBy; // ../node_modules/lodash-es/_compareAscending.js function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== void 0, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol_default(value); var othIsDefined = other !== void 0, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol_default(other); if (!othIsNull && !othIsSymbol && !valIsSymbol && value > other || valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol || valIsNull && othIsDefined && othIsReflexive || !valIsDefined && othIsReflexive || !valIsReflexive) { return 1; } if (!valIsNull && !valIsSymbol && !othIsSymbol && value < other || othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol || othIsNull && valIsDefined && valIsReflexive || !othIsDefined && valIsReflexive || !othIsReflexive) { return -1; } } return 0; } var compareAscending_default = compareAscending; // ../node_modules/lodash-es/_compareMultiple.js function compareMultiple(object, other, orders) { var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; while (++index < length) { var result = compareAscending_default(objCriteria[index], othCriteria[index]); if (result) { if (index >= ordersLength) { return result; } var order = orders[index]; return result * (order == "desc" ? -1 : 1); } } return object.index - other.index; } var compareMultiple_default = compareMultiple; // ../node_modules/lodash-es/_baseOrderBy.js function baseOrderBy(collection, iteratees, orders) { if (iteratees.length) { iteratees = arrayMap_default(iteratees, function(iteratee) { if (isArray_default(iteratee)) { return function(value) { return baseGet_default(value, iteratee.length === 1 ? iteratee[0] : iteratee); }; } return iteratee; }); } else { iteratees = [identity_default]; } var index = -1; iteratees = arrayMap_default(iteratees, baseUnary_default(baseIteratee_default)); var result = baseMap_default(collection, function(value, key, collection2) { var criteria = arrayMap_default(iteratees, function(iteratee) { return iteratee(value); }); return { "criteria": criteria, "index": ++index, "value": value }; }); return baseSortBy_default(result, function(object, other) { return compareMultiple_default(object, other, orders); }); } var baseOrderBy_default = baseOrderBy; // ../node_modules/lodash-es/_basePick.js function basePick(object, paths) { return basePickBy_default(object, paths, function(value, path2) { return hasIn_default(object, path2); }); } var basePick_default = basePick; // ../node_modules/lodash-es/pick.js var pick2 = flatRest_default(function(object, paths) { return object == null ? {} : basePick_default(object, paths); }); var pick_default = pick2; // ../node_modules/lodash-es/sortBy.js var sortBy = baseRest_default(function(collection, iteratees) { if (collection == null) { return []; } var length = iteratees.length; if (length > 1 && isIterateeCall_default(collection, iteratees[0], iteratees[1])) { iteratees = []; } else if (length > 2 && isIterateeCall_default(iteratees[0], iteratees[1], iteratees[2])) { iteratees = [iteratees[0]]; } return baseOrderBy_default(collection, baseFlatten_default(iteratees, 1), []); }); var sortBy_default = sortBy; // dist/utils/config.js async function readNapiConfig(path2, configPath) { if (configPath && !await fileExists(configPath)) { throw new Error(`NAPI-RS config not found at ${configPath}`); } if (!await fileExists(path2)) { throw new Error(`package.json not found at ${path2}`); } const content = await readFileAsync(path2, "utf8"); let pkgJson2; try { pkgJson2 = JSON.parse(content); } catch (e) { throw new Error(`Failed to parse package.json at ${path2}`, { cause: e }); } let separatedConfig; if (configPath) { const configContent = await readFileAsync(configPath, "utf8"); try { separatedConfig = JSON.parse(configContent); } catch (e) { throw new Error(`Failed to parse NAPI-RS config at ${configPath}`, { cause: e }); } } const userNapiConfig = pkgJson2.napi ?? {}; if (pkgJson2.napi && separatedConfig) { const pkgJsonPath = (0, import_colorette.underline)(path2); const configPathUnderline = (0, import_colorette.underline)(configPath); console.warn((0, import_colorette.yellow)(`Both napi field in ${pkgJsonPath} and [NAPI-RS config](${configPathUnderline}) file are found, the NAPI-RS config file will be used.`)); Object.assign(userNapiConfig, separatedConfig); } const napiConfig = merge_default({ binaryName: "index", packageName: pkgJson2.name, targets: [], packageJson: pkgJson2, npmClient: "npm" }, omit_default(userNapiConfig, "targets")); let targets = userNapiConfig.targets ?? []; if (userNapiConfig?.name) { console.warn((0, import_colorette.yellow)(`[DEPRECATED] napi.name is deprecated, use napi.binaryName instead.`)); napiConfig.binaryName = userNapiConfig.name; } if (!targets.length) { let deprecatedWarned = false; const warning = (0, import_colorette.yellow)(`[DEPRECATED] napi.triples is deprecated, use napi.targets instead.`); if (userNapiConfig.triples?.defaults) { deprecatedWarned = true; console.warn(warning); targets = targets.concat(DEFAULT_TARGETS); } if (userNapiConfig.triples?.additional?.length) { targets = targets.concat(userNapiConfig.triples.additional); if (!deprecatedWarned) { console.warn(warning); } } } napiConfig.targets = targets.map(parseTriple); return napiConfig; } // dist/utils/cargo.js var import_node_child_process3 = require("node:child_process"); function tryInstallCargoBinary(name, bin) { if (detectCargoBinary(bin)) { debug("Cargo binary already installed: %s", name); return; } try { debug("Installing cargo binary: %s", name); (0, import_node_child_process3.execSync)(`cargo install ${name}`, { stdio: "inherit" }); } catch (e) { throw new Error(`Failed to install cargo binary: ${name}`, { cause: e }); } } function detectCargoBinary(bin) { debug("Detecting cargo binary: %s", bin); try { (0, import_node_child_process3.execSync)(`cargo help ${bin}`, { stdio: "ignore" }); debug("Cargo binary detected: %s", bin); return true; } catch { debug("Cargo binary not detected: %s", bin); return false; } } // dist/utils/typegen.js var TOP_LEVEL_NAMESPACE = "__TOP_LEVEL_MODULE__"; var DEFAULT_TYPE_DEF_HEADER = `/* auto-generated by NAPI-RS */ /* eslint-disable */ `; var TypeDefKind; (function(TypeDefKind2) { TypeDefKind2["Const"] = "const"; TypeDefKind2["Enum"] = "enum"; TypeDefKind2["StringEnum"] = "string_enum"; TypeDefKind2["Interface"] = "interface"; TypeDefKind2["Type"] = "type"; TypeDefKind2["Fn"] = "fn"; TypeDefKind2["Struct"] = "struct"; TypeDefKind2["Impl"] = "impl"; })(TypeDefKind || (TypeDefKind = {})); function prettyPrint(line, constEnum, ident, ambient = false) { let s = line.js_doc ?? ""; switch (line.kind) { case TypeDefKind.Interface: s += `export interface ${line.name} { ${line.def} }`; break; case TypeDefKind.Type: s += `export type ${line.name} = ${line.def}`; break; case TypeDefKind.Enum: const enumName = constEnum ? "const enum" : "enum"; s += `${exportDeclare(ambient)} ${enumName} ${line.name} { ${line.def} }`; break; case TypeDefKind.StringEnum: if (constEnum) { s += `${exportDeclare(ambient)} const enum ${line.name} { ${line.def} }`; } else { s += `export type ${line.name} = ${line.def.replaceAll(/.*=/g, "").replaceAll(",", "|")};`; } break; case TypeDefKind.Struct: s += `${exportDeclare(ambient)} class ${line.name} { ${line.def} }`; if (line.original_name && line.original_name !== line.name) { s += ` export type ${line.original_name} = ${line.name}`; } break; case TypeDefKind.Fn: s += `${exportDeclare(ambient)} ${line.def}`; break; default: s += line.def; } return correctStringIdent(s, ident); } function exportDeclare(ambient) { if (ambient) { return "export"; } return "export declare"; } async function processTypeDef(intermediateTypeFile, constEnum, header) { const exports2 = []; const defs = await readIntermediateTypeFile(intermediateTypeFile); const groupedDefs = preprocessTypeDef(defs); header = header ?? ""; const dts = sortBy_default(Array.from(groupedDefs), ([namespace]) => namespace).map(([namespace, defs2]) => { if (namespace === TOP_LEVEL_NAMESPACE) { return defs2.map((def) => { switch (def.kind) { case TypeDefKind.Const: case TypeDefKind.Enum: case TypeDefKind.StringEnum: case TypeDefKind.Fn: case TypeDefKind.Struct: { exports2.push(def.name); if (def.original_name && def.original_name !== def.name) { exports2.push(def.original_name); } break; } default: break; } return prettyPrint(def, constEnum, 0); }).join("\n\n"); } else { exports2.push(namespace); let declaration = ""; declaration += `export declare namespace ${namespace} { `; for (const def of defs2) { declaration += prettyPrint(def, constEnum, 2, true) + "\n"; } declaration += "}"; return declaration; } }).join("\n\n") + "\n"; if (dts.indexOf("ExternalObject<") > -1) { header += ` export declare class ExternalObject { readonly '': { readonly '': unique symbol [K: symbol]: T } } `; } return { dts: header + dts, exports: exports2 }; } async function readIntermediateTypeFile(file) { const content = await readFileAsync(file, "utf8"); const defs = content.split("\n").filter(Boolean).map((line) => { line = line.trim(); if (!line.startsWith("{")) { const start = line.indexOf(":") + 1; line = line.slice(start); } return JSON.parse(line); }); return defs.sort((a, b) => { if (a.kind === TypeDefKind.Struct) { if (b.kind === TypeDefKind.Struct) { return a.name.localeCompare(b.name); } return -1; } else if (b.kind === TypeDefKind.Struct) { return 1; } else { return a.name.localeCompare(b.name); } }); } function preprocessTypeDef(defs) { const namespaceGrouped = /* @__PURE__ */ new Map(); const classDefs = /* @__PURE__ */ new Map(); for (const def of defs) { const namespace = def.js_mod ?? TOP_LEVEL_NAMESPACE; if (!namespaceGrouped.has(namespace)) { namespaceGrouped.set(namespace, []); } const group = namespaceGrouped.get(namespace); if (def.kind === TypeDefKind.Struct) { group.push(def); classDefs.set(def.name, def); } else if (def.kind === TypeDefKind.Impl) { const classDef = classDefs.get(def.name); if (classDef) { if (classDef.def) { classDef.def += "\n"; } classDef.def += def.def; } } else { group.push(def); } } return namespaceGrouped; } function correctStringIdent(src, ident) { let bracketDepth = 0; const result = src.split("\n").map((line) => { line = line.trim(); if (line === "") { return ""; } const isInMultilineComment = line.startsWith("*"); const isClosingBracket = line.endsWith("}"); const isOpeningBracket = line.endsWith("{"); const isTypeDeclaration = line.endsWith("="); const isTypeVariant = line.startsWith("|"); let rightIndent = ident; if ((isOpeningBracket || isTypeDeclaration) && !isInMultilineComment) { bracketDepth += 1; rightIndent += (bracketDepth - 1) * 2; } else { if (isClosingBracket && bracketDepth > 0 && !isInMultilineComment && !isTypeVariant) { bracketDepth -= 1; } rightIndent += bracketDepth * 2; } if (isInMultilineComment) { rightIndent += 1; } const s = `${" ".repeat(rightIndent)}${line}`; return s; }).join("\n"); return result; } // dist/api/artifacts.js var debug2 = debugFactory("artifacts"); async function collectArtifacts(userOptions) { const options = applyDefaultArtifactsOptions(userOptions); const packageJsonPath = (0, import_node_path.join)(options.cwd, options.packageJsonPath); const { targets, binaryName, packageName } = await readNapiConfig(packageJsonPath); const distDirs = targets.map((platform) => (0, import_node_path.join)(options.cwd, options.npmDir, platform.platformArchABI)); const universalSourceBins = new Set(targets.filter((platform) => platform.arch === "universal").flatMap((p) => UniArchsByPlatform[p.platform]?.map((a) => `${p.platform}-${a}`)).filter(Boolean)); await collectNodeBinaries((0, import_node_path.join)(options.cwd, options.outputDir)).then((output) => Promise.all(output.map(async (filePath) => { debug2.info(`Read [${colors2.yellowBright(filePath)}]`); const sourceContent = await readFileAsync(filePath); const parsedName = (0, import_node_path.parse)(filePath); const terms = parsedName.name.split("."); const platformArchABI = terms.pop(); const _binaryName = terms.join("."); if (_binaryName !== binaryName) { debug2.warn(`[${_binaryName}] is not matched with [${binaryName}], skip`); return; } const dir = distDirs.find((dir2) => dir2.includes(platformArchABI)); if (!dir && universalSourceBins.has(platformArchABI)) { debug2.warn(`[${platformArchABI}] has no dist dir but it is source bin for universal arch, skip`); return; } if (!dir) { throw new Error(`No dist dir found for ${filePath}`); } const distFilePath = (0, import_node_path.join)(dir, parsedName.base); debug2.info(`Write file content to [${colors2.yellowBright(distFilePath)}]`); await writeFileAsync(distFilePath, sourceContent); const distFilePathLocal = (0, import_node_path.join)((0, import_node_path.parse)(packageJsonPath).dir, parsedName.base); debug2.info(`Write file content to [${colors2.yellowBright(distFilePathLocal)}]`); await writeFileAsync(distFilePathLocal, sourceContent); }))); const wasiTarget = targets.find((t) => t.platform === "wasi"); if (wasiTarget) { const wasiDir = (0, import_node_path.join)(options.cwd, options.npmDir, wasiTarget.platformArchABI); const cjsFile = (0, import_node_path.join)(options.buildOutputDir ?? options.cwd, `${binaryName}.wasi.cjs`); const workerFile = (0, import_node_path.join)(options.buildOutputDir ?? options.cwd, `wasi-worker.mjs`); const browserEntry = (0, import_node_path.join)(options.buildOutputDir ?? options.cwd, `${binaryName}.wasi-browser.js`); const browserWorkerFile = (0, import_node_path.join)(options.buildOutputDir ?? options.cwd, `wasi-worker-browser.mjs`); debug2.info(`Move wasi binding file [${colors2.yellowBright(cjsFile)}] to [${colors2.yellowBright(wasiDir)}]`); await writeFileAsync((0, import_node_path.join)(wasiDir, `${binaryName}.wasi.cjs`), await readFileAsync(cjsFile)); debug2.info(`Move wasi worker file [${colors2.yellowBright(workerFile)}] to [${colors2.yellowBright(wasiDir)}]`); await writeFileAsync((0, import_node_path.join)(wasiDir, `wasi-worker.mjs`), await readFileAsync(workerFile)); debug2.info(`Move wasi browser entry file [${colors2.yellowBright(browserEntry)}] to [${colors2.yellowBright(wasiDir)}]`); await writeFileAsync( (0, import_node_path.join)(wasiDir, `${binaryName}.wasi-browser.js`), // https://github.com/vitejs/vite/issues/8427 (await readFileAsync(browserEntry, "utf8")).replace(`new URL('./wasi-worker-browser.mjs', import.meta.url)`, `new URL('${packageName}-wasm32-wasi/wasi-worker-browser.mjs', import.meta.url)`) ); debug2.info(`Move wasi browser worker file [${colors2.yellowBright(browserWorkerFile)}] to [${colors2.yellowBright(wasiDir)}]`); await writeFileAsync((0, import_node_path.join)(wasiDir, `wasi-worker-browser.mjs`), await readFileAsync(browserWorkerFile)); } } async function collectNodeBinaries(root2) { const files = await readdirAsync(root2, { withFileTypes: true }); const nodeBinaries = files.filter((file) => file.isFile() && (file.name.endsWith(".node") || file.name.endsWith(".wasm"))).map((file) => (0, import_node_path.join)(root2, file.name)); const dirs = files.filter((file) => file.isDirectory()); for (const dir of dirs) { if (dir.name !== "node_modules") { nodeBinaries.push(...await collectNodeBinaries((0, import_node_path.join)(root2, dir.name))); } } return nodeBinaries; } // dist/api/build.js var import_node_child_process4 = require("node:child_process"); var import_node_crypto = require("node:crypto"); var import_node_fs3 = require("node:fs"); var import_node_module2 = require("node:module"); var import_node_os = require("node:os"); var import_node_path2 = require("node:path"); var colors3 = __toESM(require("colorette"), 1); var import_wasm_sjlj = require("wasm-sjlj"); // dist/api/templates/.gitignore.js var gitIgnore = `# Created by https://www.toptal.com/developers/gitignore/api/node # Edit at https://www.toptal.com/developers/gitignore?templates=node ### Node ### # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* lerna-debug.log* # Diagnostic reports (https://nodejs.org/api/report.html) report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json # Runtime data pids *.pid *.seed *.pid.lock # Directory for instrumented libs generated by jscoverage/JSCover lib-cov # Coverage directory used by tools like istanbul coverage *.lcov # nyc test coverage .nyc_output # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) .grunt # Bower dependency directory (https://bower.io/) bower_components # node-waf configuration .lock-wscript # Compiled binary addons (https://nodejs.org/api/addons.html) build/Release # Dependency directories node_modules/ jspm_packages/ # TypeScript v1 declaration files typings/ # TypeScript cache *.tsbuildinfo # Optional npm cache directory .npm # Optional eslint cache .eslintcache # Microbundle cache .rpt2_cache/ .rts2_cache_cjs/ .rts2_cache_es/ .rts2_cache_umd/ # Optional REPL history .node_repl_history # Output of 'npm pack' *.tgz # Yarn Integrity file .yarn-integrity # dotenv environment variables file .env .env.test # parcel-bundler cache (https://parceljs.org/) .cache # Next.js build output .next # Nuxt.js build / generate output .nuxt dist # Gatsby files .cache/ # Comment in the public line in if your project uses Gatsby and not Next.js # https://nextjs.org/blog/next-9-1#public-directory-support # public # vuepress build output .vuepress/dist # Serverless directories .serverless/ # FuseBox cache .fusebox/ # DynamoDB Local files .dynamodb/ # TernJS port file .tern-port # Stores VSCode versions used for testing VSCode extensions .vscode-test # End of https://www.toptal.com/developers/gitignore/api/node # Created by https://www.toptal.com/developers/gitignore/api/macos # Edit at https://www.toptal.com/developers/gitignore?templates=macos ### macOS ### # General .DS_Store .AppleDouble .LSOverride # Icon must end with two \r Icon # Thumbnails ._* # Files that might appear in the root of a volume .DocumentRevisions-V100 .fseventsd .Spotlight-V100 .TemporaryItems .Trashes .VolumeIcon.icns .com.apple.timemachine.donotpresent # Directories potentially created on remote AFP share .AppleDB .AppleDesktop Network Trash Folder Temporary Items .apdisk ### macOS Patch ### # iCloud generated files *.icloud # End of https://www.toptal.com/developers/gitignore/api/macos # Created by https://www.toptal.com/developers/gitignore/api/windows # Edit at https://www.toptal.com/developers/gitignore?templates=windows ### Windows ### # Windows thumbnail cache files Thumbs.db Thumbs.db:encryptable ehthumbs.db ehthumbs_vista.db # Dump file *.stackdump # Folder config file [Dd]esktop.ini # Recycle Bin used on file shares $RECYCLE.BIN/ # Windows Installer files *.cab *.msi *.msix *.msm *.msp # Windows shortcuts *.lnk # End of https://www.toptal.com/developers/gitignore/api/windows #Added by cargo /target Cargo.lock .pnp.* .yarn/* !.yarn/patches !.yarn/plugins !.yarn/releases !.yarn/sdks !.yarn/versions *.node *.wasm `; // dist/api/templates/.npmignore.js var npmIgnore = `target Cargo.lock .cargo .github npm .eslintrc .prettierignore rustfmt.toml yarn.lock *.node .yarn __test__ renovate.json `; // dist/api/templates/build.rs.js var createBuildRs = () => `fn main() { napi_build::setup(); } `; // dist/api/templates/cargo.toml.js var createCargoToml = ({ name, license, features, deriveFeatures }) => `[package] name = "${name.replace("@", "").replace("/", "_").toLowerCase()}" version = "1.0.0" edition = "2021" license = "${license}" [lib] crate-type = ["cdylib"] [dependencies.napi] version = "2" default-features = false # see https://nodejs.org/api/n-api.html#node-api-version-matrix features = ${JSON.stringify(features)} [dependencies.napi-derive] version = "2" features = ${JSON.stringify(deriveFeatures)} [build-dependencies] napi-build = "2" [profile.release] lto = true strip = "symbols" `; // dist/api/templates/ci.yml.js var import_js_yaml = require("js-yaml"); // dist/api/templates/ci-template.js var YAML = (packageManager, wasiTargetName) => ` name: CI env: DEBUG: 'napi:*' MACOSX_DEPLOYMENT_TARGET: '10.13' permissions: contents: write id-token: write on: push: branches: - main tags-ignore: - '**' paths-ignore: - '**/*.md' - 'LICENSE' - '**/*.gitignore' - '.editorconfig' - 'docs/**' pull_request: jobs: build: strategy: fail-fast: false matrix: settings: - host: macos-latest target: 'x86_64-apple-darwin' build: ${packageManager} build --platform --target x86_64-apple-darwin - host: windows-latest build: ${packageManager} build --platform target: 'x86_64-pc-windows-msvc' - host: windows-latest build: | ${packageManager} build --platform --target i686-pc-windows-msvc ${packageManager} test target: 'i686-pc-windows-msvc' - host: ubuntu-latest target: 'x86_64-unknown-linux-gnu' build: ${packageManager} build --platform --target x86_64-unknown-linux-gnu --use-napi-cross - host: ubuntu-latest target: 'x86_64-unknown-linux-musl' build: ${packageManager} build --platform --target x86_64-unknown-linux-musl -x - host: macos-latest target: 'aarch64-apple-darwin' build: ${packageManager} build --platform --target aarch64-apple-darwin - host: ubuntu-latest target: 'aarch64-unknown-linux-gnu' build: ${packageManager} build --platform --target aarch64-unknown-linux-gnu --use-napi-cross - host: ubuntu-latest target: 'armv7-unknown-linux-gnueabihf' build: ${packageManager} build --platform --target armv7-unknown-linux-gnueabihf --use-napi-cross - host: ubuntu-latest target: 'armv7-unknown-linux-musleabihf' build: ${packageManager} build --platform --target armv7-unknown-linux-musleabihf -x - host: ubuntu-latest target: 'aarch64-linux-android' build: ${packageManager} build --platform --target aarch64-linux-android - host: ubuntu-latest target: 'armv7-linux-androideabi' build: ${packageManager} build --platform --target armv7-linux-androideabi - host: ubuntu-latest target: 'aarch64-unknown-linux-musl' build: ${packageManager} build --platform --target aarch64-unknown-linux-musl -x - host: windows-latest target: 'aarch64-pc-windows-msvc' build: ${packageManager} build --platform --target aarch64-pc-windows-msvc - host: ubuntu-latest target: 'riscv64gc-unknown-linux-gnu' setup: | sudo apt-get update sudo apt-get install gcc-riscv64-linux-gnu -y build: ${packageManager} build --platform --target riscv64gc-unknown-linux-gnu - host: ubuntu-latest target: 'powerpc64le-unknown-linux-gnu' setup: | sudo apt-get update sudo apt-get install gcc-powerpc64le-linux-gnu -y build: ${packageManager} build --platform --target powerpc64le-unknown-linux-gnu - host: ubuntu-latest target: 's390x-unknown-linux-gnu' setup: | sudo apt-get update sudo apt-get install gcc-s390x-linux-gnu -y build: ${packageManager} build --platform --target s390x-unknown-linux-gnu - host: ubuntu-latest target: '${wasiTargetName}' build: ${packageManager} build --platform --target ${wasiTargetName} name: stable - \${{ matrix.settings.target }} - node@20 runs-on: \${{ matrix.settings.host }} steps: - uses: actions/checkout@v4 - name: Setup node uses: actions/setup-node@v4 with: node-version: 20 cache: ${packageManager} - name: Install uses: dtolnay/rust-toolchain@stable with: toolchain: stable targets: \${{ matrix.settings.target }} - name: Cache cargo uses: actions/cache@v4 with: path: | ~/.cargo/registry/index/ ~/.cargo/registry/cache/ ~/.cargo/git/db/ ~/.napi-rs .cargo-cache target/ key: \${{ matrix.settings.target }}-cargo-\${{ matrix.settings.host }} - uses: goto-bus-stop/setup-zig@v2 if: \${{ contains(matrix.settings.target, 'musl') }} with: version: 0.13.0 - name: Install cargo-zigbuild uses: taiki-e/install-action@v2 if: \${{ contains(matrix.settings.target, 'musl') }} env: GITHUB_TOKEN: \${{ github.token }} with: tool: cargo-zigbuild - name: Setup toolchain run: \${{ matrix.settings.setup }} if: \${{ matrix.settings.setup }} shell: bash - name: Setup node x86 if: matrix.settings.target == 'i686-pc-windows-msvc' run: yarn config set supportedArchitectures.cpu "ia32" shell: bash - name: 'Install dependencies' run: ${packageManager} install - name: Setup node x86 uses: actions/setup-node@v4 if: matrix.settings.target == 'i686-pc-windows-msvc' with: node-version: 20 architecture: x86 - name: 'Build' run: \${{ matrix.settings.build }} shell: bash - name: Upload artifact uses: actions/upload-artifact@v4 if: matrix.settings.target != '${wasiTargetName}' with: name: bindings-\${{ matrix.settings.target }} path: "*.node" if-no-files-found: error - name: Upload artifact uses: actions/upload-artifact@v4 if: matrix.settings.target == '${wasiTargetName}' with: name: bindings-\${{ matrix.settings.target }} path: "*.wasm" if-no-files-found: error build-freebsd: runs-on: ubuntu-latest name: Build FreeBSD steps: - uses: actions/checkout@v4 - name: Build id: build uses: cross-platform-actions/action@v0.25.0 env: DEBUG: 'napi:*' RUSTUP_IO_THREADS: 1 with: operating_system: freebsd version: '14.1' memory: 8G cpu_count: 3 environment_variables: 'DEBUG RUSTUP_IO_THREADS' shell: bash run: | sudo pkg install -y -f curl node libnghttp2 npm sudo npm install -g ${packageManager} --ignore-scripts curl https://sh.rustup.rs -sSf --output rustup.sh sh rustup.sh -y --profile minimal --default-toolchain stable source "$HOME/.cargo/env" echo "~~~~ rustc --version ~~~~" rustc --version echo "~~~~ node -v ~~~~" node -v echo "~~~~ yarn --version ~~~~" yarn --version pwd ls -lah whoami env freebsd-version ${packageManager} install ${packageManager} build strip -x *.node yarn test rm -rf node_modules rm -rf target rm -rf .yarn/cache - name: Upload artifact uses: actions/upload-artifact@v4 with: name: bindings-freebsd path: "*.node" if-no-files-found: error test-macOS-windows-binding: name: Test bindings on \${{ matrix.settings.target }} - node@\${{ matrix.node }} needs: - build strategy: fail-fast: false matrix: settings: - host: macos-latest target: 'x86_64-apple-darwin' architecture: x64 - host: macos-latest target: 'aarch64-apple-darwin' architecture: arm64 - host: windows-latest target: 'x86_64-pc-windows-msvc' architecture: x64 node: ['18', '20'] runs-on: \${{ matrix.settings.host }} steps: - uses: actions/checkout@v4 - name: Setup node uses: actions/setup-node@v4 with: node-version: \${{ matrix.node }} cache: '${packageManager}' architecture: \${{ matrix.settings.architecture }} - name: 'Install dependencies' run: ${packageManager} install - name: Download artifacts uses: actions/download-artifact@v4 with: name: bindings-\${{ matrix.settings.target }} path: . - name: List packages run: ls -R . shell: bash - name: Test bindings run: ${packageManager} run test test-linux-x64-gnu-binding: name: Test bindings on Linux-x64-gnu - node@\${{ matrix.node }} needs: - build strategy: fail-fast: false matrix: node: ['18', '20'] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Setup node uses: actions/setup-node@v4 with: node-version: \${{ matrix.node }} cache: '${packageManager}' - name: 'Install dependencies' run: ${packageManager} install - name: Download artifacts uses: actions/download-artifact@v4 with: name: bindings-x86_64-unknown-linux-gnu path: . - name: List packages run: ls -R . shell: bash - name: Test bindings run: docker run --rm -v $(pwd):/build -w /build node:\${{ matrix.node }}-slim ${packageManager} run test test-linux-x64-musl-binding: name: Test bindings on x86_64-unknown-linux-musl - node@\${{ matrix.node }} needs: - build strategy: fail-fast: false matrix: node: ['18', '20'] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Setup node uses: actions/setup-node@v4 with: node-version: \${{ matrix.node }} cache: '${packageManager}' - name: 'Install dependencies' run: | yarn config set supportedArchitectures.libc "musl" ${packageManager} install - name: Download artifacts uses: actions/download-artifact@v4 with: name: bindings-x86_64-unknown-linux-musl path: . - name: List packages run: ls -R . shell: bash - name: Test bindings run: docker run --rm -v $(pwd):/build -w /build node:\${{ matrix.node }}-alpine ${packageManager} run test test-linux-aarch64-gnu-binding: name: Test bindings on aarch64-unknown-linux-gnu - node@\${{ matrix.node }} needs: - build strategy: fail-fast: false matrix: node: ['20'] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Download artifacts uses: actions/download-artifact@v4 with: name: bindings-aarch64-unknown-linux-gnu path: . - name: List packages run: ls -R . shell: bash - name: Install dependencies run: | yarn config set supportedArchitectures.cpu "arm64" yarn config set supportedArchitectures.libc "glibc" ${packageManager} install - name: Set up QEMU uses: docker/setup-qemu-action@v3 with: platforms: arm64 - run: docker run --rm --privileged multiarch/qemu-user-static --reset -p yes - name: Setup and run tests uses: addnab/docker-run-action@v3 with: image: node:\${{ matrix.node }}-slim options: --platform linux/arm64 -v \${{ github.workspace }}:/build -w /build run: ${packageManager} run test test-linux-aarch64-musl-binding: name: Test bindings on aarch64-unknown-linux-musl - node@\${{ matrix.node }} needs: - build strategy: fail-fast: false matrix: node: ['18', '20'] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Download artifacts uses: actions/download-artifact@v4 with: name: bindings-aarch64-unknown-linux-musl path: . - name: List packages run: ls -R . shell: bash - name: Install dependencies run: | yarn config set supportedArchitectures.cpu "arm64" yarn config set supportedArchitectures.libc "musl" ${packageManager} install - name: Set up QEMU uses: docker/setup-qemu-action@v3 with: platforms: arm64 - run: docker run --rm --privileged multiarch/qemu-user-static --reset -p yes - name: Setup and run tests uses: addnab/docker-run-action@v3 with: image: node:\${{ matrix.node }}-alpine options: --platform linux/arm64 -v \${{ github.workspace }}:/build -w /build run: ${packageManager} run test test-linux-arm-gnueabihf-binding: name: Test bindings on armv7-unknown-linux-gnueabihf - node@\${{ matrix.node }} needs: - build strategy: fail-fast: false matrix: node: ['18', '20'] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Download artifacts uses: actions/download-artifact@v4 with: name: bindings-armv7-unknown-linux-gnueabihf path: . - name: List packages run: ls -R . shell: bash - name: Install dependencies run: | yarn config set supportedArchitectures.cpu "arm" ${packageManager} install - name: Set up QEMU uses: docker/setup-qemu-action@v3 with: platforms: arm - run: docker run --rm --privileged multiarch/qemu-user-static --reset -p yes - name: Setup and run tests uses: addnab/docker-run-action@v3 with: image: node:\${{ matrix.node }}-bullseye-slim options: --platform linux/arm/v7 -v \${{ github.workspace }}:/build -w /build run: ${packageManager} test universal-macOS: name: Build universal macOS binary needs: - build runs-on: macos-latest steps: - uses: actions/checkout@v4 - name: Setup node uses: actions/setup-node@v4 with: node-version: 20 cache: ${packageManager} - name: 'Install dependencies' run: ${packageManager} install - name: Download macOS x64 artifact uses: actions/download-artifact@v4 with: name: bindings-x86_64-apple-darwin path: . - name: Download macOS arm64 artifact uses: actions/download-artifact@v4 with: name: bindings-aarch64-apple-darwin path: . - name: Combine binaries run: ${packageManager} napi universalize - name: Upload artifact uses: actions/upload-artifact@v4 with: name: bindings-universal-apple-darwin path: "*.node" if-no-files-found: error test-wasi-nodejs: name: Test bindings on wasi - node@\${{ matrix.node }} needs: - build strategy: fail-fast: false matrix: node: ['18', '20'] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Download artifacts uses: actions/download-artifact@v4 with: name: bindings-${wasiTargetName} path: . - name: List packages run: ls -R . - uses: actions/setup-node@v4 with: node-version: \${{ matrix.node }} cache: ${packageManager} - name: 'Install dependencies' run: ${packageManager} install - name: Test run: ${packageManager} test env: NAPI_RS_FORCE_WASI: true publish: name: Publish runs-on: ubuntu-latest needs: - test-linux-x64-gnu-binding - test-linux-x64-musl-binding - test-linux-aarch64-gnu-binding - test-linux-arm-gnueabihf-binding - test-macOS-windows-binding - test-linux-aarch64-musl-binding - test-wasi-nodejs - build-freebsd steps: - uses: actions/checkout@v4 - name: Setup node uses: actions/setup-node@v4 with: node-version: 20 cache: '${packageManager}' registry-url: 'https://registry.npmjs.org' - name: 'Install dependencies' run: ${packageManager} install - name: Download all artifacts uses: actions/download-artifact@v4 with: path: artifacts - name: Move artifacts run: ${packageManager} artifacts - name: List packages run: ls -R ./npm shell: bash - name: Publish run: | if git log -1 --pretty=%B | grep "^[0-9]\\+\\.[0-9]\\+\\.[0-9]\\+$"; then npm publish --access public --provenance elif git log -1 --pretty=%B | grep "^[0-9]\\+\\.[0-9]\\+\\.[0-9]\\+"; then npm publish --tag next --access public --provenance else echo "Not a release, skipping publish" fi env: GITHUB_TOKEN: \${{ secrets.GITHUB_TOKEN }} NODE_AUTH_TOKEN: \${{ secrets.NPM_TOKEN }} `; // dist/api/templates/ci.yml.js var BUILD_FREEBSD = "build-freebsd"; var TEST_MACOS_WINDOWS = "test-macOS-windows-binding"; var TEST_LINUX_X64_GNU = "test-linux-x64-gnu-binding"; var TEST_LINUX_X64_MUSL = "test-linux-x64-musl-binding"; var TEST_LINUX_AARCH64_GNU = "test-linux-aarch64-gnu-binding"; var TEST_LINUX_AARCH64_MUSL = "test-linux-aarch64-musl-binding"; var TEST_LINUX_ARM_GNUEABIHF = "test-linux-arm-gnueabihf-binding"; var TEST_WASI = "test-wasi-nodejs"; var UNIVERSAL_MACOS = "universal-macOS"; var createGithubActionsCIYml = (targets, packageManager, wasiTargetName) => { const allTargets = new Set(targets.flatMap((t) => { const platform = parseTriple(t); if (platform.arch === "universal") { const srcTriples = UniArchsByPlatform[platform.platform]?.map((arch) => t.replace("universal", NodeArchToCpu[arch])); return [t, ...srcTriples ?? []]; } return [t]; })); const fullTemplate = (0, import_js_yaml.load)(YAML(packageManager, wasiTargetName)); const requiredSteps = []; const enableWindowsX86 = allTargets.has("x86_64-pc-windows-msvc"); const enableMacOSX86 = allTargets.has("x86_64-apple-darwin"); const enableLinuxX86Gnu = allTargets.has("x86_64-unknown-linux-gnu"); const enableLinuxX86Musl = allTargets.has("x86_64-unknown-linux-musl"); const enableLinuxArm8Gnu = allTargets.has("aarch64-unknown-linux-gnu"); const enableLinuxArm8Musl = allTargets.has("aarch64-unknown-linux-musl"); const enableLinuxArm7 = allTargets.has("armv7-unknown-linux-gnueabihf"); const enableFreeBSD = allTargets.has("x86_64-unknown-freebsd"); const enableMacOSUni = allTargets.has("universal-apple-darwin"); const enableWasi = allTargets.has("wasm32-wasi-preview1-threads") || allTargets.has("wasm32-wasip1-threads") || allTargets.has("wasm32-wasip2"); fullTemplate.jobs.build.strategy.matrix.settings = fullTemplate.jobs.build.strategy.matrix.settings.filter(({ target }) => allTargets.has(target)); if (!fullTemplate.jobs.build.strategy.matrix.settings.length) { delete fullTemplate.jobs.build.strategy.matrix; } if (!enableFreeBSD) { delete fullTemplate.jobs[BUILD_FREEBSD]; } else { requiredSteps.push(BUILD_FREEBSD); } if (!enableWindowsX86 && !enableMacOSX86) { delete fullTemplate.jobs[TEST_MACOS_WINDOWS]; } else { const filterTargets = /* @__PURE__ */ new Set(); if (enableWindowsX86) { filterTargets.add("windows-latest"); } if (enableMacOSUni || enableMacOSX86) { filterTargets.add("macos-latest"); } fullTemplate.jobs[TEST_MACOS_WINDOWS].strategy.matrix.settings = fullTemplate.jobs[TEST_MACOS_WINDOWS].strategy.matrix.settings.filter(({ host }) => filterTargets.has(host)); requiredSteps.push(TEST_MACOS_WINDOWS); } if (!enableLinuxX86Gnu) { delete fullTemplate.jobs[TEST_LINUX_X64_GNU]; } else { requiredSteps.push(TEST_LINUX_X64_GNU); } if (!enableLinuxX86Musl) { delete fullTemplate.jobs[TEST_LINUX_X64_MUSL]; } else { requiredSteps.push(TEST_LINUX_X64_MUSL); } if (!enableLinuxArm8Gnu) { delete fullTemplate.jobs[TEST_LINUX_AARCH64_GNU]; } else { requiredSteps.push(TEST_LINUX_AARCH64_GNU); } if (!enableLinuxArm8Musl) { delete fullTemplate.jobs[TEST_LINUX_AARCH64_MUSL]; } else { requiredSteps.push(TEST_LINUX_AARCH64_MUSL); } if (!enableLinuxArm7) { delete fullTemplate.jobs[TEST_LINUX_ARM_GNUEABIHF]; } else { requiredSteps.push(TEST_LINUX_ARM_GNUEABIHF); } if (!enableMacOSUni) { delete fullTemplate.jobs[UNIVERSAL_MACOS]; } else { requiredSteps.push(UNIVERSAL_MACOS); } if (!enableWasi) { delete fullTemplate.jobs[TEST_WASI]; } else { requiredSteps.push(TEST_WASI); } fullTemplate.jobs.publish.needs = requiredSteps; try { return (0, import_js_yaml.dump)(fullTemplate, { lineWidth: 1e3 }); } catch (err) { console.info(fullTemplate); throw err; } }; // dist/api/templates/lib.rs.js var createLibRs = () => `use napi_derive::napi; #[napi] pub fn sum(a: i32, b: i32) -> i32 { a + b } `; // dist/api/templates/package.json.js var createPackageJson = async ({ name, binaryName, targets, license, engineRequirement, cliVersion, testFramework }) => { const hasWasmTarget = targets.some((t) => t.includes("wasm")); const universalTargets = targets.filter((t) => t in UNIVERSAL_TARGETS); const unifiedtargets = universalTargets.length ? targets.filter((target) => !universalTargets.some((t) => { return UNIVERSAL_TARGETS[t].includes(target); })) : targets; const content = { name, version: "0.0.0", license, engines: { node: engineRequirement }, type: "commonjs", main: "index.js", types: "index.d.ts", browser: "browser.js", module: void 0, exports: void 0, napi: { binaryName, targets: unifiedtargets }, scripts: { test: testFramework, build: "napi build --release --platform --strip", "build:debug": "napi build", prepublishOnly: "napi prepublish -t npm", artifacts: "napi artifacts", version: "napi version" }, devDependencies: { "@chainsafe/napi-rs-cli": `^${cliVersion}` } }; if (testFramework === "ava") { const avaMeta = await fetch(`https://registry.npmjs.org/ava`).then((res) => res.json()); content.devDependencies["ava"] = `^${avaMeta["dist-tags"].latest}`; content.ava = { timeout: "1m" }; } if (hasWasmTarget) { const wasmRuntime = await fetch(`https://registry.npmjs.org/@napi-rs/wasm-runtime`).then((res) => res.json()); const latest = wasmRuntime["dist-tags"].latest; content.devDependencies["@napi-rs/wasm-runtime"] = `^${latest}`; } return JSON.stringify(content, null, 2); }; // dist/api/templates/js-binding.js function createCjsBinding(localName, pkgName, idents) { return `${bindingHeader} const { createRequire } = require('node:module') require = createRequire(__filename) ${createCommonBinding(localName, pkgName)} ${idents.map((ident) => `module.exports.${ident} = nativeBinding.${ident}`).join("\n")} `; } function createEsmBinding(localName, pkgName, idents) { return `${bindingHeader} import { createRequire } from 'node:module' const require = createRequire(import.meta.url) const __dirname = new URL('.', import.meta.url).pathname ${createCommonBinding(localName, pkgName)} const { ${idents.join(", ")} } = nativeBinding ${idents.map((ident) => `export { ${ident} }`).join("\n")} `; } var bindingHeader = `// prettier-ignore /* eslint-disable */ // @ts-nocheck /* auto-generated by NAPI-RS */ `; function createCommonBinding(localName, pkgName) { function requireTuple(tuple) { return `try { return require('./${localName}.${tuple}.node') } catch (e) { loadErrors.push(e) } try { return require('${pkgName}-${tuple}') } catch (e) { loadErrors.push(e) } `; } return `const { readFileSync } = require('node:fs') let nativeBinding = null const loadErrors = [] const isMusl = () => { let musl = false if (process.platform === 'linux') { musl = isMuslFromFilesystem() if (musl === null) { musl = isMuslFromReport() } if (musl === null) { musl = isMuslFromChildProcess() } } return musl } const isFileMusl = (f) => f.includes('libc.musl-') || f.includes('ld-musl-') const isMuslFromFilesystem = () => { try { return readFileSync('/usr/bin/ldd', 'utf-8').includes('musl') } catch { return null } } const isMuslFromReport = () => { const report = typeof process.report.getReport === 'function' ? process.report.getReport() : null if (!report) { return null } if (report.header && report.header.glibcVersionRuntime) { return false } if (Array.isArray(report.sharedObjects)) { if (report.sharedObjects.some(isFileMusl)) { return true } } return false } const isMuslFromChildProcess = () => { try { return require('child_process').execSync('ldd --version', { encoding: 'utf8' }).includes('musl') } catch (e) { // If we reach this case, we don't know if the system is musl or not, so is better to just fallback to false return false } } function requireNative() { if (process.platform === 'android') { if (process.arch === 'arm64') { ${requireTuple("android-arm64")} } else if (process.arch === 'arm') { ${requireTuple("android-arm-eabi")} } else { loadErrors.push(new Error(\`Unsupported architecture on Android \${process.arch}\`)) } } else if (process.platform === 'win32') { if (process.arch === 'x64') { ${requireTuple("win32-x64-msvc")} } else if (process.arch === 'ia32') { ${requireTuple("win32-ia32-msvc")} } else if (process.arch === 'arm64') { ${requireTuple("win32-arm64-msvc")} } else { loadErrors.push(new Error(\`Unsupported architecture on Windows: \${process.arch}\`)) } } else if (process.platform === 'darwin') { ${requireTuple("darwin-universal")} if (process.arch === 'x64') { ${requireTuple("darwin-x64")} } else if (process.arch === 'arm64') { ${requireTuple("darwin-arm64")} } else { loadErrors.push(new Error(\`Unsupported architecture on macOS: \${process.arch}\`)) } } else if (process.platform === 'freebsd') { if (process.arch === 'x64') { ${requireTuple("freebsd-x64")} } else if (process.arch === 'arm64') { ${requireTuple("freebsd-arm64")} } else { loadErrors.push(new Error(\`Unsupported architecture on FreeBSD: \${process.arch}\`)) } } else if (process.platform === 'linux') { if (process.arch === 'x64') { if (isMusl()) { ${requireTuple("linux-x64-musl")} } else { ${requireTuple("linux-x64-gnu")} } } else if (process.arch === 'arm64') { if (isMusl()) { ${requireTuple("linux-arm64-musl")} } else { ${requireTuple("linux-arm64-gnu")} } } else if (process.arch === 'arm') { if (isMusl()) { ${requireTuple("linux-arm-musleabihf")} } else { ${requireTuple("linux-arm-gnueabihf")} } } else if (process.arch === 'riscv64') { if (isMusl()) { ${requireTuple("linux-riscv64-musl")} } else { ${requireTuple("linux-riscv64-gnu")} } } else if (process.arch === 'ppc64') { ${requireTuple("linux-ppc64-gnu")} } else if (process.arch === 's390x') { ${requireTuple("linux-s390x-gnu")} } else { loadErrors.push(new Error(\`Unsupported architecture on Linux: \${process.arch}\`)) } } else { loadErrors.push(new Error(\`Unsupported OS: \${process.platform}, architecture: \${process.arch}\`)) } } nativeBinding = requireNative() if (!nativeBinding || process.env.NAPI_RS_FORCE_WASI) { try { nativeBinding = require('./${localName}.wasi.cjs') } catch (err) { if (process.env.NAPI_RS_FORCE_WASI) { loadErrors.push(err) } } if (!nativeBinding) { try { nativeBinding = require('${pkgName}-wasm32-wasi') } catch (err) { if (process.env.NAPI_RS_FORCE_WASI) { loadErrors.push(err) } } } } if (!nativeBinding) { if (loadErrors.length > 0) { // TODO Link to documentation with potential fixes // - The package owner could build/publish bindings for this arch // - The user may need to bundle the correct files // - The user may need to re-install node_modules to get new packages throw new Error('Failed to load native binding', { cause: loadErrors }) } throw new Error(\`Failed to load native binding\`) } `; } // dist/api/templates/load-wasi-template.js var createWasiBrowserBinding = (wasiFilename, wasiRegisterFunctions, initialMemory = 4e3, maximumMemory = 65536, fs2 = false) => { const fsImport = fs2 ? `import { memfs } from '@napi-rs/wasm-runtime/fs'` : ""; const wasiCreation = fs2 ? ` export const { fs: __fs, vol: __volume } = memfs() const __wasi = new __WASI({ version: 'preview1', fs: __fs, preopens: { '/': '/', } })` : ` const __wasi = new __WASI({ version: 'preview1', })`; const workerFsHandler = fs2 ? ` worker.addEventListener('message', __wasmCreateOnMessageForFsProxy(__fs)) ` : ""; return `import { instantiateNapiModuleSync as __emnapiInstantiateNapiModuleSync, getDefaultContext as __emnapiGetDefaultContext, WASI as __WASI, createOnMessage as __wasmCreateOnMessageForFsProxy, } from '@napi-rs/wasm-runtime' ${fsImport} import __wasmUrl from './${wasiFilename}.wasm?url' ${wasiCreation} const __emnapiContext = __emnapiGetDefaultContext() const __sharedMemory = new WebAssembly.Memory({ initial: ${initialMemory}, maximum: ${maximumMemory}, shared: true, }) const __wasmFile = await fetch(__wasmUrl).then((res) => res.arrayBuffer()) const { instance: __napiInstance, module: __wasiModule, napiModule: __napiModule, } = __emnapiInstantiateNapiModuleSync(__wasmFile, { context: __emnapiContext, asyncWorkPoolSize: 4, wasi: __wasi, onCreateWorker() { const worker = new Worker(new URL('./wasi-worker-browser.mjs', import.meta.url), { type: 'module', }) ${workerFsHandler} return worker }, overwriteImports(importObject) { importObject.env = { ...importObject.env, ...importObject.napi, ...importObject.emnapi, memory: __sharedMemory, } return importObject }, beforeInit({ instance }) { __napi_rs_initialize_modules(instance) }, }) function __napi_rs_initialize_modules(__napiInstance) { ${wasiRegisterFunctions.map((name) => ` __napiInstance.exports['${name}']?.()`).join("\n")} } `; }; var createWasiBinding = (wasmFileName, packageName, wasiRegisterFunctions, initialMemory = 4e3, maximumMemory = 65536) => `/* eslint-disable */ /* prettier-ignore */ /* auto-generated by NAPI-RS */ const __nodeFs = require('node:fs') const __nodePath = require('node:path') const { WASI: __nodeWASI } = require('node:wasi') const { Worker } = require('node:worker_threads') const { instantiateNapiModuleSync: __emnapiInstantiateNapiModuleSync, getDefaultContext: __emnapiGetDefaultContext, createOnMessage: __wasmCreateOnMessageForFsProxy, } = require('@napi-rs/wasm-runtime') const __rootDir = __nodePath.parse(process.cwd()).root const __wasi = new __nodeWASI({ version: 'preview1', env: process.env, preopens: { [__rootDir]: __rootDir, } }) const __emnapiContext = __emnapiGetDefaultContext() const __sharedMemory = new WebAssembly.Memory({ initial: ${initialMemory}, maximum: ${maximumMemory}, shared: true, }) let __wasmFilePath = __nodePath.join(__dirname, '${wasmFileName}.wasm') const __wasmDebugFilePath = __nodePath.join(__dirname, '${wasmFileName}.debug.wasm') if (__nodeFs.existsSync(__wasmDebugFilePath)) { __wasmFilePath = __wasmDebugFilePath } else if (!__nodeFs.existsSync(__wasmFilePath)) { try { __wasmFilePath = __nodePath.resolve('${packageName}-wasm32-wasi') } catch { throw new Error('Cannot find ${wasmFileName}.wasm file, and ${packageName}-wasm32-wasi package is not installed.') } } const { instance: __napiInstance, module: __wasiModule, napiModule: __napiModule } = __emnapiInstantiateNapiModuleSync(__nodeFs.readFileSync(__wasmFilePath), { context: __emnapiContext, asyncWorkPoolSize: (function() { const threadsSizeFromEnv = Number(process.env.NAPI_RS_ASYNC_WORK_POOL_SIZE ?? process.env.UV_THREADPOOL_SIZE) // NaN > 0 is false if (threadsSizeFromEnv > 0) { return threadsSizeFromEnv } else { return 4 } })(), wasi: __wasi, onCreateWorker() { const worker = new Worker(__nodePath.join(__dirname, 'wasi-worker.mjs'), { env: process.env, execArgv: ['--experimental-wasi-unstable-preview1'], }) worker.onmessage = ({ data }) => { __wasmCreateOnMessageForFsProxy(__nodeFs)(data) } return worker }, overwriteImports(importObject) { importObject.env = { ...importObject.env, ...importObject.napi, ...importObject.emnapi, memory: __sharedMemory, } return importObject }, beforeInit({ instance }) { __napi_rs_initialize_modules(instance) } }) function __napi_rs_initialize_modules(__napiInstance) { ${wasiRegisterFunctions.map((name) => ` __napiInstance.exports['${name}']?.()`).join("\n")} } `; // dist/api/templates/wasi-worker-template.js var WASI_WORKER_TEMPLATE = `import fs from "node:fs"; import { createRequire } from "node:module"; import { parse } from "node:path"; import { WASI } from "node:wasi"; import { parentPort, Worker } from "node:worker_threads"; const require = createRequire(import.meta.url); const { instantiateNapiModuleSync, MessageHandler, getDefaultContext } = require("@napi-rs/wasm-runtime"); if (parentPort) { parentPort.on("message", (data) => { globalThis.onmessage({ data }); }); } Object.assign(globalThis, { self: globalThis, require, Worker, importScripts: function (f) { ;(0, eval)(fs.readFileSync(f, "utf8") + "//# sourceURL=" + f); }, postMessage: function (msg) { if (parentPort) { parentPort.postMessage(msg); } }, }); const emnapiContext = getDefaultContext(); const __rootDir = parse(process.cwd()).root; const handler = new MessageHandler({ onLoad({ wasmModule, wasmMemory }) { const wasi = new WASI({ version: 'preview1', env: process.env, preopens: { [__rootDir]: __rootDir, }, }); return instantiateNapiModuleSync(wasmModule, { childThread: true, wasi, context: emnapiContext, overwriteImports(importObject) { importObject.env = { ...importObject.env, ...importObject.napi, ...importObject.emnapi, memory: wasmMemory }; }, }); }, }); globalThis.onmessage = function (e) { handler.handle(e); }; `; var createWasiBrowserWorkerBinding = (fs2) => { const fsImport = fs2 ? `import { instantiateNapiModuleSync, MessageHandler, WASI, createFsProxy } from '@napi-rs/wasm-runtime' import { memfsExported as __memfsExported } from '@napi-rs/wasm-runtime/fs' const fs = createFsProxy(__memfsExported)` : `import { instantiateNapiModuleSync, MessageHandler, WASI } from '@napi-rs/wasm-runtime'`; const wasiCreation = fs2 ? `const wasi = new WASI({ fs, preopens: { '/': '/', }, print: function () { // eslint-disable-next-line no-console console.log.apply(console, arguments) }, printErr: function() { // eslint-disable-next-line no-console console.error.apply(console, arguments) }, })` : `const wasi = new WASI({ print: function () { // eslint-disable-next-line no-console console.log.apply(console, arguments) }, printErr: function() { // eslint-disable-next-line no-console console.error.apply(console, arguments) }, })`; return `${fsImport} const handler = new MessageHandler({ onLoad({ wasmModule, wasmMemory }) { ${wasiCreation} return instantiateNapiModuleSync(wasmModule, { childThread: true, wasi, overwriteImports(importObject) { importObject.env = { ...importObject.env, ...importObject.napi, ...importObject.emnapi, memory: wasmMemory, } }, }) }, }) globalThis.onmessage = function (e) { handler.handle(e) } `; }; // dist/api/build.js var debug3 = debugFactory("build"); var require3 = (0, import_node_module2.createRequire)(__filename); async function buildProject(options) { debug3("napi build command receive options: %O", options); const cwd = options.cwd ?? process.cwd(); const resolvePath = (...paths) => (0, import_node_path2.resolve)(cwd, ...paths); const manifestPath = resolvePath(options.manifestPath ?? "Cargo.toml"); const metadata = parseMetadata(manifestPath); const pkg = metadata.packages.find((p) => { if (options.package) { return p.name === options.package; } else { return p.manifest_path === manifestPath; } }); if (!pkg) { throw new Error("Unable to find crate to build. It seems you are trying to build a crate in a workspace, try using `--package` option to specify the package to build."); } const crateDir = (0, import_node_path2.parse)(pkg.manifest_path).dir; const builder = new Builder(options, pkg, cwd, options.target ? parseTriple(options.target) : process.env.CARGO_BUILD_TARGET ? parseTriple(process.env.CARGO_BUILD_TARGET) : getSystemDefaultTarget(), crateDir, resolvePath(options.outputDir ?? crateDir), options.targetDir ?? process.env.CARGO_BUILD_TARGET_DIR ?? metadata.target_directory, await readNapiConfig(resolvePath(options.configPath ?? options.packageJsonPath ?? "package.json"), options.configPath ? resolvePath(options.configPath) : void 0)); return builder.build(); } var Builder = class { options; crate; cwd; target; crateDir; outputDir; targetDir; config; args = []; envs = {}; outputs = []; constructor(options, crate, cwd, target, crateDir, outputDir, targetDir, config) { this.options = options; this.crate = crate; this.cwd = cwd; this.target = target; this.crateDir = crateDir; this.outputDir = outputDir; this.targetDir = targetDir; this.config = config; } get cdyLibName() { return this.crate.targets.find((t) => t.crate_types.includes("cdylib"))?.name; } get binName() { return this.options.bin ?? // only available if not cdylib or bin name specified (this.cdyLibName ? null : this.crate.targets.find((t) => t.crate_types.includes("bin"))?.name); } build() { if (!this.cdyLibName) { const warning = 'Missing `crate-type = ["cdylib"]` in [lib] config. The build result will not be available as node addon.'; if (this.binName) { debug3.warn(warning); } else { throw new Error(warning); } } return this.pickBinary().setPackage().setFeatures().setTarget().pickCrossToolchain().setEnvs().setBypassArgs().exec(); } pickCrossToolchain() { if (!this.options.useNapiCross) { return this; } if (this.options.useCross) { debug3.warn("You are trying to use both `--cross` and `--use-napi-cross` options, `--use-cross` will be ignored."); } if (this.options.crossCompile) { debug3.warn("You are trying to use both `--cross-compile` and `--use-napi-cross` options, `--cross-compile` will be ignored."); } try { const { version: version2, download } = require3("@napi-rs/cross-toolchain"); const toolchainPath = (0, import_node_path2.join)((0, import_node_os.homedir)(), ".napi-rs", "cross-toolchain", version2, this.target.triple); (0, import_node_fs3.mkdirSync)(toolchainPath, { recursive: true }); if ((0, import_node_fs3.existsSync)((0, import_node_path2.join)(toolchainPath, "package.json"))) { debug3(`Toolchain ${toolchainPath} exists, skip extracting`); } else { const tarArchive = download(process.arch, this.target.triple); tarArchive.unpack(toolchainPath); } const upperCaseTarget = targetToEnvVar(this.target.triple); const linkerEnv = `CARGO_TARGET_${upperCaseTarget}_LINKER`; this.envs[linkerEnv] = (0, import_node_path2.join)(toolchainPath, "bin", `${this.target.triple}-gcc`); if (!process.env.TARGET_SYSROOT) { this.envs[`TARGET_SYSROOT`] = (0, import_node_path2.join)(toolchainPath, this.target.triple, "sysroot"); } if (!process.env.TARGET_AR) { this.envs[`TARGET_AR`] = (0, import_node_path2.join)(toolchainPath, "bin", `${this.target.triple}-ar`); } if (!process.env.TARGET_RANLIB) { this.envs[`TARGET_RANLIB`] = (0, import_node_path2.join)(toolchainPath, "bin", `${this.target.triple}-ranlib`); } if (!process.env.TARGET_READELF) { this.envs[`TARGET_READELF`] = (0, import_node_path2.join)(toolchainPath, "bin", `${this.target.triple}-readelf`); } if (!process.env.TARGET_C_INCLUDE_PATH) { this.envs[`TARGET_C_INCLUDE_PATH`] = (0, import_node_path2.join)(toolchainPath, this.target.triple, "sysroot", "usr", "include/"); } if (!process.env.CC && !process.env.TARGET_CC) { this.envs[`CC`] = (0, import_node_path2.join)(toolchainPath, "bin", `${this.target.triple}-gcc`); this.envs[`TARGET_CC`] = (0, import_node_path2.join)(toolchainPath, "bin", `${this.target.triple}-gcc`); } if (!process.env.CXX && !process.env.TARGET_CXX) { this.envs[`CXX`] = (0, import_node_path2.join)(toolchainPath, "bin", `${this.target.triple}-g++`); this.envs[`TARGET_CXX`] = (0, import_node_path2.join)(toolchainPath, "bin", `${this.target.triple}-g++`); } if (process.env.CC === "clang" && (process.env.TARGET_CC === "clang" || !process.env.TARGET_CC) || process.env.TARGET_CC === "clang") { this.envs.CFLAGS = `--sysroot=${this.envs.TARGET_SYSROOT}`; } if (process.env.CXX === "clang++" && (process.env.TARGET_CXX === "clang++" || !process.env.TARGET_CXX) || process.env.TARGET_CXX === "clang++") { this.envs.CXXFLAGS = `--sysroot=${this.envs.TARGET_SYSROOT}`; } } catch (e) { debug3.warn("Pick cross toolchain failed", e); } return this; } exec() { debug3(`Start building crate: ${this.crate.name}`); debug3(" %i", `cargo ${this.args.join(" ")}`); const controller = new AbortController(); const watch = this.options.watch; const buildTask = new Promise((resolve7, reject) => { if (this.options.useCross && this.options.crossCompile) { throw new Error("`--use-cross` and `--cross-compile` can not be used together"); } const command = process.env.CARGO ?? (this.options.useCross ? "cross" : "cargo"); const buildProcess = (0, import_node_child_process4.spawn)(command, this.args, { env: { ...process.env, ...this.envs }, stdio: watch ? ["inherit", "inherit", "pipe"] : "inherit", cwd: this.cwd, signal: controller.signal }); buildProcess.once("exit", (code) => { if (code === 0) { debug3("%i", `Build crate ${this.crate.name} successfully!`); resolve7(); } else { reject(new Error(`Build failed with exit code ${code}`)); } }); buildProcess.once("error", (e) => { reject(new Error(`Build failed with error: ${e.message}`, { cause: e })); }); buildProcess.stderr?.on("data", (data) => { const output = data.toString(); console.error(output); if (/Finished\s(dev|release)/.test(output)) { this.postBuild().catch(() => { }); } }); }); return { task: buildTask.then(() => this.postBuild()), abort: () => controller.abort() }; } pickBinary() { let set = false; if (this.options.watch) { if (process.env.CI) { debug3.warn("Watch mode is not supported in CI environment"); } else { debug3("Use %i", "cargo-watch"); tryInstallCargoBinary("cargo-watch", "watch"); this.args.push("watch", "--why", "-i", "*.{js,ts,node}", "-w", this.crateDir, "--", "cargo", "build"); set = true; } } if (this.options.crossCompile) { if (this.target.platform === "win32") { if (process.platform === "win32") { debug3.warn("You are trying to cross compile to win32 platform on win32 platform which is unnecessary."); } else { debug3("Use %i", "cargo-xwin"); tryInstallCargoBinary("cargo-xwin", "xwin"); this.args.push("xwin", "build"); if (this.target.arch === "ia32") { this.envs.XWIN_ARCH = "x86"; } set = true; } } else { if (this.target.platform === "linux" && process.platform === "linux" && this.target.arch === process.arch && function(abi) { const glibcVersionRuntime = ( // @ts-expect-error process.report?.getReport()?.header?.glibcVersionRuntime ); const libc = glibcVersionRuntime ? "gnu" : "musl"; return abi === libc; }(this.target.abi)) { debug3.warn("You are trying to cross compile to linux target on linux platform which is unnecessary."); } else if (this.target.platform === "darwin" && process.platform === "darwin") { debug3.warn("You are trying to cross compile to darwin target on darwin platform which is unnecessary."); } else { debug3("Use %i", "cargo-zigbuild"); tryInstallCargoBinary("cargo-zigbuild", "zigbuild"); this.args.push("zigbuild"); set = true; } } } if (!set) { this.args.push("build"); } return this; } setPackage() { const args = []; if (this.options.package) { args.push("--package", this.options.package); } if (this.binName) { args.push("--bin", this.binName); } if (args.length) { debug3("Set package flags: "); debug3(" %O", args); this.args.push(...args); } return this; } setTarget() { debug3("Set compiling target to: "); debug3(" %i", this.target.triple); this.args.push("--target", this.target.triple); return this; } setEnvs() { this.envs.TYPE_DEF_TMP_PATH = this.getIntermediateTypeFile(); this.envs.WASI_REGISTER_TMP_PATH = this.getIntermediateWasiRegisterFile(); this.envs.CARGO_CFG_NAPI_RS_CLI_VERSION = CLI_VERSION; let rustflags = process.env.RUSTFLAGS ?? process.env.CARGO_BUILD_RUSTFLAGS ?? ""; if (this.target.abi?.includes("musl") && !rustflags.includes("target-feature=-crt-static")) { rustflags += " -C target-feature=-crt-static"; } if (this.options.strip && !rustflags.includes("link-arg=-s")) { rustflags += " -C link-arg=-s"; } if (rustflags.length) { this.envs.RUSTFLAGS = rustflags; } const linker = this.options.crossCompile ? void 0 : getTargetLinker(this.target.triple); const linkerEnv = `CARGO_TARGET_${targetToEnvVar(this.target.triple)}_LINKER`; if (linker && !process.env[linkerEnv]) { this.envs[linkerEnv] = linker; } if (this.target.platform === "android") { const { ANDROID_NDK_LATEST_HOME } = process.env; if (!ANDROID_NDK_LATEST_HOME) { debug3.warn(`${colors3.red("ANDROID_NDK_LATEST_HOME")} environment variable is missing`); } const targetArch = this.target.arch === "arm" ? "armv7a" : "aarch64"; const targetPlatform = this.target.arch === "arm" ? "androideabi24" : "android24"; const hostPlatform = process.platform === "darwin" ? "darwin" : process.platform === "win32" ? "windows" : "linux"; Object.assign(this.envs, { CARGO_TARGET_AARCH64_LINUX_ANDROID_LINKER: `${ANDROID_NDK_LATEST_HOME}/toolchains/llvm/prebuilt/${hostPlatform}-x86_64/bin/${targetArch}-linux-android24-clang`, CARGO_TARGET_ARMV7_LINUX_ANDROIDEABI_LINKER: `${ANDROID_NDK_LATEST_HOME}/toolchains/llvm/prebuilt/${hostPlatform}-x86_64/bin/${targetArch}-linux-androideabi24-clang`, TARGET_CC: `${ANDROID_NDK_LATEST_HOME}/toolchains/llvm/prebuilt/${hostPlatform}-x86_64/bin/${targetArch}-linux-${targetPlatform}-clang`, TARGET_CXX: `${ANDROID_NDK_LATEST_HOME}/toolchains/llvm/prebuilt/${hostPlatform}-x86_64/bin/${targetArch}-linux-${targetPlatform}-clang++`, TARGET_AR: `${ANDROID_NDK_LATEST_HOME}/toolchains/llvm/prebuilt/${hostPlatform}-x86_64/bin/llvm-ar`, TARGET_RANLIB: `${ANDROID_NDK_LATEST_HOME}/toolchains/llvm/prebuilt/${hostPlatform}-x86_64/bin/llvm-ranlib`, ANDROID_NDK: ANDROID_NDK_LATEST_HOME, PATH: `${ANDROID_NDK_LATEST_HOME}/toolchains/llvm/prebuilt/${hostPlatform}-x86_64/bin:${process.env.PATH}` }); } if (this.target.platform === "wasi") { const emnapi = (0, import_node_path2.join)(require3.resolve("emnapi"), "..", "lib", "wasm32-wasi-threads"); this.envs.EMNAPI_LINK_DIR = emnapi; this.envs.SETJMP_LINK_DIR = import_wasm_sjlj.lib; const { WASI_SDK_PATH } = process.env; if (WASI_SDK_PATH && (0, import_node_fs3.existsSync)(WASI_SDK_PATH)) { this.envs.CARGO_TARGET_WASM32_WASI_PREVIEW1_THREADS_LINKER = (0, import_node_path2.join)(WASI_SDK_PATH, "bin", "wasm-ld"); this.envs.CARGO_TARGET_WASM32_WASIP1_LINKER = (0, import_node_path2.join)(WASI_SDK_PATH, "bin", "wasm-ld"); this.envs.CARGO_TARGET_WASM32_WASIP1_THREADS_LINKER = (0, import_node_path2.join)(WASI_SDK_PATH, "bin", "wasm-ld"); this.envs.CARGO_TARGET_WASM32_WASIP2_LINKER = (0, import_node_path2.join)(WASI_SDK_PATH, "bin", "wasm-ld"); this.setEnvIfNotExists("CC", (0, import_node_path2.join)(WASI_SDK_PATH, "bin", "clang")); this.setEnvIfNotExists("CXX", (0, import_node_path2.join)(WASI_SDK_PATH, "bin", "clang++")); this.setEnvIfNotExists("AR", (0, import_node_path2.join)(WASI_SDK_PATH, "bin", "ar")); this.setEnvIfNotExists("RANLIB", (0, import_node_path2.join)(WASI_SDK_PATH, "bin", "ranlib")); this.setEnvIfNotExists("CFLAGS", `--target=wasm32-wasi-threads --sysroot=${WASI_SDK_PATH}/share/wasi-sysroot -pthread -mllvm -wasm-enable-sjlj -I${import_wasm_sjlj.include}`); this.setEnvIfNotExists("CXXFLAGS", `--target=wasm32-wasi-threads --sysroot=${WASI_SDK_PATH}/share/wasi-sysroot -pthread -mllvm -wasm-enable-sjlj -I${import_wasm_sjlj.include}`); this.setEnvIfNotExists(`LDFLAGS`, `-fuse-ld=${WASI_SDK_PATH}/bin/wasm-ld --target=wasm32-wasi-threads`); } } debug3("Set envs: "); Object.entries(this.envs).forEach(([k, v]) => { debug3(" %i", `${k}=${v}`); }); return this; } setFeatures() { const args = []; if (this.options.allFeatures && this.options.allFeatures) { throw new Error("Cannot specify --all-features and --no-default-features together"); } if (this.options.allFeatures) { args.push("--all-features"); } else if (this.options.noDefaultFeatures) { args.push("--no-default-features"); } if (this.options.features) { args.push("--features", ...this.options.features); } debug3("Set features flags: "); debug3(" %O", args); this.args.push(...args); return this; } setBypassArgs() { if (this.options.release) { this.args.push("--release"); } if (this.options.verbose) { this.args.push("--verbose"); } if (this.options.targetDir) { this.args.push("--target-dir", this.options.targetDir); } if (this.options.profile) { this.args.push("--profile", this.options.profile); } if (this.options.manifestPath) { this.args.push("--manifest-path", this.options.manifestPath); } if (this.options.cargoOptions?.length) { this.args.push(...this.options.cargoOptions); } return this; } getIntermediateTypeFile() { return (0, import_node_path2.join)((0, import_node_os.tmpdir)(), `${this.crate.name}-${(0, import_node_crypto.createHash)("sha256").update(this.crate.manifest_path).update(CLI_VERSION).digest("hex").substring(0, 8)}.napi_type_def.tmp`); } getIntermediateWasiRegisterFile() { return (0, import_node_path2.join)((0, import_node_os.tmpdir)(), `${this.crate.name}-${(0, import_node_crypto.createHash)("sha256").update(this.crate.manifest_path).update(CLI_VERSION).digest("hex").substring(0, 8)}.napi_wasi_register.tmp`); } async postBuild() { try { debug3(`Try to create output directory:`); debug3(" %i", this.outputDir); await mkdirAsync(this.outputDir, { recursive: true }); debug3(`Output directory created`); } catch (e) { throw new Error(`Failed to create output directory ${this.outputDir}`, { cause: e }); } const wasmBinaryName = await this.copyArtifact(); if (this.cdyLibName) { const idents = await this.generateTypeDef(); const intermediateWasiRegisterFile = this.envs.WASI_REGISTER_TMP_PATH; const wasiRegisterFunctions = this.config.targets.some((t) => t.platform === "wasi") ? await async function readIntermediateWasiRegisterFile() { const fileContent = await readFileAsync(intermediateWasiRegisterFile, "utf8").catch((err) => { console.warn(`Read ${colors3.yellowBright(intermediateWasiRegisterFile)} failed, reason: ${err.message}`); return ``; }); return fileContent.split("\n").map((l) => l.trim()).filter((l) => l.length).map((line) => { const [_, fn] = line.split(":"); return fn.trim(); }); }() : []; const jsOutput = await this.writeJsBinding(idents); const wasmBindingsOutput = await this.writeWasiBinding(wasiRegisterFunctions, wasmBinaryName ?? "index.wasm", idents); if (jsOutput) { this.outputs.push(jsOutput); } if (wasmBindingsOutput) { this.outputs.push(...wasmBindingsOutput); } } return this.outputs; } async copyArtifact() { const [srcName, destName, wasmBinaryName] = this.getArtifactNames(); if (!srcName || !destName) { return; } const profile = this.options.profile ?? (this.options.release ? "release" : "debug"); const src = (0, import_node_path2.join)(this.targetDir, this.target.triple, profile, srcName); debug3(`Copy artifact from: [${src}]`); const dest = (0, import_node_path2.join)(this.outputDir, destName); const isWasm = dest.endsWith(".wasm"); try { if (await fileExists(dest)) { debug3("Old artifact found, remove it first"); await unlinkAsync(dest); } debug3("Copy artifact to:"); debug3(" %i", dest); if (isWasm) { const { ModuleConfig } = await import("@napi-rs/wasm-tools"); debug3("Generate debug wasm module"); try { const debugWasmModule = new ModuleConfig().generateDwarf(true).generateNameSection(true).generateProducersSection(true).preserveCodeTransform(true).strictValidate(false).parse(await readFileAsync(src)); const debugWasmBinary = debugWasmModule.emitWasm(true); await writeFileAsync(dest.replace(".wasm", ".debug.wasm"), debugWasmBinary); debug3("Generate release wasm module"); const releaseWasmModule = new ModuleConfig().generateDwarf(false).generateNameSection(false).generateProducersSection(false).preserveCodeTransform(false).strictValidate(false).onlyStableFeatures(false).parse(debugWasmBinary); const releaseWasmBinary = releaseWasmModule.emitWasm(false); await writeFileAsync(dest, releaseWasmBinary); } catch (e) { debug3.warn(`Failed to generate debug wasm module: ${e.message ?? e}`); await copyFileAsync(src, dest); } } else { await copyFileAsync(src, dest); } this.outputs.push({ kind: dest.endsWith(".node") ? "node" : isWasm ? "wasm" : "exe", path: dest }); return wasmBinaryName ? (0, import_node_path2.join)(this.outputDir, wasmBinaryName) : null; } catch (e) { throw new Error("Failed to copy artifact", { cause: e }); } } getArtifactNames() { if (this.cdyLibName) { const cdyLib = this.cdyLibName.replace(/-/g, "_"); const wasiTarget = this.config.targets.find((t) => t.platform === "wasi"); const srcName = this.target.platform === "darwin" ? `lib${cdyLib}.dylib` : this.target.platform === "win32" ? `${cdyLib}.dll` : this.target.platform === "wasi" || this.target.platform === "wasm" ? `${cdyLib}.wasm` : `lib${cdyLib}.so`; let destName = this.config.binaryName; if (this.options.platform) { destName += `.${this.target.platformArchABI}`; } if (srcName.endsWith(".wasm")) { destName += ".wasm"; } else { destName += ".node"; } return [ srcName, destName, wasiTarget ? `${this.config.binaryName}.${wasiTarget.platformArchABI}.wasm` : null ]; } else if (this.binName) { const srcName = this.target.platform === "win32" ? `${this.binName}.exe` : this.binName; return [srcName, srcName]; } return []; } async generateTypeDef() { if (!await fileExists(this.envs.TYPE_DEF_TMP_PATH)) { return []; } const dest = (0, import_node_path2.join)(this.outputDir, this.options.dts ?? "index.d.ts"); const { dts, exports: exports2 } = await processTypeDef(this.envs.TYPE_DEF_TMP_PATH, this.options.constEnum ?? this.config.constEnum ?? true, !this.options.noDtsHeader ? this.options.dtsHeader ?? (this.config.dtsHeaderFile ? await readFileAsync((0, import_node_path2.join)(this.cwd, this.config.dtsHeaderFile), "utf-8").catch(() => { debug3.warn(`Failed to read dts header file ${this.config.dtsHeaderFile}`); return null; }) : null) ?? this.config.dtsHeader ?? DEFAULT_TYPE_DEF_HEADER : ""); try { debug3("Writing type def to:"); debug3(" %i", dest); await writeFileAsync(dest, dts, "utf-8"); this.outputs.push({ kind: "dts", path: dest }); } catch (e) { debug3.error("Failed to write type def file"); debug3.error(e); } return exports2; } async writeJsBinding(idents) { if (!this.options.platform || // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing this.options.noJsBinding || idents.length === 0) { return; } const name = this.options.jsBinding ?? "index.js"; const createBinding = this.options.esm ? createEsmBinding : createCjsBinding; const binding = createBinding(this.config.binaryName, this.config.packageName, idents); try { const dest = (0, import_node_path2.join)(this.outputDir, name); debug3("Writing js binding to:"); debug3(" %i", dest); await writeFileAsync(dest, binding, "utf-8"); return { kind: "js", path: dest }; } catch (e) { throw new Error("Failed to write js binding file", { cause: e }); } } async writeWasiBinding(wasiRegisterFunctions, distFileName, idents) { if (distFileName && wasiRegisterFunctions.length) { const { name, dir } = (0, import_node_path2.parse)(distFileName); const bindingPath = (0, import_node_path2.join)(dir, `${this.config.binaryName}.wasi.cjs`); const browserBindingPath = (0, import_node_path2.join)(dir, `${this.config.binaryName}.wasi-browser.js`); const workerPath = (0, import_node_path2.join)(dir, "wasi-worker.mjs"); const browserWorkerPath = (0, import_node_path2.join)(dir, "wasi-worker-browser.mjs"); const browserEntryPath = (0, import_node_path2.join)(dir, "browser.js"); const exportsCode = idents.map((ident) => `module.exports.${ident} = __napiModule.exports.${ident}`).join("\n"); await writeFileAsync(bindingPath, createWasiBinding(name, this.config.packageName, wasiRegisterFunctions, this.config.wasm?.initialMemory, this.config.wasm?.maximumMemory) + exportsCode + "\n", "utf8"); await writeFileAsync(browserBindingPath, createWasiBrowserBinding(name, wasiRegisterFunctions, this.config.wasm?.initialMemory, this.config.wasm?.maximumMemory, this.config.wasm?.browser?.fs) + idents.map((ident) => `export const ${ident} = __napiModule.exports.${ident}`).join("\n") + "\n", "utf8"); await writeFileAsync(workerPath, WASI_WORKER_TEMPLATE, "utf8"); await writeFileAsync(browserWorkerPath, createWasiBrowserWorkerBinding(this.config.wasm?.browser?.fs ?? false), "utf8"); await writeFileAsync(browserEntryPath, `export * from '${this.config.packageName}-wasm32-wasi' `); return [ { kind: "js", path: bindingPath }, { kind: "js", path: browserBindingPath }, { kind: "js", path: workerPath }, { kind: "js", path: browserWorkerPath }, { kind: "js", path: browserEntryPath } ]; } return []; } setEnvIfNotExists(env, value) { if (!process.env[env]) { this.envs[env] = value; } } }; // dist/api/create-npm-dirs.js var import_node_path3 = require("node:path"); var import_semver = require("semver"); // dist/def/create-npm-dirs.js var import_clipanion2 = require("clipanion"); var BaseCreateNpmDirsCommand = class extends import_clipanion2.Command { static paths = [["create-npm-dirs"]]; static usage = import_clipanion2.Command.Usage({ description: "Create npm package dirs for different platforms" }); cwd = import_clipanion2.Option.String("--cwd", process.cwd(), { description: "The working directory of where napi command will be executed in, all other paths options are relative to this path" }); configPath = import_clipanion2.Option.String("--config-path,-c", { description: "Path to `napi` config json file" }); packageJsonPath = import_clipanion2.Option.String("--package-json-path", "package.json", { description: "Path to `package.json`" }); npmDir = import_clipanion2.Option.String("--npm-dir", "npm", { description: "Path to the folder where the npm packages put" }); dryRun = import_clipanion2.Option.Boolean("--dry-run", false, { description: "Dry run without touching file system" }); getOptions() { return { cwd: this.cwd, configPath: this.configPath, packageJsonPath: this.packageJsonPath, npmDir: this.npmDir, dryRun: this.dryRun }; } }; function applyDefaultCreateNpmDirsOptions(options) { return { cwd: process.cwd(), packageJsonPath: "package.json", npmDir: "npm", dryRun: false, ...options }; } // dist/api/create-npm-dirs.js var debug4 = debugFactory("create-npm-dirs"); async function createNpmDirs(userOptions) { const options = applyDefaultCreateNpmDirsOptions(userOptions); async function mkdirAsync2(dir) { debug4("Try to create dir: %i", dir); if (options.dryRun) { return; } await mkdirAsync(dir, { recursive: true }); } async function writeFileAsync2(file, content) { debug4("Writing file %i", file); if (options.dryRun) { debug4(content); return; } await writeFileAsync(file, content); } const packageJsonPath = (0, import_node_path3.resolve)(options.cwd, options.packageJsonPath); const npmPath = (0, import_node_path3.resolve)(options.cwd, options.npmDir); debug4(`Read content from [${options.configPath ?? packageJsonPath}]`); const { targets, binaryName, packageName, packageJson } = await readNapiConfig(packageJsonPath, options.configPath ? (0, import_node_path3.resolve)(options.cwd, options.configPath) : void 0); for (const target of targets) { const targetDir = (0, import_node_path3.join)(npmPath, `${target.platformArchABI}`); await mkdirAsync2(targetDir); const binaryFileName = target.arch === "wasm32" ? `${binaryName}.${target.platformArchABI}.wasm` : `${binaryName}.${target.platformArchABI}.node`; const scopedPackageJson = { name: `${packageName}-${target.platformArchABI}`, version: packageJson.version, cpu: target.arch !== "universal" ? [target.arch] : void 0, main: binaryFileName, files: [binaryFileName], ...pick(packageJson, "description", "keywords", "author", "authors", "homepage", "license", "engines", "publishConfig", "repository", "bugs") }; if (target.arch !== "wasm32") { scopedPackageJson.os = [target.platform]; } else { const entry = `${binaryName}.wasi.cjs`; scopedPackageJson.main = entry; scopedPackageJson.browser = `${binaryName}.wasi-browser.js`; scopedPackageJson.files.push( entry, // @ts-expect-error scopedPackageJson.browser, `wasi-worker.mjs`, `wasi-worker-browser.mjs` ); let needRestrictNodeVersion = true; if (scopedPackageJson.engines?.node) { try { const { major } = (0, import_semver.parse)(scopedPackageJson.engines.node) ?? { major: 0 }; if (major >= 14) { needRestrictNodeVersion = false; } } catch { } } if (needRestrictNodeVersion) { scopedPackageJson.engines = { node: ">=14.0.0" }; } const wasmRuntime = await fetch(`https://registry.npmjs.org/@napi-rs/wasm-runtime`).then((res) => res.json()); scopedPackageJson.dependencies = { "@napi-rs/wasm-runtime": `^${wasmRuntime["dist-tags"].latest}` }; } if (target.abi === "gnu") { scopedPackageJson.libc = ["glibc"]; } else if (target.abi === "musl") { scopedPackageJson.libc = ["musl"]; } const targetPackageJson = (0, import_node_path3.join)(targetDir, "package.json"); await writeFileAsync2(targetPackageJson, JSON.stringify(scopedPackageJson, null, 2) + "\n"); const targetReadme = (0, import_node_path3.join)(targetDir, "README.md"); await writeFileAsync2(targetReadme, readme(packageName, target)); debug4.info(`${packageName} -${target.platformArchABI} created`); } } function readme(packageName, target) { return `# \`${packageName}-${target.platformArchABI}\` This is the **${target.triple}** binary for \`${packageName}\` `; } // dist/api/new.js var import_node_child_process5 = require("node:child_process"); var import_node_path4 = __toESM(require("node:path"), 1); // dist/def/new.js var import_clipanion3 = require("clipanion"); var typanion = __toESM(require("typanion"), 1); var BaseNewCommand = class extends import_clipanion3.Command { static paths = [["new"]]; static usage = import_clipanion3.Command.Usage({ description: "Create a new project with pre-configured boilerplate" }); $$path = import_clipanion3.Option.String({ required: false }); $$name = import_clipanion3.Option.String("--name,-n", { description: "The name of the project, default to the name of the directory if not provided" }); minNodeApiVersion = import_clipanion3.Option.String("--min-node-api,-v", "4", { validator: typanion.isNumber(), description: "The minimum Node-API version to support" }); packageManager = import_clipanion3.Option.String("--package-manager", "yarn", { description: "The package manager to use. Only support yarn 4.x for now." }); license = import_clipanion3.Option.String("--license,-l", "MIT", { description: "License for open-sourced project" }); targets = import_clipanion3.Option.Array("--targets,-t", [], { description: "All targets the crate will be compiled for." }); enableDefaultTargets = import_clipanion3.Option.Boolean("--enable-default-targets", true, { description: "Whether enable default targets" }); enableAllTargets = import_clipanion3.Option.Boolean("--enable-all-targets", false, { description: "Whether enable all targets" }); enableTypeDef = import_clipanion3.Option.Boolean("--enable-type-def", true, { description: "Whether enable the `type-def` feature for typescript definitions auto-generation" }); enableGithubActions = import_clipanion3.Option.Boolean("--enable-github-actions", true, { description: "Whether generate preconfigured GitHub Actions workflow" }); testFramework = import_clipanion3.Option.String("--test-framework", "ava", { description: "The JavaScript test framework to use, only support `ava` for now" }); dryRun = import_clipanion3.Option.Boolean("--dry-run", false, { description: "Whether to run the command in dry-run mode" }); getOptions() { return { path: this.$$path, name: this.$$name, minNodeApiVersion: this.minNodeApiVersion, packageManager: this.packageManager, license: this.license, targets: this.targets, enableDefaultTargets: this.enableDefaultTargets, enableAllTargets: this.enableAllTargets, enableTypeDef: this.enableTypeDef, enableGithubActions: this.enableGithubActions, testFramework: this.testFramework, dryRun: this.dryRun }; } }; function applyDefaultNewOptions(options) { return { minNodeApiVersion: 4, packageManager: "yarn", license: "MIT", targets: [], enableDefaultTargets: true, enableAllTargets: false, enableTypeDef: true, enableGithubActions: true, testFramework: "ava", dryRun: false, ...options }; } // dist/api/new.js var debug5 = debugFactory("new"); function processOptions(options) { debug5("Processing options..."); if (!options.path) { throw new Error("Please provide the path as the argument"); } options.path = import_node_path4.default.resolve(process.cwd(), options.path); debug5(`Resolved target path to: ${options.path}`); if (!options.name) { options.name = import_node_path4.default.parse(options.path).base; debug5(`No project name provided, fix it to dir name: ${options.name}`); } if (!options.targets?.length) { if (options.enableAllTargets) { options.targets = AVAILABLE_TARGETS.concat(); debug5("Enable all targets"); } else if (options.enableDefaultTargets) { options.targets = DEFAULT_TARGETS.concat(); debug5("Enable default targets"); } else { throw new Error("At least one target must be enabled"); } } if (options.targets.some((target) => target === "wasm32-wasi-preview1-threads")) { const out = (0, import_node_child_process5.execSync)(`rustup target list`, { encoding: "utf8" }); if (out.includes("wasm32-wasip1-threads")) { options.targets.map((target) => target === "wasm32-wasi-preview1-threads" ? "wasm32-wasip1-threads" : target); } } return applyDefaultNewOptions(options); } async function newProject(userOptions) { debug5("Will create napi-rs project with given options:"); debug5(userOptions); const options = processOptions(userOptions); debug5("Targets to be enabled:"); debug5(options.targets); const outputs = await generateFiles(options); await ensurePath(options.path, options.dryRun); await dumpOutputs(outputs, options.dryRun); debug5(`Project created at: ${options.path}`); } async function ensurePath(path2, dryRun = false) { const stat2 = await statAsync(path2, {}).catch(() => void 0); if (stat2) { if (stat2.isFile()) { throw new Error(`Path ${path2} for creating new napi-rs project already exists and it's not a directory.`); } else if (stat2.isDirectory()) { const files = await readdirAsync(path2); if (files.length) { throw new Error(`Path ${path2} for creating new napi-rs project already exists and it's not empty.`); } } } if (!dryRun) { try { debug5(`Try to create target directory: ${path2}`); if (!dryRun) { await mkdirAsync(path2, { recursive: true }); } } catch (e) { throw new Error(`Failed to create target directory: ${path2}`, { cause: e }); } } } async function generateFiles(options) { const packageJson = await generatePackageJson(options); return [ generateCargoToml, generateLibRs, generateBuildRs, generateGithubWorkflow, generateIgnoreFiles ].flatMap((generator) => { const output = generator(options); if (!output) { return []; } if (Array.isArray(output)) { return output.map((o) => ({ ...o, target: import_node_path4.default.join(options.path, o.target) })); } else { return [{ ...output, target: import_node_path4.default.join(options.path, output.target) }]; } }).concat([ { ...packageJson, target: import_node_path4.default.join(options.path, packageJson.target) } ]); } function generateCargoToml(options) { return { target: "./Cargo.toml", content: createCargoToml({ name: options.name, license: options.license, features: [`napi${options.minNodeApiVersion}`], deriveFeatures: options.enableTypeDef ? ["type-def"] : [] }) }; } function generateLibRs(_options) { return { target: "./src/lib.rs", content: createLibRs() }; } function generateBuildRs(_options) { return { target: "./build.rs", content: createBuildRs() }; } async function generatePackageJson(options) { return { target: "./package.json", content: await createPackageJson({ name: options.name, binaryName: getBinaryName(options.name), targets: options.targets, license: options.license, engineRequirement: napiEngineRequirement(options.minNodeApiVersion), cliVersion: CLI_VERSION, testFramework: options.testFramework }) }; } function generateGithubWorkflow(options) { if (!options.enableGithubActions) { return null; } return { target: "./.github/workflows/ci.yml", content: createGithubActionsCIYml(options.targets, options.packageManager, options.targets.find((t) => t.includes("wasm32-wasi")) ?? "wasm32-wasi-preview1-threads") }; } function generateIgnoreFiles(_options) { return [ { target: "./.gitignore", content: gitIgnore }, { target: "./.npmignore", content: npmIgnore } ]; } async function dumpOutputs(outputs, dryRun) { for (const output of outputs) { if (!output) { continue; } debug5(`Writing project file: ${output.target}`); if (dryRun) { debug5(output.content); continue; } try { await mkdirAsync(import_node_path4.default.dirname(output.target), { recursive: true }); await writeFileAsync(output.target, output.content, "utf-8"); } catch (e) { throw new Error(`Failed to write file: ${output.target}`, { cause: e }); } } } function getBinaryName(name) { return name.split("/").pop(); } // dist/api/pre-publish.js var import_node_child_process6 = require("node:child_process"); var import_node_fs4 = require("node:fs"); var import_node_path6 = require("node:path"); // ../node_modules/@octokit/rest/node_modules/universal-user-agent/index.js function getUserAgent() { if (typeof navigator === "object" && "userAgent" in navigator) { return navigator.userAgent; } if (typeof process === "object" && process.version !== void 0) { return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; } return ""; } // ../node_modules/@octokit/rest/node_modules/before-after-hook/lib/register.js function register(state, name, method, options) { if (typeof method !== "function") { throw new Error("method for before hook must be a function"); } if (!options) { options = {}; } if (Array.isArray(name)) { return name.reverse().reduce((callback, name2) => { return register.bind(null, state, name2, callback, options); }, method)(); } return Promise.resolve().then(() => { if (!state.registry[name]) { return method(options); } return state.registry[name].reduce((method2, registered) => { return registered.hook.bind(null, method2, options); }, method)(); }); } // ../node_modules/@octokit/rest/node_modules/before-after-hook/lib/add.js function addHook(state, kind, name, hook2) { const orig = hook2; if (!state.registry[name]) { state.registry[name] = []; } if (kind === "before") { hook2 = (method, options) => { return Promise.resolve().then(orig.bind(null, options)).then(method.bind(null, options)); }; } if (kind === "after") { hook2 = (method, options) => { let result; return Promise.resolve().then(method.bind(null, options)).then((result_) => { result = result_; return orig(result, options); }).then(() => { return result; }); }; } if (kind === "error") { hook2 = (method, options) => { return Promise.resolve().then(method.bind(null, options)).catch((error) => { return orig(error, options); }); }; } state.registry[name].push({ hook: hook2, orig }); } // ../node_modules/@octokit/rest/node_modules/before-after-hook/lib/remove.js function removeHook(state, name, method) { if (!state.registry[name]) { return; } const index = state.registry[name].map((registered) => { return registered.orig; }).indexOf(method); if (index === -1) { return; } state.registry[name].splice(index, 1); } // ../node_modules/@octokit/rest/node_modules/before-after-hook/index.js var bind = Function.bind; var bindable = bind.bind(bind); function bindApi(hook2, state, name) { const removeHookRef = bindable(removeHook, null).apply( null, name ? [state, name] : [state] ); hook2.api = { remove: removeHookRef }; hook2.remove = removeHookRef; ["before", "error", "after", "wrap"].forEach((kind) => { const args = name ? [state, kind, name] : [state, kind]; hook2[kind] = hook2.api[kind] = bindable(addHook, null).apply(null, args); }); } function Singular() { const singularHookName = Symbol("Singular"); const singularHookState = { registry: {} }; const singularHook = register.bind(null, singularHookState, singularHookName); bindApi(singularHook, singularHookState, singularHookName); return singularHook; } function Collection() { const state = { registry: {} }; const hook2 = register.bind(null, state); bindApi(hook2, state); return hook2; } var before_after_hook_default = { Singular, Collection }; // ../node_modules/@octokit/rest/node_modules/@octokit/endpoint/dist-bundle/index.js var VERSION = "0.0.0-development"; var userAgent = `octokit-endpoint.js/${VERSION} ${getUserAgent()}`; var DEFAULTS = { method: "GET", baseUrl: "https://api.github.com", headers: { accept: "application/vnd.github.v3+json", "user-agent": userAgent }, mediaType: { format: "" } }; function lowercaseKeys(object) { if (!object) { return {}; } return Object.keys(object).reduce((newObj, key) => { newObj[key.toLowerCase()] = object[key]; return newObj; }, {}); } function isPlainObject2(value) { if (typeof value !== "object" || value === null) return false; if (Object.prototype.toString.call(value) !== "[object Object]") return false; const proto = Object.getPrototypeOf(value); if (proto === null) return true; const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor; return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value); } function mergeDeep(defaults, options) { const result = Object.assign({}, defaults); Object.keys(options).forEach((key) => { if (isPlainObject2(options[key])) { if (!(key in defaults)) Object.assign(result, { [key]: options[key] }); else result[key] = mergeDeep(defaults[key], options[key]); } else { Object.assign(result, { [key]: options[key] }); } }); return result; } function removeUndefinedProperties(obj) { for (const key in obj) { if (obj[key] === void 0) { delete obj[key]; } } return obj; } function merge2(defaults, route, options) { if (typeof route === "string") { let [method, url] = route.split(" "); options = Object.assign(url ? { method, url } : { url: method }, options); } else { options = Object.assign({}, route); } options.headers = lowercaseKeys(options.headers); removeUndefinedProperties(options); removeUndefinedProperties(options.headers); const mergedOptions = mergeDeep(defaults || {}, options); if (options.url === "/graphql") { if (defaults && defaults.mediaType.previews?.length) { mergedOptions.mediaType.previews = defaults.mediaType.previews.filter( (preview) => !mergedOptions.mediaType.previews.includes(preview) ).concat(mergedOptions.mediaType.previews); } mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, "")); } return mergedOptions; } function addQueryParameters(url, parameters) { const separator = /\?/.test(url) ? "&" : "?"; const names = Object.keys(parameters); if (names.length === 0) { return url; } return url + separator + names.map((name) => { if (name === "q") { return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); } return `${name}=${encodeURIComponent(parameters[name])}`; }).join("&"); } var urlVariableRegex = /\{[^}]+\}/g; function removeNonChars(variableName) { return variableName.replace(/^\W+|\W+$/g, "").split(/,/); } function extractUrlVariableNames(url) { const matches = url.match(urlVariableRegex); if (!matches) { return []; } return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []); } function omit2(object, keysToOmit) { const result = { __proto__: null }; for (const key of Object.keys(object)) { if (keysToOmit.indexOf(key) === -1) { result[key] = object[key]; } } return result; } function encodeReserved(str) { return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) { if (!/%[0-9A-Fa-f]/.test(part)) { part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]"); } return part; }).join(""); } function encodeUnreserved(str) { return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { return "%" + c.charCodeAt(0).toString(16).toUpperCase(); }); } function encodeValue(operator, value, key) { value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); if (key) { return encodeUnreserved(key) + "=" + value; } else { return value; } } function isDefined(value) { return value !== void 0 && value !== null; } function isKeyOperator(operator) { return operator === ";" || operator === "&" || operator === "?"; } function getValues(context, operator, key, modifier) { var value = context[key], result = []; if (isDefined(value) && value !== "") { if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { value = value.toString(); if (modifier && modifier !== "*") { value = value.substring(0, parseInt(modifier, 10)); } result.push( encodeValue(operator, value, isKeyOperator(operator) ? key : "") ); } else { if (modifier === "*") { if (Array.isArray(value)) { value.filter(isDefined).forEach(function(value2) { result.push( encodeValue(operator, value2, isKeyOperator(operator) ? key : "") ); }); } else { Object.keys(value).forEach(function(k) { if (isDefined(value[k])) { result.push(encodeValue(operator, value[k], k)); } }); } } else { const tmp = []; if (Array.isArray(value)) { value.filter(isDefined).forEach(function(value2) { tmp.push(encodeValue(operator, value2)); }); } else { Object.keys(value).forEach(function(k) { if (isDefined(value[k])) { tmp.push(encodeUnreserved(k)); tmp.push(encodeValue(operator, value[k].toString())); } }); } if (isKeyOperator(operator)) { result.push(encodeUnreserved(key) + "=" + tmp.join(",")); } else if (tmp.length !== 0) { result.push(tmp.join(",")); } } } } else { if (operator === ";") { if (isDefined(value)) { result.push(encodeUnreserved(key)); } } else if (value === "" && (operator === "&" || operator === "?")) { result.push(encodeUnreserved(key) + "="); } else if (value === "") { result.push(""); } } return result; } function parseUrl(template) { return { expand: expand.bind(null, template) }; } function expand(template, context) { var operators = ["+", "#", ".", "/", ";", "?", "&"]; template = template.replace( /\{([^\{\}]+)\}|([^\{\}]+)/g, function(_, expression, literal) { if (expression) { let operator = ""; const values = []; if (operators.indexOf(expression.charAt(0)) !== -1) { operator = expression.charAt(0); expression = expression.substr(1); } expression.split(/,/g).forEach(function(variable) { var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); }); if (operator && operator !== "+") { var separator = ","; if (operator === "?") { separator = "&"; } else if (operator !== "#") { separator = operator; } return (values.length !== 0 ? operator : "") + values.join(separator); } else { return values.join(","); } } else { return encodeReserved(literal); } } ); if (template === "/") { return template; } else { return template.replace(/\/$/, ""); } } function parse4(options) { let method = options.method.toUpperCase(); let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); let headers = Object.assign({}, options.headers); let body; let parameters = omit2(options, [ "method", "baseUrl", "url", "headers", "request", "mediaType" ]); const urlVariableNames = extractUrlVariableNames(url); url = parseUrl(url).expand(parameters); if (!/^http/.test(url)) { url = options.baseUrl + url; } const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl"); const remainingParameters = omit2(parameters, omittedParameters); const isBinaryRequest = /application\/octet-stream/i.test(headers.accept); if (!isBinaryRequest) { if (options.mediaType.format) { headers.accept = headers.accept.split(/,/).map( (format) => format.replace( /application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, `application/vnd$1$2.${options.mediaType.format}` ) ).join(","); } if (url.endsWith("/graphql")) { if (options.mediaType.previews?.length) { const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || []; headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map((preview) => { const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; return `application/vnd.github.${preview}-preview${format}`; }).join(","); } } } if (["GET", "HEAD"].includes(method)) { url = addQueryParameters(url, remainingParameters); } else { if ("data" in remainingParameters) { body = remainingParameters.data; } else { if (Object.keys(remainingParameters).length) { body = remainingParameters; } } } if (!headers["content-type"] && typeof body !== "undefined") { headers["content-type"] = "application/json; charset=utf-8"; } if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { body = ""; } return Object.assign( { method, url, headers }, typeof body !== "undefined" ? { body } : null, options.request ? { request: options.request } : null ); } function endpointWithDefaults(defaults, route, options) { return parse4(merge2(defaults, route, options)); } function withDefaults(oldDefaults, newDefaults) { const DEFAULTS2 = merge2(oldDefaults, newDefaults); const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2); return Object.assign(endpoint2, { DEFAULTS: DEFAULTS2, defaults: withDefaults.bind(null, DEFAULTS2), merge: merge2.bind(null, DEFAULTS2), parse: parse4 }); } var endpoint = withDefaults(null, DEFAULTS); // ../node_modules/@octokit/rest/node_modules/@octokit/request-error/dist-src/index.js var RequestError = class extends Error { name; /** * http status code */ status; /** * Request options that lead to the error. */ request; /** * Response object if a response was received */ response; constructor(message, statusCode, options) { super(message); this.name = "HttpError"; this.status = Number.parseInt(statusCode); if (Number.isNaN(this.status)) { this.status = 0; } if ("response" in options) { this.response = options.response; } const requestCopy = Object.assign({}, options.request); if (options.request.headers.authorization) { requestCopy.headers = Object.assign({}, options.request.headers, { authorization: options.request.headers.authorization.replace( / .*$/, " [REDACTED]" ) }); } requestCopy.url = requestCopy.url.replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]").replace(/\baccess_token=\w+/g, "access_token=[REDACTED]"); this.request = requestCopy; } }; // ../node_modules/@octokit/rest/node_modules/@octokit/request/dist-bundle/index.js var VERSION2 = "0.0.0-development"; var defaults_default = { headers: { "user-agent": `octokit-request.js/${VERSION2} ${getUserAgent()}` } }; function isPlainObject3(value) { if (typeof value !== "object" || value === null) return false; if (Object.prototype.toString.call(value) !== "[object Object]") return false; const proto = Object.getPrototypeOf(value); if (proto === null) return true; const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor; return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value); } async function fetchWrapper(requestOptions) { const fetch2 = requestOptions.request?.fetch || globalThis.fetch; if (!fetch2) { throw new Error( "fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing" ); } const log = requestOptions.request?.log || console; const parseSuccessResponseBody = requestOptions.request?.parseSuccessResponseBody !== false; const body = isPlainObject3(requestOptions.body) || Array.isArray(requestOptions.body) ? JSON.stringify(requestOptions.body) : requestOptions.body; const requestHeaders = Object.fromEntries( Object.entries(requestOptions.headers).map(([name, value]) => [ name, String(value) ]) ); let fetchResponse; try { fetchResponse = await fetch2(requestOptions.url, { method: requestOptions.method, body, redirect: requestOptions.request?.redirect, headers: requestHeaders, signal: requestOptions.request?.signal, // duplex must be set if request.body is ReadableStream or Async Iterables. // See https://fetch.spec.whatwg.org/#dom-requestinit-duplex. ...requestOptions.body && { duplex: "half" } }); } catch (error) { let message = "Unknown Error"; if (error instanceof Error) { if (error.name === "AbortError") { error.status = 500; throw error; } message = error.message; if (error.name === "TypeError" && "cause" in error) { if (error.cause instanceof Error) { message = error.cause.message; } else if (typeof error.cause === "string") { message = error.cause; } } } const requestError = new RequestError(message, 500, { request: requestOptions }); requestError.cause = error; throw requestError; } const status = fetchResponse.status; const url = fetchResponse.url; const responseHeaders = {}; for (const [key, value] of fetchResponse.headers) { responseHeaders[key] = value; } const octokitResponse = { url, status, headers: responseHeaders, data: "" }; if ("deprecation" in responseHeaders) { const matches = responseHeaders.link && responseHeaders.link.match(/<([^>]+)>; rel="deprecation"/); const deprecationLink = matches && matches.pop(); log.warn( `[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${responseHeaders.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` ); } if (status === 204 || status === 205) { return octokitResponse; } if (requestOptions.method === "HEAD") { if (status < 400) { return octokitResponse; } throw new RequestError(fetchResponse.statusText, status, { response: octokitResponse, request: requestOptions }); } if (status === 304) { octokitResponse.data = await getResponseData(fetchResponse); throw new RequestError("Not modified", status, { response: octokitResponse, request: requestOptions }); } if (status >= 400) { octokitResponse.data = await getResponseData(fetchResponse); throw new RequestError(toErrorMessage(octokitResponse.data), status, { response: octokitResponse, request: requestOptions }); } octokitResponse.data = parseSuccessResponseBody ? await getResponseData(fetchResponse) : fetchResponse.body; return octokitResponse; } async function getResponseData(response) { const contentType = response.headers.get("content-type"); if (/application\/json/.test(contentType)) { return response.json().catch(() => response.text()).catch(() => ""); } if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) { return response.text(); } return response.arrayBuffer(); } function toErrorMessage(data) { if (typeof data === "string") { return data; } if (data instanceof ArrayBuffer) { return "Unknown error"; } if ("message" in data) { const suffix = "documentation_url" in data ? ` - ${data.documentation_url}` : ""; return Array.isArray(data.errors) ? `${data.message}: ${data.errors.map((v) => JSON.stringify(v)).join(", ")}${suffix}` : `${data.message}${suffix}`; } return `Unknown error: ${JSON.stringify(data)}`; } function withDefaults2(oldEndpoint, newDefaults) { const endpoint2 = oldEndpoint.defaults(newDefaults); const newApi = function(route, parameters) { const endpointOptions = endpoint2.merge(route, parameters); if (!endpointOptions.request || !endpointOptions.request.hook) { return fetchWrapper(endpoint2.parse(endpointOptions)); } const request2 = (route2, parameters2) => { return fetchWrapper( endpoint2.parse(endpoint2.merge(route2, parameters2)) ); }; Object.assign(request2, { endpoint: endpoint2, defaults: withDefaults2.bind(null, endpoint2) }); return endpointOptions.request.hook(request2, endpointOptions); }; return Object.assign(newApi, { endpoint: endpoint2, defaults: withDefaults2.bind(null, endpoint2) }); } var request = withDefaults2(endpoint, defaults_default); // ../node_modules/@octokit/rest/node_modules/@octokit/graphql/dist-bundle/index.js var VERSION3 = "0.0.0-development"; function _buildMessageForResponseErrors(data) { return `Request failed due to following response errors: ` + data.errors.map((e) => ` - ${e.message}`).join("\n"); } var GraphqlResponseError = class extends Error { constructor(request2, headers, response) { super(_buildMessageForResponseErrors(response)); this.request = request2; this.headers = headers; this.response = response; this.errors = response.errors; this.data = response.data; if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } } name = "GraphqlResponseError"; errors; data; }; var NON_VARIABLE_OPTIONS = [ "method", "baseUrl", "url", "headers", "request", "query", "mediaType" ]; var FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"]; var GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; function graphql(request2, query, options) { if (options) { if (typeof query === "string" && "query" in options) { return Promise.reject( new Error(`[@octokit/graphql] "query" cannot be used as variable name`) ); } for (const key in options) { if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) continue; return Promise.reject( new Error( `[@octokit/graphql] "${key}" cannot be used as variable name` ) ); } } const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query; const requestOptions = Object.keys( parsedOptions ).reduce((result, key) => { if (NON_VARIABLE_OPTIONS.includes(key)) { result[key] = parsedOptions[key]; return result; } if (!result.variables) { result.variables = {}; } result.variables[key] = parsedOptions[key]; return result; }, {}); const baseUrl = parsedOptions.baseUrl || request2.endpoint.DEFAULTS.baseUrl; if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) { requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql"); } return request2(requestOptions).then((response) => { if (response.data.errors) { const headers = {}; for (const key of Object.keys(response.headers)) { headers[key] = response.headers[key]; } throw new GraphqlResponseError( requestOptions, headers, response.data ); } return response.data.data; }); } function withDefaults3(request2, newDefaults) { const newRequest = request2.defaults(newDefaults); const newApi = (query, options) => { return graphql(newRequest, query, options); }; return Object.assign(newApi, { defaults: withDefaults3.bind(null, newRequest), endpoint: newRequest.endpoint }); } var graphql2 = withDefaults3(request, { headers: { "user-agent": `octokit-graphql.js/${VERSION3} ${getUserAgent()}` }, method: "POST", url: "/graphql" }); function withCustomRequest(customRequest) { return withDefaults3(customRequest, { method: "POST", url: "/graphql" }); } // ../node_modules/@octokit/rest/node_modules/@octokit/auth-token/dist-bundle/index.js var REGEX_IS_INSTALLATION_LEGACY = /^v1\./; var REGEX_IS_INSTALLATION = /^ghs_/; var REGEX_IS_USER_TO_SERVER = /^ghu_/; async function auth(token) { const isApp = token.split(/\./).length === 3; const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) || REGEX_IS_INSTALLATION.test(token); const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token); const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth"; return { type: "token", token, tokenType }; } function withAuthorizationPrefix(token) { if (token.split(/\./).length === 3) { return `bearer ${token}`; } return `token ${token}`; } async function hook(token, request2, route, parameters) { const endpoint2 = request2.endpoint.merge( route, parameters ); endpoint2.headers.authorization = withAuthorizationPrefix(token); return request2(endpoint2); } var createTokenAuth = function createTokenAuth2(token) { if (!token) { throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); } if (typeof token !== "string") { throw new Error( "[@octokit/auth-token] Token passed to createTokenAuth is not a string" ); } token = token.replace(/^(token|bearer) +/i, ""); return Object.assign(auth.bind(null, token), { hook: hook.bind(null, token) }); }; // ../node_modules/@octokit/rest/node_modules/@octokit/core/dist-src/version.js var VERSION4 = "6.1.2"; // ../node_modules/@octokit/rest/node_modules/@octokit/core/dist-src/index.js var noop = () => { }; var consoleWarn = console.warn.bind(console); var consoleError = console.error.bind(console); var userAgentTrail = `octokit-core.js/${VERSION4} ${getUserAgent()}`; var Octokit = class { static VERSION = VERSION4; static defaults(defaults) { const OctokitWithDefaults = class extends this { constructor(...args) { const options = args[0] || {}; if (typeof defaults === "function") { super(defaults(options)); return; } super( Object.assign( {}, defaults, options, options.userAgent && defaults.userAgent ? { userAgent: `${options.userAgent} ${defaults.userAgent}` } : null ) ); } }; return OctokitWithDefaults; } static plugins = []; /** * Attach a plugin (or many) to your Octokit instance. * * @example * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) */ static plugin(...newPlugins) { const currentPlugins = this.plugins; const NewOctokit = class extends this { static plugins = currentPlugins.concat( newPlugins.filter((plugin) => !currentPlugins.includes(plugin)) ); }; return NewOctokit; } constructor(options = {}) { const hook2 = new before_after_hook_default.Collection(); const requestDefaults = { baseUrl: request.endpoint.DEFAULTS.baseUrl, headers: {}, request: Object.assign({}, options.request, { // @ts-ignore internal usage only, no need to type hook: hook2.bind(null, "request") }), mediaType: { previews: [], format: "" } }; requestDefaults.headers["user-agent"] = options.userAgent ? `${options.userAgent} ${userAgentTrail}` : userAgentTrail; if (options.baseUrl) { requestDefaults.baseUrl = options.baseUrl; } if (options.previews) { requestDefaults.mediaType.previews = options.previews; } if (options.timeZone) { requestDefaults.headers["time-zone"] = options.timeZone; } this.request = request.defaults(requestDefaults); this.graphql = withCustomRequest(this.request).defaults(requestDefaults); this.log = Object.assign( { debug: noop, info: noop, warn: consoleWarn, error: consoleError }, options.log ); this.hook = hook2; if (!options.authStrategy) { if (!options.auth) { this.auth = async () => ({ type: "unauthenticated" }); } else { const auth2 = createTokenAuth(options.auth); hook2.wrap("request", auth2.hook); this.auth = auth2; } } else { const { authStrategy, ...otherOptions } = options; const auth2 = authStrategy( Object.assign( { request: this.request, log: this.log, // we pass the current octokit instance as well as its constructor options // to allow for authentication strategies that return a new octokit instance // that shares the same internal state as the current one. The original // requirement for this was the "event-octokit" authentication strategy // of https://github.com/probot/octokit-auth-probot. octokit: this, octokitOptions: otherOptions }, options.auth ) ); hook2.wrap("request", auth2.hook); this.auth = auth2; } const classConstructor = this.constructor; for (let i = 0; i < classConstructor.plugins.length; ++i) { Object.assign(this, classConstructor.plugins[i](this, options)); } } // assigned during constructor request; graphql; log; hook; // TODO: type `octokit.auth` based on passed options.authStrategy auth; }; // ../node_modules/@octokit/rest/node_modules/@octokit/plugin-request-log/dist-src/version.js var VERSION5 = "5.3.1"; // ../node_modules/@octokit/rest/node_modules/@octokit/plugin-request-log/dist-src/index.js function requestLog(octokit) { octokit.hook.wrap("request", (request2, options) => { octokit.log.debug("request", options); const start = Date.now(); const requestOptions = octokit.request.endpoint.parse(options); const path2 = requestOptions.url.replace(options.baseUrl, ""); return request2(options).then((response) => { const requestId = response.headers["x-github-request-id"]; octokit.log.info( `${requestOptions.method} ${path2} - ${response.status} with id ${requestId} in ${Date.now() - start}ms` ); return response; }).catch((error) => { const requestId = error.response?.headers["x-github-request-id"] || "UNKNOWN"; octokit.log.error( `${requestOptions.method} ${path2} - ${error.status} with id ${requestId} in ${Date.now() - start}ms` ); throw error; }); }); } requestLog.VERSION = VERSION5; // ../node_modules/@octokit/rest/node_modules/@octokit/plugin-paginate-rest/dist-bundle/index.js var VERSION6 = "0.0.0-development"; function normalizePaginatedListResponse(response) { if (!response.data) { return { ...response, data: [] }; } const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data); if (!responseNeedsNormalization) return response; const incompleteResults = response.data.incomplete_results; const repositorySelection = response.data.repository_selection; const totalCount = response.data.total_count; delete response.data.incomplete_results; delete response.data.repository_selection; delete response.data.total_count; const namespaceKey = Object.keys(response.data)[0]; const data = response.data[namespaceKey]; response.data = data; if (typeof incompleteResults !== "undefined") { response.data.incomplete_results = incompleteResults; } if (typeof repositorySelection !== "undefined") { response.data.repository_selection = repositorySelection; } response.data.total_count = totalCount; return response; } function iterator(octokit, route, parameters) { const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters); const requestMethod = typeof route === "function" ? route : octokit.request; const method = options.method; const headers = options.headers; let url = options.url; return { [Symbol.asyncIterator]: () => ({ async next() { if (!url) return { done: true }; try { const response = await requestMethod({ method, url, headers }); const normalizedResponse = normalizePaginatedListResponse(response); url = ((normalizedResponse.headers.link || "").match( /<([^>]+)>;\s*rel="next"/ ) || [])[1]; return { value: normalizedResponse }; } catch (error) { if (error.status !== 409) throw error; url = ""; return { value: { status: 200, headers: {}, data: [] } }; } } }) }; } function paginate(octokit, route, parameters, mapFn) { if (typeof parameters === "function") { mapFn = parameters; parameters = void 0; } return gather( octokit, [], iterator(octokit, route, parameters)[Symbol.asyncIterator](), mapFn ); } function gather(octokit, results, iterator2, mapFn) { return iterator2.next().then((result) => { if (result.done) { return results; } let earlyExit = false; function done() { earlyExit = true; } results = results.concat( mapFn ? mapFn(result.value, done) : result.value.data ); if (earlyExit) { return results; } return gather(octokit, results, iterator2, mapFn); }); } var composePaginateRest = Object.assign(paginate, { iterator }); function paginateRest(octokit) { return { paginate: Object.assign(paginate.bind(null, octokit), { iterator: iterator.bind(null, octokit) }) }; } paginateRest.VERSION = VERSION6; // ../node_modules/@octokit/rest/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/version.js var VERSION7 = "13.2.6"; // ../node_modules/@octokit/rest/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/generated/endpoints.js var Endpoints = { actions: { addCustomLabelsToSelfHostedRunnerForOrg: [ "POST /orgs/{org}/actions/runners/{runner_id}/labels" ], addCustomLabelsToSelfHostedRunnerForRepo: [ "POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" ], addSelectedRepoToOrgSecret: [ "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" ], addSelectedRepoToOrgVariable: [ "PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" ], approveWorkflowRun: [ "POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve" ], cancelWorkflowRun: [ "POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel" ], createEnvironmentVariable: [ "POST /repos/{owner}/{repo}/environments/{environment_name}/variables" ], createOrUpdateEnvironmentSecret: [ "PUT /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}" ], createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"], createOrUpdateRepoSecret: [ "PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}" ], createOrgVariable: ["POST /orgs/{org}/actions/variables"], createRegistrationTokenForOrg: [ "POST /orgs/{org}/actions/runners/registration-token" ], createRegistrationTokenForRepo: [ "POST /repos/{owner}/{repo}/actions/runners/registration-token" ], createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"], createRemoveTokenForRepo: [ "POST /repos/{owner}/{repo}/actions/runners/remove-token" ], createRepoVariable: ["POST /repos/{owner}/{repo}/actions/variables"], createWorkflowDispatch: [ "POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches" ], deleteActionsCacheById: [ "DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}" ], deleteActionsCacheByKey: [ "DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}" ], deleteArtifact: [ "DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}" ], deleteEnvironmentSecret: [ "DELETE /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}" ], deleteEnvironmentVariable: [ "DELETE /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}" ], deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"], deleteOrgVariable: ["DELETE /orgs/{org}/actions/variables/{name}"], deleteRepoSecret: [ "DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}" ], deleteRepoVariable: [ "DELETE /repos/{owner}/{repo}/actions/variables/{name}" ], deleteSelfHostedRunnerFromOrg: [ "DELETE /orgs/{org}/actions/runners/{runner_id}" ], deleteSelfHostedRunnerFromRepo: [ "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}" ], deleteWorkflowRun: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"], deleteWorkflowRunLogs: [ "DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs" ], disableSelectedRepositoryGithubActionsOrganization: [ "DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}" ], disableWorkflow: [ "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable" ], downloadArtifact: [ "GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}" ], downloadJobLogsForWorkflowRun: [ "GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs" ], downloadWorkflowRunAttemptLogs: [ "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs" ], downloadWorkflowRunLogs: [ "GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs" ], enableSelectedRepositoryGithubActionsOrganization: [ "PUT /orgs/{org}/actions/permissions/repositories/{repository_id}" ], enableWorkflow: [ "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable" ], forceCancelWorkflowRun: [ "POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel" ], generateRunnerJitconfigForOrg: [ "POST /orgs/{org}/actions/runners/generate-jitconfig" ], generateRunnerJitconfigForRepo: [ "POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig" ], getActionsCacheList: ["GET /repos/{owner}/{repo}/actions/caches"], getActionsCacheUsage: ["GET /repos/{owner}/{repo}/actions/cache/usage"], getActionsCacheUsageByRepoForOrg: [ "GET /orgs/{org}/actions/cache/usage-by-repository" ], getActionsCacheUsageForOrg: ["GET /orgs/{org}/actions/cache/usage"], getAllowedActionsOrganization: [ "GET /orgs/{org}/actions/permissions/selected-actions" ], getAllowedActionsRepository: [ "GET /repos/{owner}/{repo}/actions/permissions/selected-actions" ], getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], getCustomOidcSubClaimForRepo: [ "GET /repos/{owner}/{repo}/actions/oidc/customization/sub" ], getEnvironmentPublicKey: [ "GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/public-key" ], getEnvironmentSecret: [ "GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}" ], getEnvironmentVariable: [ "GET /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}" ], getGithubActionsDefaultWorkflowPermissionsOrganization: [ "GET /orgs/{org}/actions/permissions/workflow" ], getGithubActionsDefaultWorkflowPermissionsRepository: [ "GET /repos/{owner}/{repo}/actions/permissions/workflow" ], getGithubActionsPermissionsOrganization: [ "GET /orgs/{org}/actions/permissions" ], getGithubActionsPermissionsRepository: [ "GET /repos/{owner}/{repo}/actions/permissions" ], getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"], getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"], getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"], getOrgVariable: ["GET /orgs/{org}/actions/variables/{name}"], getPendingDeploymentsForRun: [ "GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" ], getRepoPermissions: [ "GET /repos/{owner}/{repo}/actions/permissions", {}, { renamed: ["actions", "getGithubActionsPermissionsRepository"] } ], getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"], getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"], getRepoVariable: ["GET /repos/{owner}/{repo}/actions/variables/{name}"], getReviewsForRun: [ "GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals" ], getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"], getSelfHostedRunnerForRepo: [ "GET /repos/{owner}/{repo}/actions/runners/{runner_id}" ], getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"], getWorkflowAccessToRepository: [ "GET /repos/{owner}/{repo}/actions/permissions/access" ], getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"], getWorkflowRunAttempt: [ "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}" ], getWorkflowRunUsage: [ "GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing" ], getWorkflowUsage: [ "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing" ], listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"], listEnvironmentSecrets: [ "GET /repos/{owner}/{repo}/environments/{environment_name}/secrets" ], listEnvironmentVariables: [ "GET /repos/{owner}/{repo}/environments/{environment_name}/variables" ], listJobsForWorkflowRun: [ "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs" ], listJobsForWorkflowRunAttempt: [ "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs" ], listLabelsForSelfHostedRunnerForOrg: [ "GET /orgs/{org}/actions/runners/{runner_id}/labels" ], listLabelsForSelfHostedRunnerForRepo: [ "GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" ], listOrgSecrets: ["GET /orgs/{org}/actions/secrets"], listOrgVariables: ["GET /orgs/{org}/actions/variables"], listRepoOrganizationSecrets: [ "GET /repos/{owner}/{repo}/actions/organization-secrets" ], listRepoOrganizationVariables: [ "GET /repos/{owner}/{repo}/actions/organization-variables" ], listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"], listRepoVariables: ["GET /repos/{owner}/{repo}/actions/variables"], listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"], listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"], listRunnerApplicationsForRepo: [ "GET /repos/{owner}/{repo}/actions/runners/downloads" ], listSelectedReposForOrgSecret: [ "GET /orgs/{org}/actions/secrets/{secret_name}/repositories" ], listSelectedReposForOrgVariable: [ "GET /orgs/{org}/actions/variables/{name}/repositories" ], listSelectedRepositoriesEnabledGithubActionsOrganization: [ "GET /orgs/{org}/actions/permissions/repositories" ], listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"], listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"], listWorkflowRunArtifacts: [ "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts" ], listWorkflowRuns: [ "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs" ], listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"], reRunJobForWorkflowRun: [ "POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun" ], reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"], reRunWorkflowFailedJobs: [ "POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs" ], removeAllCustomLabelsFromSelfHostedRunnerForOrg: [ "DELETE /orgs/{org}/actions/runners/{runner_id}/labels" ], removeAllCustomLabelsFromSelfHostedRunnerForRepo: [ "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" ], removeCustomLabelFromSelfHostedRunnerForOrg: [ "DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}" ], removeCustomLabelFromSelfHostedRunnerForRepo: [ "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}" ], removeSelectedRepoFromOrgSecret: [ "DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" ], removeSelectedRepoFromOrgVariable: [ "DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" ], reviewCustomGatesForRun: [ "POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule" ], reviewPendingDeploymentsForRun: [ "POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" ], setAllowedActionsOrganization: [ "PUT /orgs/{org}/actions/permissions/selected-actions" ], setAllowedActionsRepository: [ "PUT /repos/{owner}/{repo}/actions/permissions/selected-actions" ], setCustomLabelsForSelfHostedRunnerForOrg: [ "PUT /orgs/{org}/actions/runners/{runner_id}/labels" ], setCustomLabelsForSelfHostedRunnerForRepo: [ "PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" ], setCustomOidcSubClaimForRepo: [ "PUT /repos/{owner}/{repo}/actions/oidc/customization/sub" ], setGithubActionsDefaultWorkflowPermissionsOrganization: [ "PUT /orgs/{org}/actions/permissions/workflow" ], setGithubActionsDefaultWorkflowPermissionsRepository: [ "PUT /repos/{owner}/{repo}/actions/permissions/workflow" ], setGithubActionsPermissionsOrganization: [ "PUT /orgs/{org}/actions/permissions" ], setGithubActionsPermissionsRepository: [ "PUT /repos/{owner}/{repo}/actions/permissions" ], setSelectedReposForOrgSecret: [ "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories" ], setSelectedReposForOrgVariable: [ "PUT /orgs/{org}/actions/variables/{name}/repositories" ], setSelectedRepositoriesEnabledGithubActionsOrganization: [ "PUT /orgs/{org}/actions/permissions/repositories" ], setWorkflowAccessToRepository: [ "PUT /repos/{owner}/{repo}/actions/permissions/access" ], updateEnvironmentVariable: [ "PATCH /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}" ], updateOrgVariable: ["PATCH /orgs/{org}/actions/variables/{name}"], updateRepoVariable: [ "PATCH /repos/{owner}/{repo}/actions/variables/{name}" ] }, activity: { checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"], deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"], deleteThreadSubscription: [ "DELETE /notifications/threads/{thread_id}/subscription" ], getFeeds: ["GET /feeds"], getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"], getThread: ["GET /notifications/threads/{thread_id}"], getThreadSubscriptionForAuthenticatedUser: [ "GET /notifications/threads/{thread_id}/subscription" ], listEventsForAuthenticatedUser: ["GET /users/{username}/events"], listNotificationsForAuthenticatedUser: ["GET /notifications"], listOrgEventsForAuthenticatedUser: [ "GET /users/{username}/events/orgs/{org}" ], listPublicEvents: ["GET /events"], listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"], listPublicEventsForUser: ["GET /users/{username}/events/public"], listPublicOrgEvents: ["GET /orgs/{org}/events"], listReceivedEventsForUser: ["GET /users/{username}/received_events"], listReceivedPublicEventsForUser: [ "GET /users/{username}/received_events/public" ], listRepoEvents: ["GET /repos/{owner}/{repo}/events"], listRepoNotificationsForAuthenticatedUser: [ "GET /repos/{owner}/{repo}/notifications" ], listReposStarredByAuthenticatedUser: ["GET /user/starred"], listReposStarredByUser: ["GET /users/{username}/starred"], listReposWatchedByUser: ["GET /users/{username}/subscriptions"], listStargazersForRepo: ["GET /repos/{owner}/{repo}/stargazers"], listWatchedReposForAuthenticatedUser: ["GET /user/subscriptions"], listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"], markNotificationsAsRead: ["PUT /notifications"], markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"], markThreadAsDone: ["DELETE /notifications/threads/{thread_id}"], markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"], setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"], setThreadSubscription: [ "PUT /notifications/threads/{thread_id}/subscription" ], starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"], unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"] }, apps: { addRepoToInstallation: [ "PUT /user/installations/{installation_id}/repositories/{repository_id}", {}, { renamed: ["apps", "addRepoToInstallationForAuthenticatedUser"] } ], addRepoToInstallationForAuthenticatedUser: [ "PUT /user/installations/{installation_id}/repositories/{repository_id}" ], checkToken: ["POST /applications/{client_id}/token"], createFromManifest: ["POST /app-manifests/{code}/conversions"], createInstallationAccessToken: [ "POST /app/installations/{installation_id}/access_tokens" ], deleteAuthorization: ["DELETE /applications/{client_id}/grant"], deleteInstallation: ["DELETE /app/installations/{installation_id}"], deleteToken: ["DELETE /applications/{client_id}/token"], getAuthenticated: ["GET /app"], getBySlug: ["GET /apps/{app_slug}"], getInstallation: ["GET /app/installations/{installation_id}"], getOrgInstallation: ["GET /orgs/{org}/installation"], getRepoInstallation: ["GET /repos/{owner}/{repo}/installation"], getSubscriptionPlanForAccount: [ "GET /marketplace_listing/accounts/{account_id}" ], getSubscriptionPlanForAccountStubbed: [ "GET /marketplace_listing/stubbed/accounts/{account_id}" ], getUserInstallation: ["GET /users/{username}/installation"], getWebhookConfigForApp: ["GET /app/hook/config"], getWebhookDelivery: ["GET /app/hook/deliveries/{delivery_id}"], listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"], listAccountsForPlanStubbed: [ "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts" ], listInstallationReposForAuthenticatedUser: [ "GET /user/installations/{installation_id}/repositories" ], listInstallationRequestsForAuthenticatedApp: [ "GET /app/installation-requests" ], listInstallations: ["GET /app/installations"], listInstallationsForAuthenticatedUser: ["GET /user/installations"], listPlans: ["GET /marketplace_listing/plans"], listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"], listReposAccessibleToInstallation: ["GET /installation/repositories"], listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"], listSubscriptionsForAuthenticatedUserStubbed: [ "GET /user/marketplace_purchases/stubbed" ], listWebhookDeliveries: ["GET /app/hook/deliveries"], redeliverWebhookDelivery: [ "POST /app/hook/deliveries/{delivery_id}/attempts" ], removeRepoFromInstallation: [ "DELETE /user/installations/{installation_id}/repositories/{repository_id}", {}, { renamed: ["apps", "removeRepoFromInstallationForAuthenticatedUser"] } ], removeRepoFromInstallationForAuthenticatedUser: [ "DELETE /user/installations/{installation_id}/repositories/{repository_id}" ], resetToken: ["PATCH /applications/{client_id}/token"], revokeInstallationAccessToken: ["DELETE /installation/token"], scopeToken: ["POST /applications/{client_id}/token/scoped"], suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"], unsuspendInstallation: [ "DELETE /app/installations/{installation_id}/suspended" ], updateWebhookConfigForApp: ["PATCH /app/hook/config"] }, billing: { getGithubActionsBillingOrg: ["GET /orgs/{org}/settings/billing/actions"], getGithubActionsBillingUser: [ "GET /users/{username}/settings/billing/actions" ], getGithubPackagesBillingOrg: ["GET /orgs/{org}/settings/billing/packages"], getGithubPackagesBillingUser: [ "GET /users/{username}/settings/billing/packages" ], getSharedStorageBillingOrg: [ "GET /orgs/{org}/settings/billing/shared-storage" ], getSharedStorageBillingUser: [ "GET /users/{username}/settings/billing/shared-storage" ] }, checks: { create: ["POST /repos/{owner}/{repo}/check-runs"], createSuite: ["POST /repos/{owner}/{repo}/check-suites"], get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"], getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"], listAnnotations: [ "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations" ], listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"], listForSuite: [ "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs" ], listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"], rerequestRun: [ "POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest" ], rerequestSuite: [ "POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest" ], setSuitesPreferences: [ "PATCH /repos/{owner}/{repo}/check-suites/preferences" ], update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"] }, codeScanning: { deleteAnalysis: [ "DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}" ], getAlert: [ "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}", {}, { renamedParameters: { alert_id: "alert_number" } } ], getAnalysis: [ "GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}" ], getCodeqlDatabase: [ "GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}" ], getDefaultSetup: ["GET /repos/{owner}/{repo}/code-scanning/default-setup"], getSarif: ["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"], listAlertInstances: [ "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances" ], listAlertsForOrg: ["GET /orgs/{org}/code-scanning/alerts"], listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"], listAlertsInstances: [ "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", {}, { renamed: ["codeScanning", "listAlertInstances"] } ], listCodeqlDatabases: [ "GET /repos/{owner}/{repo}/code-scanning/codeql/databases" ], listRecentAnalyses: ["GET /repos/{owner}/{repo}/code-scanning/analyses"], updateAlert: [ "PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}" ], updateDefaultSetup: [ "PATCH /repos/{owner}/{repo}/code-scanning/default-setup" ], uploadSarif: ["POST /repos/{owner}/{repo}/code-scanning/sarifs"] }, codesOfConduct: { getAllCodesOfConduct: ["GET /codes_of_conduct"], getConductCode: ["GET /codes_of_conduct/{key}"] }, codespaces: { addRepositoryForSecretForAuthenticatedUser: [ "PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" ], addSelectedRepoToOrgSecret: [ "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" ], checkPermissionsForDevcontainer: [ "GET /repos/{owner}/{repo}/codespaces/permissions_check" ], codespaceMachinesForAuthenticatedUser: [ "GET /user/codespaces/{codespace_name}/machines" ], createForAuthenticatedUser: ["POST /user/codespaces"], createOrUpdateOrgSecret: [ "PUT /orgs/{org}/codespaces/secrets/{secret_name}" ], createOrUpdateRepoSecret: [ "PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" ], createOrUpdateSecretForAuthenticatedUser: [ "PUT /user/codespaces/secrets/{secret_name}" ], createWithPrForAuthenticatedUser: [ "POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces" ], createWithRepoForAuthenticatedUser: [ "POST /repos/{owner}/{repo}/codespaces" ], deleteForAuthenticatedUser: ["DELETE /user/codespaces/{codespace_name}"], deleteFromOrganization: [ "DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}" ], deleteOrgSecret: ["DELETE /orgs/{org}/codespaces/secrets/{secret_name}"], deleteRepoSecret: [ "DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" ], deleteSecretForAuthenticatedUser: [ "DELETE /user/codespaces/secrets/{secret_name}" ], exportForAuthenticatedUser: [ "POST /user/codespaces/{codespace_name}/exports" ], getCodespacesForUserInOrg: [ "GET /orgs/{org}/members/{username}/codespaces" ], getExportDetailsForAuthenticatedUser: [ "GET /user/codespaces/{codespace_name}/exports/{export_id}" ], getForAuthenticatedUser: ["GET /user/codespaces/{codespace_name}"], getOrgPublicKey: ["GET /orgs/{org}/codespaces/secrets/public-key"], getOrgSecret: ["GET /orgs/{org}/codespaces/secrets/{secret_name}"], getPublicKeyForAuthenticatedUser: [ "GET /user/codespaces/secrets/public-key" ], getRepoPublicKey: [ "GET /repos/{owner}/{repo}/codespaces/secrets/public-key" ], getRepoSecret: [ "GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" ], getSecretForAuthenticatedUser: [ "GET /user/codespaces/secrets/{secret_name}" ], listDevcontainersInRepositoryForAuthenticatedUser: [ "GET /repos/{owner}/{repo}/codespaces/devcontainers" ], listForAuthenticatedUser: ["GET /user/codespaces"], listInOrganization: [ "GET /orgs/{org}/codespaces", {}, { renamedParameters: { org_id: "org" } } ], listInRepositoryForAuthenticatedUser: [ "GET /repos/{owner}/{repo}/codespaces" ], listOrgSecrets: ["GET /orgs/{org}/codespaces/secrets"], listRepoSecrets: ["GET /repos/{owner}/{repo}/codespaces/secrets"], listRepositoriesForSecretForAuthenticatedUser: [ "GET /user/codespaces/secrets/{secret_name}/repositories" ], listSecretsForAuthenticatedUser: ["GET /user/codespaces/secrets"], listSelectedReposForOrgSecret: [ "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories" ], preFlightWithRepoForAuthenticatedUser: [ "GET /repos/{owner}/{repo}/codespaces/new" ], publishForAuthenticatedUser: [ "POST /user/codespaces/{codespace_name}/publish" ], removeRepositoryForSecretForAuthenticatedUser: [ "DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" ], removeSelectedRepoFromOrgSecret: [ "DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" ], repoMachinesForAuthenticatedUser: [ "GET /repos/{owner}/{repo}/codespaces/machines" ], setRepositoriesForSecretForAuthenticatedUser: [ "PUT /user/codespaces/secrets/{secret_name}/repositories" ], setSelectedReposForOrgSecret: [ "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories" ], startForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/start"], stopForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/stop"], stopInOrganization: [ "POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop" ], updateForAuthenticatedUser: ["PATCH /user/codespaces/{codespace_name}"] }, copilot: { addCopilotSeatsForTeams: [ "POST /orgs/{org}/copilot/billing/selected_teams" ], addCopilotSeatsForUsers: [ "POST /orgs/{org}/copilot/billing/selected_users" ], cancelCopilotSeatAssignmentForTeams: [ "DELETE /orgs/{org}/copilot/billing/selected_teams" ], cancelCopilotSeatAssignmentForUsers: [ "DELETE /orgs/{org}/copilot/billing/selected_users" ], getCopilotOrganizationDetails: ["GET /orgs/{org}/copilot/billing"], getCopilotSeatDetailsForUser: [ "GET /orgs/{org}/members/{username}/copilot" ], listCopilotSeats: ["GET /orgs/{org}/copilot/billing/seats"], usageMetricsForEnterprise: ["GET /enterprises/{enterprise}/copilot/usage"], usageMetricsForOrg: ["GET /orgs/{org}/copilot/usage"], usageMetricsForTeam: ["GET /orgs/{org}/team/{team_slug}/copilot/usage"] }, dependabot: { addSelectedRepoToOrgSecret: [ "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" ], createOrUpdateOrgSecret: [ "PUT /orgs/{org}/dependabot/secrets/{secret_name}" ], createOrUpdateRepoSecret: [ "PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" ], deleteOrgSecret: ["DELETE /orgs/{org}/dependabot/secrets/{secret_name}"], deleteRepoSecret: [ "DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" ], getAlert: ["GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"], getOrgPublicKey: ["GET /orgs/{org}/dependabot/secrets/public-key"], getOrgSecret: ["GET /orgs/{org}/dependabot/secrets/{secret_name}"], getRepoPublicKey: [ "GET /repos/{owner}/{repo}/dependabot/secrets/public-key" ], getRepoSecret: [ "GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" ], listAlertsForEnterprise: [ "GET /enterprises/{enterprise}/dependabot/alerts" ], listAlertsForOrg: ["GET /orgs/{org}/dependabot/alerts"], listAlertsForRepo: ["GET /repos/{owner}/{repo}/dependabot/alerts"], listOrgSecrets: ["GET /orgs/{org}/dependabot/secrets"], listRepoSecrets: ["GET /repos/{owner}/{repo}/dependabot/secrets"], listSelectedReposForOrgSecret: [ "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories" ], removeSelectedRepoFromOrgSecret: [ "DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" ], setSelectedReposForOrgSecret: [ "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories" ], updateAlert: [ "PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}" ] }, dependencyGraph: { createRepositorySnapshot: [ "POST /repos/{owner}/{repo}/dependency-graph/snapshots" ], diffRange: [ "GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}" ], exportSbom: ["GET /repos/{owner}/{repo}/dependency-graph/sbom"] }, emojis: { get: ["GET /emojis"] }, gists: { checkIsStarred: ["GET /gists/{gist_id}/star"], create: ["POST /gists"], createComment: ["POST /gists/{gist_id}/comments"], delete: ["DELETE /gists/{gist_id}"], deleteComment: ["DELETE /gists/{gist_id}/comments/{comment_id}"], fork: ["POST /gists/{gist_id}/forks"], get: ["GET /gists/{gist_id}"], getComment: ["GET /gists/{gist_id}/comments/{comment_id}"], getRevision: ["GET /gists/{gist_id}/{sha}"], list: ["GET /gists"], listComments: ["GET /gists/{gist_id}/comments"], listCommits: ["GET /gists/{gist_id}/commits"], listForUser: ["GET /users/{username}/gists"], listForks: ["GET /gists/{gist_id}/forks"], listPublic: ["GET /gists/public"], listStarred: ["GET /gists/starred"], star: ["PUT /gists/{gist_id}/star"], unstar: ["DELETE /gists/{gist_id}/star"], update: ["PATCH /gists/{gist_id}"], updateComment: ["PATCH /gists/{gist_id}/comments/{comment_id}"] }, git: { createBlob: ["POST /repos/{owner}/{repo}/git/blobs"], createCommit: ["POST /repos/{owner}/{repo}/git/commits"], createRef: ["POST /repos/{owner}/{repo}/git/refs"], createTag: ["POST /repos/{owner}/{repo}/git/tags"], createTree: ["POST /repos/{owner}/{repo}/git/trees"], deleteRef: ["DELETE /repos/{owner}/{repo}/git/refs/{ref}"], getBlob: ["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"], getCommit: ["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"], getRef: ["GET /repos/{owner}/{repo}/git/ref/{ref}"], getTag: ["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"], getTree: ["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"], listMatchingRefs: ["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"], updateRef: ["PATCH /repos/{owner}/{repo}/git/refs/{ref}"] }, gitignore: { getAllTemplates: ["GET /gitignore/templates"], getTemplate: ["GET /gitignore/templates/{name}"] }, interactions: { getRestrictionsForAuthenticatedUser: ["GET /user/interaction-limits"], getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits"], getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits"], getRestrictionsForYourPublicRepos: [ "GET /user/interaction-limits", {}, { renamed: ["interactions", "getRestrictionsForAuthenticatedUser"] } ], removeRestrictionsForAuthenticatedUser: ["DELETE /user/interaction-limits"], removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits"], removeRestrictionsForRepo: [ "DELETE /repos/{owner}/{repo}/interaction-limits" ], removeRestrictionsForYourPublicRepos: [ "DELETE /user/interaction-limits", {}, { renamed: ["interactions", "removeRestrictionsForAuthenticatedUser"] } ], setRestrictionsForAuthenticatedUser: ["PUT /user/interaction-limits"], setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits"], setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits"], setRestrictionsForYourPublicRepos: [ "PUT /user/interaction-limits", {}, { renamed: ["interactions", "setRestrictionsForAuthenticatedUser"] } ] }, issues: { addAssignees: [ "POST /repos/{owner}/{repo}/issues/{issue_number}/assignees" ], addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"], checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"], checkUserCanBeAssignedToIssue: [ "GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}" ], create: ["POST /repos/{owner}/{repo}/issues"], createComment: [ "POST /repos/{owner}/{repo}/issues/{issue_number}/comments" ], createLabel: ["POST /repos/{owner}/{repo}/labels"], createMilestone: ["POST /repos/{owner}/{repo}/milestones"], deleteComment: [ "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}" ], deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"], deleteMilestone: [ "DELETE /repos/{owner}/{repo}/milestones/{milestone_number}" ], get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"], getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"], getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"], getLabel: ["GET /repos/{owner}/{repo}/labels/{name}"], getMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}"], list: ["GET /issues"], listAssignees: ["GET /repos/{owner}/{repo}/assignees"], listComments: ["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"], listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"], listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"], listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"], listEventsForTimeline: [ "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline" ], listForAuthenticatedUser: ["GET /user/issues"], listForOrg: ["GET /orgs/{org}/issues"], listForRepo: ["GET /repos/{owner}/{repo}/issues"], listLabelsForMilestone: [ "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels" ], listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"], listLabelsOnIssue: [ "GET /repos/{owner}/{repo}/issues/{issue_number}/labels" ], listMilestones: ["GET /repos/{owner}/{repo}/milestones"], lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"], removeAllLabels: [ "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels" ], removeAssignees: [ "DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees" ], removeLabel: [ "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}" ], setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"], unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"], update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"], updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"], updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"], updateMilestone: [ "PATCH /repos/{owner}/{repo}/milestones/{milestone_number}" ] }, licenses: { get: ["GET /licenses/{license}"], getAllCommonlyUsed: ["GET /licenses"], getForRepo: ["GET /repos/{owner}/{repo}/license"] }, markdown: { render: ["POST /markdown"], renderRaw: [ "POST /markdown/raw", { headers: { "content-type": "text/plain; charset=utf-8" } } ] }, meta: { get: ["GET /meta"], getAllVersions: ["GET /versions"], getOctocat: ["GET /octocat"], getZen: ["GET /zen"], root: ["GET /"] }, migrations: { deleteArchiveForAuthenticatedUser: [ "DELETE /user/migrations/{migration_id}/archive" ], deleteArchiveForOrg: [ "DELETE /orgs/{org}/migrations/{migration_id}/archive" ], downloadArchiveForOrg: [ "GET /orgs/{org}/migrations/{migration_id}/archive" ], getArchiveForAuthenticatedUser: [ "GET /user/migrations/{migration_id}/archive" ], getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}"], getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}"], listForAuthenticatedUser: ["GET /user/migrations"], listForOrg: ["GET /orgs/{org}/migrations"], listReposForAuthenticatedUser: [ "GET /user/migrations/{migration_id}/repositories" ], listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories"], listReposForUser: [ "GET /user/migrations/{migration_id}/repositories", {}, { renamed: ["migrations", "listReposForAuthenticatedUser"] } ], startForAuthenticatedUser: ["POST /user/migrations"], startForOrg: ["POST /orgs/{org}/migrations"], unlockRepoForAuthenticatedUser: [ "DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock" ], unlockRepoForOrg: [ "DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock" ] }, oidc: { getOidcCustomSubTemplateForOrg: [ "GET /orgs/{org}/actions/oidc/customization/sub" ], updateOidcCustomSubTemplateForOrg: [ "PUT /orgs/{org}/actions/oidc/customization/sub" ] }, orgs: { addSecurityManagerTeam: [ "PUT /orgs/{org}/security-managers/teams/{team_slug}" ], assignTeamToOrgRole: [ "PUT /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" ], assignUserToOrgRole: [ "PUT /orgs/{org}/organization-roles/users/{username}/{role_id}" ], blockUser: ["PUT /orgs/{org}/blocks/{username}"], cancelInvitation: ["DELETE /orgs/{org}/invitations/{invitation_id}"], checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"], checkMembershipForUser: ["GET /orgs/{org}/members/{username}"], checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"], convertMemberToOutsideCollaborator: [ "PUT /orgs/{org}/outside_collaborators/{username}" ], createCustomOrganizationRole: ["POST /orgs/{org}/organization-roles"], createInvitation: ["POST /orgs/{org}/invitations"], createOrUpdateCustomProperties: ["PATCH /orgs/{org}/properties/schema"], createOrUpdateCustomPropertiesValuesForRepos: [ "PATCH /orgs/{org}/properties/values" ], createOrUpdateCustomProperty: [ "PUT /orgs/{org}/properties/schema/{custom_property_name}" ], createWebhook: ["POST /orgs/{org}/hooks"], delete: ["DELETE /orgs/{org}"], deleteCustomOrganizationRole: [ "DELETE /orgs/{org}/organization-roles/{role_id}" ], deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"], enableOrDisableSecurityProductOnAllOrgRepos: [ "POST /orgs/{org}/{security_product}/{enablement}" ], get: ["GET /orgs/{org}"], getAllCustomProperties: ["GET /orgs/{org}/properties/schema"], getCustomProperty: [ "GET /orgs/{org}/properties/schema/{custom_property_name}" ], getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"], getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"], getOrgRole: ["GET /orgs/{org}/organization-roles/{role_id}"], getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"], getWebhookConfigForOrg: ["GET /orgs/{org}/hooks/{hook_id}/config"], getWebhookDelivery: [ "GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}" ], list: ["GET /organizations"], listAppInstallations: ["GET /orgs/{org}/installations"], listBlockedUsers: ["GET /orgs/{org}/blocks"], listCustomPropertiesValuesForRepos: ["GET /orgs/{org}/properties/values"], listFailedInvitations: ["GET /orgs/{org}/failed_invitations"], listForAuthenticatedUser: ["GET /user/orgs"], listForUser: ["GET /users/{username}/orgs"], listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"], listMembers: ["GET /orgs/{org}/members"], listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"], listOrgRoleTeams: ["GET /orgs/{org}/organization-roles/{role_id}/teams"], listOrgRoleUsers: ["GET /orgs/{org}/organization-roles/{role_id}/users"], listOrgRoles: ["GET /orgs/{org}/organization-roles"], listOrganizationFineGrainedPermissions: [ "GET /orgs/{org}/organization-fine-grained-permissions" ], listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"], listPatGrantRepositories: [ "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories" ], listPatGrantRequestRepositories: [ "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories" ], listPatGrantRequests: ["GET /orgs/{org}/personal-access-token-requests"], listPatGrants: ["GET /orgs/{org}/personal-access-tokens"], listPendingInvitations: ["GET /orgs/{org}/invitations"], listPublicMembers: ["GET /orgs/{org}/public_members"], listSecurityManagerTeams: ["GET /orgs/{org}/security-managers"], listWebhookDeliveries: ["GET /orgs/{org}/hooks/{hook_id}/deliveries"], listWebhooks: ["GET /orgs/{org}/hooks"], patchCustomOrganizationRole: [ "PATCH /orgs/{org}/organization-roles/{role_id}" ], pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"], redeliverWebhookDelivery: [ "POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" ], removeCustomProperty: [ "DELETE /orgs/{org}/properties/schema/{custom_property_name}" ], removeMember: ["DELETE /orgs/{org}/members/{username}"], removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"], removeOutsideCollaborator: [ "DELETE /orgs/{org}/outside_collaborators/{username}" ], removePublicMembershipForAuthenticatedUser: [ "DELETE /orgs/{org}/public_members/{username}" ], removeSecurityManagerTeam: [ "DELETE /orgs/{org}/security-managers/teams/{team_slug}" ], reviewPatGrantRequest: [ "POST /orgs/{org}/personal-access-token-requests/{pat_request_id}" ], reviewPatGrantRequestsInBulk: [ "POST /orgs/{org}/personal-access-token-requests" ], revokeAllOrgRolesTeam: [ "DELETE /orgs/{org}/organization-roles/teams/{team_slug}" ], revokeAllOrgRolesUser: [ "DELETE /orgs/{org}/organization-roles/users/{username}" ], revokeOrgRoleTeam: [ "DELETE /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" ], revokeOrgRoleUser: [ "DELETE /orgs/{org}/organization-roles/users/{username}/{role_id}" ], setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"], setPublicMembershipForAuthenticatedUser: [ "PUT /orgs/{org}/public_members/{username}" ], unblockUser: ["DELETE /orgs/{org}/blocks/{username}"], update: ["PATCH /orgs/{org}"], updateMembershipForAuthenticatedUser: [ "PATCH /user/memberships/orgs/{org}" ], updatePatAccess: ["POST /orgs/{org}/personal-access-tokens/{pat_id}"], updatePatAccesses: ["POST /orgs/{org}/personal-access-tokens"], updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"], updateWebhookConfigForOrg: ["PATCH /orgs/{org}/hooks/{hook_id}/config"] }, packages: { deletePackageForAuthenticatedUser: [ "DELETE /user/packages/{package_type}/{package_name}" ], deletePackageForOrg: [ "DELETE /orgs/{org}/packages/{package_type}/{package_name}" ], deletePackageForUser: [ "DELETE /users/{username}/packages/{package_type}/{package_name}" ], deletePackageVersionForAuthenticatedUser: [ "DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}" ], deletePackageVersionForOrg: [ "DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" ], deletePackageVersionForUser: [ "DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" ], getAllPackageVersionsForAPackageOwnedByAnOrg: [ "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", {}, { renamed: ["packages", "getAllPackageVersionsForPackageOwnedByOrg"] } ], getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: [ "GET /user/packages/{package_type}/{package_name}/versions", {}, { renamed: [ "packages", "getAllPackageVersionsForPackageOwnedByAuthenticatedUser" ] } ], getAllPackageVersionsForPackageOwnedByAuthenticatedUser: [ "GET /user/packages/{package_type}/{package_name}/versions" ], getAllPackageVersionsForPackageOwnedByOrg: [ "GET /orgs/{org}/packages/{package_type}/{package_name}/versions" ], getAllPackageVersionsForPackageOwnedByUser: [ "GET /users/{username}/packages/{package_type}/{package_name}/versions" ], getPackageForAuthenticatedUser: [ "GET /user/packages/{package_type}/{package_name}" ], getPackageForOrganization: [ "GET /orgs/{org}/packages/{package_type}/{package_name}" ], getPackageForUser: [ "GET /users/{username}/packages/{package_type}/{package_name}" ], getPackageVersionForAuthenticatedUser: [ "GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}" ], getPackageVersionForOrganization: [ "GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" ], getPackageVersionForUser: [ "GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" ], listDockerMigrationConflictingPackagesForAuthenticatedUser: [ "GET /user/docker/conflicts" ], listDockerMigrationConflictingPackagesForOrganization: [ "GET /orgs/{org}/docker/conflicts" ], listDockerMigrationConflictingPackagesForUser: [ "GET /users/{username}/docker/conflicts" ], listPackagesForAuthenticatedUser: ["GET /user/packages"], listPackagesForOrganization: ["GET /orgs/{org}/packages"], listPackagesForUser: ["GET /users/{username}/packages"], restorePackageForAuthenticatedUser: [ "POST /user/packages/{package_type}/{package_name}/restore{?token}" ], restorePackageForOrg: [ "POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}" ], restorePackageForUser: [ "POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}" ], restorePackageVersionForAuthenticatedUser: [ "POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" ], restorePackageVersionForOrg: [ "POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" ], restorePackageVersionForUser: [ "POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" ] }, projects: { addCollaborator: ["PUT /projects/{project_id}/collaborators/{username}"], createCard: ["POST /projects/columns/{column_id}/cards"], createColumn: ["POST /projects/{project_id}/columns"], createForAuthenticatedUser: ["POST /user/projects"], createForOrg: ["POST /orgs/{org}/projects"], createForRepo: ["POST /repos/{owner}/{repo}/projects"], delete: ["DELETE /projects/{project_id}"], deleteCard: ["DELETE /projects/columns/cards/{card_id}"], deleteColumn: ["DELETE /projects/columns/{column_id}"], get: ["GET /projects/{project_id}"], getCard: ["GET /projects/columns/cards/{card_id}"], getColumn: ["GET /projects/columns/{column_id}"], getPermissionForUser: [ "GET /projects/{project_id}/collaborators/{username}/permission" ], listCards: ["GET /projects/columns/{column_id}/cards"], listCollaborators: ["GET /projects/{project_id}/collaborators"], listColumns: ["GET /projects/{project_id}/columns"], listForOrg: ["GET /orgs/{org}/projects"], listForRepo: ["GET /repos/{owner}/{repo}/projects"], listForUser: ["GET /users/{username}/projects"], moveCard: ["POST /projects/columns/cards/{card_id}/moves"], moveColumn: ["POST /projects/columns/{column_id}/moves"], removeCollaborator: [ "DELETE /projects/{project_id}/collaborators/{username}" ], update: ["PATCH /projects/{project_id}"], updateCard: ["PATCH /projects/columns/cards/{card_id}"], updateColumn: ["PATCH /projects/columns/{column_id}"] }, pulls: { checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"], create: ["POST /repos/{owner}/{repo}/pulls"], createReplyForReviewComment: [ "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies" ], createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], createReviewComment: [ "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments" ], deletePendingReview: [ "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" ], deleteReviewComment: [ "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}" ], dismissReview: [ "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals" ], get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"], getReview: [ "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" ], getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"], list: ["GET /repos/{owner}/{repo}/pulls"], listCommentsForReview: [ "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments" ], listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"], listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"], listRequestedReviewers: [ "GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" ], listReviewComments: [ "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments" ], listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"], listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"], removeRequestedReviewers: [ "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" ], requestReviewers: [ "POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" ], submitReview: [ "POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events" ], update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"], updateBranch: [ "PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch" ], updateReview: [ "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" ], updateReviewComment: [ "PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}" ] }, rateLimit: { get: ["GET /rate_limit"] }, reactions: { createForCommitComment: [ "POST /repos/{owner}/{repo}/comments/{comment_id}/reactions" ], createForIssue: [ "POST /repos/{owner}/{repo}/issues/{issue_number}/reactions" ], createForIssueComment: [ "POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" ], createForPullRequestReviewComment: [ "POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" ], createForRelease: [ "POST /repos/{owner}/{repo}/releases/{release_id}/reactions" ], createForTeamDiscussionCommentInOrg: [ "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" ], createForTeamDiscussionInOrg: [ "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" ], deleteForCommitComment: [ "DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}" ], deleteForIssue: [ "DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}" ], deleteForIssueComment: [ "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}" ], deleteForPullRequestComment: [ "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}" ], deleteForRelease: [ "DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}" ], deleteForTeamDiscussion: [ "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}" ], deleteForTeamDiscussionComment: [ "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}" ], listForCommitComment: [ "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions" ], listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"], listForIssueComment: [ "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" ], listForPullRequestReviewComment: [ "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" ], listForRelease: [ "GET /repos/{owner}/{repo}/releases/{release_id}/reactions" ], listForTeamDiscussionCommentInOrg: [ "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" ], listForTeamDiscussionInOrg: [ "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" ] }, repos: { acceptInvitation: [ "PATCH /user/repository_invitations/{invitation_id}", {}, { renamed: ["repos", "acceptInvitationForAuthenticatedUser"] } ], acceptInvitationForAuthenticatedUser: [ "PATCH /user/repository_invitations/{invitation_id}" ], addAppAccessRestrictions: [ "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { mapToData: "apps" } ], addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"], addStatusCheckContexts: [ "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { mapToData: "contexts" } ], addTeamAccessRestrictions: [ "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { mapToData: "teams" } ], addUserAccessRestrictions: [ "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { mapToData: "users" } ], cancelPagesDeployment: [ "POST /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}/cancel" ], checkAutomatedSecurityFixes: [ "GET /repos/{owner}/{repo}/automated-security-fixes" ], checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"], checkPrivateVulnerabilityReporting: [ "GET /repos/{owner}/{repo}/private-vulnerability-reporting" ], checkVulnerabilityAlerts: [ "GET /repos/{owner}/{repo}/vulnerability-alerts" ], codeownersErrors: ["GET /repos/{owner}/{repo}/codeowners/errors"], compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"], compareCommitsWithBasehead: [ "GET /repos/{owner}/{repo}/compare/{basehead}" ], createAutolink: ["POST /repos/{owner}/{repo}/autolinks"], createCommitComment: [ "POST /repos/{owner}/{repo}/commits/{commit_sha}/comments" ], createCommitSignatureProtection: [ "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" ], createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"], createDeployKey: ["POST /repos/{owner}/{repo}/keys"], createDeployment: ["POST /repos/{owner}/{repo}/deployments"], createDeploymentBranchPolicy: [ "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" ], createDeploymentProtectionRule: [ "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" ], createDeploymentStatus: [ "POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" ], createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"], createForAuthenticatedUser: ["POST /user/repos"], createFork: ["POST /repos/{owner}/{repo}/forks"], createInOrg: ["POST /orgs/{org}/repos"], createOrUpdateCustomPropertiesValues: [ "PATCH /repos/{owner}/{repo}/properties/values" ], createOrUpdateEnvironment: [ "PUT /repos/{owner}/{repo}/environments/{environment_name}" ], createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"], createOrgRuleset: ["POST /orgs/{org}/rulesets"], createPagesDeployment: ["POST /repos/{owner}/{repo}/pages/deployments"], createPagesSite: ["POST /repos/{owner}/{repo}/pages"], createRelease: ["POST /repos/{owner}/{repo}/releases"], createRepoRuleset: ["POST /repos/{owner}/{repo}/rulesets"], createTagProtection: ["POST /repos/{owner}/{repo}/tags/protection"], createUsingTemplate: [ "POST /repos/{template_owner}/{template_repo}/generate" ], createWebhook: ["POST /repos/{owner}/{repo}/hooks"], declineInvitation: [ "DELETE /user/repository_invitations/{invitation_id}", {}, { renamed: ["repos", "declineInvitationForAuthenticatedUser"] } ], declineInvitationForAuthenticatedUser: [ "DELETE /user/repository_invitations/{invitation_id}" ], delete: ["DELETE /repos/{owner}/{repo}"], deleteAccessRestrictions: [ "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" ], deleteAdminBranchProtection: [ "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" ], deleteAnEnvironment: [ "DELETE /repos/{owner}/{repo}/environments/{environment_name}" ], deleteAutolink: ["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"], deleteBranchProtection: [ "DELETE /repos/{owner}/{repo}/branches/{branch}/protection" ], deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"], deleteCommitSignatureProtection: [ "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" ], deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"], deleteDeployment: [ "DELETE /repos/{owner}/{repo}/deployments/{deployment_id}" ], deleteDeploymentBranchPolicy: [ "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" ], deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"], deleteInvitation: [ "DELETE /repos/{owner}/{repo}/invitations/{invitation_id}" ], deleteOrgRuleset: ["DELETE /orgs/{org}/rulesets/{ruleset_id}"], deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages"], deletePullRequestReviewProtection: [ "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" ], deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"], deleteReleaseAsset: [ "DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}" ], deleteRepoRuleset: ["DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}"], deleteTagProtection: [ "DELETE /repos/{owner}/{repo}/tags/protection/{tag_protection_id}" ], deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"], disableAutomatedSecurityFixes: [ "DELETE /repos/{owner}/{repo}/automated-security-fixes" ], disableDeploymentProtectionRule: [ "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" ], disablePrivateVulnerabilityReporting: [ "DELETE /repos/{owner}/{repo}/private-vulnerability-reporting" ], disableVulnerabilityAlerts: [ "DELETE /repos/{owner}/{repo}/vulnerability-alerts" ], downloadArchive: [ "GET /repos/{owner}/{repo}/zipball/{ref}", {}, { renamed: ["repos", "downloadZipballArchive"] } ], downloadTarballArchive: ["GET /repos/{owner}/{repo}/tarball/{ref}"], downloadZipballArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}"], enableAutomatedSecurityFixes: [ "PUT /repos/{owner}/{repo}/automated-security-fixes" ], enablePrivateVulnerabilityReporting: [ "PUT /repos/{owner}/{repo}/private-vulnerability-reporting" ], enableVulnerabilityAlerts: [ "PUT /repos/{owner}/{repo}/vulnerability-alerts" ], generateReleaseNotes: [ "POST /repos/{owner}/{repo}/releases/generate-notes" ], get: ["GET /repos/{owner}/{repo}"], getAccessRestrictions: [ "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" ], getAdminBranchProtection: [ "GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" ], getAllDeploymentProtectionRules: [ "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" ], getAllEnvironments: ["GET /repos/{owner}/{repo}/environments"], getAllStatusCheckContexts: [ "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts" ], getAllTopics: ["GET /repos/{owner}/{repo}/topics"], getAppsWithAccessToProtectedBranch: [ "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps" ], getAutolink: ["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"], getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"], getBranchProtection: [ "GET /repos/{owner}/{repo}/branches/{branch}/protection" ], getBranchRules: ["GET /repos/{owner}/{repo}/rules/branches/{branch}"], getClones: ["GET /repos/{owner}/{repo}/traffic/clones"], getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"], getCollaboratorPermissionLevel: [ "GET /repos/{owner}/{repo}/collaborators/{username}/permission" ], getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"], getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"], getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"], getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"], getCommitSignatureProtection: [ "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" ], getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"], getContent: ["GET /repos/{owner}/{repo}/contents/{path}"], getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"], getCustomDeploymentProtectionRule: [ "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" ], getCustomPropertiesValues: ["GET /repos/{owner}/{repo}/properties/values"], getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"], getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"], getDeploymentBranchPolicy: [ "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" ], getDeploymentStatus: [ "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}" ], getEnvironment: [ "GET /repos/{owner}/{repo}/environments/{environment_name}" ], getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"], getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"], getOrgRuleSuite: ["GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}"], getOrgRuleSuites: ["GET /orgs/{org}/rulesets/rule-suites"], getOrgRuleset: ["GET /orgs/{org}/rulesets/{ruleset_id}"], getOrgRulesets: ["GET /orgs/{org}/rulesets"], getPages: ["GET /repos/{owner}/{repo}/pages"], getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"], getPagesDeployment: [ "GET /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}" ], getPagesHealthCheck: ["GET /repos/{owner}/{repo}/pages/health"], getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"], getPullRequestReviewProtection: [ "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" ], getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"], getReadme: ["GET /repos/{owner}/{repo}/readme"], getReadmeInDirectory: ["GET /repos/{owner}/{repo}/readme/{dir}"], getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"], getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"], getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"], getRepoRuleSuite: [ "GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}" ], getRepoRuleSuites: ["GET /repos/{owner}/{repo}/rulesets/rule-suites"], getRepoRuleset: ["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}"], getRepoRulesets: ["GET /repos/{owner}/{repo}/rulesets"], getStatusChecksProtection: [ "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" ], getTeamsWithAccessToProtectedBranch: [ "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams" ], getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"], getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"], getUsersWithAccessToProtectedBranch: [ "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users" ], getViews: ["GET /repos/{owner}/{repo}/traffic/views"], getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"], getWebhookConfigForRepo: [ "GET /repos/{owner}/{repo}/hooks/{hook_id}/config" ], getWebhookDelivery: [ "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}" ], listActivities: ["GET /repos/{owner}/{repo}/activity"], listAutolinks: ["GET /repos/{owner}/{repo}/autolinks"], listBranches: ["GET /repos/{owner}/{repo}/branches"], listBranchesForHeadCommit: [ "GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head" ], listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"], listCommentsForCommit: [ "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments" ], listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"], listCommitStatusesForRef: [ "GET /repos/{owner}/{repo}/commits/{ref}/statuses" ], listCommits: ["GET /repos/{owner}/{repo}/commits"], listContributors: ["GET /repos/{owner}/{repo}/contributors"], listCustomDeploymentRuleIntegrations: [ "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps" ], listDeployKeys: ["GET /repos/{owner}/{repo}/keys"], listDeploymentBranchPolicies: [ "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" ], listDeploymentStatuses: [ "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" ], listDeployments: ["GET /repos/{owner}/{repo}/deployments"], listForAuthenticatedUser: ["GET /user/repos"], listForOrg: ["GET /orgs/{org}/repos"], listForUser: ["GET /users/{username}/repos"], listForks: ["GET /repos/{owner}/{repo}/forks"], listInvitations: ["GET /repos/{owner}/{repo}/invitations"], listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"], listLanguages: ["GET /repos/{owner}/{repo}/languages"], listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"], listPublic: ["GET /repositories"], listPullRequestsAssociatedWithCommit: [ "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls" ], listReleaseAssets: [ "GET /repos/{owner}/{repo}/releases/{release_id}/assets" ], listReleases: ["GET /repos/{owner}/{repo}/releases"], listTagProtection: ["GET /repos/{owner}/{repo}/tags/protection"], listTags: ["GET /repos/{owner}/{repo}/tags"], listTeams: ["GET /repos/{owner}/{repo}/teams"], listWebhookDeliveries: [ "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries" ], listWebhooks: ["GET /repos/{owner}/{repo}/hooks"], merge: ["POST /repos/{owner}/{repo}/merges"], mergeUpstream: ["POST /repos/{owner}/{repo}/merge-upstream"], pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"], redeliverWebhookDelivery: [ "POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" ], removeAppAccessRestrictions: [ "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { mapToData: "apps" } ], removeCollaborator: [ "DELETE /repos/{owner}/{repo}/collaborators/{username}" ], removeStatusCheckContexts: [ "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { mapToData: "contexts" } ], removeStatusCheckProtection: [ "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" ], removeTeamAccessRestrictions: [ "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { mapToData: "teams" } ], removeUserAccessRestrictions: [ "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { mapToData: "users" } ], renameBranch: ["POST /repos/{owner}/{repo}/branches/{branch}/rename"], replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics"], requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"], setAdminBranchProtection: [ "POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" ], setAppAccessRestrictions: [ "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { mapToData: "apps" } ], setStatusCheckContexts: [ "PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { mapToData: "contexts" } ], setTeamAccessRestrictions: [ "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { mapToData: "teams" } ], setUserAccessRestrictions: [ "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { mapToData: "users" } ], testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"], transfer: ["POST /repos/{owner}/{repo}/transfer"], update: ["PATCH /repos/{owner}/{repo}"], updateBranchProtection: [ "PUT /repos/{owner}/{repo}/branches/{branch}/protection" ], updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"], updateDeploymentBranchPolicy: [ "PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" ], updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"], updateInvitation: [ "PATCH /repos/{owner}/{repo}/invitations/{invitation_id}" ], updateOrgRuleset: ["PUT /orgs/{org}/rulesets/{ruleset_id}"], updatePullRequestReviewProtection: [ "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" ], updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"], updateReleaseAsset: [ "PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}" ], updateRepoRuleset: ["PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}"], updateStatusCheckPotection: [ "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", {}, { renamed: ["repos", "updateStatusCheckProtection"] } ], updateStatusCheckProtection: [ "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" ], updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"], updateWebhookConfigForRepo: [ "PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config" ], uploadReleaseAsset: [ "POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", { baseUrl: "https://uploads.github.com" } ] }, search: { code: ["GET /search/code"], commits: ["GET /search/commits"], issuesAndPullRequests: ["GET /search/issues"], labels: ["GET /search/labels"], repos: ["GET /search/repositories"], topics: ["GET /search/topics"], users: ["GET /search/users"] }, secretScanning: { getAlert: [ "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" ], listAlertsForEnterprise: [ "GET /enterprises/{enterprise}/secret-scanning/alerts" ], listAlertsForOrg: ["GET /orgs/{org}/secret-scanning/alerts"], listAlertsForRepo: ["GET /repos/{owner}/{repo}/secret-scanning/alerts"], listLocationsForAlert: [ "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations" ], updateAlert: [ "PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" ] }, securityAdvisories: { createFork: [ "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/forks" ], createPrivateVulnerabilityReport: [ "POST /repos/{owner}/{repo}/security-advisories/reports" ], createRepositoryAdvisory: [ "POST /repos/{owner}/{repo}/security-advisories" ], createRepositoryAdvisoryCveRequest: [ "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve" ], getGlobalAdvisory: ["GET /advisories/{ghsa_id}"], getRepositoryAdvisory: [ "GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}" ], listGlobalAdvisories: ["GET /advisories"], listOrgRepositoryAdvisories: ["GET /orgs/{org}/security-advisories"], listRepositoryAdvisories: ["GET /repos/{owner}/{repo}/security-advisories"], updateRepositoryAdvisory: [ "PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}" ] }, teams: { addOrUpdateMembershipForUserInOrg: [ "PUT /orgs/{org}/teams/{team_slug}/memberships/{username}" ], addOrUpdateProjectPermissionsInOrg: [ "PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}" ], addOrUpdateRepoPermissionsInOrg: [ "PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" ], checkPermissionsForProjectInOrg: [ "GET /orgs/{org}/teams/{team_slug}/projects/{project_id}" ], checkPermissionsForRepoInOrg: [ "GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" ], create: ["POST /orgs/{org}/teams"], createDiscussionCommentInOrg: [ "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" ], createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"], deleteDiscussionCommentInOrg: [ "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" ], deleteDiscussionInOrg: [ "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" ], deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"], getByName: ["GET /orgs/{org}/teams/{team_slug}"], getDiscussionCommentInOrg: [ "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" ], getDiscussionInOrg: [ "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" ], getMembershipForUserInOrg: [ "GET /orgs/{org}/teams/{team_slug}/memberships/{username}" ], list: ["GET /orgs/{org}/teams"], listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"], listDiscussionCommentsInOrg: [ "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" ], listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"], listForAuthenticatedUser: ["GET /user/teams"], listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"], listPendingInvitationsInOrg: [ "GET /orgs/{org}/teams/{team_slug}/invitations" ], listProjectsInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects"], listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"], removeMembershipForUserInOrg: [ "DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}" ], removeProjectInOrg: [ "DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}" ], removeRepoInOrg: [ "DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" ], updateDiscussionCommentInOrg: [ "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" ], updateDiscussionInOrg: [ "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" ], updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"] }, users: { addEmailForAuthenticated: [ "POST /user/emails", {}, { renamed: ["users", "addEmailForAuthenticatedUser"] } ], addEmailForAuthenticatedUser: ["POST /user/emails"], addSocialAccountForAuthenticatedUser: ["POST /user/social_accounts"], block: ["PUT /user/blocks/{username}"], checkBlocked: ["GET /user/blocks/{username}"], checkFollowingForUser: ["GET /users/{username}/following/{target_user}"], checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"], createGpgKeyForAuthenticated: [ "POST /user/gpg_keys", {}, { renamed: ["users", "createGpgKeyForAuthenticatedUser"] } ], createGpgKeyForAuthenticatedUser: ["POST /user/gpg_keys"], createPublicSshKeyForAuthenticated: [ "POST /user/keys", {}, { renamed: ["users", "createPublicSshKeyForAuthenticatedUser"] } ], createPublicSshKeyForAuthenticatedUser: ["POST /user/keys"], createSshSigningKeyForAuthenticatedUser: ["POST /user/ssh_signing_keys"], deleteEmailForAuthenticated: [ "DELETE /user/emails", {}, { renamed: ["users", "deleteEmailForAuthenticatedUser"] } ], deleteEmailForAuthenticatedUser: ["DELETE /user/emails"], deleteGpgKeyForAuthenticated: [ "DELETE /user/gpg_keys/{gpg_key_id}", {}, { renamed: ["users", "deleteGpgKeyForAuthenticatedUser"] } ], deleteGpgKeyForAuthenticatedUser: ["DELETE /user/gpg_keys/{gpg_key_id}"], deletePublicSshKeyForAuthenticated: [ "DELETE /user/keys/{key_id}", {}, { renamed: ["users", "deletePublicSshKeyForAuthenticatedUser"] } ], deletePublicSshKeyForAuthenticatedUser: ["DELETE /user/keys/{key_id}"], deleteSocialAccountForAuthenticatedUser: ["DELETE /user/social_accounts"], deleteSshSigningKeyForAuthenticatedUser: [ "DELETE /user/ssh_signing_keys/{ssh_signing_key_id}" ], follow: ["PUT /user/following/{username}"], getAuthenticated: ["GET /user"], getByUsername: ["GET /users/{username}"], getContextForUser: ["GET /users/{username}/hovercard"], getGpgKeyForAuthenticated: [ "GET /user/gpg_keys/{gpg_key_id}", {}, { renamed: ["users", "getGpgKeyForAuthenticatedUser"] } ], getGpgKeyForAuthenticatedUser: ["GET /user/gpg_keys/{gpg_key_id}"], getPublicSshKeyForAuthenticated: [ "GET /user/keys/{key_id}", {}, { renamed: ["users", "getPublicSshKeyForAuthenticatedUser"] } ], getPublicSshKeyForAuthenticatedUser: ["GET /user/keys/{key_id}"], getSshSigningKeyForAuthenticatedUser: [ "GET /user/ssh_signing_keys/{ssh_signing_key_id}" ], list: ["GET /users"], listBlockedByAuthenticated: [ "GET /user/blocks", {}, { renamed: ["users", "listBlockedByAuthenticatedUser"] } ], listBlockedByAuthenticatedUser: ["GET /user/blocks"], listEmailsForAuthenticated: [ "GET /user/emails", {}, { renamed: ["users", "listEmailsForAuthenticatedUser"] } ], listEmailsForAuthenticatedUser: ["GET /user/emails"], listFollowedByAuthenticated: [ "GET /user/following", {}, { renamed: ["users", "listFollowedByAuthenticatedUser"] } ], listFollowedByAuthenticatedUser: ["GET /user/following"], listFollowersForAuthenticatedUser: ["GET /user/followers"], listFollowersForUser: ["GET /users/{username}/followers"], listFollowingForUser: ["GET /users/{username}/following"], listGpgKeysForAuthenticated: [ "GET /user/gpg_keys", {}, { renamed: ["users", "listGpgKeysForAuthenticatedUser"] } ], listGpgKeysForAuthenticatedUser: ["GET /user/gpg_keys"], listGpgKeysForUser: ["GET /users/{username}/gpg_keys"], listPublicEmailsForAuthenticated: [ "GET /user/public_emails", {}, { renamed: ["users", "listPublicEmailsForAuthenticatedUser"] } ], listPublicEmailsForAuthenticatedUser: ["GET /user/public_emails"], listPublicKeysForUser: ["GET /users/{username}/keys"], listPublicSshKeysForAuthenticated: [ "GET /user/keys", {}, { renamed: ["users", "listPublicSshKeysForAuthenticatedUser"] } ], listPublicSshKeysForAuthenticatedUser: ["GET /user/keys"], listSocialAccountsForAuthenticatedUser: ["GET /user/social_accounts"], listSocialAccountsForUser: ["GET /users/{username}/social_accounts"], listSshSigningKeysForAuthenticatedUser: ["GET /user/ssh_signing_keys"], listSshSigningKeysForUser: ["GET /users/{username}/ssh_signing_keys"], setPrimaryEmailVisibilityForAuthenticated: [ "PATCH /user/email/visibility", {}, { renamed: ["users", "setPrimaryEmailVisibilityForAuthenticatedUser"] } ], setPrimaryEmailVisibilityForAuthenticatedUser: [ "PATCH /user/email/visibility" ], unblock: ["DELETE /user/blocks/{username}"], unfollow: ["DELETE /user/following/{username}"], updateAuthenticated: ["PATCH /user"] } }; var endpoints_default = Endpoints; // ../node_modules/@octokit/rest/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/endpoints-to-methods.js var endpointMethodsMap = /* @__PURE__ */ new Map(); for (const [scope, endpoints] of Object.entries(endpoints_default)) { for (const [methodName, endpoint2] of Object.entries(endpoints)) { const [route, defaults, decorations] = endpoint2; const [method, url] = route.split(/ /); const endpointDefaults = Object.assign( { method, url }, defaults ); if (!endpointMethodsMap.has(scope)) { endpointMethodsMap.set(scope, /* @__PURE__ */ new Map()); } endpointMethodsMap.get(scope).set(methodName, { scope, methodName, endpointDefaults, decorations }); } } var handler = { has({ scope }, methodName) { return endpointMethodsMap.get(scope).has(methodName); }, getOwnPropertyDescriptor(target, methodName) { return { value: this.get(target, methodName), // ensures method is in the cache configurable: true, writable: true, enumerable: true }; }, defineProperty(target, methodName, descriptor) { Object.defineProperty(target.cache, methodName, descriptor); return true; }, deleteProperty(target, methodName) { delete target.cache[methodName]; return true; }, ownKeys({ scope }) { return [...endpointMethodsMap.get(scope).keys()]; }, set(target, methodName, value) { return target.cache[methodName] = value; }, get({ octokit, scope, cache }, methodName) { if (cache[methodName]) { return cache[methodName]; } const method = endpointMethodsMap.get(scope).get(methodName); if (!method) { return void 0; } const { endpointDefaults, decorations } = method; if (decorations) { cache[methodName] = decorate( octokit, scope, methodName, endpointDefaults, decorations ); } else { cache[methodName] = octokit.request.defaults(endpointDefaults); } return cache[methodName]; } }; function endpointsToMethods(octokit) { const newMethods = {}; for (const scope of endpointMethodsMap.keys()) { newMethods[scope] = new Proxy({ octokit, scope, cache: {} }, handler); } return newMethods; } function decorate(octokit, scope, methodName, defaults, decorations) { const requestWithDefaults = octokit.request.defaults(defaults); function withDecorations(...args) { let options = requestWithDefaults.endpoint.merge(...args); if (decorations.mapToData) { options = Object.assign({}, options, { data: options[decorations.mapToData], [decorations.mapToData]: void 0 }); return requestWithDefaults(options); } if (decorations.renamed) { const [newScope, newMethodName] = decorations.renamed; octokit.log.warn( `octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()` ); } if (decorations.deprecated) { octokit.log.warn(decorations.deprecated); } if (decorations.renamedParameters) { const options2 = requestWithDefaults.endpoint.merge(...args); for (const [name, alias] of Object.entries( decorations.renamedParameters )) { if (name in options2) { octokit.log.warn( `"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead` ); if (!(alias in options2)) { options2[alias] = options2[name]; } delete options2[name]; } } return requestWithDefaults(options2); } return requestWithDefaults(...args); } return Object.assign(withDecorations, requestWithDefaults); } // ../node_modules/@octokit/rest/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/index.js function restEndpointMethods(octokit) { const api = endpointsToMethods(octokit); return { rest: api }; } restEndpointMethods.VERSION = VERSION7; function legacyRestEndpointMethods(octokit) { const api = endpointsToMethods(octokit); return { ...api, rest: api }; } legacyRestEndpointMethods.VERSION = VERSION7; // ../node_modules/@octokit/rest/dist-src/version.js var VERSION8 = "21.0.2"; // ../node_modules/@octokit/rest/dist-src/index.js var Octokit2 = Octokit.plugin(requestLog, legacyRestEndpointMethods, paginateRest).defaults( { userAgent: `octokit-rest.js/${VERSION8}` } ); // dist/def/pre-publish.js var import_clipanion4 = require("clipanion"); var BasePrePublishCommand = class extends import_clipanion4.Command { static paths = [["pre-publish"], ["prepublish"]]; static usage = import_clipanion4.Command.Usage({ description: "Update package.json and copy addons into per platform packages" }); cwd = import_clipanion4.Option.String("--cwd", process.cwd(), { description: "The working directory of where napi command will be executed in, all other paths options are relative to this path" }); configPath = import_clipanion4.Option.String("--config-path,-c", { description: "Path to `napi` config json file" }); packageJsonPath = import_clipanion4.Option.String("--package-json-path", "package.json", { description: "Path to `package.json`" }); npmDir = import_clipanion4.Option.String("--npm-dir,-p", "npm", { description: "Path to the folder where the npm packages put" }); tagStyle = import_clipanion4.Option.String("--tag-style,--tagstyle,-t", "lerna", { description: "git tag style, `npm` or `lerna`" }); ghRelease = import_clipanion4.Option.Boolean("--gh-release", true, { description: "Whether create GitHub release" }); ghReleaseName = import_clipanion4.Option.String("--gh-release-name", { description: "GitHub release name" }); ghReleaseId = import_clipanion4.Option.String("--gh-release-id", { description: "Existing GitHub release id" }); dryRun = import_clipanion4.Option.Boolean("--dry-run", false, { description: "Dry run without touching file system" }); getOptions() { return { cwd: this.cwd, configPath: this.configPath, packageJsonPath: this.packageJsonPath, npmDir: this.npmDir, tagStyle: this.tagStyle, ghRelease: this.ghRelease, ghReleaseName: this.ghReleaseName, ghReleaseId: this.ghReleaseId, dryRun: this.dryRun }; } }; function applyDefaultPrePublishOptions(options) { return { cwd: process.cwd(), packageJsonPath: "package.json", npmDir: "npm", tagStyle: "lerna", ghRelease: true, dryRun: false, ...options }; } // dist/api/version.js var import_node_path5 = require("node:path"); // dist/def/version.js var import_clipanion5 = require("clipanion"); var BaseVersionCommand = class extends import_clipanion5.Command { static paths = [["version"]]; static usage = import_clipanion5.Command.Usage({ description: "Update version in created npm packages" }); cwd = import_clipanion5.Option.String("--cwd", process.cwd(), { description: "The working directory of where napi command will be executed in, all other paths options are relative to this path" }); configPath = import_clipanion5.Option.String("--config-path,-c", { description: "Path to `napi` config json file" }); packageJsonPath = import_clipanion5.Option.String("--package-json-path", "package.json", { description: "Path to `package.json`" }); npmDir = import_clipanion5.Option.String("--npm-dir", "npm", { description: "Path to the folder where the npm packages put" }); getOptions() { return { cwd: this.cwd, configPath: this.configPath, packageJsonPath: this.packageJsonPath, npmDir: this.npmDir }; } }; function applyDefaultVersionOptions(options) { return { cwd: process.cwd(), packageJsonPath: "package.json", npmDir: "npm", ...options }; } // dist/api/version.js var debug6 = debugFactory("version"); async function version(userOptions) { const options = applyDefaultVersionOptions(userOptions); const packageJsonPath = (0, import_node_path5.resolve)(options.cwd, options.packageJsonPath); const config = await readNapiConfig(packageJsonPath, options.configPath ? (0, import_node_path5.resolve)(options.cwd, options.configPath) : void 0); for (const target of config.targets) { const pkgDir = (0, import_node_path5.resolve)(options.cwd, options.npmDir, target.platformArchABI); debug6(`Update version to %i in [%i]`, config.packageJson.version, pkgDir); await updatePackageJson((0, import_node_path5.join)(pkgDir, "package.json"), { version: config.packageJson.version }); } } // dist/api/pre-publish.js var debug7 = debugFactory("pre-publish"); async function prePublish(userOptions) { debug7("Receive pre-publish options:"); debug7(" %O", userOptions); const options = applyDefaultPrePublishOptions(userOptions); const packageJsonPath = (0, import_node_path6.resolve)(options.cwd, options.packageJsonPath); const { packageJson, targets, packageName, binaryName, npmClient } = await readNapiConfig(packageJsonPath, options.configPath ? (0, import_node_path6.resolve)(options.cwd, options.configPath) : void 0); async function createGhRelease(packageName2, version2) { if (!options.ghRelease) { return { owner: null, repo: null, pkgInfo: { name: null, version: null, tag: null } }; } const { repo: repo2, owner: owner2, pkgInfo: pkgInfo2, octokit: octokit2 } = getRepoInfo(packageName2, version2); if (!repo2 || !owner2) { return { owner: null, repo: null, pkgInfo: { name: null, version: null, tag: null } }; } if (!options.dryRun) { try { await octokit2.repos.createRelease({ owner: owner2, repo: repo2, tag_name: pkgInfo2.tag, name: options.ghReleaseName, prerelease: version2.includes("alpha") || version2.includes("beta") || version2.includes("rc") }); } catch (e) { debug7(`Params: ${JSON.stringify({ owner: owner2, repo: repo2, tag_name: pkgInfo2.tag }, null, 2)}`); console.error(e); } } return { owner: owner2, repo: repo2, pkgInfo: pkgInfo2, octokit: octokit2 }; } function getRepoInfo(packageName2, version2) { const headCommit = (0, import_node_child_process6.execSync)("git log -1 --pretty=%B", { encoding: "utf-8" }).trim(); const { GITHUB_REPOSITORY } = process.env; if (!GITHUB_REPOSITORY) { return { owner: null, repo: null, pkgInfo: { name: null, version: null, tag: null } }; } debug7(`Github repository: ${GITHUB_REPOSITORY}`); const [owner2, repo2] = GITHUB_REPOSITORY.split("/"); const octokit2 = new Octokit2({ auth: process.env.GITHUB_TOKEN }); let pkgInfo2; if (options.tagStyle === "lerna") { const packagesToPublish = headCommit.split("\n").map((line) => line.trim()).filter((line, index) => line.length && index).map((line) => line.substring(2)).map(parseTag); pkgInfo2 = packagesToPublish.find((pkgInfo3) => pkgInfo3.name === packageName2); if (!pkgInfo2) { throw new TypeError(`No release commit found with ${packageName2}, original commit info: ${headCommit}`); } } else { pkgInfo2 = { tag: `v${version2}`, version: version2, name: packageName2 }; } return { owner: owner2, repo: repo2, pkgInfo: pkgInfo2, octokit: octokit2 }; } if (!options.dryRun) { await version(userOptions); await updatePackageJson(packageJsonPath, { optionalDependencies: targets.reduce((deps, target) => { deps[`${packageName}-${target.platformArchABI}`] = packageJson.version; return deps; }, {}) }); } const { owner, repo, pkgInfo, octokit } = options.ghReleaseId ? getRepoInfo(packageName, packageJson.version) : await createGhRelease(packageName, packageJson.version); for (const target of targets) { const pkgDir = (0, import_node_path6.resolve)(options.cwd, options.npmDir, `${target.platformArchABI}`); const ext = target.platform === "wasi" || target.platform === "wasm" ? "wasm" : "node"; const filename = `${binaryName}.${target.platformArchABI}.${ext}`; const dstPath = (0, import_node_path6.join)(pkgDir, filename); if (!options.dryRun) { if (!(0, import_node_fs4.existsSync)(dstPath)) { debug7.warn(`%s doesn't exist`, dstPath); continue; } (0, import_node_child_process6.execSync)(`${npmClient} publish`, { cwd: pkgDir, env: process.env }); if (options.ghRelease && repo && owner) { debug7.info(`Creating GitHub release ${pkgInfo.tag}`); try { const releaseId = options.ghReleaseId ? Number(options.ghReleaseId) : (await octokit.repos.getReleaseByTag({ repo, owner, tag: pkgInfo.tag })).data.id; const dstFileStats = (0, import_node_fs4.statSync)(dstPath); const assetInfo = await octokit.repos.uploadReleaseAsset({ owner, repo, name: filename, release_id: releaseId, mediaType: { format: "raw" }, headers: { "content-length": dstFileStats.size, "content-type": "application/octet-stream" }, // @ts-expect-error octokit types are wrong data: await readFileAsync(dstPath) }); debug7.info(`GitHub release created`); debug7.info(`Download URL: %s`, assetInfo.data.browser_download_url); } catch (e) { debug7.error(`Param: ${JSON.stringify({ owner, repo, tag: pkgInfo.tag, filename: dstPath }, null, 2)}`); debug7.error(e); } } } } } function parseTag(tag) { const segments = tag.split("@"); const version2 = segments.pop(); const name = segments.join("@"); return { name, version: version2, tag }; } // dist/api/rename.js var import_node_path7 = require("node:path"); // dist/def/rename.js var import_clipanion6 = require("clipanion"); var BaseRenameCommand = class extends import_clipanion6.Command { static paths = [["rename"]]; static usage = import_clipanion6.Command.Usage({ description: "Rename the NAPI-RS project" }); cwd = import_clipanion6.Option.String("--cwd", process.cwd(), { description: "The working directory of where napi command will be executed in, all other paths options are relative to this path" }); configPath = import_clipanion6.Option.String("--config-path,-c", { description: "Path to `napi` config json file" }); packageJsonPath = import_clipanion6.Option.String("--package-json-path", "package.json", { description: "Path to `package.json`" }); npmDir = import_clipanion6.Option.String("--npm-dir", "npm", { description: "Path to the folder where the npm packages put" }); $$name = import_clipanion6.Option.String("--name,-n", { description: "The new name of the project" }); binaryName = import_clipanion6.Option.String("--binary-name,-b", { description: "The new binary name *.node files" }); packageName = import_clipanion6.Option.String("--package-name", { description: "The new package name of the project" }); manifestPath = import_clipanion6.Option.String("--manifest-path", "Cargo.toml", { description: "Path to `Cargo.toml`" }); repository = import_clipanion6.Option.String("--repository", { description: "The new repository of the project" }); description = import_clipanion6.Option.String("--description", { description: "The new description of the project" }); getOptions() { return { cwd: this.cwd, configPath: this.configPath, packageJsonPath: this.packageJsonPath, npmDir: this.npmDir, name: this.$$name, binaryName: this.binaryName, packageName: this.packageName, manifestPath: this.manifestPath, repository: this.repository, description: this.description }; } }; function applyDefaultRenameOptions(options) { return { cwd: process.cwd(), packageJsonPath: "package.json", npmDir: "npm", manifestPath: "Cargo.toml", ...options }; } // dist/api/rename.js async function renameProject(userOptions) { const options = applyDefaultRenameOptions(userOptions); const packageJsonPath = (0, import_node_path7.resolve)(options.cwd, options.packageJsonPath); const cargoTomlPath = (0, import_node_path7.resolve)(options.cwd, options.manifestPath); const packageJsonContent = await readFileAsync(packageJsonPath, "utf8"); const packageJsonData = JSON.parse(packageJsonContent); merge_default(packageJsonData, omitBy_default(pick_default(options, ["name", "description", "author", "license"]), isNil_default), { napi: omitBy_default({ binaryName: options.binaryName, packageName: options.packageName }, isNil_default) }); if (options.configPath) { const configPath = (0, import_node_path7.resolve)(options.cwd, options.configPath); const configContent = await readFileAsync(configPath, "utf8"); const configData = JSON.parse(configContent); configData.binaryName = options.binaryName; configData.packageName = options.packageName; await writeFileAsync(configPath, JSON.stringify(configData, null, 2)); } await writeFileAsync(packageJsonPath, JSON.stringify(packageJsonData, null, 2)); let tomlContent = await readFileAsync(cargoTomlPath, "utf8"); tomlContent = tomlContent.replace(/name\s?=\s?"([\w+])"/, `name = "${options.binaryName}"`); await writeFileAsync(cargoTomlPath, tomlContent); await createNpmDirs({ cwd: options.cwd, packageJsonPath: options.packageJsonPath, npmDir: options.npmDir, dryRun: false }); } // dist/api/universalize.js var import_node_child_process7 = require("node:child_process"); var import_node_path8 = require("node:path"); // dist/def/universalize.js var import_clipanion7 = require("clipanion"); var BaseUniversalizeCommand = class extends import_clipanion7.Command { static paths = [["universalize"]]; static usage = import_clipanion7.Command.Usage({ description: "Combile built binaries into one universal binary" }); cwd = import_clipanion7.Option.String("--cwd", process.cwd(), { description: "The working directory of where napi command will be executed in, all other paths options are relative to this path" }); configPath = import_clipanion7.Option.String("--config-path,-c", { description: "Path to `napi` config json file" }); packageJsonPath = import_clipanion7.Option.String("--package-json-path", "package.json", { description: "Path to `package.json`" }); outputDir = import_clipanion7.Option.String("--output-dir,-o", "./", { description: "Path to the folder where all built `.node` files put, same as `--output-dir` of build command" }); getOptions() { return { cwd: this.cwd, configPath: this.configPath, packageJsonPath: this.packageJsonPath, outputDir: this.outputDir }; } }; function applyDefaultUniversalizeOptions(options) { return { cwd: process.cwd(), packageJsonPath: "package.json", outputDir: "./", ...options }; } // dist/api/universalize.js var debug8 = debugFactory("universalize"); var universalizers = { darwin: (inputs, output) => { (0, import_node_child_process7.spawnSync)("lipo", ["-create", "-output", output, ...inputs], { stdio: "inherit" }); } }; async function universalizeBinaries(userOptions) { const options = applyDefaultUniversalizeOptions(userOptions); const packageJsonPath = (0, import_node_path8.join)(options.cwd, options.packageJsonPath); const config = await readNapiConfig(packageJsonPath, options.configPath ? (0, import_node_path8.resolve)(options.cwd, options.configPath) : void 0); const target = config.targets.find((t) => t.platform === process.platform && t.arch === "universal"); if (!target) { throw new Error(`'universal' arch for platform '${process.platform}' not found in config!`); } const srcFiles = UniArchsByPlatform[process.platform]?.map((arch) => (0, import_node_path8.resolve)(options.cwd, options.outputDir, `${config.binaryName}.${process.platform}-${arch}.node`)); if (!srcFiles || !universalizers[process.platform]) { throw new Error(`'universal' arch for platform '${process.platform}' not supported.`); } debug8(`Looking up source binaries to combine: `); debug8(" %O", srcFiles); const srcFileLookup = await Promise.all(srcFiles.map((f) => fileExists(f))); const notFoundFiles = srcFiles.filter((_, i) => !srcFileLookup[i]); if (notFoundFiles.length) { throw new Error(`Some binary files were not found: ${JSON.stringify(notFoundFiles)}`); } const output = (0, import_node_path8.resolve)(options.cwd, options.outputDir, `${config.binaryName}.${process.platform}-universal.node`); universalizers[process.platform]?.(srcFiles, output); debug8(`Produced universal binary: ${output}`); } // dist/index.js var NapiCli = class { artifacts = collectArtifacts; new = newProject; build = buildProject; createNpmDirs = createNpmDirs; prePublish = prePublish; rename = renameProject; universalize = universalizeBinaries; version = version; }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { NapiCli, parseTriple }); /*! Bundled license information: lodash-es/lodash.js: (** * @license * Lodash (Custom Build) * Build: `lodash modularize exports="es" -o ./` * Copyright OpenJS Foundation and other contributors * Released under MIT license * Based on Underscore.js 1.8.3 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors *) */